Native Tally transcript
✓ virtual odd channels split the two equal-rest kinetic coefficients (by cross-pairing plus and minus sides; derived)
✓ an even hopping fit recovers the first target coefficient (by cross-pairing plus and minus sides; derived)
✓ transferring only the even hopping misses the second target (by cross-pairing plus and minus sides; derived)
✓ the same odd and even hopping restores both target coefficients (by cross-pairing plus and minus sides; derived)
✓ a residual cubic odd coupling gives sixth-order splitting (by cross-pairing plus and minus sides; derived)
✓ the scalar midpoint energy gives the correct opposite-transfer clock loop (by cross-pairing plus and minus sides; derived)
✓ the signed linear Dirac product gives the exact mixed-mode shift coefficient (by cross-pairing plus and minus sides; derived)
✓ the spin commutator terms cancel between the two transfer orders (by cross-pairing plus and minus sides; derived)
✓ independent Fourier harmonics of the z-velocity carry total mean-square weight seven eighths (by cross-pairing plus and minus sides; derived)
✓ the three torus weights follow by independent sine and cosine averages (by cross-pairing plus and minus sides; derived)
✓ two real contact coefficients give their exact squared norm (by cross-pairing plus and minus sides; derived)
✓ opposite signed sector intensities recover the diagonal spectral weights (by cross-pairing plus and minus sides; derived)
✓ a single symmetric contact matrix sends the prescribed local state to its inverse-kernel source (by cross-pairing plus and minus sides; derived)
✓ eliminating the mixed band adds a positive contribution to the cutoff residue (by cross-pairing plus and minus sides; derived)
✓ the limiting normalized mixed-band weight follows from the same residue (by cross-pairing plus and minus sides; derived)
✓ only the in-phase density mode softens for two identical components (by cross-pairing plus and minus sides; derived)
✓ crossing the Jeans threshold leaves a positive relative-density mode (by cross-pairing plus and minus sides; derived)
✓ a bounded polynomial window vanishes at the zone edge and starts quadratically in its argument (by cross-pairing plus and minus sides; derived)
✓ the zero-curvature dust energy equation recovers the enclosed gravitational mass (by cross-pairing plus and minus sides; derived)
✓ the six direction and recoil groups contain all 1481 rubidium shots (by cross-pairing plus and minus sides; derived)
✓ the held-out recoil order is at the midpoint of the two training orders (by cross-pairing plus and minus sides; derived)
Native Tally source
# Exact rational controls for mobile contacts, shared bands and self-gravitating matter.
ratchet 32 step
import "atom"
let zero=whole(0 trial)
let one=whole(1 trial)
let two=whole(2 trial)
let three=whole(3 trial)
let four=whole(4 trial)
let half=fraction(1 trial,2 trial)
let fourth=fraction(1 trial,4 trial)
let densitygap=two
let massgap=flip(one)
let stiffness=fraction(3 trial,8 trial)
let mix=half
fn curvature_term(even,odd,gap)
return even+share(odd*odd,gap)
end
let cd=curvature_term(stiffness,mix,densitygap)
let cm=curvature_term(stiffness,mix,massgap)
check cd==half and cm==fraction(1 trial,8 trial) "virtual odd channels split the two equal-rest kinetic coefficients"
let trained=fourth+flip(cd)
check cd+trained==fourth "an even hopping fit recovers the first target coefficient"
check cm+trained==flip(fraction(1 trial,8 trial)) "transferring only the even hopping misses the second target"
let common=stiffness+flip(fraction(1 trial,8 trial))
check curvature_term(common,mix+flip(half),densitygap)==fourth and curvature_term(common,mix+flip(half),massgap)==fourth "the same odd and even hopping restores both target coefficients"
let k=fraction(1 trial,8 trial)
let q=fraction(1 trial,4 trial)
fn cube(x)
return x*x*x
end
fn split(x)
let a=cube(x)
return share(a*a,densitygap)+flip(share(a*a,massgap))
end
check split(two*k)==whole(64 trial)*split(k) "a residual cubic odd coupling gives sixth-order splitting"
fn midpoint_square(x,p)
return four+(x+share(p,two))*(x+share(p,two))
end
check share(midpoint_square(k,q)+flip(midpoint_square(k,flip(q))),two)==k*q "the scalar midpoint energy gives the correct opposite-transfer clock loop"
let p=half
let r=fraction(1 trial,8 trial)
let left=(k+p+share(r,two))*(k+share(p,two))
let right=(k+r+share(p,two))*(k+share(r,two))
check left+flip(right)==(p+flip(r))*(k+share(p+r,two)) "the signed linear Dirac product gives the exact mixed-mode shift coefficient"
check (k+p+share(r,two))+flip(k+share(p,two))==(k+r+share(p,two))+flip(k+share(r,two)) "the spin commutator terms cancel between the two transfer orders"
let wxx=fraction(1 trial,8 trial)
let wyy=fraction(1 trial,4 trial)
let wzz=half
check wxx+wyy+wzz==fraction(7 trial,8 trial) "independent Fourier harmonics of the z-velocity carry total mean-square weight seven eighths"
check wxx==half*half*half and wyy==half*half and wzz==half "the three torus weights follow by independent sine and cosine averages"
let u=half
let v=fraction(3 trial,4 trial)
let gram=u*u+v*v
check gram==fraction(13 trial,16 trial) "two real contact coefficients give their exact squared norm"
let pos=half*(u+v)*(u+v)
let neg=half*(u+flip(v))*(u+flip(v))
check pos+neg==gram "opposite signed sector intensities recover the diagonal spectral weights"
let ua=fraction(3 trial,5 trial)
let ub=fraction(4 trial,5 trial)
let ya=half
let yb=flip(fourth)
let uy=ua*ya+ub*yb
let m11=two*ua*ya+flip(uy*ua*ua)
let m12=ua*yb+ub*ya+flip(uy*ua*ub)
let m22=two*ub*yb+flip(uy*ub*ub)
check m11*ua+m12*ub==ya and m12*ua+m22*ub==yb "a single symmetric contact matrix sends the prescribed local state to its inverse-kernel source"
let D=fraction(1 trial,3 trial)
let C=fraction(2 trial,3 trial)
let A=fraction(1 trial,8 trial)
let L=A+share(D*D,C)
check L==fraction(7 trial,24 trial) "eliminating the mixed band adds a positive contribution to the cutoff residue"
check share(D*D,C*L)==fraction(4 trial,7 trial) "the limiting normalized mixed-band weight follows from the same residue"
let grav=fraction(3 trial,4 trial)
let kinetic=one
let occ=half
let diag=kinetic+flip(grav*occ)
let off=flip(grav*occ)
check diag+off==fraction(1 trial,4 trial) and diag+flip(off)==one "only the in-phase density mode softens for two identical components"
let strong=fraction(5 trial,4 trial)
let d2=kinetic+flip(strong*occ)
let f2=flip(strong*occ)
check d2+f2==flip(fourth) and d2+flip(f2)==one "crossing the Jeans threshold leaves a positive relative-density mode"
fn envelope_value(s)
return (one+flip(s))*(one+s)
end
check envelope_value(zero)==one and envelope_value(one)==zero and one+flip(envelope_value(fourth))==fraction(1 trial,16 trial) "a bounded polynomial window vanishes at the zone edge and starts quadratically in its argument"
let areal=two
let mass=fraction(1 trial,8 trial)
let speed2=share(two*mass,areal)
check speed2==fraction(1 trial,8 trial) and share(areal*speed2,two)==mass "the zero-curvature dust energy equation recovers the enclosed gravitational mass"
let shots=whole(244 trial)+whole(243 trial)+whole(244 trial)+whole(260 trial)+whole(245 trial)+whole(245 trial)
check shots==whole(1481 trial) "the six direction and recoil groups contain all 1481 rubidium shots"
let scale=whole(4 trial)+whole(12 trial)
check share(scale,two)==whole(8 trial) "the held-out recoil order is at the midpoint of the two training orders"
collision_transport.py
"""Local translation of a coincident pair; build coefficients and solve the actual 3D poles.
Requires NumPy and the released bound_3d.py. A torus is periodic integration
over relative momentum, not a finite apparatus limiting the COM momentum.
"""
import argparse
from pathlib import Path
import sys
import numpy as np
HERE = Path(__file__).resolve().parent
if not (HERE / 'bound_3d.py').exists():
sys.path.insert(0, str(HERE.parent / 'shell-clocks'))
from bound_3d import (Torus, rest_calibration, IDENTITY, BETA_PAIR, TENSORS,
mode, extract_curvature, BASIS, X, Y, Z)
CONTACTS = {'density': IDENTITY, 'mass': BETA_PAIR}
P_ODD = (IDENTITY-BETA_PAIR)/2
def hermitian(a):
return (a + a.conj().T)/2
def design(torus, spacing=.004):
"""Fit the ordered equal-rest pole. J[j], m[j], even[j] describe three axes.
J is the odd bond matrix; m is the even scalar in the common repair.
even is the even-only scalar calibrated on density. Matrices use the
six-component orthonormal coincidence basis exported by bound_3d.py.
"""
cal = rest_calibration(torus)
green0, lam, u, green_e = cal
inv0 = np.linalg.inv(green0)
weight = lam**2 / (-green_e)
assert np.min(np.abs(np.linalg.eigvalsh(green0))) > 1e-4
first, second, base = [], [], []
for j in range(3):
data = []
for h in (spacing, spacing/2):
gp = torus.green(torus.rest, j, h)
pp = np.linalg.inv(gp)
pm = BETA_PAIR @ pp @ BETA_PAIR
data.append(((pp-pm) @ u/(2*h),
np.vdot(u, (pp+pm-2*inv0)@u).real/h**2,
extract_curvature(torus.rest, h, gp, cal)))
v, crv, before = [(4*b-a)/3 for a,b in zip(*data)]
assert np.linalg.norm(v-P_ODD@v) < 1e-10
v = P_ODD@v
J = np.outer(v, u.conj()) + np.outer(u, v.conj())
assert np.linalg.norm(J@u-v) < 1e-12
first.append(J)
second.append((crv+1/(torus.rest*weight))/2)
base.append(before)
base = np.array(base)
even = (1-base[:,0])/(2*torus.rest*weight)
return dict(cal=cal, J=np.array(first), m=np.array(second), even=even,
base=base, weight=weight, rest=torus.rest)
def symbol(d, k, variant='common'):
"""Added Hermitian coincidence-space potential at the given 3-vector k."""
k = np.asarray(k)
if variant == 'bare':
return np.zeros_like(IDENTITY)
if variant not in ('even','common','range2'):
raise ValueError(variant)
factors = 4*np.sin(k/2)**2
if variant == 'even':
return (factors@d['even'])*IDENTITY
scalar = factors@d['m']
if variant == 'range2':
scalar += factors@d['quartic']@factors
return scalar*IDENTITY + np.tensordot(np.sin(k), d['J'], axes=1)
def vertex(d, k_final, k_initial, variant='common'):
"""Endpoint energy density of the added bond, SOLELY on coincidence."""
return (symbol(d,k_final,variant)+symbol(d,k_initial,variant))/2
class Fiber:
"""Precompute free signed energies at fixed total momentum, including oblique k."""
def __init__(self, torus, k):
n = torus.size
k = np.asarray(k, dtype=float)
self.n = n
grid = [p*(2*np.pi/n) for p in torus.grid]
shape = (n,n,n)
a, self.ua = mode([p+s/2 for p,s in zip(grid,k)], shape)
b, self.ub = mode([-p+s/2 for p,s in zip(grid,k)], shape)
self.e = [a+b, a-b, -a+b, -a-b]
def green(self,z,derivative=False):
den = [z-e for e in self.e]
assert min(np.min(np.abs(a)) for a in den) > .01
pp,pm,mp,mm = [(-.25/a**2 if derivative else .25/a) for a in den]
moments = np.empty((5,5))
moments[0,0] = (pp+pm+mp+mm).sum()
moments[1:,0] = (pp+pm-mp-mm) @ self.ua
moments[0,1:] = (pp-pm+mp-mm) @ self.ub
moments[1:,1:] = self.ua.T @ ((pp-pm-mp+mm)[:,None]*self.ub)
return hermitian(np.tensordot(moments.ravel()/self.n**3,TENSORS,axes=1))
def pole(fiber,d,k,contact,variant='common',extra=0.):
"""Return pole energy, unit coincidence spinor, and normalized coincidence weight."""
_,lam,u0,_ = d['cal']
V = contact/lam + symbol(d,k,variant) + extra*IDENTITY
energy = np.hypot(d['rest'], np.linalg.norm(k))
for _ in range(9):
inv = np.linalg.inv(fiber.green(energy))
vals,vecs = np.linalg.eigh(hermitian(inv-V))
target = np.argmax(abs(vecs.conj().T@u0)**2)
u = vecs[:,target]
assert abs(np.vdot(u0,u)) > .95
source = inv@u
slope = -np.vdot(source,fiber.green(energy,derivative=True)@source).real
assert slope>0
if abs(vals[target]) < 2e-13:
return energy,u,1/slope
energy -= vals[target]/slope
raise ArithmeticError('bound-state pole did not converge')
def quartic_design(torus,d):
"""Fit six quartic coefficients on density; a symmetric matrix includes cross terms twice."""
u0=d['cal'][2]
inv_lam=1/d['cal'][1]
result=np.zeros((3,3))
for axes in [(0,),(1,),(2,),(0,1),(0,2),(1,2)]:
direction=np.sum(np.eye(3)[list(axes)],axis=0)
data=[]
for h in (.008,.016,.032):
k=h*direction
q=4*np.sin(h/2)**2
target=np.hypot(d['rest'],np.linalg.norm(k))
inv=np.linalg.inv(Fiber(torus,k).green(target))
vals,vecs=np.linalg.eigh(hermitian(inv-inv_lam*IDENTITY-symbol(d,k)))
j=np.argmax(abs(vecs.conj().T@u0)**2)
assert abs(np.vdot(u0,vecs[:,j]))>.97
data.append((q,vals[j]/q))
(x,a),(y,b),(z,c)=data
left=(b-a)/(y-x)
right=(c-b)/(z-y)
coefficient=left-(right-left)*(x+y)/(z-x)
i,j=axes[0],axes[-1]
if i==j:
result[i,i]=coefficient
else:
result[i,j]=result[j,i]=(coefficient-result[i,i]-result[j,j])/2
return result
def readout(torus,d,khat,k,variant,extra=0.,delta=.00004):
"""Finite-k forward clock flux E dE/dK / K and odd-coincidence probability."""
ks = np.array([k-delta,k,k+delta])
energies=[]; odd=[]
for ki in ks:
vec = ki*khat
fiber = Fiber(torus,vec)
row=[]
for contact in CONTACTS.values():
energy,u,w = pole(fiber,d,vec,contact,variant,extra)
row.append(energy)
if ki == k:
odd.append(w*np.linalg.norm(P_ODD@u)**2)
energies.append(row)
energies=np.array(energies)
flux=energies[1]*(energies[2]-energies[0])/(2*delta*k)
return energies[1], flux, np.array(odd)
def symmetry_check(d):
k=np.array([.037,-.021,.052])
end=np.array([.023,.014,-.011])
M=d['m']
# Rebuild the nearest-neighbor bond from its actual matrix elements.
onsite=2*sum(M)*IDENTITY
def from_bonds(momentum):
value=onsite.astype(complex)
for j in range(3):
plus=-M[j]*IDENTITY+d['J'][j]/(2j)
t=plus*np.exp(1j*momentum[j])
value += t+t.conj().T
return value
assert np.max(abs((from_bonds(k)+from_bonds(end))/2-vertex(d,k,end)))<2e-14
for j,sigma in enumerate((X,Y,Z)):
flip=np.kron(Z,sigma)
r=BASIS.T@np.kron(flip,flip)@BASIS
reflected=k.copy()
reflected[j]*=-1
assert np.max(abs(r@symbol(d,k)@r.conj().T-symbol(d,reflected)))<2e-11
def run(n, fine=False):
torus=Torus(n)
d=design(torus)
z=d['rest']
weight=d['weight']
symmetry_check(d)
u=d['cal'][2]
print(f'mesh {n}, z={z}, contact probability {weight:.10f}')
print('axis Rbare(density,mass) even-density m-common norm(Ju)')
for j,axis in enumerate('xyz'):
print(axis, *(f'{x:.9f}' for x in (*d['base'][j],d['even'][j],d['m'][j],
np.linalg.norm(d['J'][j]@u))))
assert np.allclose(vertex(d,[.1,0,0],[-.1,0,0]),4*np.sin(.05)**2*d['m'][0]*IDENTITY)
k=.07
assert np.max(abs(Fiber(torus,[0,0,k]).green(z)-torus.green(z,2,k)))<1e-12
even_rest=d['base'] + 2*z*weight*d['even'][:,None]
assert np.allclose(even_rest[:,0],1)
d['quartic']=quartic_design(torus,d)
print('range-two c_ii, then cross coefficients c_xy,c_xz,c_yz')
print(*(f'{x:.7f}' for x in (*d['quartic'].diagonal(), *(2*d['quartic'][i,j]
for i,j in [(0,1),(0,2),(1,2)]))))
results={}
for axis,unit,values in [('z',np.array([0.,0.,1.]),(.025,.05,.10)),
('xyz',np.ones(3)/np.sqrt(3),(.04,.08))]:
for kt in values:
variants=('bare','even','common','range2') if axis=='z' and kt==.05 else ('common','range2')
for variant in variants:
e,f,odd=readout(torus,d,unit,kt,variant)
results[axis,kt,variant]=(e,f,odd)
print(f'{axis} k={kt:.3f} {variant}: E={e[0]:.12f},{e[1]:.12f}'
f' E*v/k={f[0]:.9f},{f[1]:.9f}'
f' P(odd contact)={odd[0]:.5e},{odd[1]:.5e}')
a,b=[results['z',k,'common'] for k in (.025,.05)]
print('doubling .025 to .05: odd contact factors',b[2]/a[2],
' energy-split factor',np.diff(b[0])[0]/np.diff(a[0])[0])
assert np.all((b[2]/a[2] > 45) & (b[2]/a[2] < 85))
corrected=results['xyz',.08,'range2'][1]
assert np.max(abs(corrected-1)) < .008
assert np.max(abs(corrected-1)) < .2*np.max(abs(results['xyz',.08,'common'][1]-1))
if fine:
# Independent three-point difference of direct pole energies for the
# curvature rather than differentiating the inverse kernel.
for j in range(3):
direct=[]
unit=np.eye(3)[j]
for k in (.008,.004):
vec=k*unit
fiber=Fiber(torus,vec)
energies=np.array([pole(fiber,d,vec,c)[0] for c in CONTACTS.values()])
direct.append(2*z*(energies-z)/k**2)
result=(4*direct[1]-direct[0])/3
print('direct common R', 'xyz'[j], result)
assert np.max(abs(result-1))<5e-6
return d,results
if __name__ == '__main__':
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--size',type=int,default=32)
parser.add_argument('--fine',action='store_true',help='direct curvature checks on all axes')
args=parser.parse_args()
run(args.size,args.fine)
fall_measurement.py
"""Replay the three-order rubidium free-fall fit from Figure 3 of Asenbaum et al."""
import argparse
import hashlib
import io
import math
from pathlib import Path
import statistics
import tarfile
SOURCE_URL = "https://arxiv.org/src/2005.11624v2"
SOURCE_SHA = "e61b7ef455e146bc7139f4e5e226977514f6358b14b623e0678498b8301171a6"
FIGURE = "epdatafigunblindedv3.pdf"
FIGURE_SHA = "c37ba618dfb9d6366bfad017f381ffc157e44437e7ef8142d0401e6b7b621ca9"
# order n, initial beam direction (-1 down, +1 up), count,
# sum of phase differences in microradians, sum of squares in microradians squared
MOMENTS = (
(4, -1, 244, -2702784, 75960537736),
(4, 1, 243, 828487, 50654447667),
(8, -1, 244, -2332247, 77695001229),
(8, 1, 260, 1109761, 69168401729),
(12, -1, 245, -1067877, 154257480273),
(12, 1, 245, 1037667, 86715548019),
)
K = 2 * math.pi / 780e-9
T = 0.955
G = 9.81
MODEL = 0.05251
def recovered_moments(archive_path):
"""Audit the six integer rows from the pinned arXiv source, using PyMuPDF 1.26.5."""
import pymupdf
source = archive_path.read_bytes()
if hashlib.sha256(source).hexdigest() != SOURCE_SHA:
raise ValueError("Unexpected arXiv source checksum")
with tarfile.open(fileobj=io.BytesIO(source), mode="r:*") as archive:
members = [m for m in archive if Path(m.name).name == FIGURE and m.isfile()]
if len(members) != 1:
raise ValueError("Expected one Figure 3 vector graphic")
figure = archive.extractfile(members[0]).read()
if hashlib.sha256(figure).hexdigest() != FIGURE_SHA:
raise ValueError("Unexpected Figure 3 checksum")
colors = {(1.0, 0.0, 0.0): 4, (0.0, 0.0, 0.0): 8, (0.0, 0.0, 1.0): 12}
groups = {(order, direction): [] for order in (4, 8, 12) for direction in (-1, 1)}
with pymupdf.open(stream=figure, filetype="pdf") as document:
drawings = document[0].get_drawings()
zero = drawings[1575]["rect"].y0
points_per_rad = (drawings[1578]["rect"].y0 - drawings[1593]["rect"].y0) / 0.1
for marker in drawings[94:1575]:
if marker["type"] not in ("f", "s"):
raise ValueError("Unexpected marker type")
hollow = marker["type"] == "s"
order = colors[marker["color"] if hollow else marker["fill"]]
rightmost = marker["items"][0][1]
assert abs(rightmost.x - marker["rect"].x1) < 0.002
micro_rad = round((zero - rightmost.y) / points_per_rad * 1e6)
groups[order, -1 if hollow else 1].append(micro_rad)
return tuple((n, d, len(v), sum(v), sum(i*i for i in v))
for (n, d), v in sorted(groups.items()))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--from-figure", type=Path, metavar="ARXIV_SOURCE_TAR",
help=f"audit the group summaries against the archive at {SOURCE_URL}")
args = parser.parse_args()
if args.from_figure:
assert recovered_moments(args.from_figure) == MOMENTS
print("All 1,481 vector markers reproduce the six stored moment rows.")
samples = {}
for order, direction, count, phase_sum, square_sum in MOMENTS:
mean = phase_sum / count * 1e-6
var_mean = (square_sum - phase_sum**2 / count) / ((count-1)*count) * 1e-12
samples[order, direction] = (mean, var_mean)
assert sum(row[2] for row in MOMENTS) == 1481
means, weights = {}, {}
for order in (4, 8, 12):
down, up = samples[order, -1], samples[order, 1]
means[order] = (down[0] + up[0]) / 2
weights[order] = 4 / (down[1] + up[1])
print(f"order {order:2}: {means[order]*1000:+.4f} +/- "
f"{1000/math.sqrt(weights[order]):.4f} mrad")
total_weight = sum(weights.values())
xbar = sum(n*w for n, w in weights.items()) / total_weight
ybar = sum(means[n]*w for n, w in weights.items()) / total_weight
sxx = sum(w*(n-xbar)**2 for n, w in weights.items())
slope = sum(w*(n-xbar)*(means[n]-ybar) for n, w in weights.items()) / sxx
intercept = ybar - slope*xbar
chi_sq = sum(w*(means[n]-intercept-slope*n)**2 for n, w in weights.items())
middle_prediction = (means[4] + means[12]) / 2
prediction_variance = (1/weights[4] + 1/weights[12]) / 4
holdout = (means[8]-middle_prediction) / math.sqrt(1/weights[8]+prediction_variance)
scale = 1e12 / (K*G*T**2)
raw, stat = slope*scale, scale/math.sqrt(sxx)
correction = 1.5-5.9
systematic = 3.4
corrected = raw + correction
joint_sigma = math.hypot(stat, systematic)
radius = statistics.NormalDist().inv_cdf(0.975)*joint_sigma
lo, hi = ((corrected+x)*1e-12/MODEL for x in (-radius, radius))
print(f"free intercept {intercept*1000:+.4f} mrad; chi^2(1)={chi_sq:.4f}")
print(f"endpoint prediction for order 8: {middle_prediction*1000:+.4f} +/- "
f"{1000*math.sqrt(prediction_variance):.4f} mrad; discrepancy {holdout:+.3f} sigma")
print(f"eta before correction: ({raw:.4f} +/- {stat:.4f} stat) e-12")
print(f"eta after correction: ({corrected:.4f} +/- {stat:.4f} stat "
f"+/- {systematic:.1f} syst) e-12")
print(f"conditional 95% fD interval: [{lo:.4e}, {hi:.4e}]")
print(f"ideal four-recoil phase-alias spacing: {2*math.pi/(4*K*G*T**2):.4e}")
print(f"trajectory illustration for a full model contrast: "
f"{0.5*MODEL*G*(2*T)**2:.3f} m")
assert abs(raw-6.1174) < 0.001 and abs(stat-1.9520) < 0.001
assert abs(chi_sq - holdout**2) < 1e-10
assert 1.70 < corrected < 1.73 and -1.15e-10 < lo < -1.12e-10 < hi < 1.81e-10
if __name__ == "__main__":
main()
binding_transfer.py
"""Can the same collision hopping coefficients predict inertia at a new binding energy?"""
from pathlib import Path
import argparse
import sys
import numpy as np
HERE=Path(__file__).resolve().parent
if not (HERE/'bound_3d.py').exists():
sys.path.insert(0,str(HERE.parent/'shell-clocks'))
from bound_3d import Torus, rest_calibration, IDENTITY, BETA_PAIR
from collision_transport import hermitian, Fiber
EVEN=[0,5]
ODD=np.flatnonzero(np.diag(BETA_PAIR)<0)
class RestPole:
def __init__(self,n,energy):
self.torus=Torus(n,energy)
self.energy=energy
green,lam,u,de=rest_calibration(self.torus)
self.inv=np.linalg.inv(green)
self.g=1/lam
self.weight=-lam**2/de
self.u=u if u[0].real>=0 else -u
self.first=[]
self.second=[]
for axis in range(3):
values=[]
for h in (.004,.002):
plus=np.linalg.inv(self.torus.green(energy,axis,h))
minus=BETA_PAIR@plus@BETA_PAIR
values.append(((plus-minus)@self.u/(2*h),
np.vdot(self.u,(plus+minus-2*self.inv)@self.u).real/h**2))
self.first.append((4*values[1][0]-values[0][0])/3)
self.second.append((4*values[1][1]-values[0][1])/3)
self.first=np.array(self.first)
self.second=np.array(self.second)
def curvature(self,J,M,axis,contact):
# The energy-dependent inverse kernel is a six-dimensional Schur complement.
P=hermitian(self.inv-self.g*contact)
field=self.first[axis]-J[axis]@self.u
assert np.linalg.norm(field[[0,5]])<2e-8
mixing=2*np.vdot(field[ODD],np.linalg.solve(P[np.ix_(ODD,ODD)],field[ODD])).real
bare=self.second[axis]-2*np.vdot(self.u,M[axis]@self.u).real
return -self.energy*self.weight*(bare-mixing)
def moving(self,J,M,axis,k,contact):
momentum=k*np.eye(3)[axis]
V=self.g*contact+np.sin(k)*J[axis]+4*np.sin(k/2)**2*M[axis]
fiber=Fiber(self.torus,momentum)
energy=np.hypot(self.energy,k)
for _ in range(8):
inv=np.linalg.inv(fiber.green(energy))
vals,v=np.linalg.eigh(hermitian(inv-V))
j=np.argmax(abs(v.conj().T@self.u))
if abs(vals[j])<4e-13:return energy
x=inv@v[:,j]
derivative=-np.vdot(x,fiber.green(energy,derivative=True)@x).real
energy-=vals[j]/derivative
raise ArithmeticError('moving pole failed to converge')
def coefficients(rows,cutoff=1e-12):
# A two-column even sector gives the general odd/even Hermitian hopping for
# these first derivatives. Only the even 2-by-2 block of M enters the curvature.
vectors=np.stack([r.u[EVEN] for r in rows]).real
quadratic=np.array([[a*a,2*a*b,b*b] for a,b in vectors])
J=np.zeros((3,6,6),complex)
M=np.zeros_like(J)
for axis in range(3):
targets=np.stack([r.first[axis][ODD] for r in rows])
oddmap=np.linalg.lstsq(vectors,targets,rcond=cutoff)[0].T
J[axis][np.ix_(ODD,EVEN)]=oddmap
J[axis]+=J[axis].conj().T.copy()
inputs=[(r.second[axis]+1/(r.energy*r.weight))/2 for r in rows]
m11,m12,m22=np.linalg.lstsq(quadratic,inputs,rcond=cutoff)[0]
M[axis][np.ix_(EVEN,EVEN)]=[[m11,m12],[m12,m22]]
return J,M
def single(row):
J=[]
M=[]
for axis,f in enumerate(row.first):
J.append(np.outer(f,row.u.conj())+np.outer(row.u,f.conj()))
m=(row.second[axis]+1/(row.energy*row.weight))/2
M.append(m*IDENTITY)
return np.array(J),np.array(M)
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--fine',action='store_true')
n=48 if parser.parse_args().fine else 32
train=(1.68,1.81,1.90)
held=(1.61,1.75,1.86,1.94)
data={e:RestPole(n,e) for e in (*train,*held)}
basic=single(data[1.90])
learned=coefficients([data[e] for e in train])
bounded=coefficients([data[e] for e in train],cutoff=1e-3)
print('training rest energies',train,'mesh',n)
print('truncated-fit operator norms J,M:',*[max(np.linalg.norm(m,2) for m in cols) for cols in bounded])
print('largest multi-energy operator norms J,M:',*[max(np.linalg.norm(m,2) for m in cols) for cols in learned])
# Restrict the full Hamiltonian at K=(0,pi,0) to two normalized onsite
# even-orbital trial states. This gives bounds independently of any pole fit.
for name,pair in [('three-energy',learned),('truncated',bounded)]:
M=pair[1][1][np.ix_(EVEN,EVEN)]
block=np.diag([20.,-20.])+data[1.90].g*np.eye(2)+4*M
limits=np.linalg.eigvalsh(block)
print(f'{name} variational trial energies at y zone face: {limits}',flush=True)
assert limits[0]<(-4900 if name=='three-energy' else -180)
if name=='truncated':assert limits[1]>180
for e in (*train,*held):
row=data[e]
results=[]
for J,M in (basic,learned,bounded):
values=np.array([[row.curvature(J,M,j,c) for c in (IDENTITY,BETA_PAIR)] for j in range(3)])
results.append(values)
print(f'E_rest={e:.3f}: one-calibration z {results[0][2]}, three-calibration z {results[1][2]}, '
f'max three-axis target error {np.max(abs(results[1]-1)):.7f}; truncated {np.max(abs(results[2]-1)):.7f}',flush=True)
if e in (1.75,1.94):
J,M=learned
for contact,expected in zip((IDENTITY,BETA_PAIR),results[1][2]):
ratios=[]
for k in (.006,.003):
energy=row.moving(J,M,2,k,contact)
ratios.append(2*e*(energy-e)/k**2)
direct=(4*ratios[1]-ratios[0])/3
assert abs(direct-expected)<1e-5,(direct,expected)
assert np.max(abs(np.array([data[1.90].curvature(*basic,j,IDENTITY) for j in range(3)])-1))<2e-8
if __name__=='__main__':
main()
rest_clock.py
"""Unprojected rest clock loop for a hopping bound pair. All relative momenta are retained."""
from pathlib import Path
import argparse
import sys
import numpy as np
HERE = Path(__file__).resolve().parent
for sibling in ('shell-clocks','pair-inertia'):
if not (HERE/'bound_3d.py').exists():
sys.path.insert(0,str(HERE.parent/sibling))
from bound_3d import Torus, rest_calibration, BASIS, BETA_PAIR, GAMMA, IDENTITY
from form_factor import block, wave
from collision_transport import design, vertex
def inner(f,g):
return np.vdot(f,g)/len(f)
def norm2(f):
return inner(f,f).real
def embed(x):
return (BASIS@x).reshape(4,4)
def local(f):
return BASIS.conj().T@f.mean(axis=0).reshape(16)
def free(ha,hb,f):
return ha@f+f@hb.swapaxes(-1,-2)
def derivative(p,axis):
x,y,z=p
sx,sy,sz=np.sin(x),np.sin(y),np.sin(z)
cx,cy,cz=np.cos(x),np.cos(y),np.cos(z)
zero=np.zeros_like(x+y+z)
db=((cx*cy*cz,zero,zero),(-sx*sy*cz,cy*cz,zero),
(-sx*cy*sz,-sy*sz,cz))[axis]
ts=[1-cx,1-cy,1-cz]
dm=np.sin(p[axis])*(4*ts[axis]/3+2*sum(v for j,v in enumerate(ts) if j!=axis))
c=np.stack(np.broadcast_arrays(*db,dm),axis=-1).reshape(-1,4)
return (c@np.array(GAMMA[1:]).reshape(4,16)).reshape(-1,4,4)
class RestClock:
def __init__(self,n,d,axis=2):
self.n,self.d,self.axis=n,d,axis
torus=Torus(n)
_,self.lam,u,ge=rest_calibration(torus)
self.energy=torus.rest
self.v=self.lam*u/np.sqrt(-ge)
self.source=embed(u/np.sqrt(-ge))
self.p=tuple(k*(2*np.pi/n) for k in torus.grid)
self.ha,e=block(self.p)
self.hb,f=block([-k for k in self.p])
self.psi=wave(self.source,self.energy,self.ha,e,self.hb,f)
np.testing.assert_allclose(local(self.psi),self.v,atol=2e-12)
assert abs(norm2(self.psi)-1)<2e-11
self.da=derivative(self.p,axis)/2
self.db=derivative([-v for v in self.p],axis)/2
def h(self,contact,f):
return free(self.ha,self.hb,f)+embed(contact@local(f)/self.lam)
def leak(self,contact,repaired=True):
# The free-free commutator is identically zero at rest.
direct=free(self.da,self.db,self.source)
hit=embed(contact@local(free(self.da,self.db,self.psi))/self.lam)
if not repaired:
return direct+hit
j=self.d['J'][self.axis]@self.v/2
return direct+hit+free(self.ha,self.hb,embed(j))+embed(contact@j/self.lam+self.energy*j)
def finite(self,q,contact,repaired=True,W=None):
# Split the full product into hopping-contact, contact-hopping, and contact-contact.
# Integrating each first-leg hopping over its receiving momentum gives the same
# anticommutator that acts on a constant spinor on the return leg.
sums=[]
for sign in (1,-1):
step=sign*q
vec=np.eye(3)[self.axis]*step
ha,_=block([k+s for k,s in zip(self.p,vec)])
hb,_=block([-k+s for k,s in zip(self.p,vec)])
a,b=(self.ha+ha)/2,(self.hb+hb)/2
V=contact/self.lam
if repaired:V=V+vertex(self.d,vec,np.zeros(3))
if W is not None:V=V+1j*np.sin(step)*W
kick=V@self.v
local_first=local(free(a,b,self.psi))+kick
sums.append(free(a,b,embed(kick))+embed(V.conj().T@local_first))
return (sums[0]-sums[1])/(2*q)
def floor(self):
# The functions d(b_j)/dk_i have zero mean, are orthogonal, and their
# squared torus norms are rational numbers (one per independent sine/cosine).
weights=((1/8,0,0),(1/8,1/4,0),(1/8,1/4,1/2))[self.axis]
moments=[]
for alpha in GAMMA[1:4]:
f=(alpha@self.source+self.source@alpha.T)/2
moments.append(np.vdot(f,f).real)
return np.dot(weights,moments)
def odd_fluctuation(self,f):
beta=GAMMA[-1]
odd=(f-beta@f@beta.T)/2
return odd-odd.mean(axis=0)
def fit_polarization(clock):
# W v spans the four odd contact spinors. H−E maps them to the leading
# change in the microscopic clock loop while leaving the flat energy fixed.
odd=np.eye(6,dtype=complex)[:,np.diag(BETA_PAIR)<0]
gram=np.zeros((4,4),complex)
rhs=np.zeros(4,complex)
for c in (IDENTITY,BETA_PAIR):
columns=[]
for j in odd.T:
field=embed(j)
columns.append(1j*(free(clock.ha,clock.hb,field)+embed(c@j/clock.lam-clock.energy*j)))
b=clock.leak(c)
gram+=np.array([[inner(u,v) for v in columns] for u in columns])
rhs+=np.array([inner(u,b) for u in columns])
w=-odd@np.linalg.solve(gram,rhs)
W=(np.outer(w,clock.v.conj())+np.outer(clock.v,w.conj()))/np.vdot(clock.v,clock.v)
np.testing.assert_allclose(W@clock.v,w,atol=1e-12)
np.testing.assert_allclose(BETA_PAIR@W@BETA_PAIR,-W,atol=1e-12)
return W
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--fine',action='store_true')
args=parser.parse_args()
train_size=24
fit=design(Torus(train_size))
train=RestClock(train_size,fit)
W=fit_polarization(train)
n=48 if args.fine else 32
clock=RestClock(n,fit)
for label,c in [('density',IDENTITY),('mass',BETA_PAIR)]:
initial=clock.leak(c,False)
repaired=clock.leak(c)
w=W@clock.v
added=1j*(free(clock.ha,clock.hb,embed(w))+embed(c@w/clock.lam-clock.energy*w))
lowered=repaired+added
floor=clock.floor()
for f in (initial,repaired,lowered):
assert abs(inner(clock.psi,f))<2e-10
assert abs(norm2(clock.odd_fluctuation(f))-floor)<2e-10
print(f'{label} mesh {n}: initial={norm2(initial):.9f} repaired={norm2(repaired):.9f} '
f'common polarization={norm2(lowered):.9f} protected contribution={floor:.9f}',flush=True)
for do_repair,pol,target in ((False,None,initial),(True,None,repaired),(True,W,lowered)):
coarse=clock.finite(.10,c,do_repair,pol)
fine=clock.finite(.05,c,do_repair,pol)
err=np.sqrt(norm2(fine-target))
assert err < .27*np.sqrt(norm2(coarse-target))
assert np.sqrt(norm2((4*fine-coarse)/3-target))<1e-4
print(f' endpoint finite-q checks converged; norm of W={np.linalg.norm(W,2):.7f}',flush=True)
if __name__=='__main__':
main()
extended_clock.py
"""Finite-range two-particle energy polarizations and the unrestricted common-fit floor."""
import argparse
from itertools import product
import numpy as np
from rest_clock import (RestClock, norm2, embed, local, free, design, Torus,
GAMMA, BASIS, IDENTITY, BETA_PAIR)
CONTACTS = (IDENTITY,BETA_PAIR)
BETA = GAMMA[-1]
PARITY = np.real(np.diag(BETA)).astype(int)
ODD = np.eye(6)[:,np.diag(BETA_PAIR)<0]
FFT_AXES = (0,1,2)
def inverse_free(clock,f):
"""Inverse of H_free-E over all four energy-sign channels."""
ha,hb=clock.ha,clock.hb
ea=np.sqrt(np.einsum('nij,nji->n',ha,ha).real/4)
eb=np.sqrt(np.einsum('nij,nji->n',hb,hb).real/4)
identity=np.eye(4)
out=np.zeros_like(clock.psi)
for s in (-1,1):
left=(identity+s*ha/ea[:,None,None])/2
for t in (-1,1):
right=(identity+t*hb/eb[:,None,None])/2
gap=s*ea+t*eb-clock.energy
out+=(left@f@right.swapaxes(-1,-2))/gap[:,None,None]
return out
def unrestricted(clock,leaks):
"""Least loss over every common odd cloud, independent of finite cluster fitting."""
avg=(leaks[0]+leaks[1])/2
diff=(leaks[0]-leaks[1])/2
np.testing.assert_allclose(diff,np.broadcast_to(embed(local(diff)),diff.shape),atol=2e-11)
u=inverse_free(clock,avg)
np.testing.assert_allclose(free(clock.ha,clock.hb,u)-clock.energy*u,avg,atol=3e-12)
g=1/clock.lam
d=ODD.T@(local(diff)-g*local(u))
rows=np.array([inverse_free(clock,embed(col)).ravel() for col in ODD.T])
gram=g*g*(rows.conj()@rows.T)/len(u)
y=np.linalg.solve(np.eye(len(d))+gram,d)
f=inverse_free(clock,-avg-g*(y@rows).reshape(u.shape))
residuals=np.array([norm2(l+clock.h(c,f)-clock.energy*f) for l,c in zip(leaks,CONTACTS)])
floor=np.vdot(d,y).real
assert abs(np.mean(residuals)-floor)<3e-10
return np.linalg.norm(d),floor,residuals
def analytic_repair(clock):
"""Jv for the exact rest derivative, independent of finite differences of the pole."""
dpsi=free(clock.da,clock.db,clock.psi)
rdpsi=-inverse_free(clock,dpsi)
columns=[local(-inverse_free(clock,embed(e))) for e in np.eye(6)]
green=np.column_stack(columns)
return -np.linalg.solve(green,local(rdpsi))
def exact_cloud(clock):
h=clock
du=free(h.da,h.db,h.source)
j=embed(analytic_repair(h)/2)
s=du+free(h.ha,h.hb,j)+h.energy*j
f=-inverse_free(h,s)
dpsi=free(h.da,h.db,h.psi)
anti=embed((local(dpsi)+local(np.broadcast_to(j,dpsi.shape)))/h.lam)
errors=[]
for sign,contact in zip((1,-1),CONTACTS):
errors.append(norm2(s+sign*anti+h.h(contact,f)-h.energy*f))
assert max(errors)<2e-24
return f,errors
def real_field(f,n):
return np.fft.ifftn(f.reshape(n,n,n,4,4),axes=FFT_AXES)
def sample_real(field,offset):
return field[tuple(v%field.shape[0] for v in offset)]
def positions(radius):
return [p for p in product(range(-radius,radius+1),repeat=3) if sum(map(abs,p))<=radius]
def basis_clouds(radius):
zero=(0,0,0)
basis=[{zero:embed(col).copy()} for col in ODD.T]
for r in positions(radius):
if r<=zero:
continue
neg=tuple(-i for i in r)
for i in range(4):
for j in range(i,4):
z=np.zeros((4,4),dtype=complex)
z[i,j]=1
z[j,i]=PARITY[i]*PARITY[j]
z/=np.sqrt(2*np.vdot(z,z).real)
basis.append({r:z,neg:-z.T})
return basis
def stencils(clock):
# Both single-particle Bloch symbols have no Fourier components beyond Manhattan 3.
a,b=(real_field(h,clock.n) for h in (clock.ha,clock.hb))
shifts={}
for r in positions(3):
av,bv=sample_real(a,r),sample_real(b,r)
if max(np.max(abs(av)),np.max(abs(bv)))>2e-12:
shifts[r]=(av,bv)
for arr in (a,b):
tail=arr.copy()
for r in shifts:
tail[r]=0.
assert np.max(abs(tail))<2e-12
return shifts
def fit_cloud(clock,leaks,radius,u):
"""Fit one normalized finite-range F to both contacts, retaining all sixteen components."""
overlap=np.vdot(u,clock.v)
avg=real_field((leaks[0]+leaks[1])/2,clock.n)
diff_at_zero=(leaks[0]-leaks[1]).mean(axis=0)/2
shifts=stencils(clock)
basis=basis_clouds(radius)
outputs=sorted({tuple(a+b for a,b in zip(r,s))
for r in positions(radius) for s in shifts})
ix={r:i for i,r in enumerate(outputs)}
zero=(0,0,0)
mat=np.zeros((len(outputs)+1,16,len(basis)),complex)
for j,b in enumerate(basis):
for r,z in b.items():
mat[ix[r],:,j]-=(clock.energy*z).ravel()
if r==zero:
mat[-1,:,j]+=(z/clock.lam).ravel()
for s,(av,bv) in shifts.items():
dest=tuple(a+d for a,d in zip(r,s))
mat[ix[dest],:,j]+=(av@z+z@bv.T).ravel()
target=np.array([sample_real(avg,r) for r in outputs]+[diff_at_zero]).ravel()
mat=overlap*mat.reshape(-1,len(basis))
coeff,_,rank,_=np.linalg.lstsq(mat,-target,rcond=2e-13)
assert rank==len(coeff)
f={}
for a,b in zip(coeff,basis):
for r,z in b.items():
f[r]=f.get(r,0)+a*z
return f,len(coeff)
def evaluate(clock,leaks,f,u):
n=clock.n
real=np.zeros((n,n,n,4,4),complex)
for r,z in f.items():
real[r]=z
momentum=np.fft.fftn(real,axes=FFT_AXES).reshape(-1,4,4)
for r,z in f.items():
other=f[tuple(-x for x in r)]
np.testing.assert_allclose(other,-z.T,atol=1e-12)
np.testing.assert_allclose(other,-BETA@z@BETA,atol=1e-12)
assert abs(np.vdot(momentum,clock.psi)/len(momentum))<1e-11
hit=np.vdot(u,clock.v)*momentum
return np.array([norm2(l+clock.h(c,hit)-clock.energy*hit) for l,c in zip(leaks,CONTACTS)])
def check_two_fiber_vertex(f,u):
"""Check Hermiticity and zero total energy for an endpoint-anchored local two-body vertex."""
offsets=list(f)
seed=np.zeros((len(offsets),4,4),complex)
seed[offsets.index((0,0,0))]=embed(u)
seed=seed.ravel()
def moved_cloud(k):
return np.array([z*np.cos(k*r[2]/2) for r,z in f.items()]).ravel()
def change(ko,ki,state):
outgoing=moved_cloud(ko)
incoming=moved_cloud(ki)
return np.sin(ko-ki)*(outgoing*np.vdot(seed,state)-seed*np.vdot(incoming,state))
ki,ko=-0.43,0.27
incoming=seed+0.38j*moved_cloud(ki)
outgoing=0.19j*seed+moved_cloud(ko)
forward=np.vdot(outgoing,change(ko,ki,incoming))
backward=np.vdot(incoming,change(ki,ko,outgoing))
assert abs(forward)>1e-5
assert abs(forward-backward.conjugate())<2e-12
assert not np.any(change(ki,ki,incoming))
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument("--fine",action="store_true",help="train at 36 cubed and test at 56 cubed")
args=parser.parse_args()
train,test=(36,56) if args.fine else (24,40)
d=design(Torus(train))
r=RestClock(train,d)
u=r.v/np.linalg.norm(r.v)
ref=[r.leak(c) for c in CONTACTS]
common,errors=exact_cloud(r)
print(f"ideal J at training mesh: exact unrestricted residual norm squared {max(errors):.3g}")
print("training frozen finite-difference repair compatibility and unrestricted mean-square floor",unrestricted(r,ref)[:2])
spectra=[]
for radius in (0,1,2,3):
f,num=fit_cloud(r,ref,radius,u)
check_two_fiber_vertex(f,u)
train_res=evaluate(r,ref,f,u)
spectra.append((radius,f,num,train_res))
del r,ref,common
r=RestClock(test,d)
ref=[r.leak(c) for c in CONTACTS]
raw=np.array([norm2(a) for a in ref])
print(f"untouched test mesh {test}^3 baseline: density={raw[0]:.10g} mass={raw[1]:.10g}")
for radius,f,num,train_res in spectra:
held=evaluate(r,ref,f,u)
print(f"R={radius} complex cloud amplitudes={num}: training {train_res[0]:.9g}, {train_res[1]:.9g};"
f" held-out {held[0]:.9g}, {held[1]:.9g}")
if radius==0:
floor=held
assert np.all(held<floor/2)
_,errors=exact_cloud(r)
print(f"independent ideal derivative mesh {test}: exact unrestricted squared residual {max(errors):.3g}")
print("frozen repair on held-out mesh: incompatibility and unrestricted mean-square floor",unrestricted(r,ref)[:2])
if __name__=="__main__":
main()
common_band.py
"""Inverse construction of a band shared by two microscopic contacts."""
from pathlib import Path
import argparse
import sys
import numpy as np
from numpy.polynomial import chebyshev as cheb
HERE=Path(__file__).resolve().parent
for sibling in ('shell-clocks','pair-inertia'):
if not (HERE/'bound_3d.py').exists():
sys.path.insert(0,str(HERE.parent/sibling))
from bound_3d import Torus, rest_calibration, IDENTITY, BETA_PAIR, BASIS
from collision_transport import Fiber, hermitian
from form_factor import block, wave
def local_matrix(y,u):
# Minimal Hermitian extension with prescribed action on the even rest spinor.
b=np.outer(y,u.conj())
return b+b.conj().T-np.vdot(u,y).real*np.outer(u,u.conj())
class Designer:
def __init__(self,n):
self.torus=Torus(n)
_,lam,self.u,_=rest_calibration(self.torus)
self.g=1/lam
def exact(self,k):
k=np.asarray(k)
energy=np.hypot(self.torus.rest,np.linalg.norm(k))
fiber=Fiber(self.torus,k)
green=fiber.green(energy)
source=np.linalg.solve(green,self.u)
y=source-self.g*self.u
V=local_matrix(y,self.u)
for c in (IDENTITY,BETA_PAIR):
assert np.linalg.norm(green@((V+self.g*c)@self.u)-self.u)<2e-13
return V
class AxialStencil:
def __init__(self,model,degree,kmax=.13):
self.xmax=4*np.sin(kmax/2)**2
t=np.cos(np.pi*(np.arange(degree)+.5)/degree)
x=self.xmax*(t+1)/2
k=2*np.arcsin(np.sqrt(x)/2)
even=[]
odd=[]
for z,s in zip(k,x):
V=model.exact([0.,0.,z])
P=BETA_PAIR@V@BETA_PAIR
even.append(((V+P)/(2*s)).ravel())
odd.append(((V-P)/(2*np.sin(z))).ravel())
self.even=cheb.chebfit(t,even,degree-1)
self.odd=cheb.chebfit(t,odd,degree-1)
def at(self,k):
x=4*np.sin(k/2)**2
t=2*x/self.xmax-1
return (x*cheb.chebval(t,self.even)+np.sin(k)*cheb.chebval(t,self.odd)).reshape(6,6)
def measure(model,vec,V,c):
fiber=Fiber(model.torus,np.asarray(vec))
z=np.hypot(model.torus.rest,np.linalg.norm(vec))
for _ in range(10):
inv=np.linalg.inv(fiber.green(z))
vals,vecs=np.linalg.eigh(hermitian(inv-model.g*c-V))
j=np.argmax(abs(vecs.conj().T@model.u))
u=vecs[:,j]
delta=vals[j]
if abs(delta)<3e-13:
return z,np.linalg.norm((IDENTITY-BETA_PAIR)@u)/2
source=inv@u
derivative=-np.vdot(source,fiber.green(z,derivative=True)@source).real
z-=delta/derivative
raise ArithmeticError('moving pole failed to converge')
def record(model,k):
fiber=Fiber(model.torus,k)
z=np.hypot(model.torus.rest,np.linalg.norm(k))
G=fiber.green(z)
src=np.linalg.solve(G,model.u)
scale=np.sqrt(-np.vdot(src,fiber.green(z,True)@src).real)
source=(BASIS@(src/scale)).reshape(4,4)
p=[v*(2*np.pi/model.torus.size) for v in model.torus.grid]
def fields(offset):
a,e=block([v+o+d/2 for v,o,d in zip(p,offset,k)])
b,f=block([-v-o+d/2 for v,o,d in zip(p,offset,k)])
return a,b,e,f
def state(offset):
a,b,e,f=fields(offset)
return wave(source,z,a,e,b,f)
b=state(np.zeros(3))
assert abs(np.vdot(b,b).real/len(b)-1)<2e-12
np.testing.assert_allclose(BASIS.T@b.mean(axis=0).ravel(),model.u/scale,atol=2e-12)
return z,model.u/scale,state,fields
def pulse_test(model,ki,kf):
# Endpoint vertex acting on the actual normalized shared pole in all 16 spins.
ki,kf=np.asarray(ki),np.asarray(kf)
q=kf-ki
_,cv,initial,_=record(model,ki)
target=record(model,kf)[2](np.zeros(3))
p=[v*(2*np.pi/model.torus.size) for v in model.torus.grid]
def hs(sign,shift):
return block([sign*v+d for v,d in zip(p,shift)])[0]
a=(hs(1,kf/2)+hs(1,(ki-q)/2))/2
b=(hs(-1,kf/2)+hs(-1,(ki-q)/2))/2
kinetic=a@initial(-q/2)+initial(q/2)@b.swapaxes(-1,-2)
mid=(model.exact(ki)+model.exact(kf))/2
raw=[]
for c in (IDENTITY,BETA_PAIR):
phi=kinetic+(BASIS@((model.g*c+mid)@cv)).reshape(4,4)
raw.append(phi)
assert np.max(abs(raw[0]-raw[1]))<3e-13
f=np.vdot(target,raw[0])/len(target)
rejected=raw[0]-f*target
loss=np.vdot(rejected,rejected).real/len(rejected)
wanted=np.hypot(model.torus.rest,np.linalg.norm((ki+kf)/2))
ans=raw[1]-rejected+(wanted-f)*target
assert np.max(abs(ans-wanted*target))<2e-13
return f,loss
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--fine',action='store_true')
n=48 if parser.parse_args().fine else 32
model=Designer(n)
for k in ([0.,0.,.115],[.039,-.042,.051]):
v=model.exact(k)
masses=[measure(model,k,v,c) for c in (IDENTITY,BETA_PAIR)]
wanted=np.hypot(model.torus.rest,np.linalg.norm(k))
assert max(abs(z-wanted)+o for z,o in masses)<1e-10
for degree in (1,2,3,4):
stencil=AxialStencil(model,degree)
errors=[];odds=[]
for z in (.018,.053,.086,.117,.13):
k=[0.,0.,z]
e=np.hypot(model.torus.rest,z)
for c in (IDENTITY,BETA_PAIR):
obs,odd=measure(model,k,stencil.at(z),c)
errors.append(abs(obs-e));odds.append(odd)
print(f'range {degree} axial cells: max held-out energy error {max(errors):.8g}; '
f'max odd coincidence amplitude {max(odds):.8g}',flush=True)
if degree==4:assert max(errors)<2e-6 and max(odds)<1e-5
k=np.array([.008,-.011,.036]);q=np.array([.012,.013,.047])
f,loss=pulse_test(model,k,k+q)
reverse,_=pulse_test(model,k+q,k)
assert abs(f-reverse.conjugate())<(4e-6 if n==32 else 2e-8)
print(f'common unprojected pulse amplitude {f.real:.9f}, internal norm outside band {loss:.8g}')
eplus=model.torus.rest**2+np.dot(k+q/2,k+q/2)
eminus=model.torus.rest**2+np.dot(k-q/2,k-q/2)
assert abs((eplus-eminus)/2-np.dot(q,k))<1e-15
if __name__=='__main__':
main()
lapse_algebra.py
"""Compare two-lapse brackets in a scalar band, a signed Dirac field and its positive subspace."""
from collections import defaultdict
from math import atan2, cos, sin, sqrt
MASS = 1.0
STEP = 0.25
LIMIT = 28
def spin(k, sign=1):
theta = atan2(k, MASS) / 2
return (cos(theta), sin(theta)) if sign == 1 else (-sin(theta), cos(theta))
def project(states, sign):
keep = {}
for j, (a, b) in states.items():
x, y = spin(STEP*j, sign)
val = x*a+y*b
keep[j] = (x*val, y*val)
return keep
def real_profile(constant, positive):
modes = {0: complex(constant)}
for j, a in positive.items():
modes[j] = a
modes[-j] = complex(a).conjugate()
return modes
def derivative(modes):
return {j: 1j*j*STEP*a for j, a in modes.items()}
def multiply(a, b):
c = defaultdict(complex)
for j, x in a.items():
for k, y in b.items():
c[j+k] += x*y
return c
def subtract_modes(a, b):
return {j: a.get(j, 0)-b.get(j, 0) for j in a.keys() | b.keys()}
def vertex(kind, modes, states):
"""Spectral derivative with an explicitly finite momentum cutoff."""
out = {}
for j, (x, y) in states.items():
for transfer, coeff in modes.items():
dest = j+transfer
if abs(dest) > LIMIT:
continue
mid = STEP*(j+dest)/2
if kind == "dirac":
a, b = MASS*x+mid*y, mid*x-MASS*y
elif kind == "scalar":
energy = sqrt(MASS**2+mid**2)
a, b = energy*x, energy*y
elif kind == "shift":
a, b = mid*x, mid*y
else:
raise ValueError(kind)
u, v = out.get(dest, (0j, 0j))
out[dest] = (u+coeff*a, v+coeff*b)
return out
def combine(a, b, x=1, y=-1):
out = {}
for j in a.keys() | b.keys():
z, w = a.get(j, (0j, 0j))
s, t = b.get(j, (0j, 0j))
out[j] = (x*z+y*s, x*w+y*t)
return out
def dot(a, b):
return sum(a[j][0].conjugate()*b[j][0] + a[j][1].conjugate()*b[j][1]
for j in a.keys() & b.keys())
def norm(a):
return sqrt(max(0, dot(a, a).real))
def loop(kind, f, g, src, mid_sign=None, other=None):
"""i[H[f],H[g]] or mixed i[D[f],H[g]], optionally resolving intermediate sign."""
left = other or kind
first_g = vertex(kind, g, src)
first_f = vertex(left, f, src)
if mid_sign is not None:
first_g = project(first_g, mid_sign)
first_f = project(first_f, mid_sign)
return combine(vertex(left, f, first_g), vertex(kind, g, first_f), 1j, -1j)
def single_modes(k, q, r):
energy = lambda p: sqrt(MASS**2+p*p)
scalar = energy(k+q+r/2)*energy(k+q/2)-energy(k+r+q/2)*energy(k+r/2)
shift = (q-r)*(k+(q+r)/2)
start, end = spin(k), spin(k+q+r)
overlap = sum(x*y for x,y in zip(start,end))
def via(s, a, b):
mid = spin(k+a,s)
a0 = (energy(k)+s*energy(k+a))/2
a1 = (s*energy(k+a)+energy(k+a+b))/2
return (a0*a1*sum(x*y for x,y in zip(mid,start))*
sum(x*y for x,y in zip(end,mid)))
plus, minus = [via(s,q,r)-via(s,r,q) for s in (1,-1)]
assert abs(plus+minus-shift*overlap)<1e-13
print(f"mixed q={q:g}, r={r:g}, k={k:g}: scalar={scalar:.9f} shift={shift:.9f}")
print(f"external positive spinors: positive intermediate={plus:.9f}, negative={minus:.9f}, "
f"signed target={shift*overlap:.9f}")
return abs(scalar-shift), abs(minus)
def main():
e0, e1 = single_modes(.5, 1.5, .5)
assert e0 > .005 and e1 > .001
f = real_profile(.35, {1:.31+.19j, 4:.12-.28j, 7:-.09+.16j})
g = real_profile(-.22, {2:-.23+.07j, 3:.39-.14j, 6:.06+.21j})
w = subtract_modes(multiply(f,derivative(g)),multiply(g,derivative(f)))
src = {j:(complex(cos(j+.2),sin(j*.8)),complex(.3*sin(j),cos(j+.1)))
for j in (-7,-3,0,2,6)}
probe = {j:(complex(.2*j,1),complex(1,.13*j)) for j in (-5,0,2,6,9)}
assert max(map(abs,src))+max(map(abs,f))+max(map(abs,g)) <= LIMIT
for kind in ("scalar","dirac","shift"):
h1 = dot(probe,vertex(kind,f,src))
h2 = dot(vertex(kind,f,probe),src)
assert abs(h1-h2)<2e-13
for j in (1,3,7):
cc, ss = real_profile(0,{j:.5}), real_profile(0,{j:-.5j})
target = vertex("shift",{0:j*STEP},src)
for kind in ("scalar","dirac"):
assert norm(combine(loop(kind,cc,ss,src),target))<1e-13
dst = vertex("shift",w,src)
for kind in ("dirac","scalar"):
error = norm(combine(loop(kind,f,g,src),dst))/norm(dst)
print(f"finite Fourier profiles: {kind} relative bracket error {error:.10g}")
assert error<1e-13 if kind=="dirac" else error>.001
external = project(src,1)
target = project(vertex("shift",w,external),1)
pos = project(loop("dirac",f,g,external,1),1)
neg = project(loop("dirac",f,g,external,-1),1)
missing = norm(combine(pos,target))/norm(target)
assert norm(combine(combine(pos,neg,1,1),target))<1e-13
print(f"external positive packet: positive-only relative error {missing:.10g}, "
f"negative intermediate norm / target {norm(neg)/norm(target):.10g}")
assert missing>.0001
mixed = loop("dirac",f,g,src,other="shift")
normal = vertex("dirac",multiply(f,derivative(g)),src)
correction = {j:(-y,-x) for j,(x,y) in vertex("shift",multiply(g,derivative(f)),src).items()}
assert norm(combine(combine(mixed,normal),correction))<2e-13
print(f"fixed-frame shift-normal remainder / H[f g'] {norm(correction)/norm(normal):.10g}")
edge = {LIMIT: (1+0j,0j)}
edge_error=norm(combine(loop("dirac",cc,ss,edge),vertex("shift",{0:7*STEP},edge)))
assert edge_error>1
print(f"edge packet: cutoff-induced cosine/sine residual {edge_error:.9g}")
if __name__ == "__main__":
main()
band_audit.py
"""Audit all 16 coincidence spin channels of the corrected 3D pair across momentum."""
from pathlib import Path
import argparse
import sys
import numpy as np
from collision_transport import (Torus, BASIS, CONTACTS, design, quartic_design, symbol,
Fiber, hermitian, pole)
from bound_3d import FULL_TENSORS, mode, GAMMA
I16=np.eye(16)
C16={'density':I16,'mass':FULL_TENSORS[-1]}
class FullFiber(Fiber):
"""All four energy signs and all sixteen spins; no bound-pole starting vector."""
def green16(self,energy):
moments=np.zeros((5,5))
n=self.n
for sign,t,e in zip((1,1,-1,-1),(1,-1,1,-1),self.e):
weight=.25/(energy-e)
moments[0,0]+=weight.sum()
moments[1:,0]+=sign*(weight@self.ua)
moments[0,1:]+=t*(weight@self.ub)
moments[1:,1:]+=sign*t*self.ua.T@(weight[:,None]*self.ub)
return hermitian(np.tensordot(moments.ravel()/n**3,FULL_TENSORS,axes=1))
def potential(d,k,kind,variant):
g=1/d['cal'][1]
return (g*C16[kind]+BASIS@symbol(d,k,variant)@BASIS.T)
def inertia(fiber,vinv,e):
return int(np.count_nonzero(np.linalg.eigvalsh(fiber.green16(e)-vinv)<0))
def root(fiber,vinv,lo,hi,start):
"""Quantile by monotone inertia of G(E)-V^-1 in a known free gap."""
for _ in range(34):
mid=(lo+hi)/2
if inertia(fiber,vinv,mid)>start:
hi=mid
else:
lo=mid
return (lo+hi)/2
def energy(p):
p=np.asarray(p)
en,_=mode(p,())
return float(en[0])
def corner(torus,d):
k=np.full(3,np.pi)
fiber=FullFiber(torus,k)
free_neg=float(np.min(fiber.e[3]))
assert free_neg>=-35 and abs(free_neg+34)<.005
onsite=10*(np.kron(GAMMA[-1],GAMMA[0])+np.kron(GAMMA[0],GAMMA[-1]))
for variant in ('bare','common','range2'):
for kind in C16:
v=potential(d,k,kind,variant)
inv=np.linalg.inv(v)
trial=np.linalg.eigvalsh(BASIS.T@(onsite+v)@BASIS)
# -35 is strictly below all four continua by the analytical bound.
n_start=inertia(fiber,inv,-1100.)
n_end=inertia(fiber,inv,-35.)
num=n_end-n_start
low=root(fiber,inv,-1100.,-35.,n_start) if num else 0
high=root(fiber,inv,-1100.,-35.,n_end-1) if num>1 else low
print(f'corner {variant:6} {kind:7}: N(E<−35)={num}, '
f'extrema {low:.6f},{high:.6f}, trial {trial[0]:.4f} to {trial[-1]:.4f}')
if variant=='range2':
assert num==6 and high < -800 and trial[-1]<-800
if variant=='common':
assert num>=1 and low < -39
return free_neg
def certify_corner(d):
# At corner, ||Hfree(p)|| <= 34 analytically. A truncated Chebyshev
# expansion integrates exactly on this grid through polynomial degree m.
n=48; degree=(n-1)//2
k=np.full(3,np.pi)
matrix=FullFiber(Torus(n),k).green16(-35.)
ratio=(35-np.sqrt(69))/34
twice_tail=4/np.sqrt(69)*ratio**(degree+1)/(1-ratio)
margins=[]
for kind in C16:
inv=np.linalg.inv(potential(d,k,kind,'bare'))
ev=np.linalg.eigvalsh(matrix-inv)
margins.append(min(abs(ev)))
assert min(abs(ev))>twice_tail+.0001
assert sum(ev<0)==sum(np.linalg.eigvalsh(-inv)<0)
print(f'bare corner no levels below -35: quadrature error <= {twice_tail:.7f},'
f' smallest inverse-kernel margin {min(margins):.7f}')
def axial(torus,d):
# Explicit continuum-overlap witnesses, independent of any integration mesh.
p=np.array([np.pi,np.pi,np.pi/2])
for q in (.20,.225,.25):
half=np.array([0.,0.,q/2])
mixed=abs(energy(p+half)-energy(p-half))
same=2*energy(half)
print(f'Kz={q:g}: mixed continuum reaches at least {mixed:.8f}, '
f'positive same-sign continuum starts no higher than {same:.8f}')
if q>=.225:
assert mixed>same
# Within rigorously separated subwindows count ALL discrete poles, including
# those with no overlap whatsoever with the tracked rest bound-pair source.
for q in (0.,.10,.15):
k=np.array([0.,0.,q])
f=FullFiber(torus,k)
lo=1.67
hi=1.98
assert np.hypot(1.,32/3)*q < lo < hi<2.
for kind in C16:
numbers=[]
for variant in ('bare','common','range2'):
inv=np.linalg.inv(potential(d,k,kind,variant))
ng=inertia(f,inv,hi)-inertia(f,inv,lo)
neg=inertia(f,inv,-lo)-inertia(f,inv,-hi)
numbers.append((ng,neg))
print(f'Kz={q:.2f} {kind}: counts in (1.67,1.98), (−1.98,−1.67): {numbers}')
def window(s,L):
return (1-s)**L*(1+L*s)
def short_window(s):
if s==0:
return 1.
if s==1:
return 0.
f=(np.sin(16*np.arcsin(np.sqrt(s)))/(16*np.sqrt(s)))**2
return f*f*(6-8*f+3*f*f)
def bounded_completion(torus,d,L=128):
# For q_j=4sin²(K_j/2), sum q_j=12s. The J_j link even to odd.
# Bound their sum by Cauchy-Schwarz, with each ||J_j||=||J_j u||.
jnorm=np.array([np.linalg.norm(J,2) for J in d['J']])
coefficients=[np.sqrt(12)*np.linalg.norm(jnorm),
12*np.max(abs(d['m'])),144*np.max(abs(d['quartic']))]
terms=[]
for power,C in zip((.5,1,2),coefficients):
t=(power+np.sqrt(power**2+4*power))/2
terms.append(C*t**power*(1+t)*np.exp(-t)/L**power)
limit=sum(terms)
assert limit<.42
# Rational upward envelopes tolerate numerical quadrature/refinement errors.
assert coefficients[0]<2.6 and coefficients[1]<12.1 and coefficients[2]<1380
crude=0.
for a,C in ((.5,2.6),(1.,12.1),(2.,1380.)):
t=(a+np.sqrt(a*a+4*a))/2
crude+=C*t**a*(1+t)*np.exp(-t)/L**a
print(f'L={L} uniform perturbation norm <= {limit:.6f}; rounded envelope {crude:.6f}')
assert crude<.41
assert window(1,L)==0 and window(0,L)==1
for direction,q in ((np.array([0.,0.,1.]),.05),(np.array([0.,0.,1.]),.10),
(np.ones(3)/np.sqrt(3),.08)):
E=[]
short=[]
eps=.00004
for momentum in (q-eps,q,q+eps):
k=direction*momentum
s=sum(np.sin(k/2)**2)/3
w=window(s,L)
damped={**d,**{key:w*d[key] for key in ('J','m','quartic')}}
f=Fiber(torus,k)
E.append(np.array([pole(f,damped,k,c,'range2')[0] for c in CONTACTS.values()]))
damped={**d,**{key:short_window(s)*d[key] for key in ('J','m','quartic')}}
short.append(np.array([pole(f,damped,k,c,'range2')[0] for c in CONTACTS.values()]))
current=E[1]*(E[2]-E[0])/(2*eps*q)
compact=short[1]*(short[2]-short[0])/(2*eps*q)
print(f'taper q={q:.3f}: E*v/k={current[0]:.7f},{current[1]:.7f}; '
f'62-cell stencil {compact[0]:.7f},{compact[1]:.7f}')
constants=[]
for a in (.5,1.):
# Max of t^a h(1/t) on t>=1. Max on t<=1 is at most 1.
t=max(np.roots([6*(a-2),-8*(a-3),3*(a-4)]))
constants.append(max(1.,t**(a-2)*(6-8/t+3/t**2)))
limit2=2.6*constants[0]/16+12.1*constants[1]/256+1380*6/16**4
print(f'62-cell stencil: global perturbation norm <= {limit2:.6f}')
assert limit2<.371 and short_window(0)==1 and short_window(1)==0
def dense_control(d):
# A true 4 x 4 x 4 periodic box at corner K, with all 16 spins at every p.
n=4
k=np.full(3,np.pi)
pts=n**3
fiber=FullFiber(Torus(n),k)
free=[]
for p in np.ndindex(n,n,n):
rel=np.array(p)*2*np.pi/n
a,ua=mode(rel+k/2,())
b,ub=mode(-rel+k/2,())
ha=a[0]*np.tensordot(ua[0],GAMMA[1:],axes=1)
hb=b[0]*np.tensordot(ub[0],GAMMA[1:],axes=1)
free.append(np.kron(ha,GAMMA[0])+np.kron(GAMMA[0],hb))
for variant in ('bare','common','range2'):
for kind in C16:
v=potential(d,k,kind,variant)
# V acts at relative position zero; Fourier transform gives V / n³.
H=np.tile(v/pts,(pts,pts)).astype(complex)
for i,b in enumerate(free):
sl=slice(16*i,16*i+16)
H[sl,sl]+=b
direct=np.linalg.eigvalsh(H)
v_inv=np.linalg.inv(v)
start=inertia(fiber,v_inv,-1100.)
count=inertia(fiber,v_inv,-35.)-start
assert np.count_nonzero(direct<-35.)==count
if count:
low=root(fiber,v_inv,-1100.,-35.,start)
assert abs(direct[0]-low)<1e-7
print('independent 1024 x 1024 dense torus: six spectra checked')
def run(n):
torus=Torus(n)
d=design(torus)
d['quartic']=quartic_design(torus,d)
print(f'mesh {n}, g={1/d["cal"][1]:.9f}')
# Rigorous starting point below the full spectrum for every corner scan.
for variant in ('bare','common','range2'):
for kind in C16:
assert 2*np.sqrt(33.**2+1)+np.linalg.norm(
potential(d,np.full(3,np.pi),kind,variant),2)<1100
axial(torus,d)
f0=FullFiber(torus,np.zeros(3))
for kind in C16:
inv=np.linalg.inv(potential(d,np.zeros(3),kind,'bare'))
for lo,hi in ((.01,1.67),(-1.67,-.01),(1.67,1.98)):
a=inertia(f0,inv,lo); b=inertia(f0,inv,hi)
levels=[root(f0,inv,lo,hi,j) for j in range(a,b)]
print(f'rest {kind} {lo:g}..{hi:g}:',np.round(levels,6))
free_min=corner(torus,d)
dense_control(d)
certify_corner(d)
bounded_completion(torus,d)
print(f'sampled free minimum at corner {free_min:.8f}')
return d
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--size',type=int,default=24)
args=parser.parse_args()
run(args.size)
cutoff_flow.py
"""Remove the lattice cutoff while holding the one-body mass, speed and pair energy fixed."""
import argparse
from pathlib import Path
import sys
import numpy as np
HERE = Path(__file__).resolve().parent
if not (HERE / 'bound_3d.py').exists():
sys.path.insert(0, str(HERE.parent / 'shell-clocks'))
from bound_3d import BASIS, BETA_PAIR, GAMMA, IDENTITY, TENSORS, Torus, extract_curvature
def symbol(momentum, spacing):
x,y,z = momentum
t = [2*np.sin(k/2)**2 for k in momentum]
regulator = 2*sum(v*v for v in t)/3 + 2*(t[0]*t[1]+t[1]*t[2]+t[0]*t[2])
coeff = np.stack(np.broadcast_arrays(np.sin(x)*np.cos(y)*np.cos(z),
np.sin(y)*np.cos(z),np.sin(z),spacing+regulator), axis=-1).reshape(-1,4)
energy = np.linalg.norm(coeff,axis=1)
return energy,coeff/energy[:,None]
class Cutoff:
def __init__(self,a,order,rest_ratio=1.9):
self.a = a
self.rest = a*rest_ratio
# Resolve the diminishing physical-momentum interval |k| ~ a without
# sampling a different physical box at every cutoff.
nodes, weights = np.polynomial.legendre.leggauss(order)
tmax = np.arcsinh(np.pi/a)
t = (nodes+1)*tmax/2
k = a*np.sinh(t)
w = weights*tmax/2*a*np.cosh(t)/(2*np.pi)
self.nodes = np.r_[-k[::-1],k]
self.weights = np.r_[w[::-1],w]
assert abs(self.weights.sum()-1)<2e-13
def chunks(self):
k, w = self.nodes,self.weights
for i in range(0,len(k),4):
momenta=(k[i:i+4,None,None],k[None,:,None],k[None,None,:])
weights=(w[i:i+4,None,None]*w[None,:,None]*w[None,None,:]).ravel()
yield momenta,weights
def green(self,energy,axis=2,momentum=0.,derivative=False):
moments=np.zeros((5,5))
for p,w in self.chunks():
shift=[momentum/2 if j==axis else 0. for j in range(3)]
e,u=symbol([v+d for v,d in zip(p,shift)],self.a)
f,v=symbol([-v+d for v,d in zip(p,shift)],self.a)
sectors=[]
for s,t in ((1,1),(1,-1),(-1,1),(-1,-1)):
den=energy-s*e-t*f
sectors.append(-.25*w/den**2 if derivative else .25*w/den)
pp,pm,mp,mm=sectors
moments[0,0]+=np.sum(pp+pm+mp+mm)
moments[1:,0]+=(pp+pm-mp-mm)@u
moments[0,1:]+=(pp-pm+mp-mm)@v
moments[1:,1:]+=u.T@((pp-pm-mp+mm)[:,None]*v)
return np.tensordot(moments.ravel(),TENSORS,axes=1)
def calibrate(self,previous):
green=self.green(self.rest)
loc=[0,5]
ev,vec=np.linalg.eigh(green[np.ix_(loc,loc)])
j=np.argmax(abs(vec.conj().T@previous[loc]))
state=np.zeros(6,dtype=complex)
state[loc]=vec[:,j]
assert np.linalg.norm(green@state-ev[j]*state)<2e-11
dE=(state.conj()@self.green(self.rest,derivative=True)@state).real
return green,ev[j],state,dE
def occupations(self,state,dE,physical_width=2.):
# The coefficients of the wave at the pole are the four free signed
# pair projectors acting on its common, normalized coincident source.
plus=(state[0]+state[5])/np.sqrt(2)
minus=(state[0]-state[5])/np.sqrt(2)
occupations=np.zeros(3)
low=0.
for p,w in self.chunks():
e,v=symbol(p,self.a)
# Exact even singlet projectors avoid subtracting nearly equal
# mixed-band terms when the bare mass in lattice units is tiny.
m=v[:,3]
norms=(abs(plus+m*minus)**2/2,
abs(minus)**2*np.sum(v[:,:3]**2,axis=1),
abs(plus-m*minus)**2/2)
gaussian=np.exp(-sum(k*k for k in p)/(2*(self.a*physical_width)**2)).ravel()
for j,(norm,den) in enumerate(zip(norms,(self.rest-2*e,self.rest,self.rest+2*e))):
measure=w*norm/(den**2*(-dE))
occupations[j]+=measure.sum()
low+=np.dot(measure,gaussian)
assert abs(occupations.sum()-1)<2e-8
return occupations,low
def asymptote(self):
# UV constants of the zero-lattice-mass regulator. The s+ local spin
# singlet has no mixed-band projection at any momentum.
A=D=C=0.
for p,w in self.chunks():
e,v=symbol(p,0.)
A+=np.dot(w,1/(4*e**2))
D+=np.dot(w,v[:,3]/(2*e))
C+=np.dot(w,1-v[:,3]**2)
L=A+D**2/C
return L,D**2/(C*L)
def even_matrix(self):
e0=self.rest
hp=hm=cross=0.
for p,w in self.chunks():
e,v=symbol(p,self.a)
m=e*v[:,3]
den=e0**2-4*e**2
hp+=np.dot(w,e0/den)
cross+=np.dot(w,2*m/den)
hm+=np.dot(w,v[:,3]**2*e0/den+(1-v[:,3]**2)/e0)
return np.array([[hp,cross],[cross,hm]])
def row(self,previous):
cal=self.calibrate(previous)
g,lam,state,dE=cal
rotate=np.array([[1.,1.],[1.,-1.]])/np.sqrt(2)
np.testing.assert_allclose(rotate.T@g[np.ix_([0,5],[0,5])]@rotate,
self.even_matrix(),atol=2e-12)
steps=self.a*np.array([.008,.004])
rows=[]
for axis in (0,1,2):
values=[extract_curvature(self.rest,k,self.green(self.rest,axis,k),cal) for k in steps]
rows.append((4*values[1]-values[0])/3)
occ,low=self.occupations(state,dE)
return state,np.array(rows),lam**2/(-dE),occ,low,lam
def sweep(order,scales):
state=np.eye(6)[0]
rows=[]
for a in scales:
kernel=Cutoff(a,order)
state,R,coincidence,occupation,low,lam=kernel.row(state)
print(f'a={a:g} Rz={R[2,0]:.8f}/{R[2,1]:.8f} Rx={R[0,0]:.7f}/{R[0,1]:.7f} '
f'contact={coincidence:.7f} (++,+-,- -)={occupation} low={low:.7f} '
f'lambda={lam:.8g} upper={abs(state[0])**2:.5f}',flush=True)
rows.append((R,coincidence,occupation,low,lam))
return rows
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--fine',action='store_true',help='use 32 Gauss nodes per half-axis')
parser.add_argument('--order',type=int,help='override the number of nodes per half-axis')
args=parser.parse_args()
order=args.order or (32 if args.fine else 20)
scales=[1.,.75,.5,.375,.25,.125,.0625,.03125,.015625]
result=sweep(order,scales)
reference=Torus(48)
rest=reference.green(reference.rest)
np.testing.assert_allclose(Cutoff(1,order).green(reference.rest),rest,atol=2e-7)
L,mixed=Cutoff(.25,max(28,order)).asymptote()
print(f'limiting contact probability / a²={1.9**2*L:.8f}, mixed-band occupation={mixed:.8f}')
assert abs(result[-1][1]/scales[-1]**2-1.9**2*L)<.02
assert abs(result[-1][2][1]-mixed)<.02
assert result[-1][3]<.02 and result[0][3]>.85
assert result[-1][0][2,0]>3 and result[-1][0][0,0]>5
collective_gravity.py
"""Two dilute condensates sourcing their shared, constrained Newtonian potential.
NumPy; both published single-pair kernels are imported unmodified.
"""
from pathlib import Path
import argparse
import sys
import numpy as np
HERE = Path(__file__).resolve().parent
if not (HERE/'form_factor.py').exists():
sys.path.insert(0,str(HERE.parent/'pair-inertia'))
from collision_transport import (Torus, BASIS, CONTACTS, design, symbol,
vertex, Fiber, pole)
from form_factor import block, wave
N_TOTAL = .01
K_REFERENCE = .08
Z = 1.90
# Fix the point-energy, parabolic common-metric Jeans wavenumber to 0.08.
FOUR_PI_G = K_REFERENCE**4/(4*Z**3*N_TOTAL)
def vertices(torus,d,k,variant):
"""Rest-to-moving endpoint energy and number per constituent, in common real phase."""
n=torus.size
k=np.asarray(k)
z=d['rest']
_,lam,u0,_=d['cal']
w0=d['weight']
u0=np.sqrt(w0)*u0
fiber=Fiber(torus,k)
final=[]
# The free ++ continuum is >=2, the -- continuum <=-2. The mixed sign
# continuum is bounded by the Lipschitz constant of the one-body energy.
max_mixed=np.linalg.norm(k,ord=1)*np.hypot(1.,32/3)
assert max_mixed < z-.03 < z+.03 < 2.
green_edges=[fiber.green(z+offset) for offset in (-.03,.03)]
for contact in CONTACTS.values():
e,u,w=pole(fiber,d,k,contact,variant)
u=np.sqrt(w)*u*np.exp(-1j*np.angle(np.vdot(u0,u)))
v=contact/lam + symbol(d,k,variant)
# Every eigenvalue of G(E)-V^-1 decreases strictly between free poles.
edge=[np.linalg.eigvalsh(g-np.linalg.inv(v)) for g in green_edges]
assert min(np.min(abs(a)) for a in edge)>1e-4
assert np.count_nonzero(edge[1]<0)-np.count_nonzero(edge[0]<0)==1
s0=(BASIS@(contact@u0/lam)).reshape(4,4)
sf=(BASIS@(v@u)).reshape(4,4)
f_contact=np.vdot(u,(contact/lam+vertex(d,k,np.zeros(3),variant))@u0)
final.append((e,s0,sf,f_contact))
accum=np.zeros((2,4),dtype=complex)
grid=torus.grid
for lo in range(0,n,3):
p=[g*(2*np.pi/n) for g in (grid[0][lo:lo+3],grid[1],grid[2])]
ha,a=block(p)
hb,b=block([-t for t in p])
haf,af=block([t+s for t,s in zip(p,k)])
for i,(e,s0,sf,_) in enumerate(final):
wi=wave(s0,z,ha,a,hb,b)
wf=wave(sf,e,haf,af,hb,b)
accum[i]+= [np.vdot(wf,(haf+ha)@wi), np.vdot(wf,wi),
np.vdot(wi,wi),np.vdot(wf,wf)]
accum/=n**3
for i,(_,_,_,v) in enumerate(final):
accum[i,0]+=v
assert np.max(abs(accum.imag))<2e-10
assert np.max(abs(accum[:,2:].real-1))<5e-4
return (np.array([p[0]-z for p in final]),accum[:,0].real,
accum[:,1].real)
def modes(data,k,fractions):
gap,f,number=data
density=N_TOTAL*np.array(fractions)
v=np.sqrt(density*gap)*f
D=np.diag(gap**2)-(2*FOUR_PI_G/k**2)*np.outer(v,v)
eigen,U=np.linalg.eigh(D)
# Choose the sign of each mode so density contact's ripple starts positive.
U=U*np.where(U[0]>=0,1.,-1.)
contrast=number[:,None]*np.sqrt(gap/density)[:,None]*U
bias=2*(contrast[0,0]-contrast[1,0])/(contrast[0,0]+contrast[1,0])
charge=v*U[:,1]
relative_charge=abs(sum(charge))/sum(abs(charge))
critical=1/((2*FOUR_PI_G/k**2)*np.sum(density*f*f/gap))
assert bool(eigen[0]<0)==bool(critical<1)
assert eigen[1]>0 and U[0,1]*U[1,1]<0
return eigen,U,bias,relative_charge,critical
def evolve(data,k,fractions):
"""Self-consistent nonlinear three-COM-mode check, retaining the ±q potential."""
gap,f,num=data
density=N_TOTAL*np.array(fractions)
eigen,U,_,_,_=modes(data,k,fractions)
assert eigen[0]<0
t=2.2/np.sqrt(-eigen[0])
# A and B multiply the zero-momentum state and the even ±q combination.
B0=np.array([.00003,0])
fields=np.array([np.sqrt(1-B0**2),B0],dtype=complex)
def potential(state):
A,B=state
rho=np.sqrt(2)*np.sum(density*f*(A.conj()*B).real)
return -FOUR_PI_G*rho/k**2,rho
def rhs(state):
A,B=state
phi,_=potential(state)
drive=np.sqrt(2)*f*phi
return -1j*np.array([drive*B,gap*B+drive*A])
def energy(state):
phi,rho=potential(state)
return np.sum(density*gap*np.abs(state[1])**2)+phi*rho
e0=energy(fields)
norm0=np.sum(abs(fields)**2,axis=0)
steps=320
dt=t/steps
for _ in range(steps):
a=rhs(fields)
b=rhs(fields+dt*a/2)
c=rhs(fields+dt*b/2)
dv=rhs(fields+dt*c)
fields+=dt*(a+2*b+2*c+dv)/6
scale=np.sqrt(gap/density)
coeff=U.T@(B0/scale)
linear=scale*(U@(coeff*np.array([np.cosh(t*np.sqrt(-eigen[0])),
np.cos(t*np.sqrt(eigen[1]))])))
measured=np.sqrt(2)*num*(fields[0].conj()*fields[1]).real
prediction=np.sqrt(2)*num*linear
err=np.max(abs(measured-prediction))/np.max(abs(prediction))
drift=abs(energy(fields)-e0)/(np.sum(density*gap*B0**2))
norm=np.max(abs(np.sum(abs(fields)**2,axis=0)-norm0))
assert err<1e-6 and drift<1e-8 and norm<2e-13
return t,measured,err,drift,norm
def run(n, extra=False):
torus=Torus(n,Z)
d=design(torus)
print(f'mesh {n}, total density {N_TOTAL}, 4piG {FOUR_PI_G:.12g}')
at0=vertices(torus,d,np.zeros(3),'common')
assert np.max(abs(at0[0]))<1e-10 and np.max(abs(at0[1]-Z))<1e-10
assert np.max(abs(at0[2]-1))<1e-10
cases=[('z',np.array([0.,0.,1.]),.05,(.5,.5)),
('z',np.array([0.,0.,1.]),.076,(.5,.5)),
('xyz',np.ones(3)/np.sqrt(3),.065,(.25,.75))]
if extra:
cases.append(('z',np.array([0.,0.,1.]),.025,(.5,.5)))
for axis,unit,k,fractions in cases:
for variant in ('bare','common'):
data=vertices(torus,d,k*unit,variant)
eigen,vec,bias,charge,crit=modes(data,k,fractions)
low=np.sign(eigen[0])*np.sqrt(abs(eigen[0]))
print(f'{axis} {k:g} {fractions} {variant}:'
f' eps={data[0][0]:.10g},{data[0][1]:.10g}'
f' F={data[1][0]:.8f},{data[1][1]:.8f}'
f' N={data[2][0]:.8f},{data[2][1]:.8f}')
print(f' signed-low/high {low:.10g},{np.sqrt(eigen[1]):.10g},'
f' bias={bias:.7f}, relCharge={charge:.7f}, ncrit/n={crit:.7f}')
if axis=='z' and k==.076:
_,_,_,_,point_crit=modes((data[0],np.full(2,Z),data[2]),k,fractions)
rod_factor=np.sum(4*np.sin(k*unit/2)**2)/k**2
print(f' ncrit/n for point energy {point_crit:.7f}; for lattice Poisson {crit*rod_factor:.7f}')
assert (point_crit<1)==(crit<1)==(crit*rod_factor<1)
if axis=='z' and k==.05:
t,nmod,err,drift,norm=evolve(data,k,fractions)
print(f' time={t:.7f} fractional Fourier densities={nmod},'
f' relative error={err:.3g}, H drift={drift:.3g}, norm={norm:.3g}')
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--size',type=int,default=32)
parser.add_argument('--extra',action='store_true',help='include a longer wavelength')
args=parser.parse_args()
run(args.size,args.extra)
live_collapse.py
"""Spherical pressureless Einstein-matter evolution and two clock-ray readouts. Standard library."""
from math import cos, exp, pi, sin, sqrt, tan
MASS=.05
RECEPTION=2.8
def profile(r, contrast):
"""M/r^3, its derivative, and 4*pi*initial proper density."""
u=r*r
f=1+contrast*u*(1-u)**2
df=2*contrast*r*(1-u)*(1-3*u)
return MASS*f, MASS*df, MASS*(3*f+r*df)
def shell(t,r,contrast):
m3,dm3,d0=profile(r,contrast)
tau=1/sqrt(8*m3)
if not 0<=t<pi*tau:
raise ValueError("outside the pre-focusing collapse branch")
eta=t/tau/2
for _ in range(24):
d=(eta+sin(eta)-t/tau)/(1+cos(eta))
eta-=d
if abs(d)<2e-15:
break
s=(1+cos(eta))/2
b=-r*dm3/(2*m3)
f=eta+sin(eta)
u=tan(eta/2)
j=s+b*u*f/2
dj=(-sin(eta)/2+b*((1+u*u)*f/2+u*(1+cos(eta)))/2)/(2*tau*s)
v=-r*u/(2*tau)
gamma=sqrt(1-2*m3*r*r)
return r*s,v,j,dj,gamma,s
def fields(t,r,contrast):
radius,v,j,dj,gamma,s=shell(t,r,contrast)
if j<=0:
raise ValueError("a dust shell has already crossed")
density=profile(r,contrast)[2]/(s*s*j)
return radius,v,j,dj,gamma,density
def midpoint_integrals(f,h):
"""Cumulative Simpson integration, including separate half-panel rules at odd nodes."""
n=len(f)-1
assert n%2==0
mass=[0.]*(n+1)
for i in range(0,n,2):
mass[i+1]=mass[i]+h*(5*f[i]+8*f[i+1]-f[i+2])/12
mass[i+2]=mass[i]+h*(f[i]+4*f[i+1]+f[i+2])/3
return mass
def live_mesh(n,steps,end):
"""Update matter and geometry together; rebuild enclosed mass from current density every RHS."""
rs=[i/n for i in range(n+1)]
init=[profile(r,3)[2] for r in rs]
y=[(1.,0.,1.,0.,d) for d in init] # R/r, Rdot/r, R', Rdot', 4*pi*rho
def masses(state):
return midpoint_integrals([d*(r*s)**2*j for r,(s,v,j,w,d) in zip(rs,state)],1/n)
initial_mass=masses(y)
gamma=[sqrt(1-2*m/r) if r else 1. for r,m in zip(rs,initial_mass)]
def baryon(state):
return midpoint_integrals([d*(r*s)**2*j/g for r,g,(s,v,j,w,d) in zip(rs,gamma,state)],1/n)[-1]
initial_baryon=baryon(y)
def rate(state):
mf=masses(state)
ans=[]
for r,m,(s,v,j,w,d) in zip(rs,mf,state):
curvature=m/(r*s)**3 if r else d/3
ans.append((v,-curvature*s,w,(2*curvature-d)*j,-d*(2*v/s+w/j)))
return ans
def advance(state,rates,dt):
return [tuple(a+dt*b for a,b in zip(row,dr)) for row,dr in zip(state,rates)]
dt=end/steps
history=[y]
for _ in range(steps):
k1=rate(y)
k2=rate(advance(y,k1,dt/2))
k3=rate(advance(y,k2,dt/2))
k4=rate(advance(y,k3,dt))
y=[tuple(a+dt*(b+2*c+2*d+e)/6 for a,b,c,d,e in zip(*rows))
for rows in zip(y,k1,k2,k3,k4)]
history.append(y)
mf=masses(y)
radius_error=ms_error=density_error=0.
for r,m,g,(s,v,j,w,d) in zip(rs,mf,gamma,y):
radius,_,_,_,_,exact_d=fields(end,r,3)
radius_error=max(radius_error,abs(r*s-radius))
ms_error=max(ms_error,abs(m-(r*s/2)*(1+(r*v)**2-g*g)))
density_error=max(density_error,abs(d-exact_d))
# Bilinearly interpolate the time-evolved geometry and dust onto the past light cone.
def numerical_fields(t,r,contrast):
ix,it=min(int(r*n),n-1),min(int(t/dt),steps-1)
u,v=r*n-ix,t/dt-it
def value(component):
return sum(wr*wt*history[row][col][component]
for col,wr in ((ix,1-u),(ix+1,u))
for row,wt in ((it,1-v),(it+1,v)))
g=(1-u)*gamma[ix]+u*gamma[ix+1]
return r*value(0),r*value(1),value(2),value(3),g,value(4)
te,ratio,da,_=cone(end,1.,3,n*2,geometry=numerical_fields)
_,exact_ratio,exact_da,_=cone(end,1.,3)
return (radius_error,density_error,ms_error,abs(baryon(y)-initial_baryon),
initial_baryon,abs(ratio-exact_ratio),abs(da-exact_da))
def rk4(fun,x,y,h):
def stage(vec,f,step):
return tuple(v+step*d for v,d in zip(vec,f))
k1=fun(x,y)
k2=fun(x+h/2,stage(y,k1,h/2))
k3=fun(x+h/2,stage(y,k2,h/2))
k4=fun(x+h,stage(y,k3,h))
return tuple(v+h*(a+2*b+2*c+d)/6 for v,a,b,c,d in zip(y,k1,k2,k3,k4))
def cone(tobs,emitter,contrast,n=160,focusing_contrast=None,geometry=fields):
"""Past-directed null ray and Sachs angular-distance initial-value problem."""
def rate(r,state):
t,logw,dist,slope=state
radius,_,j,dj,gamma,d=geometry(t,r,contrast)
if focusing_contrast is not None:
# Passive comoving density on the chosen geometry; an intentionally mismatched optical source.
scale=radius/r if r else fields(t,1e-8,contrast)[0]/1e-8
d=profile(r,focusing_contrast)[2]/(scale**2*j)
w=exp(logw)
return -j/gamma,dj/gamma,slope*j/(gamma*w),-d*w*dist*j/gamma
state=(tobs,0.,0.,1.)
h=emitter/n
for i in range(n):
state=rk4(rate,i*h,state,h)
t,logw,dist,slope=state
return t,exp(logw),dist,geometry(t,emitter,contrast)[0]
def crossing_at(r):
m3,dm3,_=profile(r,3)
tau=1/sqrt(8*m3)
b=r*dm3/(2*m3)
if b<=0:
return pi*tau
lo,hi=0.,pi
for _ in range(52):
eta=(lo+hi)/2
if (1+cos(eta))>b*tan(eta/2)*(eta+sin(eta)):
lo=eta
else:
hi=eta
return tau*(eta+sin(eta))
def first_crossing():
# The mean inside density rises only on 0<r<1/sqrt(3); there each shell has a unique crossing root.
results=[]
for n in (256,1024):
grid=[i/n/sqrt(3) for i in range(n+1)]
vals=[crossing_at(r) for r in grid]
loc=[i for i in range(1,n) if vals[i-1]>vals[i]<vals[i+1]]
assert len(loc)==1
i=loc[0]
lo,hi=grid[i-1],grid[i+1]
for _ in range(44):
l=(2*lo+hi)/3
r=(lo+2*hi)/3
if crossing_at(l)<crossing_at(r):
hi=r
else:
lo=l
r=(lo+hi)/2
results.append((r,crossing_at(r)))
assert abs(results[0][1]-results[1][1])<2e-13
return results[-1]
def main():
for contrast in (0,3):
print("homogeneous" if contrast==0 else "redistributed")
for r in (.55,1.):
t,w,d,areal=cone(RECEPTION,r,contrast)
h=1e-4
dt=(cone(RECEPTION+h,r,contrast)[0]-cone(RECEPTION-h,r,contrast)[0])/(2*h)
assert abs(1/dt-w)<3e-9 and abs(d-areal)<2e-9
print(f" r={r:.2f} emission={t:.9f} period ratio={w:.9f} D_A={d:.9f} "
f"Sachs error={abs(d-areal):.3g} neighboring-ray error={abs(1/dt-w):.3g}")
t,w,d,areal=cone(RECEPTION,1.,0,focusing_contrast=3)
print(f"mismatched passive density in Sachs equation: D_A={d:.9f}, areal={areal:.9f}")
assert abs(d-areal)>.001
r,t=first_crossing()
# Avoid evaluating a singular density exactly at J=0.
before=fields(t-1e-5,r,3)
# The formal Jacobian alone brackets the loss of rank; no post-crossing density is evolved.
after=shell(t+1e-5,r,3)
m=profile(r,3)[0]*r**3
first_focus=pi/sqrt(8*profile(1/sqrt(3),3)[0])
assert before[2]>0>after[2] and before[0]>2*m and t<first_focus
print(f"first crossing r={r:.8f} time={t:.9f} R={before[0]+1e-5*before[1]:.8f}"
f" 2M/R={2*m/before[0]:.7f} earliest focusing time={first_focus:.9f}")
for rem in (.05,.005):
radius,v,j,dj,gamma,d=fields(t-rem,r,3)
print(f" time before crossing {rem}: R'={j:.8f}, 4*pi*rho={d:.6f}")
tests=[live_mesh(n,n,RECEPTION) for n in (32,64,128)]
for n,test in zip((32,64,128),tests):
print(f"live grid {n}: R error={test[0]:.4g} density error={test[1]:.4g} "
f"Misner-Sharp mismatch={test[2]:.4g} proper-mass drift={test[3]:.4g} rest mass={test[4]:.9f}"
f" numerical-ray period and distance errors={test[5]:.3g},{test[6]:.3g}")
assert tests[-1][0]<tests[0][0]/10 and tests[-1][1]<tests[0][1]/10
assert tests[-1][2]<1e-8 and tests[-1][3]<1e-8
for i in (5,6):
assert tests[-1][i]<tests[0][i]/8 and tests[-1][i]<8e-5
if __name__=="__main__":
main()
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()
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-transport study and compare all native Tally checks."""
import argparse
from hashlib import sha256
from io import BytesIO
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
from zipfile import ZipFile
ROOT = Path(__file__).resolve().parent
RELEASES = {
"6f3e168661968c1ff3e32d0390de7ba79fd72ef452b6fd44efce7012df2263ee": 184,
"47745797b8be634dbbb667c2bc2417a34f86ce2b73db8051a64fbbb65543fe16": 195,
"72fecb20c9f83442bcf85a0cf68b6aa1104d2edef829fd27e0ea149eae2cbe41": 192,
}
ATOM_SHA = "4c08a122480cb2d6c1efb48b9e868b5b45432d78dc40b339dbe9db7ebdacf02d"
NATIVE_CHECKS = 21
STANDARD = (
("fall_measurement", ()),
("live_collapse", ()),
("lapse_algebra", ()),
)
NUMERICAL = (
("collision_transport", ("--size", "64", "--fine")),
("rest_clock", ("--fine",)),
("extended_clock", ("--fine",)),
("binding_transfer", ("--fine",)),
("cutoff_flow", ("--fine",)),
("common_band", ("--fine",)),
("collective_gravity", ("--size", "64", "--extra")),
("band_audit", ("--size", "48")),
)
def check_native(runtime):
archive = runtime.read_bytes()
release = RELEASES.get(sha256(archive).hexdigest())
if release is None:
raise ValueError(f"{runtime.name} does not match a pinned Tally runtime ZIP")
atom = ROOT / "lib/atom.tly"
if not atom.is_file():
atom = ROOT.parent / "walk-clock-recoil/tally/lib/atom.tly"
library = atom.read_bytes()
if sha256(library).hexdigest() != ATOM_SHA:
raise ValueError(f"Unexpected SHA-256 for {atom}")
expected = (ROOT / "transport.out").read_text(encoding="utf-8").splitlines()
if len(expected) != NATIVE_CHECKS or not all(row.startswith("✓") for row in expected):
raise ValueError("The reference transcript must contain all 21 native checks")
with tempfile.TemporaryDirectory() as dirname:
work = Path(dirname)
with ZipFile(BytesIO(archive)) as bundle:
bundle.extractall(work)
tally = work / "Tally-0.3.0"
(tally / "lib/atom.tly").write_bytes(library)
shutil.copyfile(ROOT / "transport.tly", work / "transport.tly")
result = subprocess.run(
[sys.executable, "-B", str(tally / "tally.py"), "transport.tly"],
cwd=work, env=dict(os.environ, PYTHONIOENCODING="utf-8"),
stdout=subprocess.PIPE, encoding="utf-8", check=True,
)
if result.stdout.splitlines() != expected:
raise ValueError(f"Tally release {release} output differs from transport.out")
print(f"Tally release {release} matched all {NATIVE_CHECKS} native checks.", flush=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path, help="path to a pinned Tally release ZIP")
parser.add_argument("--full", action="store_true", help="run eight additional NumPy calculations at publication settings")
args = parser.parse_args()
check_native(args.runtime)
programs = STANDARD + (NUMERICAL if args.full else ())
env = dict(os.environ, OPENBLAS_NUM_THREADS="1", OMP_NUM_THREADS="1", MKL_NUM_THREADS="1")
for name, options in programs:
print("Running", name + ".py", *options, flush=True)
subprocess.run([sys.executable, "-B", str(ROOT / (name + ".py")), *options],
cwd=ROOT, env=env, check=True)
print(f"Passed {len(programs)} calculation programs and all {NATIVE_CHECKS} native Tally checks.")
if __name__ == "__main__":
main()