Native Tally transcript
✓ the oblique transverse polarization axis has unit norm (by cross-pairing plus and minus sides; derived)
✓ the polarization axis is transverse to momentum (3,4,0) (by cross-pairing plus and minus sides; derived)
✓ the plus tensor has zero three-dimensional trace (by cross-pairing plus and minus sides; derived)
✓ contracting the plus tensor with the momentum gives zero (by cross-pairing plus and minus sides; derived)
✓ the plus polarization has squared tensor norm two (by cross-pairing plus and minus sides; derived)
✓ the cross xz and yz entries give the same tensor norm (by cross-pairing plus and minus sides; derived)
✓ a constant-norm transverse wave gives K squared equal to 0.54 in the normalized torus (by cross-pairing plus and minus sides; derived)
✓ the homogeneous conformal Hamiltonian constraint cancels pointwise (by cross-pairing plus and minus sides; derived)
✓ normalized Einstein kinetic and curvature coefficients give a common shift without a trace gradient (by cross-pairing plus and minus sides; derived)
✓ changing the trace weight to 0.43 leaves a trace anomaly (by cross-pairing plus and minus sides; derived)
✓ changing only gradient stiffness leaves a species-dependent shift (by cross-pairing plus and minus sides; derived)
✓ nonlinear scalar reciprocal Hamiltonian slopes close the bracket (by cross-pairing plus and minus sides; derived)
✓ the same nonlinear scalar has energy two at these gradient and momentum values (by cross-pairing plus and minus sides; derived)
✓ the two-level clock commutator gives unit excitation amplitude in the control (by cross-pairing plus and minus sides; derived)
✓ a normalized polynomial in the squared gap cancels that control transition (by cross-pairing plus and minus sides; derived)
✓ the same energy improvement preserves matrix elements at zero gap (by cross-pairing plus and minus sides; derived)
✓ two adjacent edge shifts generate a two-site transition (by cross-pairing plus and minus sides; derived)
✓ seven-step face centroids obstruct two-to-one covering below seven ninths (by cross-pairing plus and minus sides; derived)
✓ at seven shifts eight copies reach three fifths and need at least nine sixteenths (by cross-pairing plus and minus sides; derived)
✓ a seven-stage extreme endpoint carries one part in ninety-six for uniform release phase (by cross-pairing plus and minus sides; derived)
✓ the odd-channel rest gap sets the squared-gap exponent in energy-window suppression (by cross-pairing plus and minus sides; derived)
Native Tally source
# Exact controls for tensor clocks and the convex body of walk endpoints.
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 eight=whole(8 trial)
let half=fraction(1 trial,2 trial)
let x=fraction(4 trial,5 trial)
let y=flip(fraction(3 trial,5 trial))
check x*x+y*y==one "the oblique transverse polarization axis has unit norm"
check three*x+four*y==zero "the polarization axis is transverse to momentum (3,4,0)"
let plus_xx=x*x
let plus_xy=x*y
let plus_yy=y*y
check plus_xx+plus_yy+flip(one)==zero "the plus tensor has zero three-dimensional trace"
check three*plus_xx+four*plus_xy==zero and three*plus_xy+four*plus_yy==zero "contracting the plus tensor with the momentum gives zero"
check plus_xx*plus_xx+two*plus_xy*plus_xy+plus_yy*plus_yy+one==two "the plus polarization has squared tensor norm two"
check two*(x*x+y*y)==two "the cross xz and yz entries give the same tensor norm"
let amp=fraction(3 trial,5 trial)
let traceKsq=share(three,two)*amp*amp
check traceKsq==fraction(27 trial,50 trial) "a constant-norm transverse wave gives K squared equal to 0.54 in the normalized torus"
check share(traceKsq,whole(12 trial))==share(amp*amp,eight) "the homogeneous conformal Hamiltonian constraint cancels pointwise"
let ka=fraction(8 trial,5 trial)
let kb=fraction(5 trial,8 trial)
check ka*kb==one and one+flip(two*half)==zero "normalized Einstein kinetic and curvature coefficients give a common shift without a trace gradient"
let trace_weight=fraction(43 trial,100 trial)
check one+flip(two*trace_weight)==fraction(7 trial,50 trial) "changing the trace weight to 0.43 leaves a trace anomaly"
let slow=fraction(31 trial,50 trial)
check one*slow==slow and slow+fraction(19 trial,50 trial)==one "changing only gradient stiffness leaves a species-dependent shift"
let root_s=two
let root_y=fraction(3 trial,2 trial)
check share(root_y,root_s)*share(root_s,root_y)==one "nonlinear scalar reciprocal Hamiltonian slopes close the bracket"
check root_s*root_y+flip(one)==two "the same nonlinear scalar has energy two at these gradient and momentum values"
let delta=two
let offdiag=half
check delta*offdiag==one "the two-level clock commutator gives unit excitation amplitude in the control"
check one+flip(share(delta*delta,four))==zero "a normalized polynomial in the squared gap cancels that control transition"
check one+flip(share(zero,four))==one "the same energy improvement preserves matrix elements at zero gap"
check half*half==fraction(1 trial,4 trial) "two adjacent edge shifts generate a two-site transition"
let shrink=fraction(2 trial,3 trial)
let a=two
let mark=a+fraction(1 trial,3 trial)
check share(mark,a+one)==fraction(7 trial,9 trial) "seven-step face centroids obstruct two-to-one covering below seven ninths"
check share(a+one,two*a+one)==fraction(3 trial,5 trial) and share(three*(a+one),whole(6 trial)*a+four)==fraction(9 trial,16 trial) "at seven shifts eight copies reach three fifths and need at least nine sixteenths"
check share(one,whole(6 trial))*share(one,whole(16 trial))==fraction(1 trial,96 trial) "a seven-stage extreme endpoint carries one part in ninety-six for uniform release phase"
let gap=fraction(1 trial,10 trial)
check gap*gap==fraction(1 trial,100 trial) "the odd-channel rest gap sets the squared-gap exponent in energy-window suppression"
lapse_loop.py
"""Sine-cosine local-energy commutator on the normalized 3D pair pole. Requires NumPy."""
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, BASIS, BETA_PAIR, GAMMA, IDENTITY
if not (HERE/'form_factor.py').is_file():
sys.path.insert(0,str(HERE.parent/'pair-inertia'))
from form_factor import block, bound, wave
def push(k,d,incoming,contact_amplitude,h_at,origin=0.):
"""Output at relative momentum p after rho(d) maps total momentum k to k+d."""
fa=h_at(1,(k+d)/2)[0]
ia=h_at(1,(k-d)/2)[0]
fb=h_at(-1,(k+d)/2)[0]
ib=h_at(-1,(k-d)/2)[0]
# The constituent receiving momentum d has its initial relative momentum shifted.
from_a,from_b=incoming(-d/2),incoming(d/2)
result=((fa+ia)@from_a+from_b@(fb+ib).swapaxes(1,2))/2+contact_amplitude
if origin:
result+=(origin/2)*(from_a+from_b)
return result
class Pair:
def __init__(self,torus,cal,k,contact):
energy,src=bound(torus,cal,2,k,contact)
self.energy=energy
self.source=(BASIS@src).reshape(4,4)
self.k=k
def spinwave(pair,offset,h_at):
a,e=h_at(1,offset+pair.k/2)
b,f=h_at(-1,-offset+pair.k/2)
return wave(pair.source,pair.energy,a,e,b,f)
def evaluate(torus,cal,k,q,contact,second_action=False,include_band=True,origin=0.):
"""All relative momenta and all 16 spins enter before any pole projection."""
n=torus.size
directions=(q,-q)
initial=Pair(torus,cal,k,contact)
final=[Pair(torus,cal,k+d,contact) for d in directions] if include_band else []
norms=np.zeros(2)
contact_means=np.zeros((2,4,4),complex)
projected=np.zeros(2,complex)
# A branch source in the published resolvent is V|psi>, constant over p.
def chunks():
for lo in range(0,n,2):
p=[a*(2*np.pi/n) for a in (torus.grid[0][lo:lo+2],*torus.grid[1:])]
h_cache={}
def h_at(sign,offset):
key=sign,round(offset,11)
if key not in h_cache:
h_cache[key]=block([sign*p[0],sign*p[1],sign*p[2]+offset])
return h_cache[key]
psi_cache={}
def psi(offset):
key=round(offset,11)
if key not in psi_cache:
psi_cache[key]=spinwave(initial,offset,h_at)
return psi_cache[key]
first_cache={}
def first(d,offset):
key=round(d,11),round(offset,11)
if key not in first_cache:
sym=lambda s: psi(offset+s)
hshift=lambda sign,s: h_at(sign,s+sign*offset)
first_cache[key]=push(k,d,sym,initial.source,hshift,origin)
return first_cache[key]
yield h_at,psi,first
for h_at,psi,first in chunks():
for j,d in enumerate(directions):
out=first(d,0.)
norms[j]+=np.vdot(out,out).real
contact_means[j]+=out.sum(axis=0)
if include_band:
projected[j]+=np.vdot(spinwave(final[j],0.,h_at),out)
norms/=n**3
contact_means/=n**3
projected/=n**3
if np.min(norms-abs(projected)**2)<-2e-7:
raise ArithmeticError('projection exceeded complete norm')
full=(norms[0]-norms[1])/2
band=(abs(projected[0])**2-abs(projected[1])**2)/2
if not second_action:
return full,band,float('nan'),projected
# Contact in the intermediate momentum fiber acts on the entire coincident spinor.
g=1/cal[1]
if np.array_equal(contact,IDENTITY):
kicks=g*contact_means
else:
beta=GAMMA[-1]
kicks=g*beta@contact_means@beta.T
expectation=0j
current=0j
bnorm=0.
for h_at,psi,first in chunks():
products=[]
if include_band and k>0.:
chi=first(q,0.)
ha=h_at(1,(k+q)/2)[0]
hb=h_at(-1,(k+q)/2)[0]
dh=ha@chi+chi@hb.swapaxes(1,2)+kicks[0]-initial.energy*chi
current+=np.vdot(spinwave(final[0],0.,h_at),dh)/(2*np.sin(q/2))
for j,d in enumerate(directions):
incoming=lambda offset: first(d,offset)
products.append(push(k+d,-d,incoming,kicks[j],h_at,origin))
bpsi=(products[0]-products[1])/2
expectation+=np.vdot(psi(0.),bpsi)
bnorm+=np.vdot(bpsi,bpsi).real
if include_band and k>0.:
predicted=(final[0].energy-initial.energy)*projected[0]/(2*np.sin(q/2))
assert abs(current/n**3-predicted)<3e-7
print(f' endpoint continuity current K={k:g} to {k+q:g}: {predicted.real:.9f}',flush=True)
expectation/=n**3
variance=bnorm/n**3-abs(expectation)**2
# quadratures of shifted integration variables coincide in the continuum.
assert abs(expectation-full)<(3e-4 if n<=32 else 2e-5)
assert variance>=-1e-12
return full,band,variance,projected
def finite_torus_loop():
"""Independent finite-duration test in physical momenta (K,k_A), no intermediate projection."""
n=8
stride=2
q=stride*2*np.pi/n
torus=Torus(n)
cal=rest_calibration(torus)
c=IDENTITY
rest=Pair(torus,cal,0.,c)
_,_,variance,_=evaluate(torus,cal,0.,q,c,True,False)
k,x,y,z=[i*2*np.pi/n for i in np.ogrid[0:n,0:n,0:n,0:n]]
def symbol(arr):
h,_=block(arr)
return h.reshape(*np.broadcast_shapes(*(s.shape for s in arr)),4,4)
ha=symbol((x,y,z))
hb=symbol((-x,-y,k-z)).swapaxes(-1,-2)
s=np.zeros((n,n,n,n,4,4),complex)
spin=rest.source
h1,a=block((x,y,z))
h2,b=block((-x,-y,-z))
s[0]=wave(spin,rest.energy,h1,a,h2,b).reshape(n,n,n,4,4)/np.sqrt(n**3)
assert abs(np.linalg.norm(s)-1)<1e-12
a_links={}
b_links={}
for step in (stride,-stride):
a_links[step]=(ha+np.roll(ha,step,axis=3))/2
b_links[step]=(hb+np.roll(hb,step,axis=0))/2
def hopping(state,step):
shifted=np.roll(state,step,axis=0)
return a_links[step]@np.roll(shifted,step,axis=3)+shifted@b_links[step]
def contact(state,step):
mean=state.mean(axis=(1,2,3),keepdims=True)/cal[1]
return np.broadcast_to(np.roll(mean,step,axis=0),state.shape)
def vertex(state,step):
return hopping(state,step)+contact(state,step)
def pulse(state,kind,factor):
result=state.copy()
term=state.copy()
for j in range(1,32):
plus,minus=vertex(term,stride),vertex(term,-stride)
h=(plus+minus)/2 if kind=='cos' else (plus-minus)/(2j)
term=(factor/j)*h
result+=term
if np.linalg.norm(term)<1e-16:
return result
raise ArithmeticError('finite pulse did not converge')
bstate=(vertex(vertex(s,stride),-stride)-vertex(vertex(s,-stride),stride))/2
free=(hopping(hopping(s,stride),-stride)-hopping(hopping(s,-stride),stride))/2
contact_first=(hopping(contact(s,stride),-stride)-hopping(contact(s,-stride),stride))/2
contact_last=(contact(hopping(s,stride),-stride)-contact(hopping(s,-stride),stride))/2
assert np.linalg.norm(free)<1e-12
assert np.linalg.norm(contact_first.mean(axis=(1,2,3)))<1e-12
assert abs(np.vdot(contact_first,contact_last))<1e-12
assert np.linalg.norm(bstate-contact_first-contact_last)<1e-12
direct=np.vdot(bstate,bstate).real-abs(np.vdot(s,bstate))**2
assert abs(direct-variance)<2e-10
print(f'independent eight-cell torus, q=pi/2: Var(B)={direct:.9f}')
errors=[]
for angle in (.01,.005,.0025):
out=s
for kind,sign in (('sin',1),('cos',1),('sin',-1),('cos',-1)):
out=pulse(out,kind,sign*1j*angle)
assert abs(np.linalg.norm(out)-1)<4e-13
lost=out-np.vdot(s,out)*s
rate=np.vdot(lost,lost).real/angle**4
errors.append(abs(rate-direct))
print(f' area {angle:g}: measured loss/area^4={rate:.9f}')
assert errors[2]<errors[1]<errors[0] and errors[2]<direct*.01
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('mesh',type=int,nargs='?',default=40)
parser.add_argument('--origin',action='store_true',help='minimize rest loss over a common energy offset')
parser.add_argument('--unitary',action='store_true',help='also run independent finite-duration eight-cell control')
parser.add_argument('--fine',action='store_true',help='use 64 cubed instead of the default mesh')
args=parser.parse_args()
if args.unitary:
finite_torus_loop()
size=64 if args.fine else args.mesh
torus=Torus(size)
cal=rest_calibration(torus)
if args.origin:
q=.05
variance=[evaluate(torus,cal,0.,q,IDENTITY,True,False,offset)[2]/q**2
for offset in (-1.,0.,1.)]
slope=(variance[2]-variance[0])/2
curve=(variance[2]+variance[0])/2-variance[1]
optimum=-slope/(2*curve)
floor=variance[1]+slope*optimum/2
independent=evaluate(torus,cal,0.,q,IDENTITY,True,False,optimum)[2]/q**2
assert curve>0 and floor>0 and abs(independent-floor)<2e-8
print(f'rest loss/q^2 polynomial: {variance[1]:.9f} + offset*({slope:.9f}) + '
f'offset^2*({curve:.9f}); min at {optimum:.9f}, floor={floor:.9f}',flush=True)
for name,c in (('density',IDENTITY),('mass',BETA_PAIR)):
print(f'{name} contact, size={size}, g={1/cal[1]:.9f}',flush=True)
for k,q in ((0.,.10),(0.,.05),(0.,.025),(.05,.05),(.10,.10),(.10,.05),(.10,.025)):
full,band,variance,vertex=evaluate(torus,cal,k,q,c,second_action=(k==0 or (k==.10 and q==.05)))
extra=f' Var(B)/q^2={variance/q**2:.9f}' if np.isfinite(variance) else ''
print(f' K={k:.3f} q={q:.3f} full B/q={full/q:.9f} band B/q={band/q:.9f}'
f'{extra} |Fplus|={abs(vertex[0]):.9f}',flush=True)
if k==0.:
assert max(abs(full),abs(band))<2e-11
step=.0002
e0=Pair(torus,cal,.10,c).energy
em,ep=[Pair(torus,cal,.10+s,c).energy for s in (-step,step)]
print(f' K=.100 forward E dE/dK={e0*(ep-em)/(2*step):.9f}',flush=True)
if __name__=='__main__':
main()
loop_spectrum.py
"""Energy-resolved survival defect of the rest-pair lapse loop. NumPy only."""
import argparse
from math import exp, pi, sinh
import numpy as np
from lapse_loop import Torus, rest_calibration, Pair, IDENTITY, BETA_PAIR, GAMMA, block, wave
def source(n,q,contact):
torus=Torus(n)
cal=rest_calibration(torus)
pole=Pair(torus,cal,0.,contact)
p=[k*(2*np.pi/n) for k in torus.grid]
def symbol(sign,shift):
return block([sign*p[0],sign*p[1],sign*p[2]+shift])
a,e=symbol(1,0.)
b,eb=symbol(-1,0.)
assert np.max(abs(e-eb))<2e-13
if q:
da=(symbol(1,q)[0]-symbol(1,-q)[0])/(4*q)
db=((symbol(-1,q)[0]-symbol(-1,-q)[0])/(4*q)).swapaxes(1,2)
else:
def half_derivative(k):
x,y,z=k
tx,ty,tz=[2*np.sin(t/2)**2 for t in k]
ds=(-np.sin(x)*np.cos(y)*np.sin(z),-np.sin(y)*np.sin(z),np.cos(z),
np.sin(z)*(4*tz/3+2*(tx+ty)))
out=np.stack(np.broadcast_arrays(*ds),axis=-1).reshape(-1,4)
return (out@np.array(GAMMA[1:]).reshape(4,16)).reshape(-1,4,4)/2
da=half_derivative(p)
db=half_derivative([-x for x in p]).swapaxes(1,2)
v=pole.source
psi=wave(v,pole.energy,a,e,b,eb)
# Exact contact-first / contact-last rest vector at energy origin zero.
first=da@v+v@db
coincident=(da@psi+psi@db).mean(axis=0)
beta=GAMMA[-1]
strength=1/cal[1]
if np.array_equal(contact,BETA_PAIR):
last=strength*beta@coincident@beta.T
else:
last=strength*coincident
assert np.linalg.norm(first.mean(axis=0))<1e-12
assert np.linalg.norm(beta@coincident@beta.T+coincident)<1e-12
d=coincident/np.linalg.norm(coincident)
u=first+last
assert abs(np.vdot(psi,u)/n**3)<1e-12
return e,a,b,pole.energy,strength,d,u
def sectors(vec,a,b):
spin_a=a@vec
spin_b=vec@b.swapaxes(1,2)
both=spin_a@b.swapaxes(1,2)
return ((vec+spin_a+spin_b+both)/4,(vec-both)/2,(vec-spin_a-spin_b+both)/4)
def compressed(n,q,contact):
e,a,b,e0,g,d,u=source(n,q,contact)
# At K=0 the free bands have only three energies +2e, 0, -2e.
# Within each energy eigenspace the cyclic span needs only P_E d and P_E u.
# Bin by permutation/reflection classes, not by floating-point closeness.
ijk=np.indices((n,n,n))
folded=np.sort(np.minimum(ijk,n-ijk),axis=0).reshape(3,-1)
index=folded[0]*n**2+folded[1]*n+folded[2]
_,labels=np.unique(index,return_inverse=True)
label_count=labels.max()+1
ones=np.ones_like(labels)
ea=np.bincount(labels,weights=e)/np.bincount(labels)
norm=n**3
dvec=[];uvec=[];energies=[]
ps=sectors(u,a/e[:,None,None],b/e[:,None,None])
ds=sectors(d,a/e[:,None,None],b/e[:,None,None])
for step,us,dd in zip((1,0,-1),ps,ds):
group=labels if step else 0*ones
count=label_count if step else 1
# The coincident sector is one-dimensional on these reflected spin textures.
# Verify it for both generated vectors in every free energy class.
for arr in (us,dd):
pooled=np.zeros((count,4,4),complex)
np.add.at(pooled,group,arr/norm)
component=pooled.reshape(count,16)@d.conj().ravel()
assert np.max(abs(pooled-component[:,None,None]*d))<2e-12
ua=np.bincount(group,weights=np.sum(abs(us)**2,axis=(1,2)))/norm
db=np.bincount(group,weights=np.sum(abs(dd)**2,axis=(1,2)))/norm
prod=np.sum(dd.conj()*us,axis=(1,2))
cross=(np.bincount(group,weights=prod.real)+1j*np.bincount(group,weights=prod.imag))/norm
dlen=np.sqrt(db)
parallel=np.divide(cross,dlen,out=np.zeros_like(cross),where=dlen>1e-18)
rem=ua-abs(parallel)**2
assert rem.min()>-3e-13
dvec.extend(np.column_stack((dlen,0*dlen)).ravel())
uvec.extend(np.column_stack((parallel,np.sqrt(np.maximum(rem,0)))).ravel())
energies.extend(np.repeat(2*step*ea if step else [0.],2))
sign=1 if np.array_equal(contact,IDENTITY) else -1
D=np.array(dvec);U=np.array(uvec);L=np.array(energies)
assert abs(np.vdot(D,D)-1)<2e-12
assert abs(np.vdot(U,U)-np.vdot(u,u)/norm)<2e-11
return L-e0,D,U,g*sign
def rest_spectrum(mesh,q,contact,steps):
"""Signed Ritz gaps (H-Eb) and absolute Gauss weights with sum ||B(q)|b>/q||².
q=0 uses the exact derivative. Use BETA_PAIR or IDENTITY as contact; smooth
polynomial moments through degree 2*steps-1 are exact in exact arithmetic.
A Ritz node inside a gap need not be a physical eigenstate.
"""
if steps<1:
raise ValueError('steps must be positive')
L,D,U,g=compressed(mesh,q,contact)
norm=np.linalg.norm(U)
v=U/norm
prev=np.zeros_like(v)
diag=[];off=[]
b=0.
for j in range(steps):
w=L*v+g*D*np.vdot(D,v)-b*prev
a=np.vdot(v,w).real
diag.append(a)
w-=a*v
b=np.linalg.norm(w)
if b<1e-13 or j+1==steps:
break
off.append(b)
prev,v=v,w/b
tridiag=np.diag(diag)+np.diag(off,1)+np.diag(off,-1)
gaps,vectors=np.linalg.eigh(tridiag)
weights=norm**2*abs(vectors[0])**2
assert abs(sum(weights)-norm**2)<1e-11
return gaps,weights
def gaussian_weights(L,D,U,g,taus):
scale=80.
assert (max(abs(L))+abs(g))/scale<1
tau_max=max(taus)
count=int(16*scale*tau_max)+80
angles=(np.arange(count)+.5)*(pi/count)
# Chebyshev interpolation at first-kind nodes, using the mirrored FFT.
coeff=[]
for tau in taus:
y=np.exp(-(tau*scale*np.cos(angles))**2)
cc=(np.fft.rfft(np.r_[y,y[::-1]])[:count]*np.exp(-.5j*pi*np.arange(count)/count)).real/count
cc[0]/=2
coeff.append(cc)
def apply(x):
return (L*x+g*D*np.vdot(D,x))/scale
prev=U
curr=apply(U)
moments=[np.vdot(U,prev).real,np.vdot(U,curr).real]
for _ in range(2,count):
prev,curr=curr,2*apply(curr)-prev
moments.append(np.vdot(U,curr).real)
# Bernstein ellipse: bound on Gaussian analytic continuation is exp[(tau R sinh eta)^2].
eta=4/(tau_max*scale)
exponent=(tau_max*scale*sinh(eta))**2-(count-1)*eta
err=4*np.vdot(U,U).real*exp(exponent)/(exp(eta)-1)
assert err<1e-12
return np.array(coeff)@moments,err
def independent(n,q,contact,taus):
# Direct full diagonalization of all relative momenta and all 16 spins.
e,a,b,e0,g,d,u=source(n,q,contact)
count=n**3
c=np.eye(16) if np.array_equal(contact,IDENTITY) else np.kron(GAMMA[-1],GAMMA[-1])
h=np.tile(g*c/count,(count,count)).astype(complex)
for j in range(count):
s=slice(16*j,16*j+16)
h[s,s]+=np.kron(a[j],np.eye(4))+np.kron(np.eye(4),b[j])
values,vecs=np.linalg.eigh(h)
weights=abs(vecs.conj().T@u.ravel())**2/count
return np.array([weights@np.exp(-(tau*(values-e0))**2) for tau in taus])
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('mesh',type=int,nargs='?',default=28)
parser.add_argument('--fine',action='store_true',help='use 48 cubed')
args=parser.parse_args()
taus=(0.,.1,.5,1.,2.,4.)
for name,c in (('density',IDENTITY),('mass',BETA_PAIR)):
small=gaussian_weights(*compressed(3,.05,c),taus)[0]
direct=independent(3,.05,c,taus)
assert np.max(abs(small-direct))<5e-10
print(f'{name} direct 432-spin-momentum check {max(abs(small-direct)):.2g}',flush=True)
n=48 if args.fine else args.mesh
L,D,U,g=compressed(n,.05,c)
at_edge=abs(L-.1)<1e-10 # zero residue at the free +2 edge: gap +0.1
assert np.sum(D[at_edge]**2)<1e-20
green_at_edge=np.sum(D[~at_edge]**2/(.1-L[~at_edge]))
assert green_at_edge>7/25 and 1/g<7/25
print(f' endpoint odd Green {green_at_edge:.9f}, inverse coupling {1/g:.9f}')
vals,bound=gaussian_weights(L,D,U,g,taus)
print(f'{name} mesh={n}, uniform polynomial error below {bound:.2g}',flush=True)
for t,v in zip(taus,vals):
print(f' tau={t:.1f} W={v:.10f}, fraction={v/vals[0]:.10f}',flush=True)
if __name__=='__main__':
main()
energy_improvement.py
"""Finite-range alternatives to the local energy density of the ordered 3D pair."""
import argparse
from math import comb,pi
import numpy as np
from loop_spectrum import (source, compressed, rest_spectrum, IDENTITY, BETA_PAIR,
GAMMA, Torus, rest_calibration, Pair, block, wave)
SCALE=80.
CONTACTS=(IDENTITY,BETA_PAIR)
NAMES=('density','mass')
def fit(spectra,degree):
x=np.concatenate([(gaps/SCALE)**2 for gaps,_ in spectra])
w=np.concatenate([weights/weights.sum() for _,weights in spectra])
powers=np.column_stack([x**j for j in range(1,degree+1)])
coeff,*_=np.linalg.lstsq(np.sqrt(w)[:,None]*powers,-np.sqrt(w),rcond=None)
return np.r_[1.,coeff]
def evaluate(comp,coeff):
L,D,U,g=comp
def centered(v):
return (L*v+g*D*np.vdot(D,v))/SCALE
y=coeff[-1]*U
for a in coeff[-2::-1]:
y=centered(centered(y))+a*U
return np.vdot(y,y).real/np.vdot(U,U).real
def full_forward(n,c,coeff):
e,a,b,e0,g,d,u=source(n,0.,c)
bt=b.swapaxes(1,2)
beta=GAMMA[-1]
def centered(v):
mean=v.mean(axis=0)
if np.array_equal(c,BETA_PAIR):
mean=beta@mean@beta.T
return (a@v+v@bt+g*mean-e0*v)/SCALE
y=coeff[-1]*u
for x in coeff[-2::-1]:
y=centered(centered(y))+x*u
return np.vdot(y,y).real/np.vdot(u,u).real
def finite_loop(n,c,coeff,stride=1):
"""Both improved generators, without projecting their intermediate states.
On an n cubed torus choose q=2pi/n along z, so momentum kicks shift the
physical constituent-A momentum by exactly one index. Total K=0 initially.
"""
t=Torus(n)
cal=rest_calibration(t)
pair=Pair(t,cal,0.,c)
energy=pair.energy
g=1/cal[1]
q=stride*2*pi/n
p=[k*(2*pi/n) for k in t.grid]
ha,ea=block(p)
hb={}
for step in (0,-1,1):
hb[step]=block([-p[0],-p[1],-p[2]+step*q])[0].swapaxes(1,2)
b0,eb=block([-k for k in p])
psi=wave(pair.source,energy,ha,ea,b0,eb)
def shift(v,j):
return np.roll(v.reshape(n,n,n,4,4),j*stride,axis=2).reshape(-1,4,4)
def collision(v):
m=v.mean(axis=0)
return g*(m if np.array_equal(c,IDENTITY) else GAMMA[-1]@m@GAMMA[-1].T)
def centered(v,k):
return (ha@v+v@hb[k]+collision(v)-energy*v)/SCALE
hak={i:(ha+shift(ha,i))/2 for i in (-1,1)}
def vertex(v,kin,kout):
j=kout-kin
return hak[j]@shift(v,j)+v@((hb[kin]+hb[kout])/2)+collision(v)
def complete(d):
base=vertex(psi,0,d)
first=coeff[-1]*base
for a in coeff[-2::-1]:
first=centered(centered(first,d),d)+a*base
# The second leg is applied to a noneigenstate. Expand ad_H binomially
# and use Horner evaluation for the left powers of the outgoing H.
powers=[]
v=first
highest=2*(len(coeff)-1)
for j in range(highest+1):
powers.append(vertex(v,d,0))
if j<highest:
v=centered(v,d)
result=np.zeros_like(psi)
for r in range(highest,-1,-1):
if r<highest:
result=centered(result,0)
for l in range(highest-r+1):
if (r+l)%2==0:
result+=((-1)**l*comb(r+l,l)*coeff[(r+l)//2])*powers[l]
return result
u=(complete(1)-complete(-1))/(2*q)
assert abs(np.vdot(psi,u)/n**3)<1e-8
return np.vdot(u,u).real/n**3
def finite_dense(c,coeff):
"""Three-cubed independent check: filter both vertices in exact energy eigenbases."""
n=3
count=n**3
q=2*pi/n
cal=rest_calibration(Torus(n))
kgrid=np.array(list(np.ndindex(n,n,n)))
p=[kgrid[:,j]*q for j in range(3)]
A=block(p)[0]
B={i:block([-p[0],-p[1],-p[2]+i*q])[0] for i in (-1,0,1)}
spin_c=np.eye(16) if np.array_equal(c,IDENTITY) else np.kron(GAMMA[-1],GAMMA[-1])
onsite=np.tile(spin_c/(count*cal[1]),(count,count)).astype(complex)
one=np.eye(4)
def eigensystem(k):
h=onsite.copy()
for i in range(count):
sl=slice(16*i,16*i+16)
h[sl,sl]+=np.kron(A[i],one)+np.kron(one,B[k][i])
return np.linalg.eigh(h)
e0,v0=eigensystem(0)
j=np.argmin(abs(e0-1.9))
assert abs(e0[j]-1.9)<1e-12
terms=[]
for step in (1,-1):
a=onsite.copy()
for i,(x,y,z) in enumerate(kgrid):
k=np.ravel_multi_index((x,y,(z+step)%n),(n,n,n))
src=slice(16*i,16*i+16)
dest=slice(16*k,16*k+16)
a[dest,src]+=np.kron((A[k]+A[i])/2,one)
a[src,src]+=np.kron(one,(B[step][i]+B[0][i])/2)
ef,vf=eigensystem(step)
gaps=ef[:,None]-e0[None,:]
filtered=(vf.conj().T@a@v0)*np.polynomial.polynomial.polyval((gaps/SCALE)**2,coeff)
terms.append(filtered.conj().T@filtered[:,j])
u=(terms[0]-terms[1])/(2*q)
return np.vdot(u,u).real-abs(u[j])**2
def moving_phase(n,k,q,c,coeff):
"""Complete one-pulse norms for a moving initial eigenstate at arbitrary q."""
t=Torus(n)
cal=rest_calibration(t)
pair=Pair(t,cal,k,c)
p=[v*(2*pi/n) for v in t.grid]
def symbol(sign,offset):
return block([sign*p[0],sign*p[1],sign*p[2]+offset])
def local(v):
m=v.mean(axis=0)
return (m if np.array_equal(c,IDENTITY) else GAMMA[-1]@m@GAMMA[-1].T)/cal[1]
result=[]
for d in (q,-q):
hf,ef=symbol(1,(k+d)/2)
bf,ff=symbol(-1,(k+d)/2)
hi,ei=symbol(1,(k-d)/2)
bi,fi=symbol(-1,(k-d)/2)
a=wave(pair.source,pair.energy,hi,ei,bf,ff)
b=wave(pair.source,pair.energy,hf,ef,bi,fi)
outgoing=((hf+hi)@a+b@(bf+bi).swapaxes(1,2))/2+pair.source
def centered(v):
return (hf@v+v@bf.swapaxes(1,2)+local(v)-pair.energy*v)/SCALE
y=coeff[-1]*outgoing
for coef in coeff[-2::-1]:
y=centered(centered(y))+coef*outgoing
result.append(np.vdot(y,y).real/n**3)
return (result[0]-result[1])/(2*q)
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--fine',action='store_true',help='validate at 64 cubed instead of 36 cubed')
parser.add_argument('--finite',action='store_true',help='also evaluate the full finite-q loop on periodic boxes')
args=parser.parse_args()
train=24
test=64 if args.fine else 36
spectra=[rest_spectrum(train,0.,c,32) for c in CONTACTS]
checks=[compressed(test,0.,c) for c in CONTACTS]
fits=[]
for degree in (1,2,3):
coeff=fit(spectra,degree)
fits.append(coeff)
ratios=[evaluate(data,coeff) for data in checks]
print(f'degree {degree}, p(x) coefficients {coeff.tolist()}; test loss fractions {ratios}',flush=True)
for name,spec in zip(NAMES,spectra):
coeff=fit([spec],3)
print(f'train {name} only; held-out density and mass loss fractions',
[evaluate(data,coeff) for data in checks],flush=True)
for data in checks:
fractions=[evaluate(data,poly) for poly in fits]
assert 0<fractions[2]<fractions[1]<fractions[0]<1
coeff=fits[-1]
safe=np.array([1.,-.75,3/16,-1/64]) # (1 - (Delta/160)^2)^3
print('bounded comparison fractions:',[evaluate(data,safe) for data in checks])
print('joint cubic amplitude factor at gap 60:',np.polynomial.polynomial.polyval((60/SCALE)**2,coeff))
for name,c in zip(NAMES,CONTACTS):
comp=compressed(18,0.,c)
raw=full_forward(18,c,coeff)
gaps,weights=rest_spectrum(18,0.,c,20)
profile=np.polynomial.polynomial.polyval((gaps/SCALE)**2,coeff)
ritz=np.sum(weights*profile**2)/weights.sum()
assert max(abs(raw-ritz),abs(raw-evaluate(comp,coeff)))<2e-10
print(f'{name} direct full-state and Ritz check: {raw:.10f}, {ritz:.10f}',flush=True)
if args.finite:
for name,c in zip(NAMES,CONTACTS):
direct=finite_loop(3,c,coeff)
dense=finite_dense(c,coeff)
assert abs(direct-dense)<1e-9
print(f'{name} finite-q 432-dimensional energy-eigenbasis error: {direct-dense:.3g}')
for n in (16,24,32):
for name,c in zip(NAMES,CONTACTS):
raw=finite_loop(n,c,np.array([1.]))
improved=finite_loop(n,c,coeff)
print(f'finite {n} cubed q={2*pi/n:.7f} {name}: unmodified {raw:.8f}, '
f'improved {improved:.8f}, fraction={improved/raw:.8f}',flush=True)
if args.fine:
for name,c in zip(NAMES,CONTACTS):
raw=finite_loop(48,c,np.array([1.]),stride=2)
changed=finite_loop(48,c,coeff,stride=2)
print(f'fixed q=2pi/24, 48 cubed {name}: fraction {changed/raw:.9f}',flush=True)
for name,c in zip(NAMES,CONTACTS):
for q in (.05,.025,.0125):
ph=moving_phase(40,.10,q,c,coeff)
print(f'moving {name} K=.10 q={q:g}: improved <B>/q={ph:.9f}',flush=True)
if __name__=='__main__':
main()
tensor_lattice.py
"""Staggered linearized ADM on a periodic cubic spatial grid. Python 3 + NumPy."""
from itertools import product
import numpy as np
AX = range(3)
FOUR = range(4)
ETA = (-1, 1, 1, 1)
ALPHA = 4.0 # 16 pi G: the static Poisson coefficient 4 pi G is one
RNG = np.random.default_rng(20261201)
def bit(i):
return 1 << i
def derivatives(field, mask, *axes):
"""The input lives on half-grid mask; each derivative toggles one bit (a=1)."""
for i in axes:
if mask & bit(i):
field = field - np.roll(field, 1, axis=i)
else:
field = np.roll(field, -1, axis=i) - field
mask ^= bit(i)
return field
def symmetric(rows, n):
raw = RNG.integers(-3, 4, size=(rows, rows, n, n, n))
return raw + raw.swapaxes(0, 1)
def mat(f):
return np.array([[f(i, j) for j in AX] for i in AX])
def trace(t):
return sum(t[i, i] for i in AX)
def div_tensor(t):
return np.array([sum(derivatives(t[i, j], bit(i)^bit(j), j) for j in AX)
for i in AX])
def div_vector(v):
return sum(derivatives(v[i], bit(i), i) for i in AX)
def lap(f, mask=0):
return sum(derivatives(f, mask, i, i) for i in AX)
def hessian_trace_adjusted(f):
lf = lap(f)
return mat(lambda i, j: derivatives(f, 0, i, j) - (i == j)*lf)
def spatial_curvature(h):
div = div_tensor(h)
tr = trace(h)
scalar = div_vector(div) - lap(tr)
def twice_einstein(i, j):
return (derivatives(div[j], bit(j), i) + derivatives(div[i], bit(i), j)
- lap(h[i, j], bit(i)^bit(j)) - derivatives(tr, 0, i, j)
- (i == j)*scalar)
return scalar, mat(twice_einstein)/2
def sym_grad(v):
return mat(lambda i, j: derivatives(v[j], bit(j), i) + derivatives(v[i], bit(i), j))
def kinetic(p):
tr = trace(p)
return mat(lambda i, j: 2*p[i, j] - (i == j)*tr)
def canonical_rhs(h, p, lapse, shift, stress):
_, g3 = spatial_curvature(h)
return kinetic(p)+sym_grad(shift), -g3+hessian_trace_adjusted(lapse)+ALPHA*stress/2
def constraints(h, p, density, current):
scalar, _ = spatial_curvature(h)
return scalar - ALPHA*density, -2*div_tensor(p) - ALPHA*current
def spatial_mask(a):
return 0 if a == 0 else bit(a-1)
def spacetime_einstein(jets):
"""Independent covariant G_ab using flat signature -+++; jets = h, hdot, hddot."""
def dd(a, b, mu, nu):
spatial = tuple(d-1 for d in (mu, nu) if d)
order = 2-len(spatial)
return derivatives(jets[order][a, b], spatial_mask(a)^spatial_mask(b), *spatial)
def wave(a, b):
return sum(ETA[c]*dd(a, b, c, c) for c in FOUR)
scalar = sum(ETA[c]*ETA[d]*dd(c, d, c, d) for c in FOUR for d in FOUR)
scalar -= sum(ETA[c]*wave(c, c) for c in FOUR)
def comp(a, b):
r = sum(ETA[c]*(dd(c, b, a, c)+dd(c, a, b, c)-dd(c, c, a, b)) for c in FOUR)
return (r-wave(a, b)-(a == b)*ETA[a]*scalar)/2
return np.array([[comp(a, b) for b in FOUR] for a in FOUR])
def peak(*fields):
return max(float(np.max(np.abs(f))) for f in fields)
def check_bianchi(n=4):
jets = [symmetric(4, n) for _ in range(4)]
g = spacetime_einstein(jets[:3])
dg = spacetime_einstein(jets[1:])
residuals = [-dg[0, b]+sum(derivatives(g[a, b], spatial_mask(a)^spatial_mask(b), a-1)
for a in (1, 2, 3)) for b in FOUR]
vectors = RNG.integers(-3, 4, size=(4, 4, n, n, n))
def dx(t, a, b):
if a == 0:
return vectors[t+1, b]
return derivatives(vectors[t, b], spatial_mask(b), a-1)
gauge = [np.array([[dx(t, a, b)+dx(t, b, a) for b in FOUR] for a in FOUR])
for t in range(3)]
result = peak(*residuals, spacetime_einstein(gauge))
assert result == 0
return result
def check_canonical(n=4):
h, p, stress = [symmetric(3, n) for _ in range(3)]
lapse, rho = RNG.integers(-3, 4, size=(2, n, n, n))
shift, current, dshift = RNG.integers(-3, 4, size=(3, 3, n, n, n))
dh, dp = canonical_rhs(h, p, lapse, shift, stress)
_, momentum = constraints(h, p, rho, current)
drho, dj = -div_vector(current), -div_tensor(stress)
dc, dm = constraints(dh, dp, drho, dj)
# Arbitrary initial data: the homogeneous constraint law holds even off shell.
assert peak(dc+div_vector(momentum), dm) == 0
# Residual from adding a unit of unbalanced local energy / current derivative.
bad_rho = drho.copy()
bad_rho[0, 0, 0] += 1
bad_c, _ = constraints(dh, dp, bad_rho, dj)
assert peak(bad_c+div_vector(momentum)) == ALPHA
jets = np.zeros((3, 4, 4, n, n, n))
jets[0, 0, 0] = -2*lapse
for t, vec in enumerate((shift, dshift)):
jets[t, 0, 1:] = jets[t, 1:, 0] = vec
jets[:, 1:, 1:] = [h, dh, kinetic(dp)+sym_grad(dshift)]
g = spacetime_einstein(jets)
r, _ = spatial_curvature(h)
assert peak(2*g[0, 0]-r, g[0, 1:]-div_tensor(p), 2*g[1:, 1:]-ALPHA*stress) == 0
# Quadratic Hamiltonian directional gradient with all fields varied on their own grids.
def energy(x, y):
scalar, g3 = spatial_curvature(x)
return (np.sum(y*y)-np.sum(trace(y)**2)/2 + np.sum(x*g3)/2
- np.sum(lapse*scalar)-2*np.sum(shift*div_tensor(y))
- ALPHA*np.sum(x*stress)/2)
a, b = symmetric(3, n), symmetric(3, n)
finite = (energy(h+a, p+b)-energy(h-a, p-b))/2
assert finite == np.sum(b*dh)-np.sum(a*dp)
return peak(bad_c+div_vector(momentum))
def modes(n=8):
pairs = [(i,j) for i in AX for j in range(i,3)]
axis = 2*np.sin(np.pi*np.fft.fftfreq(n))
count = 0
for k in product(axis, repeat=3):
q = np.array(k)
if np.linalg.norm(q) == 0:
continue
div = np.array([[(i == a)*q[b]+(b != a)*(i == b)*q[a] for a,b in pairs]
for i in AX])
tr = np.array([a == b for a,b in pairs])
q2 = q@q
r = np.array([(q2 if a == b else 0)-(1 if a == b else 2)*q[a]*q[b]
for a,b in pairs])
assert np.linalg.matrix_rank(div) == 3 and np.linalg.norm(r)>0
assert np.linalg.matrix_rank(np.vstack([div,tr])) == 4
count += 1
assert count==n**3-1
# Same Euclidean wave-number length, two orientations of the cubic grid.
same_length = ((3,0,0),(2,2,1))
freq = [np.linalg.norm(2*np.sin(np.pi*np.array(m)/n)) for m in same_length]
assert freq[0] < freq[1]
return count, freq
def check_waves(n=8):
labels=np.array([1, 2, -1])
k=2*np.pi*labels/n
q=2*np.sin(k/2)
u=np.cross(q,[0.,0.,1.])
u/=np.linalg.norm(u)
v=np.cross(q,u)/np.linalg.norm(q)
pols=[np.outer(u,u)-np.outer(v,v), np.outer(u,v)+np.outer(v,u)]
coords=np.indices((n,)*3)
def field(pol, angle):
def comp(i,j):
mask=bit(i)^bit(j)
arg=sum(k[d]*(coords[d]+0.5*bool(mask & bit(d))) for d in AX)
return pol[i,j]*np.cos(arg+angle)
return mat(comp)
h=field(pols[0],0) + .4*field(pols[1],.3)
p=field(pols[1],.7)/3
r,g=spatial_curvature(h)
q2=q@q
residual=peak(r,div_tensor(h),trace(h),2*g-q2*h)
assert residual<2e-13
# Strang kick-drift-kick using the full local gravity RHS, without a TT projection.
# Initial data deliberately mix both oscillators with different initial phases.
def trajectory(dt,steps):
x,y=h.copy(),p.copy()
for _ in range(steps):
y-=dt/2*spatial_curvature(x)[1]
x+=dt*kinetic(y)
y-=dt/2*spatial_curvature(x)[1]
omega=np.sqrt(q2)
exact=h*np.cos(omega*dt*steps)+2*p/omega*np.sin(omega*dt*steps)
e0=np.sum(p*p)+np.sum(h*g)/2
e1=np.sum(y*y)-np.sum(trace(y)**2)/2+np.sum(x*spatial_curvature(x)[1])/2
assert e0>0
return peak(x-exact), peak(div_tensor(y),spatial_curvature(x)[0]), abs(e1/e0-1)
coarse, fine=trajectory(.04,30), trajectory(.02,60)
assert 3.8<coarse[0]/fine[0]<4.2 and fine[1]<2e-12
return np.sqrt(q2), coarse, fine
def static_source(n=16):
rho=np.full((n,)*3,-1/n**3)
rho[0,0,0]+=1
q=2*np.sin(np.pi*np.fft.fftfreq(n))
q2=sum(x*x for x in np.ix_(q,q,q))
kernel=np.zeros_like(q2)
kernel[q2>0]=-1/q2[q2>0]
phi=np.fft.ifftn(kernel*np.fft.fftn(rho)).real
h=mat(lambda i,j:-2*(i==j)*phi)
zero=np.zeros_like(h)
dh,dp=canonical_rhs(h,zero,phi,zero[0],zero)
c,m=constraints(h,zero,rho,zero[0])
residual=peak(dh,dp,c,m,lap(phi)-rho)
assert residual<1e-12
# Sum outward normal gradients over the six faces of a 5^3 cube.
rad=2
flux=0.
for i in AX:
grad=derivatives(phi,0,i)
transverse=[j for j in AX if j!=i]
for x,y in product(range(-rad,rad+1),repeat=2):
pos=[0]*3
pos[transverse[0]],pos[transverse[1]]=x,y
pos[i]=rad
flux+=grad[tuple(pos)]
pos[i]=-rad-1
flux-=grad[tuple(pos)]
expected=1-(2*rad+1)**3/n**3
assert abs(flux-expected)<1e-12 and phi[0,0,0]<0
# A divergence-free transverse stress with no density.
# Specify the stress from a compact scalar f: S_ij=(delta_ij Lap-D_i D_j)f.
source=zero[0,0].copy()
source[1,2,0]=1
source-=np.mean(source)
stress=-hessian_trace_adjusted(source)
lapse=ALPHA*source/2 # Delta n = ALPHA*tr(S)/4
_,dp=canonical_rhs(zero,zero,lapse,zero[0],stress)
assert peak(div_tensor(stress),dp,lap(lapse)-ALPHA*trace(stress)/4)<1e-12
return phi[0,0,0], flux, residual
def main():
print("Bianchi and pure-gauge identities max residual",check_bianchi())
print("Canonical Hamiltonian gradient and constraint identities pass. Unit injected source defect",check_canonical())
count, freq=modes()
print("Nonzero 8^3 momenta with two TT amplitudes",count)
print(f"Equal-length (3,0,0) and (2,2,1) frequencies {freq[0]:.10f}, {freq[1]:.10f}")
omega,coarse,fine=check_waves()
print(f"Oblique TT frequency {omega:.12f}")
for dt,data in ((.04,coarse),(.02,fine)):
print(f"dt {dt:.2f} displacement error {data[0]:.10g}, constraint {data[1]:.3g}, relative energy drift {data[2]:.3g}")
phi,flux,error=static_source()
print(f"Newtonian central potential {phi:.12f}, outward flux {flux:.12f}, canonical residual {error:.3g}")
if __name__=="__main__":
main()
network_polarization.py
"""GW170814 three-site polarization projections. Default uses frozen filter statistics."""
import argparse
from hashlib import sha256
from math import asin, atan2, cos, degrees, pi, radians, sin, sqrt
from pathlib import Path
from urllib.request import urlopen
# Earth-fixed coordinates (metres) and upper triangles of the dimensionless response
# tensors, in Hanford, Livingston, Virgo order. Signs follow LAL's calibrated arms.
SITES = (
((-2161414.92636, -3834695.17889, 4600350.22664),
(-.3926140964, -.07761341333, -.24738904834, .31952407956, .22799783945, .07309003174)),
((-74276.0447238, -5496283.71971, 3224257.01744),
(.41128087044, .14021027088, .24729458988, -.10900568962, -.18161563575, -.30227515101)),
((4546374.099, 842989.697626, 4378576.96241),
(.24387404323, -.09908378124, -.23257622123, -.44782584906, .18783310056, .20395180583)),
)
C_LIGHT = 299792458
GMST = 2.1069911633280825 # radians, LAL at GPS 1186741861.53
SKY_RA, SKY_DEC = 47.75, -44.95 # rounded collaboration maximum under its tensor model
STRAIN_BASE = "https://dcc.ligo.org/public/0146/P1700341/001/"
SHA = (
"83c965394a55108091c689c1c458fa18410dbbe4fee32364d905e0562471262d",
"6f18a52d8e2466dbb092ad8be503943d83dee8a24bf0c5b11b93aa943cdd430f",
"b3b00c0feba1d0325f3568f9b908510bdd2f9bce5bd45e2c93acb677fc7f74d2",
)
# (detector-frame solar masses; relative filter sensitivities; three complex data)
FILTERS = (
((33, 28), (.7704872009, 1., .2959552981),
(8.99096383-3.32458103j, -9.44824868+8.58617363j, -2.53983568+3.66434072j)),
((31, 26), (.7629674488, 1., .2946010733),
(-4.24131485-8.37497967j, 8.61143832+7.86294126j, 4.11397132+1.03630722j)),
((35, 30), (.7755986376, 1., .2981250956),
(2.93852993+8.42863832j, -8.15056934-8.02792036j, -3.32966049-2.96057840j)),
)
PEAK_DELAYS = (.00838512586, .01470144625)
PEAK_DATA = (9.13960908-2.90041434j, -10.03895340+7.90796850j, -4.25513131+1.74949373j)
def dot(a, b):
return sum(x*y for x, y in zip(a, b))
def cross(a, b):
return (a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0])
def unit(v):
scale = sqrt(dot(v, v))
return tuple(x/scale for x in v)
def direction(ra, dec):
phi, lat = radians(ra)-GMST, radians(dec)
return (cos(phi)*cos(lat), sin(phi)*cos(lat), sin(lat))
def coordinates(n):
return degrees(atan2(n[1], n[0])+GMST) % 360, degrees(asin(n[2]))
def baselines():
return [tuple((a-b)/C_LIGHT for a, b in zip(SITES[i][0], SITES[1][0])) for i in (0, 2)]
def timing_pair(h_minus_l, v_minus_l):
a, b = baselines()
aa, ab, bb = dot(a, a), dot(a, b), dot(b, b)
det = aa*bb-ab*ab
ca = (-bb*h_minus_l+ab*v_minus_l)/det
cb = (ab*h_minus_l-aa*v_minus_l)/det
plane = tuple(ca*x+cb*y for x, y in zip(a, b))
height = sqrt(1-dot(plane, plane))
normal = unit(cross(a, b))
return sorted([tuple(x+s*height*y for x, y in zip(plane, normal)) for s in (-1, 1)],
key=lambda n: coordinates(n)[1])
def antenna(n):
p = unit(cross((0, 0, 1), n))
q = cross(n, p)
rows = []
for _, (xx, xy, xz, yy, yz, zz) in SITES:
tensor = ((xx, xy, xz), (xy, yy, yz), (xz, yz, zz))
def product(a, b):
return sum(x*dot(row, b) for x, row in zip(a, tensor))
pp, qq = product(p, p), product(q, q)
rows.append((pp-qq, 2*product(p, q), 2*product(p, n), 2*product(q, n), pp+qq))
return rows
def project(direction_vector, sensitivity, data):
response = antenna(direction_vector)
columns = [tuple(s*r[k] for s, r in zip(sensitivity, response)) for k in range(5)]
# For rank two, a unit vector perpendicular to both real antenna columns
# annihilates both arbitrary complex amplitudes. For rank one, remove its projection.
tnull = unit(cross(*columns[:2]))
vnull = unit(cross(*columns[2:4]))
breath = unit(columns[4])
total = sum(abs(z)**2 for z in data)
return abs(dot(tnull, data)), abs(dot(vnull, data)), sqrt(max(0, total-abs(dot(breath, data))**2))
def replay():
n = direction(SKY_RA, SKY_DEC)
dt = [-dot(b, n) for b in baselines()]
south, north = timing_pair(*dt)
assert max(abs(x-y) for x, y in zip(south, n)) < 1e-10
for v in (south, north):
assert max(abs(-dot(b, v)-d) for b, d in zip(baselines(), dt)) < 1e-12
print("Fixed delays H-L and V-L (ms):", *(f"{v*1000:.5f}" for v in dt))
for masses, sensitivity, strain in FILTERS:
left, right = (project(d, sensitivity, strain) for d in (south, north))
assert left[0] < 1.52 and right[0] > 5.2
print("Masses", masses, "tensor residuals", f"{left[0]:.5f}", f"{right[0]:.5f}")
if masses == (33, 28):
assert abs(left[0]-.94915975) < 1e-6 and abs(right[0]-5.66717107) < 1e-6
print("Tensor/vector/scalar:", [round(v, 5) for v in left], [round(v, 5) for v in right])
for sky, fit in ((south, left), (north, right)):
antenna_rows = antenna(sky)
matrix = [tuple(s*r[k] for s, r in zip(sensitivity, antenna_rows)) for k in (0, 1)]
weights = unit(cross(*matrix))
virgo = -(weights[0]*strain[0]+weights[1]*strain[1])/weights[2]
assert abs(abs(weights[2]*(strain[2]-virgo))-fit[0]) < 1e-8
print(f"Virgo from the two LIGO amplitudes: {virgo:.3f}; observed {strain[2]:.3f}")
print("Independent peak-time solutions:")
for d, expected in zip(timing_pair(*PEAK_DELAYS), (2.50016, 5.99940)):
result = project(d, FILTERS[0][1], PEAK_DATA)[0]
assert abs(result-expected) < .00002
print("RA and dec (deg), tensor residual:", *(f"{a:.5f}" for a in (*coordinates(d), result)))
def raw_check(folder):
"""Regenerate the compressed statistics and fixed-window background from GWOSC."""
import numpy as np
import lal
import lalsimulation as ls
from scipy.signal import periodogram, windows
folder.mkdir(exist_ok=True, parents=True)
records = []
for site, pin in zip("HLV", SHA):
name = f"{site}-{site}1_LOSC_CLN_4_V1-1186741845-32.txt.gz"
path = folder/name
if not path.exists():
with urlopen(STRAIN_BASE+name, timeout=60) as response:
data = response.read()
if sha256(data).hexdigest() != pin:
raise ValueError(f"Unexpected download for {name}")
path.write_bytes(data)
if sha256(path.read_bytes()).hexdigest() != pin:
raise ValueError(f"Different strain file at {path}")
records.append(np.loadtxt(path))
fs, duration = 4096, 32
count = fs*duration
frequency = np.fft.rfftfreq(count, 1/fs)
keep = np.flatnonzero((frequency>=30) & (frequency<=300))
frequency = frequency[keep]
spectra, noises = [], []
for data in records:
spectra.append(np.fft.rfft(windows.tukey(count, alpha=.12)*data)[keep]/fs)
pieces = []
for start in range(31):
if 14 <= start <= 18:
continue
bins, spectrum = periodogram(data[start*fs:(start+2)*fs], fs, window="hann")
pieces.append(spectrum)
noises.append(np.interp(frequency, bins, np.mean(pieces, axis=0)))
n = direction(SKY_RA, SKY_DEC)
delay_h, delay_v = [-dot(b, n) for b in baselines()]
delays = np.array([delay_h, 0., delay_v])
sample_times = np.arange(count)/fs
for masses, sensitivities, frozen in FILTERS:
h, _ = ls.SimInspiralChooseFDWaveform(
masses[0]*lal.MSUN_SI, masses[1]*lal.MSUN_SI, 0., 0., 0., 0., 0., 0.,
1e8*lal.PC_SI, 0., 0., 0., 0., 0., 1/duration, 25., 512., 30.,
lal.CreateDict(), ls.IMRPhenomD)
template = h.data.data[keep]
norms, aligned, unshifted, products = [], [], [], []
for spectrum, noise, delay in zip(spectra, noises, delays):
norm = np.sqrt(4/duration * np.sum(abs(template)**2/noise))
norms.append(norm)
coefficients = 4/duration * spectrum*np.conjugate(template)/noise/norm
products.append(coefficients)
bins = np.zeros(count, dtype=complex)
bins[keep] = coefficients
unshifted.append(np.fft.ifft(bins)*count)
bins[keep] *= np.exp(2j*np.pi*frequency*delay)
aligned.append(np.fft.ifft(bins)*count)
aligned = np.asarray(aligned)
ratios = np.array(norms)/norms[1]
on = np.flatnonzero((sample_times>16.48) & (sample_times<16.57))
tick = on[np.argmax(abs(aligned[1, on]))]
measured = aligned[:, tick]
assert np.allclose(ratios, sensitivities, rtol=2e-6)
assert np.allclose(measured, frozen, rtol=2e-5, atol=2e-5)
print("Raw strain agrees for masses", masses, "site SNRs", np.abs(measured).round(3))
if masses != (33, 28):
continue
times, independent_data = [], []
for signal, coeff in zip(unshifted, products):
lo, hi = int(16.48*fs), int(16.60*fs)
mid = lo + np.argmax(np.abs(signal[lo:hi]))
left, center, right = np.abs(signal[mid-1:mid+2])**2
t = (mid+.5*(left-right)/(left-2*center+right))/fs
times.append(t)
independent_data.append(np.sum(coeff*np.exp(2j*np.pi*frequency*t)))
assert np.allclose(np.array(times)[[0, 2]]-times[1], PEAK_DELAYS, atol=2e-8, rtol=0)
assert np.allclose(independent_data, PEAK_DATA, rtol=2e-5)
for sky in timing_pair(delay_h, delay_v):
off = []
for mid in np.r_[np.arange(3,13.01,.25),np.arange(20,29.01,.25)]:
window = np.arange(int((mid-.045)*fs), int((mid+.045)*fs)+1)
j = window[np.argmax(abs(aligned[1, window]))]
off.append(project(sky, ratios, aligned[:,j])[0])
print("78 control windows, 10th/50th/90th percentile null:",
np.percentile(off, (10, 50, 90)).round(4))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--from-strain", type=Path, help="cache and analyze the three checksum-pinned GWOSC files")
args = parser.parse_args()
replay()
if args.from_strain:
raw_check(args.from_strain)
quadrupole_exchange.py
"""Exchange between one mechanical quadrupole and transverse tensor modes (NumPy)."""
from itertools import product
import numpy as np
G, SIGMA, OMEGA = .15, .6, 1.2
LBOX = 4*np.pi
S = np.diag([1.,-1.,0.])/np.sqrt(2)
def transverse(n):
p=np.eye(3)-np.outer(n,n)
transverse_stress=p@S@p
return transverse_stress-p*np.trace(transverse_stress)/2
def polarizations(n):
seed=np.eye(3)[np.argmin(np.abs(n))]
u=np.cross(n,seed)
u/=np.linalg.norm(u)
v=np.cross(n,u)
return (np.outer(u,u)-np.outer(v,v))/np.sqrt(2),(np.outer(u,v)+np.outer(v,u))/np.sqrt(2)
def angular_check():
nodes,weights=np.polynomial.legendre.leggauss(12)
total=0.
for mu,w in zip(nodes,weights):
s=np.sqrt(1-mu**2)
for az in np.arange(24)*2*np.pi/24:
n=np.array([s*np.cos(az),s*np.sin(az),mu])
proj=transverse(n)
power=np.sum(proj**2)
assert abs(power-sum(np.sum(e*S)**2 for e in polarizations(n)))<2e-15
total+=w*power/48
assert abs(total-.4*np.sum(S**2))<2e-15
return total
def discrete_modes(cut):
labels=[]; magnitudes=[]; couplings=[]
v=LBOX**3
for triple in product(range(-cut,cut+1),repeat=3):
m=np.array(triple)
first_nonzero=next((x for x in triple if x),0)
if first_nonzero<=0:
continue
norm2=m@m
if norm2>cut**2:
continue
k=2*np.pi*np.sqrt(norm2)/LBOX
W=np.exp(-SIGMA**2*k**2/2)
for pol,e in enumerate(polarizations(m/np.sqrt(norm2))):
g=-np.sqrt(4*np.pi*G/v)*W*np.sum(e*S)
labels.append((*triple,pol))
magnitudes.append(k)
couplings.append(g)
return labels,np.asarray(magnitudes),np.asarray(couplings)
def velocities(p,g):
v=np.empty_like(p)
v[0]=(p[0]-g@p[1:])/(1-g@g)
v[1:]=p[1:]-g*v[0]
return v
def evolve(y,p,g,w,t,steps):
dt=t/steps
y,p=y.copy(),p.copy()
w2=w*w
for _ in range(steps):
p-=dt*w2*y/2
y+=dt*velocities(p,g)
p-=dt*w2*y/2
return y,velocities(p,g)
def energies(y,v,g,w):
return np.array([.5*(v[0]**2+(w[0]*y[0])**2),
.5*(v[1:]@v[1:]+(w[1:]*y[1:])@(w[1:]*y[1:])),
v[0]*(g@v[1:])])
def normal_release(k,g,t):
# At equal bare frequency only the combination parallel to g couples.
shells,inv=np.unique(k,return_inverse=True)
b=np.sqrt(np.bincount(inv,weights=g*g))
mass=np.eye(len(b)+1)
mass[1:,0]=mass[0,1:]=b
stiffness=np.diag(np.r_[OMEGA,shells]**2)
d,u=np.linalg.eigh(mass)
assert min(d)>0
im=(u*d**(-.5))@u.T
sm=(u*d**.5)@u.T
q,v=np.linalg.eigh(im@stiffness@im)
f=np.sqrt(q)
initial=v.T@sm[:,0]
y=im@v@(np.cos(f*t)*initial)
dy=im@v@(-f*np.sin(f*t)*initial)
return energies(y,dy,b,np.r_[OMEGA,shells])
def box_test(cut=8):
labels,k,g=discrete_modes(cut)
assert g@g<1
w=np.r_[OMEGA,k]
z=np.zeros_like(w)
tc=6.
mech=z.copy(); mech[0]=1.
exact=normal_release(k,g,tc)
for steps in (600,1200):
y,v=evolve(mech,z,g,w,tc,steps)
e=energies(y,v,g,w)
error=np.max(abs(e-exact))
if steps==600:
coarse=error
else:
assert 3.8<coarse/error<4.2
assert abs(sum(exact)-OMEGA**2/2)<1e-12 and exact[1]>.05
# True initial field displacement with zero velocity in every degree of freedom.
j=1+labels.index((0,0,2,0))
j_dark=1+labels.index((0,0,2,1))
incoming=z.copy(); incoming[j]=OMEGA/w[j]
y,v=evolve(incoming,z,g,w,tc,1200)
absorption=energies(y,v,g,w)[0]
incoming_dark=z.copy(); incoming_dark[j_dark]=OMEGA/w[j_dark]
y,v=evolve(incoming_dark,z,g,w,tc,1200)
assert absorption>1e-5 and abs(y[0])+abs(v[0])<1e-14
# Impulses specify canonical momentum rather than bare velocity.
pj=z.copy(); pj[j]=1.
out,_=evolve(z,mech,g,w,tc,1200)
back,_=evolve(z,pj,g,w,tc,1200)
assert abs(out[j]-back[0])<1e-12
return len(g),g@g,exact,error,absorption,out[j]
def fourier_q(k,width):
return width*np.sqrt(np.pi/2)*(np.exp(-.5*width**2*(k-OMEGA)**2)
+np.exp(-.5*width**2*(k+OMEGA)**2))
def packet_box(nper,width):
# Full list of signed k uses the complex convention, with the reality factor.
kmax=4.5
k=np.arange(-int(kmax*nper),int(kmax*nper)+1)/nper
x,y,z=np.ix_(k,k,k)
k2=x*x+y*y+z*z
safe=np.where(k2==0,1,k2)
# STF unit S=diag(1,-1,0)/sqrt(2). Contract projector explicitly.
tt=1-(x*x+y*y)/safe+(x*x-y*y)**2/(4*safe**2)
weight=tt*np.exp(-SIGMA**2*k2)*k2**2*fourier_q(np.sqrt(k2),width)**2
return np.pi*G*np.sum(np.where(k2<=kmax**2,weight,0))/(2*np.pi*nper)**3
def packet_test(angular):
width=3.
nodes,weights=np.polynomial.legendre.leggauss(100)
k=3*(nodes+1)
f=fourier_q(k,width)
# Start with one-half g^2 k^4 |Qhat|^2 per real mode, then integrate its density.
e_modes=(np.pi*G/(2*np.pi)**3)*4*np.pi*angular*np.sum(3*weights*np.exp(-SIGMA**2*k*k)*k**6*f**2)
variance=width**2+SIGMA**2
nu=OMEGA*width**2/variance
amp=width/np.sqrt(variance)*np.exp(-OMEGA**2*width**2*SIGMA**2/(2*variance))
t=np.linspace(-10*np.sqrt(variance),10*np.sqrt(variance),4097)
d=-t/variance+1j*nu
q3=(amp*(d**3-3*d/variance)*np.exp(-t*t/(2*variance)+1j*nu*t)).real
e_time=G/5*np.sum(q3*q3)*(t[1]-t[0])
assert abs(e_modes-e_time)<1e-12
sums=[packet_box(n,width) for n in (2,4,8)]
assert abs(sums[-1]-e_time)<1e-11 and abs(sums[0]-e_time)>1e-5
return e_time,sums
def source_check():
k=np.array([.3,-1.7,.8])
sd=S@k
# Suppress the common W(k)/2. Use time derivatives of a freely chosen history.
q,dq,ddq=.7,-.8,1.3
rho=-q*(k@sd)
drho=-dq*(k@sd)
j=-1j*dq*sd
dj=-1j*ddq*sd
stress=ddq*S
assert abs(drho+1j*k@j)<1e-15 and np.max(abs(dj+1j*k@stress))<1e-15
# Compute mass moments from the differentiated Gaussian (Gauss-Hermite quadrature).
nodes,weights=np.polynomial.hermite.hermgauss(5)
monopole=0.
dipole=np.zeros(3)
quadrupole=np.zeros((3,3))
for ix in product(range(len(nodes)),repeat=3):
v=np.sqrt(2)*SIGMA*nodes[list(ix)]
prob=np.prod(weights[list(ix)])/np.pi**1.5
dm=prob*q*(v@S@v)/(2*SIGMA**4)
monopole+=dm
dipole+=dm*v
quadrupole+=dm*(np.outer(v,v)-np.eye(3)*(v@v)/3)
assert max(abs(monopole),np.max(abs(dipole)),np.max(abs(quadrupole-q*S)))<1e-14
def main():
source_check()
ang=angular_check()
print(f"angular TT mean {ang:.12f}")
for cut in (6,8):
size,coupling,e,error,absorb,recip=box_test(cut)
print(f"cut={cut} cosine polarization coordinates={size}, sum(g^2)={coupling:.9f}")
print(f"release t=6: mechanical={e[0]:.10f}, field={e[1]:.10f}, interaction={e[2]:+.10f}, total={sum(e):.10f}, Verlet max error={error:.3g}")
print(f"axial mode preparation transfers mechanical energy={absorb:.9f}; reciprocal unit-impulse displacements={recip:+.9f}")
power=G*OMEGA**6*np.exp(-SIGMA**2*OMEGA**2)/10
energy,sums=packet_test(ang)
print(f"monochromatic mean power={power:.10f}; continuum packet energy={energy:.12f}")
print("periodic packet energy at L/(2*pi)=2,4,8:",*(f"{e:.12f}" for e in sums))
if __name__=="__main__":
main()
wave_weight.py
"""Vacuum Einstein CMC initial data on a cubic three-torus. Requires NumPy."""
import numpy as np
AX = range(3)
K_WAVE = 1 # box periods 2*pi in all directions, c=1
def conformal_tensor(z, a, quadrature=False):
"""Contravariant TT seed referred to the flat conformal metric."""
scale = a/np.sqrt(2) if quadrature else a
tensor = np.zeros((len(z), 3, 3))
tensor[:, 0, 0] = scale*np.cos(K_WAVE*z)
tensor[:, 1, 1] = -tensor[:, 0, 0]
if quadrature:
tensor[:, 0, 1] = tensor[:, 1, 0] = scale*np.sin(K_WAVE*z)
return tensor
def solve(a, n=48, quadrature=False):
"""Solve simultaneously for a positive conformal factor and K squared."""
z = 2*np.pi*np.arange(n)/n
seed = conformal_tensor(z,a,quadrature)
seed2 = np.sum(seed**2,axis=(1,2))
freq = np.fft.fftfreq(n,1/n)
lap = np.fft.ifft(-freq[:,None]**2*np.fft.fft(np.eye(n),axis=0),axis=0).real
psi = np.ones(n)
k2 = 1.5*np.mean(seed2)
def residual(p,s):
return np.r_[lap@p + seed2*p**(-7)/8 - s*p**5/12, np.mean(p**6)-1]
for _ in range(12):
error = residual(psi,k2)
if max(abs(error)) < 3e-13:
break
jac = np.empty((n+1,n+1))
jac[:-1,:-1] = lap + np.diag(-7*seed2*psi**(-8)/8 - 5*k2*psi**4/12)
jac[:-1,-1] = -psi**5/12
jac[-1,:-1] = 6*psi**5/n
jac[-1,-1] = 0
delta = np.linalg.solve(jac,-error)
psi += delta[:-1]
k2 += delta[-1]
assert min(psi)>0 and k2>=0
else:
raise ArithmeticError("nonlinear spectral solve did not converge")
expected = 1.5*np.mean(seed2*psi**(-7))/np.mean(psi**5)
assert abs(k2-expected) < 1e-11
return psi,k2
def interpolate(psi,z):
"""Independently sample the periodic interpolant at staggered verification points."""
n=len(psi)
modes=np.fft.fftfreq(n,1/n)
return (np.exp(1j*np.outer(z,modes))@(np.fft.fft(psi)/n)).real
def physical_constraints(psi_seed, k2, a, n, quadrature=False, defect=0, sign=-1):
"""Reconstruct physical tensors, finite-difference Christoffels and contract Ricci."""
z=2*np.pi*(np.arange(n)+0.375)/n
dz=2*np.pi/n
psi=interpolate(psi_seed,z)
metric=psi[:,None,None]**4*np.eye(3)[None,:,:]
inverse=np.linalg.inv(metric)
mean=sign*np.sqrt(k2)
extrinsic=psi[:,None,None]**(-10)*conformal_tensor(z,a,quadrature) + mean*inverse/3
# Deliberately non-conserved shear for the detector-sensitivity check.
extrinsic[:,0,2]+=defect*np.sin(z)
extrinsic[:,2,0]+=defect*np.sin(z)
def diff(x,i):
if i!=2:
return np.zeros_like(x)
return (np.roll(x,2,axis=0)-8*np.roll(x,1,axis=0)+8*np.roll(x,-1,axis=0)
-np.roll(x,-2,axis=0))/(12*dz)
metric_grad=[diff(metric,i) for i in AX]
christ=np.zeros((n,3,3,3))
for k in AX:
for i in AX:
for j in AX:
christ[:,k,i,j]=sum(inverse[:,k,l]*(metric_grad[i][:,l,j]+metric_grad[j][:,l,i]
-metric_grad[l][:,i,j])/2 for l in AX)
ricci=np.zeros_like(metric)
for i in AX:
for j in AX:
for k in AX:
ricci[:,i,j]+=diff(christ[:,k,i,j],k)-diff(christ[:,k,i,k],j)
for l in AX:
ricci[:,i,j]+=(christ[:,k,k,l]*christ[:,l,i,j]
-christ[:,k,j,l]*christ[:,l,i,k])
scalar=np.einsum("nij,nij->n",inverse,ricci)
physical_trace=np.einsum("nij,nij->n",metric,extrinsic)
fully_lowered=metric@extrinsic@metric
norm=np.einsum("nij,nij->n",extrinsic,fully_lowered)
ham=scalar+physical_trace**2-norm
mom=np.zeros((n,3))
for i in AX:
for j in AX:
mom[:,i]+=diff(extrinsic[:,i,j],j)-inverse[:,i,j]*diff(physical_trace,j)
for l in AX:
mom[:,i]+=(christ[:,i,j,l]*extrinsic[:,l,j]
+christ[:,j,j,l]*extrinsic[:,i,l])
return np.max(np.abs(ham)),np.max(np.abs(mom)),np.max(abs(physical_trace-mean))
def observables(p,k2):
z=2*np.pi*np.arange(len(p))/len(p)
coeff=2*np.mean((p-1)*np.cos(2*K_WAVE*z))
return np.sqrt(k2)/3,coeff
def main():
for a in (.05,.2,.6):
p,s=solve(a)
ref,rs=solve(a,32)
h,mode=observables(p,s)
assert abs(s-rs)<1e-11 and abs(mode-observables(ref,rs)[1])<1e-12
assert abs(np.mean(p**6)-1)<2e-13
leading=a*a/(32*K_WAVE**2)
ratio=s/(1.5*a*a)
small_prediction=1-7*a*a/(64*K_WAVE**2)
if a<=.2:
refined=small_prediction+33*(a/K_WAVE)**4/512
assert abs(ratio-refined)<abs(ratio-small_prediction)/10
harmonic2=leading-3*(a/K_WAVE)**4/256
assert abs(mode-harmonic2)<abs(mode-leading)/10
print(f"a={a:.2f} K^2={s:.12f} |H|={h:.9f} "
f"psi_2k={mode:.10f} leading={leading:.10f} K^2/leading={ratio:.9f}")
p,s=solve(.6)
errors=[]
for n in (64,128,256):
ec,em,et=physical_constraints(p,s,.6,n)
errors.append(ec)
print(f"direct tensors n={n}: max Hamiltonian={ec:.4g} momentum={em:.4g} trace error={et:.3g}")
assert em<1e-5 and et<2e-15
assert min(errors[0]/errors[1],errors[1]/errors[2])>14 and errors[-1]<3e-7
ec,em,_=physical_constraints(p,s,.6,256,sign=1)
assert ec<3e-7 and em<1e-7
_,bad,_=physical_constraints(p,s,.6,256,defect=.01)
assert bad>.009
a=.6
p,s=solve(a,quadrature=True)
ec,em,_=physical_constraints(p,s,a,128,quadrature=True)
assert np.max(abs(p-1))<1e-12 and abs(s-1.5*a*a)<1e-12
assert max(ec,em)<1e-10
print(f"same mean TT seed norm, quadrature: psi error={max(abs(p-1)):.3g} "
f"K^2={s:.9f}; imposed spurious longitudinal shear momentum defect={bad:.6g}")
if __name__=="__main__":
main()
constraint_closure.py
"""Off-shell normal-deformation brackets on a nonlinear three-dimensional spatial metric."""
import numpy as np
class Slice:
def __init__(self,n,phase):
self.n=n
self.k=np.fft.fftfreq(n,1/n)
# Real periodic fields. Remove the single even-grid Nyquist derivative.
if n%2==0:self.k[n//2]=0.
x,y,z=np.meshgrid(*(3*[2*np.pi*np.arange(n)/n]),indexing="ij")
sin,cos=np.sin,np.cos
p=phase
g=np.zeros(x.shape+(3,3))
g[...,0,0]=1+.13*cos(y+z+p)+.08*sin(x)
g[...,1,1]=1+.14*sin(x+y-p)
g[...,2,2]=1+.11*cos(y)+.07*sin(2*z+p)
g[...,0,1]=g[...,1,0]=.075*cos(x-y)
g[...,1,2]=g[...,2,1]=.055*sin(x+z+p)
g[...,2,0]=g[...,0,2]=.04*cos(z-y)
self.g=g
mom=np.zeros_like(g)
mom[...,0,0]=.5*cos(x+p)+.24*sin(y)
mom[...,1,1]=.4*cos(x)-.3*sin(x+y+z)
mom[...,2,2]=.26*sin(z+p)+.2*cos(x-y)
mom[...,0,1]=mom[...,1,0]=.15*sin(x-y+p)
mom[...,1,2]=mom[...,2,1]=.12*cos(x+z)
mom[...,2,0]=mom[...,0,2]=.10*sin(y-z)
self.P=mom
self.field=.5*sin(x+y)+.31*cos(x-z+p)+.16*sin(z)
self.p=.55+.19*cos(y)+.12*sin(x-z)
self.lapse=1+.30*cos(x+y)+.18*sin(z+p)+.11*cos(x)
self.second=.30*sin(x+y+p)+.27*cos(y+z)+.18*sin(x)
self.inv=np.linalg.inv(g)
self.root=np.sqrt(np.linalg.det(g))
self.dg=self.gradient(g)
self.df=self.gradient(self.field)
self.trace=np.einsum('...ij,...ij->...',g,mom)
def gradient(self,x):
outs=[]
for axis in range(3):
shape=[1]*x.ndim
shape[axis]=self.n
k=self.k.reshape(shape)
outs.append(np.fft.ifft(1j*k*np.fft.fft(x,axis=axis),axis=axis).real)
return np.stack(outs,axis=3)
def curvature(self,g,inv):
# d[...,i,j,k] = partial_i g_jk; Γ[...,i,j,k] = Γ^i_jk.
d=self.gradient(g)
lower=d.swapaxes(-3,-2)+d.swapaxes(-3,-1)-d
connection=.5*np.einsum('...ia,...ajk->...ijk',inv,lower)
dc=self.gradient(connection)
ricci=np.einsum('...kkij->...ij',dc)-np.einsum('...jkik->...ij',dc)
ricci+=np.einsum('...kkl,...lij->...ij',connection,connection)
ricci-=np.einsum('...kjl,...lik->...ij',connection,connection)
return np.einsum('...ij,...ij->...',inv,ricci)
def matter(self,s,y,model):
if model=="canonical":return s+y,np.ones_like(s),np.ones_like(s)
if model=="slow":return s+.62*y,np.ones_like(s),np.full_like(s,.62)
# A nonlinear covariant scalar with tension 1; background gradients change its wave speeds.
ratio=np.sqrt((1+2*y)/(1+2*s))
return np.sqrt((1+2*s)*(1+2*y))-1,ratio,1/ratio
def energy(self,g,field,lapse,A,B,weight,model,cosm=.037):
inv=np.linalg.inv(g)
root=np.sqrt(np.linalg.det(g))
low=g@self.P@g
tr=np.einsum('...ij,...ij->...',g,self.P)
pp=np.einsum('...ij,...ij->...',low,self.P)
gravity=A*(pp-weight*tr*tr)/root-B*root*self.curvature(g,inv)+cosm*root
df=self.gradient(field)
y=.5*np.einsum('...i,...ij,...j->...',df,inv,df)
F=self.matter(.5*(self.p/root)**2,y,model)[0]
potential=.17*field**2+.053*field**4
return np.mean(lapse*(gravity+root*(F+potential)))
def bracket(self,A,B,weight,model,eps=1e-5):
g,P,N,M=self.g,self.P,self.lapse,self.second
root=self.root
low=g@P@g
v=2*A*(low-weight*self.trace[...,None,None]*g)/root[...,None,None]
y=.5*np.einsum('...i,...ij,...j->...',self.df,self.inv,self.df)
_,Fs,Fy=self.matter(.5*(self.p/root)**2,y,model)
u=Fs*self.p/root
# {H[N],H[M]} from directional changes of the actual Hamiltonian functional.
# Neither curvature variation nor the expected momentum constraint is used here.
def direction(test,step):
dg=eps*step[...,None,None]*v
df=eps*step*u
return (self.energy(g+dg,self.field+df,test,A,B,weight,model)-
self.energy(g-dg,self.field-df,test,A,B,weight,model))/(2*eps)
raw=direction(N,M)-direction(M,N)
lower=N[...,None]*self.gradient(M)-M[...,None]*self.gradient(N)
beta=np.einsum('...ij,...j->...i',self.inv,lower)
dbeta=self.gradient(beta)
lie=np.einsum('...k,...kij->...ij',beta,self.dg)
stretch=np.einsum('...kj,...ik->...ij',g,dbeta)
lie+=stretch+stretch.swapaxes(-2,-1)
gravity=np.mean(np.einsum('...ij,...ij->...',P,lie))
current=self.p*np.einsum('...i,...i->...',beta,self.df)
matter=current.mean()
trace_gradient=self.gradient(self.trace/root)
anomaly=2*np.mean(root*np.einsum('...i,...i->...',beta,trace_gradient))
prediction=A*B*(gravity+(1-2*weight)*anomaly)+np.mean(Fs*Fy*current)
return raw,gravity,matter,anomaly,prediction
def main():
for n in (10,16,24):
state=Slice(n,.41)
if n==24:
coords=2*np.pi*np.arange(n)/n
x,y,z=np.meshgrid(coords,coords,coords,indexing="ij")
wave=.03*np.cos(x+y)+.02*np.sin(z)
conformal=1+wave
g=conformal[...,None,None]**4*np.eye(3)
laplace=-.06*np.cos(x+y)-.02*np.sin(z)
expected=-8*laplace/conformal**5
assert np.max(abs(state.curvature(g,np.linalg.inv(g))-expected))<3e-9
for label,A,B,w,model in [('Einstein + scalar',1.6,.625,.5,'canonical'),
('Einstein + nonlinear scalar',.8,1.25,.5,'DBI'),
('deformed trace',1.6,.625,.43,'canonical'),
('unequal speeds',1.6,.625,.5,'slow')]:
raw,dg,dm,trace,pred=state.bracket(A,B,w,model)
err=raw-pred
print(f'n={n} {label}: bracket={raw:+.9f}, common shift={dg+dm:+.9f}, '
f'defect={raw-dg-dm:+.9f}, analytic residual={err:+.3g}')
if n==24:
assert abs(err)<1e-7
if model=='slow' or w!=.5:assert abs(raw-dg-dm)>.0001
# Fit the single common coefficient and the trace anomaly on two preparations,
# then compare a third phase using the unsimplified numerical functional.
rows=[]
for phase in (.13,.89,1.7):
raw,dg,dm,trace,_=Slice(20,phase).bracket(1.3,.73,.46,'DBI')
rows.append((raw-dm,dg,trace))
fit=np.linalg.solve([r[1:] for r in rows[:2]],[r[0] for r in rows[:2]])
expect=1.3*.73
np.testing.assert_allclose(fit,[expect,expect*(1-2*.46)],atol=2e-6)
held=rows[2]
assert abs(held[0]-np.dot(held[1:],fit))<2e-7
print('Fit AB and AB(1-2lambda):',fit,'held-out residual:',held[0]-np.dot(held[1:],fit))
if __name__=="__main__":
main()
matter_response.py
"""What normal-deformation closure predicts from a homogeneous scalar calibration."""
from math import exp, sqrt
def bump(x):
return exp(x+1/x) if x<0 else 0.
def integrate(func,a,b,n=800):
if a==b:return 0.
h=(b-a)/n
return h*(func(a)+func(b)+4*sum(func(a+j*h) for j in range(1,n,2))+
2*sum(func(a+j*h) for j in range(2,n,2)))/3
def pressure(x,coefficient):
if x>=0:return x,1.,0.
return (x+coefficient*integrate(lambda u:(u-x)*bump(u),x,0.),
1-coefficient*integrate(bump,x,0.),coefficient*bump(x))
def hamiltonian(s,y,coefficient):
momentum=sqrt(2*s)
# P_X is positive and monotone in X. At fixed gradient this map is one-to-one.
low,high=0.,2*momentum+1.
for _ in range(58):
v=(low+high)/2
x=v*v/2-y
_,px,_=pressure(x,coefficient)
if v*px>momentum:high=v
else:low=v
value,px,_=pressure(v*v/2-y,coefficient)
return momentum*v-value
def reconstruct(s,y):
# g(s)=sqrt(1+2s)-1 is measured on the homogeneous edge y=0.
# No spatial-gradient value of the target function enters the root search.
lo,hi=0.,s
if y>s:raise ValueError('This characteristic misses the measured edge.')
for _ in range(58):
t=(hi+lo)/2
slope=1/sqrt(1+2*t)
if t+y/slope**2>s:hi=t
else:lo=t
g=sqrt(1+2*t)-1
return g+2*y/slope
def main():
for s,y in ((.8,.15),(1.2,.51),(2.,.4)):
f=reconstruct(s,y)
exact=sqrt((1+2*s)*(1+2*y))-1
assert abs(f-exact)<2e-14
print(f'homogeneous data continued to (s,y)=({s},{y}): H={f:.9f}')
for s in (.05,.5,1.8):
assert abs(hamiltonian(s,0.,.5)-s)<2e-12
for s,y in ((.25,.1),(.1,1.),(.6,1.3)):
for alpha in (0.,.5):
eps=1e-5
fs=(hamiltonian(s+eps,y,alpha)-hamiltonian(s-eps,y,alpha))/(2*eps)
fy=(hamiltonian(s,y+eps,alpha)-hamiltonian(s,y-eps,alpha))/(2*eps)
assert abs(fs*fy-1)<2e-8
for alpha in (0.,.5):
val,px,pxx=pressure(-1.,alpha)
parallel=sqrt(1-2*pxx/px)
print(f'alpha={alpha:g} on a static gradient |grad phi|=sqrt(2): '
f'energy density={-val:.9f} parallel speed={parallel:.9f} transverse=1')
# Independent check from the Hessian of P(dotphi^2/2-gradphi^2/2).
step=1e-4
grad=sqrt(2.)
def action(v,d):return pressure((v*v-d*d)/2,alpha)[0]
temporal=(action(step,grad)-2*action(0,grad)+action(-step,grad))/step**2
spatial=(action(0,grad+step)-2*action(0,grad)+action(0,grad-step))/step**2
assert abs(sqrt(-spatial/temporal)-parallel)<2e-6
if __name__=="__main__":
main()
moving_samples.py
"""Fixed-site shift obstruction and transport on finite moving spacetime samples."""
from math import pi
import numpy as np
def edge_shift(beta,spacing=1.):
"""Shift that follows from the site kinetic term and an edge-averaged lapse."""
n=len(beta)
matrix=np.zeros((n,n))
for j in range(n):
k=(j+1)%n
for row in (j,k):
matrix[row,j]-=beta[j]/(2*spacing)
matrix[row,k]+=beta[j]/(2*spacing)
return matrix
def basis(nodes,derivative=0):
m=np.arange(1,(len(nodes)+1)//2)
angle=nodes[:,None]*m+derivative*pi/2
constant=np.full((len(nodes),1),float(derivative==0))
return np.column_stack((constant,np.cos(angle)*m**derivative,np.sin(angle)*m**derivative))
def spectral(nodes):
return np.linalg.solve(basis(nodes).T,basis(nodes,1).T).T
def local(nodes):
"""Three-node quadratic derivative for nonuniform periodic coordinates."""
n=len(nodes)
dm=nodes-np.roll(nodes,1)
dm[0]+=2*pi
dp=np.roll(dm,-1)
D=np.zeros((n,n))
ii=np.arange(n)
D[ii,(ii-1)%n]=-dp/(dm*(dm+dp))
D[ii,ii]=(dp-dm)/(dm*dp)
D[ii,(ii+1)%n]=dm/(dp*(dm+dp))
return D
def curvature(nodes,v,w,derivative,eps=1e-6):
d=derivative(nodes)
Av=v[:,None]*d
Aw=w[:,None]*d
if derivative is spectral:
dd=np.linalg.solve(basis(nodes).T,basis(nodes,2).T).T
delta_v=v[:,None]*dd-d@Av
delta_w=w[:,None]*dd-d@Aw
if len(nodes)<=31:
finite=(spectral(nodes+eps*v)-spectral(nodes-eps*v))/(2*eps)
assert np.max(abs(finite-delta_v))<3e-7
else:
delta_v=(derivative(nodes+eps*v)-derivative(nodes-eps*v))/(2*eps)
delta_w=(derivative(nodes+eps*w)-derivative(nodes-eps*w))/(2*eps)
return w[:,None]*delta_v-v[:,None]*delta_w+Aw@Av-Av@Aw
def normal(T,X,sigma,D):
# The unwrapped spatial embedding has winding one.
dT=D@T
dX=1+D@(X-sigma)
e=np.sqrt(dX*dX-dT*dT)
return np.column_stack((dX/e,dT/e)),np.column_stack((dT/e,dX/e)),e
def minkowski(a,b):
return -a[:,0]*b[:,0]+a[:,1]*b[:,1]
def local_lapse_test(n):
sigma=2*pi*np.arange(n)/n
T=.16*np.sin(sigma)+.04*np.sin(2*sigma)
X=sigma+.09*np.cos(2*sigma)
D=local(sigma)
N=1+.22*np.cos(2*sigma)
M=.33*np.sin(sigma)-.14*np.cos(3*sigma)
norm,tan,e=normal(T,X,sigma,D)
def step(A,B,eps):
TN=T+eps*A*norm[:,0]
XN=X+eps*A*norm[:,1]
return B[:,None]*normal(TN,XN,sigma,D)[0]
eps=2e-6
measured=(step(N,M,eps)-step(N,M,-eps)-step(M,N,eps)+step(M,N,-eps))/(2*eps)
beta=(N*minkowski(norm,D@(M[:,None]*norm))-M*minkowski(norm,D@(N[:,None]*norm)))/e**2
continuum=(M*(D@N)-N*(D@M))/e**2
assert np.max(abs(measured-beta[:,None]*e[:,None]*tan))<3e-9
return np.max(abs(beta-continuum))
def main():
v,w=np.eye(9)[:2]
first,second=edge_shift(v),edge_shift(w)
bracket=first@second-second@first
assert bracket[0,2]==.25
assert max(abs(edge_shift(b)[0,2]) for b in np.eye(9))==0
print('Fixed sites: commutator coefficient from site 2 to site 0:',bracket[0,2])
errors=[]
for n in (15,31,63):
x=2*pi*np.arange(n)/n
nodes=x+.08*np.sin(x)
v=.6*np.cos(2*x)+.1
w=.4*np.sin(x)-.15*np.cos(3*x)
wave=np.sin(2*nodes)-.3*np.cos(nodes)
curv_local=curvature(nodes,v,w,local)
curv_full=curvature(nodes,v,w,spectral)
err=np.max(abs(curv_local@wave))
spectral_err=np.max(abs(curv_full@wave))
assert spectral_err<5e-8
lapse_err=local_lapse_test(n)
errors.append((err,lapse_err))
print(f'n={n}: local sampling path defect {err:.7g}; full sampling {spectral_err:.3g}; '
f'discrete vs ordinary normal shift {lapse_err:.7g}')
assert errors[1][0]<errors[0][0]/2.5 and errors[2][0]<errors[1][0]/3
assert errors[2][1]<errors[1][1]/3
# Finite deformations of two chiral massless waves on a prescribed flat spacetime.
n=21
x=2*pi*np.arange(n)/n
t=.11*np.sin(x)
X=x+.06*np.cos(2*x)
rng=np.random.default_rng(216)
for sign in (-1,1):
U=X+sign*t
U1=U+.03*np.cos(3*x)
U2=U+.05*np.sin(x)
dest=U1+U2-U
coeff=rng.standard_normal(n)
data=basis(U)@coeff
def transfer(a,b,f):
return basis(b)@np.linalg.solve(basis(a),f)
one=transfer(U1,dest,transfer(U,U1,data))
two=transfer(U2,dest,transfer(U,U2,data))
assert np.max(abs(one-two))<2e-12
assert np.max(abs(one-basis(dest)@coeff))<2e-12
print('Both chiral records agree around finite moving-node paths.')
if __name__=="__main__":
main()
convex_cover.py
"""Exact covers of phase-unresolved readout windows in the six-stage Pauli walk."""
from collections import defaultdict
from fractions import Fraction as F
from itertools import combinations, product
from math import ceil, log, log1p
CYCLE=(0,1,2,2,1,0)
AXES=range(3)
NORMALS=[p for p in product((-1,0,1),repeat=3) if any(p)]
def projected_twice(axis,s,spin):
"""Apply I+s sigma_axis to a Gaussian-integer spinor, in real/imag pairs."""
r,i,u,v=spin
if axis==0:
return (r+s*u,i+s*v,u+s*r,v+s*i)
if axis==1:
return (r+s*v,i-s*u,u-s*i,v+s*r)
return ((1+s)*r,(1+s)*i,(1-s)*u,(1-s)*v)
def run(steps):
probability=defaultdict(int)
for start in range(6):
for spin in ((1,0,0,0),(0,0,1,0)):
states={(0,0,0):spin}
for t in range(steps):
axis=CYCLE[(start+t)%6]
out=defaultdict(lambda:[0,0,0,0])
for point,values in states.items():
for s in (-1,1):
shifted=list(point)
shifted[axis]+=s
amp=projected_twice(axis,s,values)
for j in range(4):
out[tuple(shifted)][j]+=amp[j]
states={p:v for p,v in out.items() if any(v)}
for p,v in states.items():
probability[p]+=sum(c*c for c in v)
total=12*4**steps
assert sum(probability.values())==total
return {p:F(weight,total) for p,weight in probability.items()}
def dot(x,y):
return sum(a*b for a,b in zip(x,y))
def det(rows):
a,b,c=rows
return (a[0]*(b[1]*c[2]-b[2]*c[1])-a[1]*(b[0]*c[2]-b[2]*c[0])
+a[2]*(b[0]*c[1]-b[1]*c[0]))
def intersection(rows):
A,rhs=zip(*rows)
d=det(A)
if not d:
return None
cols=list(zip(*A))
result=[]
for i in AXES:
changed=cols.copy()
changed[i]=rhs
result.append(F(det(changed),d)) # determinant unchanged by transposition
return tuple(result)
def chamber(a):
rows=[((-1,1,0),0),((0,-1,1),0),((0,0,-1),0),
((1,0,0),a+1),((1,1,0),2*a+1),((1,1,1),3*a+1)]
verts=set()
for chosen in combinations(rows,3):
v=intersection(chosen)
if v is not None and all(dot(row,v)<=b for row,b in rows):
verts.add(v)
return verts
def gauge(v,a):
# Each nonzero signed subset inequality: n.v <= a |n|_1 + 1.
return max(F(dot(n,v),a*sum(abs(i) for i in n)+1) for n in NORMALS)
def shifted(x,c):
return tuple(i-j for i,j in zip(x,c))
def check_cover(a):
verts=chamber(a)
six=1-F(1,3*(2*a+1))
t=F(3*a+1,3*(2*a+1))
axis=(t,0,0)
# Every signed permutation of this chamber uses its own corresponding center.
assert max(gauge(shifted(x,axis),a) for x in verts)==six
centroid=(a+F(1,3),)*3
assert gauge(centroid,a)==1 and 2*centroid[0]/(2*a+1)==six
eighth=F(a+1,2*a+1)
cube=(a*eighth,)*3
assert max(gauge(shifted(x,cube),a) for x in verts)<=eighth
seven_min=F(3*a+1,3*(a+1))
if a:
assert F(3*(a+1),6*a+4)<=eighth<=F(2,3)<seven_min
assert max(gauge(shifted(x,cube),a) for x in verts)==eighth
return six,eighth,seven_min
def verify(n):
a=2*n
sites=run(6*n+1)
corners=set()
for axis in AXES:
lengths=[a]*3
lengths[axis]+=1
for sign in product((-1,1),repeat=3):
corners.add(tuple(k*s for k,s in zip(lengths,sign)))
assert all(gauge(p,a)<=1 for p in sites) and corners<=set(sites)
probability=F(1,6*16**n)
assert all(sites[p]==probability for p in corners)
six,eight,seven_min=check_cover(a)
print(f"{6*n+1} stages: {len(sites)} occupied sites, {len(corners)} vertices,"
f" probability each {probability}, six-axis scale {six}")
if a:
print(f" eight-copy scale between {F(3*(a+1),6*a+4)} and {eight}, seven-copy scale at least {seven_min}")
count=ceil(log(len(corners)/.05)/-log1p(-float(probability)))
# Exact rational check that 24(1-p)^M <= .05 first passes here.
assert len(corners)*(1-probability)**count<=F(1,20)<len(corners)*(1-probability)**(count-1)
print(f" minimum shots meeting 95% union-bound guarantee: {count}")
if __name__=="__main__":
for n in (0,1,2):
verify(n)
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 tensor-clocks calculations and compare the native Tally transcript."""
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,
"72fecb20c9f83442bcf85a0cf68b6aa1104d2edef829fd27e0ea149eae2cbe41": 192,
}
ATOM_SHA = "4c08a122480cb2d6c1efb48b9e868b5b45432d78dc40b339dbe9db7ebdacf02d"
NATIVE_CHECKS = 21
STANDARD = (("matter_response", ()), ("network_polarization", ()), ("convex_cover", ()))
NUMERICAL = (
("tensor_lattice", ()),
("lapse_loop", ("--fine", "--origin", "--unitary")),
("loop_spectrum", ("--fine",)),
("energy_improvement", ("--fine", "--finite")),
("constraint_closure", ()),
("moving_samples", ()),
("wave_weight", ()),
("quadrupole_exchange", ()),
)
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 the SHA-256 of Tally release 184 or 192")
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/"tensor.out").read_text(encoding="utf-8").splitlines()
if sum(row.startswith("✓") for row in expected) != NATIVE_CHECKS:
raise ValueError("The reference transcript has an unexpected number of checks")
with tempfile.TemporaryDirectory() as temp:
work = Path(temp)
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/"tensor.tly", work/"tensor.tly")
result = subprocess.run(
[sys.executable, "-B", str(tally/"tally.py"), "tensor.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 tensor.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="published Tally release 184 or 192 ZIP")
parser.add_argument("--full", action="store_true", help="include all eight NumPy calculations and the publication mesh 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(f"Running {name}.py {' '.join(options)}".rstrip(), 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()