import numpy as np
from fractions import Fraction as F
from collections import Counter
# Integer ladder representation, ascending magnetic weights.
m=range(-2,3); z=np.diag(list(m)).astype(object); p=np.zeros((5,5),dtype=object); q=p.copy()
for i,k in enumerate(list(m)[:-1]): p[i+1,i]=(2-k)*(3+k); q[i,i+1]=1
I5=np.eye(5,dtype=int).astype(object); I=np.eye(125,dtype=int).astype(object)
def total(a): return np.kron(np.kron(a,I5),I5)+np.kron(np.kron(I5,a),I5)+np.kron(np.kron(I5,I5),a)
z,p,q=map(total,(z,p,q)); C=z@z-z+p@q
mu=F(np.trace(C),125); var=F(np.trace(C@C),125)-mu**2
K=(C-mu*I)@(C-mu*I)-var*I; A=K@K
# Independently enumerate spin coupling.
counts=Counter(J for L in range(5) for J in range(abs(L-2),L+3)); levels={J*(J+1):v*(2*J+1) for J,v in counts.items()}
energies={l:((l-mu)**2-var)**2 for l in levels}; gap=min(e for e in energies.values() if e>0); eta=gap/2
P=I.copy()
for e in sorted(set(energies.values())-{0}): P=P@(I-A/e)
assert np.all(P@P==P) and np.all(A@P==0)
r=np.trace(P); assert r==47
assert np.trace(P@(A-eta*I))==-274104
# Exact certificate for A-gap*(I-P) PSD via spectral decomposition.
for l,e in energies.items(): assert e==0 or e>=gap
print('EXACT:',mu,var,gap,eta,r,np.trace(P@(A-eta*I)))
# Hermitian similarity; ascending weights 576,144,24,4,1.
w=np.sqrt(np.kron(np.kron([576,144,24,4,1],[576,144,24,4,1]),[576,144,24,4,1]))
Ch=w[:,None]*np.asarray(C,float)/w[None,:]; assert np.allclose(Ch,Ch.T)
v,U=np.linalg.eigh(Ch); E=((v-float(mu))**2-float(var))**2/float(gap); mask=E<1e-10; E[mask]=0
Ph=U[:,mask]@U[:,mask].T; assert np.max(abs(Ph-w[:,None]*np.asarray(P,float)/w[None,:]))<1e-10
# Seven-qubit system + ancilla, unitary dilation of imaginary-time filter.
# Three padding states receive positive energy 16, not spurious ground states.
E128=np.r_[E,[16]*3]; rng=np.random.default_rng(47); psi=rng.normal(size=125)+1j*rng.normal(size=125); psi/=np.linalg.norm(psi); a=np.r_[U.T@psi,[0j]*3]
for t in [0,1,3,6,12]:
 f=np.exp(-t*E128); s=np.sqrt(np.maximum(0,1-f*f)); state=np.stack([f*a,s*a]); assert abs(np.sum(abs(state)**2)-1)<1e-12
 prob=np.sum(abs(state[0])**2); occ=np.sum(abs(state[0,:125][mask])**2)/prob
 print(f't={t:2} success={prob:.12f} ground={occ:.12f}')
# Exact sharpness: remove one ground direction or add one first-excited direction.
assert eta==gap-eta
print('PASS exact projector, energy census, Hermitian replay, unitary statevector dilation')