"""Independent checks for
"Entanglement as Geometric Correlation: No Communication Needed When Geometry Encodes Everything" (r3).

Recomputes, without the FDT Bell simulation code, every derived statement of the paper.
NumPy only; seeded; a few minutes.

    python3 entanglement-geometric-correlation-fdt-r3-checks.py
"""
import numpy as np
from numpy import pi, sqrt, cos, sin
from numpy.polynomial import legendre as L
rng = np.random.default_rng(20261120)
def P(*a): print(*a)
zeta = lambda x: np.sign(cos(x))

N = 2_000_000
phi = (np.arange(N)+0.5)*2*pi/N; w = 2*pi/N
def tables(a,b,host="A",measure="proj"):
    if measure=="proj": rho = np.abs(cos(phi-a))/4 if host=="A" else np.abs(cos(phi+pi-b))/4
    else: rho = np.full_like(phi,1/(2*pi))
    A = np.sign(cos(phi-a)); B = np.sign(cos(phi+pi-b))
    return (rho*A*B).sum()*w, (rho*(A>0)).sum()*w, (rho*(B>0)).sum()*w, rho.sum()*w
aq=(0,pi/2); bq=(-3*pi/4,3*pi/4)

P("== 1. Kernel theorem: kernel and marginals on the projection measure; triangle on the uniform measure")
errs=[]; merr=[]; terr=[]
for D in np.linspace(-2*pi,2*pi,97):
    a = 0.3; b = a-D
    for host in "AB":
        E,pa,pb,nrm = tables(a,b,host); errs.append(abs(E+cos(D))); merr += [abs(pa-.5),abs(pb-.5),abs(nrm-1)]
    Dm = abs((D+pi)%(2*pi)-pi); terr.append(abs(tables(a,b,measure="uni")[0]-(-1+2*Dm/pi)))
P(f"   max|E+cos D| = {max(errs):.1e} (midpoint rule, 2e6 points)   marginals/normalisation to {max(merr):.1e}   triangle to {max(terr):.1e}")
def S(measure="proj",host="A"):
    e = lambda a,b: tables(a,b,host,measure)[0]
    return e(aq[0],bq[0])+e(aq[0],bq[1])+e(aq[1],bq[0])-e(aq[1],bq[1])
P(f"   CHSH: projection host A {S('proj','A'):.9f}, host B {S('proj','B'):.9f}; uniform {S('uni'):.9f}; 2 sqrt 2 = {2*sqrt(2):.9f}")
a,b=0.4,1.3; rho=np.abs(cos(phi-a))/4; A=np.sign(cos(phi-a)); Bv=np.sign(cos(phi+pi-b))
P(f"   certainty corollary: P(B=+|A=+) = {(rho*(A>0)*(Bv>0)).sum()/(rho*(A>0)).sum():.6f} vs (1-cos(a-b))/2 = {(1-cos(a-b))/2:.6f};"
  f" equal clamps: A*B = -1 at every phase: {bool(np.all(np.sign(cos(phi-a))*np.sign(cos(phi+pi-a))==-1))}")

P("== 2. Sphere theorem: inner-product kernel on the sphere (2e6 records per axis pair)")
def unit(n):
    v=rng.normal(size=(3,n)); return v/np.linalg.norm(v,axis=0)
def sample_disc(sax,n):
    r=sqrt(rng.random(n)); t=2*pi*rng.random(n); x,y=r*cos(t),r*sin(t); z=sqrt(np.maximum(0,1-r*r))*rng.choice([-1,1],n)
    sax=sax/np.linalg.norm(sax); e1=np.cross(sax,[1,0,0])
    if np.linalg.norm(e1)<1e-6: e1=np.cross(sax,[0,1,0])
    e1/=np.linalg.norm(e1); e2=np.cross(sax,e1)
    return np.outer(x,e1)+np.outer(y,e2)+np.outer(z,sax)
zs=[]
for _ in range(3):
    av,bv=unit(1)[:,0],unit(1)[:,0]; n=2_000_000; eta=sample_disc(av,n)
    Ar=np.sign(eta@av); Br=-np.sign(eta@bv); E=(Ar*Br).mean(); se=sqrt((1-E*E)/n); zs.append((E+av@bv)/se)
    P(f"   a.b = {av@bv:+.6f}: E = {E:+.6f} +/- {se:.6f}, z = {zs[-1]:+.2f}, P(A+) = {np.mean(Ar>0):.5f}, P(B+) = {np.mean(Br>0):.5f}")
P(f"   largest |z| = {max(abs(z) for z in zs):.2f}")

P("== 3. Uniqueness theorem: uniqueness of the projection measure")
for Ng in (360,720,1440):
    u=(np.arange(Ng)+0.5)*2*pi/Ng; wg=2*pi/Ng; D=np.arange(Ng)*2*pi/Ng; Sg=zeta(u[None,:]+D[:,None])
    Aop=np.vstack([(Sg*zeta(u)[None,:])*wg, Sg*wg]); rhs=np.concatenate([cos(D),np.zeros(Ng)])
    sol,res,rk,sv=np.linalg.lstsq(Aop,rhs,rcond=None)
    P(f"   {Ng} phase points: rank {rk} of {Ng}; max|rho - |cos|/4| = {np.max(np.abs(sol-np.abs(cos(u))/4)):.1e}")
Ng=720; u=(np.arange(Ng)+0.5)*2*pi/Ng; wg=2*pi/Ng; D=np.arange(Ng)*2*pi/Ng; Sg=zeta(u[None,:]+D[:,None])
P(f"   kernel constraints alone: rank {np.linalg.matrix_rank((Sg*zeta(u)[None,:])*wg)} of {Ng}")
for eps in (0.0,0.3,0.8):
    r=np.abs(cos(phi))*(1+eps*zeta(phi))/4
    Ee=max(abs(-(r*zeta(phi)*zeta(phi+d)).sum()*w+cos(d)) for d in np.linspace(0,2*pi,25))
    pB=[(r*(zeta(phi+d)<0)).sum()*w for d in (0,pi/3,pi/2,pi)]
    P(f"   family eps = {eps}: max|E+cos| = {Ee:.1e}; Pr(A=+1) = {(r*(zeta(phi)>0)).sum()*w:.4f}; Pr(B=+1) at Delta = 0, pi/3, pi/2, pi: "+" ".join(f"{x:.4f}" for x in pB))
mu=[]
for l in range(1,202,2):
    c=np.zeros(l+1); c[l]=1; ci=L.legint(c); mu.append(4*pi*(L.legval(1,ci)-L.legval(0,ci)))
mu=np.array(mu); ls=np.arange(1,202,2)
closed=4*pi*np.array([(L.legval(0,np.eye(1,k,k-1)[0])-L.legval(0,np.eye(1,k+2,k+1)[0]))/(2*k+1) for k in ls])
P(f"   Funk-Hecke multipliers of sgn(b.eta), odd l = 1..201: smallest |mu_l| = {np.min(np.abs(mu)):.2e}; mu_1 = {mu[0]:.6f} (2 pi); closed form to {np.max(np.abs(mu-closed)):.0e}")

P("== 4. One-sided bound: the price and the ceiling")
def M1(th): return (np.abs(np.abs(cos(phi))-np.abs(cos(phi-th)))/4).sum()*w
P(f"   max|M1(theta) - (2 sqrt(1+sin theta) - 2)| over 61 separations = {max(abs(M1(t)-(2*sqrt(1+sin(t))-2)) for t in np.linspace(0,pi,61)):.1e}; D1 = {M1(pi/2):.9f}")
rho0=np.abs(cos(phi-aq[0]))/4; rho1=np.abs(cos(phi-aq[1]))/4; B0=np.sign(cos(phi+pi-bq[0])); B1=np.sign(cos(phi+pi-bq[1]))
P(f"   int (rho0-rho1) B0 B1 = {((rho0-rho1)*B0*B1).sum()*w:.9f}")
bb=np.linspace(-pi,pi,721)
for th in (pi/6,pi/3,pi/2,2*pi/3):
    best=np.max(-cos(0-bb)-cos(th-bb))+np.max(-cos(0-bb)+cos(th-bb))
    P(f"   theta = {th:.4f}: largest S on the kernel = {best:.6f}; 2 + M1 = {2+M1(th):.6f}; |a+a'|+|a-a'| = {2*cos(th/2)+2*sin(th/2):.6f}")
p=np.abs(cos(phi))/4
P(f"   mutual information, host clamp uniform on the circle: {(p*np.log2(p*2*pi)).sum()*w:.6f} bits; closed form {np.log2(pi/2)+1-1/np.log(2):.6f}")
p0=np.abs(cos(phi))/4; p1=np.abs(cos(phi-pi/2))/4; pm=(p0+p1)/2
P(f"   mutual information, two equiprobable clamps a quarter turn apart: {0.5*(p0*np.log2(p0/pm)).sum()*w+0.5*(p1*np.log2(p1/pm)).sum()*w:.6f} bits")

P("== 5. Event by event, every record kept (1e6 records per setting pair)")
def sample_phase(a,n):
    x = rng.uniform(-1,1,n); front = rng.random(n)<0.5
    return np.where(front,np.arcsin(x),pi-np.arcsin(x)) + a
def ebe(a,b,n,measure):
    ph = sample_phase(a,n) if measure=="proj" else rng.uniform(0,2*pi,n)
    return (np.sign(cos(ph-a))*np.sign(cos(ph+pi-b))).mean()
n=1_000_000
for m in ("proj","uni"):
    e=[[ebe(a,b,n,m) for b in bq] for a in aq]; s=e[0][0]+e[0][1]+e[1][0]-e[1][1]; se=sqrt(sum(1-x*x for r in e for x in r)/n)
    P(f"   {m}: S = {s:.4f} +/- {se:.4f}   (sqrt(2/N) = {sqrt(2/n):.4f})")
tot=[]; 
for a_ in aq:
    for b_ in bq:
        phs=rng.uniform(0,2*pi,n); keep=rng.random(n)<np.abs(cos(phs-a_)); AB=np.sign(cos(phs-a_))*np.sign(cos(phs+pi-b_))
        tot.append((AB[keep].mean(),(AB*keep).mean(),keep.mean()))
sg=np.array([1,1,1,-1])
P(f"   selection on a uniform phase: accepted-pair S = {sum(sg*[t[0] for t in tot]):.4f} at wing efficiency {np.mean([t[2] for t in tot]):.4f} (2/pi = {2/pi:.4f}); all-record S, nulls as 0 = {sum(sg*[t[1] for t in tot]):.4f}")

P("== 6. Rank propositions: rank of the table and of its arcsine rounding")
Am,Bm=unit(5),unit(5)
P("   5x5 kernel table at random axes, singular values:",np.round(np.linalg.svd(-Am.T@Bm,compute_uv=False),6))
c3=np.radians([0,60,120]); Dm=c3[:,None]-c3[None,:]; fold=lambda x: np.abs((x+pi)%(2*pi)-pi)
Kt=-cos(Dm); Tt=-1+2*fold(Dm)/pi
P(f"   clamps 0, 60, 120 deg at both wings: det(kernel) = {np.linalg.det(Kt):+.1e}; det(triangle) = {np.linalg.det(Tt):+.6f} (-16/27 = {-16/27:.6f}); singular values of the triangle table {np.round(np.linalg.svd(Tt,compute_uv=False),4)}")
tet=np.array([[1,1,1],[1,-1,-1],[-1,1,-1],[-1,-1,1]]).T/sqrt(3); G=tet.T@tet; q=(2/pi)*np.arcsin(1/3)
P(f"   tetrahedral axes at both wings: det(kernel) = {np.linalg.det(-G):+.1e}; det(arcsine) = {np.linalg.det(-(2/pi)*np.arcsin(np.clip(G,-1,1))):.6f}; (1+q)^3 (1-3q) = {(1+q)**3*(1-3*q):.6f}, q = {q:.6f}")
Ck=np.array([[(-1)**(i+j)*np.linalg.det(np.delete(np.delete(Kt,i,0),j,1)) for j in range(3)] for i in range(3)])
se1=sqrt((Ck**2*(1-Kt**2)).sum())
P(f"   counting SE of the determinant on the kernel = {se1:.4f}/sqrt(N per cell); records per cell for five SE: {int(np.ceil((5*se1/(16/27))**2))}")
def cell(measure,aa,bb,n):
    ph = sample_phase(aa,n) if measure=="proj" else rng.uniform(0,2*pi,n)
    return (np.sign(cos(ph-aa))*np.sign(cos(ph+pi-bb))).mean()
nc=2000; reps=600
for m in ("proj","uni"):
    dets=[np.linalg.det(np.array([[cell(m,x,y,nc) for y in c3] for x in c3])) for _ in range(reps)]
    P(f"   Monte Carlo, {reps} runs of {nc} records per cell, {m}: det = {np.mean(dets):+.4f} +/- {np.std(dets):.4f}   (formula SE {se1/sqrt(nc):.4f})")
for V in (1.0,0.8,0.5):
    P(f"   visibility {V}: det(V*kernel) = {np.linalg.det(V*Kt):+.1e}; det(V*triangle) = {np.linalg.det(V*Tt):+.4f}")

P("== 7. Transport proposition: kernel under transport, phase model on the sphere")
def rot(axis,ang):
    axis=np.asarray(axis,float); axis=axis/np.linalg.norm(axis); K=np.array([[0,-axis[2],axis[1]],[axis[2],0,-axis[0]],[-axis[1],axis[0],0]])
    return np.eye(3)+sin(ang)*K+(1-cos(ang))*K@K
OA=rot(rng.normal(size=3),1.1); OB=rot(rng.normal(size=3),-0.7); av,bv=unit(1)[:,0],unit(1)[:,0]; n=2_000_000
for host in "AB":
    eta=sample_disc(OA.T@av if host=="A" else OB.T@bv,n); Ar=np.sign((eta@OA.T)@av); Br=-np.sign((eta@OB.T)@bv)
    E=(Ar*Br).mean(); se=sqrt((1-E*E)/n); pred=-av@OA@OB.T@bv
    P(f"   host {host}: E = {E:+.6f} +/- {se:.6f}; -a.O_rel b = {pred:+.6f}; z = {(E-pred)/se:+.2f}; P(A+) = {np.mean(Ar>0):.5f}, P(B+) = {np.mean(Br>0):.5f}")
P("   same sense = opposite sense with a half-turn about the normal: table diagonal",np.round(np.diag(-rot([0,1,0],pi)),6),"(circle in the x-z plane)")

P("== 8. Pooled-pair theorem and its corollaries: the pooled pair from the spectrum of the mean relative rotation")
sx=np.array([[0,1],[1,0]],complex); sy=np.array([[0,-1j],[1j,0]]); sz=np.array([[1,0],[0,-1]],complex); pa=(sx,sy,sz)
psi=np.array([0,1,-1,0],complex)/sqrt(2)
def su2(axis,ang):
    axis=np.asarray(axis,float); axis=axis/np.linalg.norm(axis); return cos(ang/2)*np.eye(2)-1j*sin(ang/2)*(axis[0]*sx+axis[1]*sy+axis[2]*sz)
def negativity(rho):
    pt=rho.reshape(2,2,2,2).transpose(0,3,2,1).reshape(4,4); ev=np.linalg.eigvalsh(pt); return -ev[ev<0].sum()
def report(name,Us,gamma=None):
    rho=np.zeros((4,4),complex)
    for UA,UB in Us:
        v=np.kron(UA,UB)@psi; rho+=np.outer(v,v.conj())
    rho/=len(Us); T=np.array([[np.trace(rho@np.kron(p_,q_)).real for q_ in pa] for p_ in pa]); M=-T
    sv=np.linalg.svd(M,compute_uv=False); sg=1.0 if np.linalg.det(M)>=0 else -1.0; s1,s2,s3=sv[0],sv[1],sv[2]*sg
    wts=np.array([1+s1+s2+s3,1+s1-s2-s3,1-s1+s2-s3,1-s1-s2+s3])/4; ev=np.sort(np.linalg.eigvalsh(rho))[::-1]
    F=(psi.conj()@rho@psi).real; best=0
    for _ in range(3000):
        qd=unit(4); best=max(best,abs(qd[:,0]@T@qd[:,2]+qd[:,0]@T@qd[:,3]+qd[:,1]@T@qd[:,2]-qd[:,1]@T@qd[:,3]))
    P(f"   {name}: s = ({s1:.4f}, {s2:.4f}, {s3:+.4f})")
    P(f"      frequencies {np.round(np.sort(wts)[::-1],6)} vs eigenvalues {np.round(ev,6)}")
    P(f"      fidelity {F:.6f} vs {(1+np.trace(M))/4:.6f}; purity {np.trace(rho@rho).real:.6f} vs {(1+s1*s1+s2*s2+s3*s3)/4:.6f}; negativity {negativity(rho):.6f} vs {max(0,(s1+s2+s3-1)/4):.6f}")
    P(f"      CHSH ceiling {2*sqrt(s1*s1+s2*s2):.6f}; largest |S| in 3000 random quartets {best:.4f}")
    if gamma is not None:
        ax=lambda t: np.array([sin(t),0,cos(t)]); Sf=ax(0)@T@ax(-3*pi/4)+ax(0)@T@ax(3*pi/4)+ax(pi/2)@T@ax(-3*pi/4)-ax(pi/2)@T@ax(3*pi/4)
        g=gamma; P(f"      gamma: |gamma| = {abs(g):.6f}, Re gamma = {g.real:.6f}; (1+Re gamma)/2 = {(1+g.real)/2:.6f}; |gamma|/2 = {abs(g)/2:.6f}; (1+|gamma|^2)/2 = {(1+abs(g)**2)/2:.6f}")
        P(f"      S fixed = {Sf:.6f} vs 2 sqrt2 Re gamma = {2*sqrt(2)*g.real:.6f}; 2 sqrt2 |gamma| = {2*sqrt(2)*abs(g):.6f}; 2 sqrt(1+|gamma|^2) = {2*sqrt(1+abs(g)**2):.6f}")
m=3000
report("random small rotations about random axes",[(su2(rng.normal(size=3),rng.normal(0,0.5)),su2(rng.normal(size=3),rng.normal(0,0.3))) for _ in range(m)])
report("a birefringent arm against a turning arm",[(su2([1,1,0.3],rng.normal(0.2,0.6)),su2([0,1,0],rng.normal(0,0.4))) for _ in range(m)])
report("equal mixture of three half-turns (det M < 0)",[(su2(np.eye(3)[k%3],pi),np.eye(2)) for k in range(m)])
bA=rng.normal(0.05,0.33,m); bB=rng.normal(-0.02,0.21,m)
report("turns about the ray",[(su2([0,1,0],2*x),su2([0,1,0],2*y)) for x,y in zip(bA,bB)],gamma=np.mean(np.exp(2j*(bA-bB))))
dl=rng.normal(0.1,0.3,4_000_000)
P(f"   Gaussian turn: <e^(2i delta)> = {np.round(np.mean(np.exp(2j*dl)),5)} vs exp(2i dbar - 2 var) = {np.round(np.exp(2j*0.1-2*0.09),5)}; threshold var < ln2/4 = {np.log(2)/4:.4f} rad^2, sd < {np.degrees(sqrt(np.log(2)/4)):.1f} deg")
for name,draw,chi2 in (("Gaussian, sd 0.1",lambda k: rng.normal(0,0.1,k),np.exp(-2*0.1**2)),("uniform on [-0.3, 0.3]",lambda k: rng.uniform(-0.3,0.3,k),sin(0.6)/0.6),("two-valued +-0.25",lambda k: rng.choice([-0.25,0.25],k),cos(0.5))):
    Nst=20; d=draw(400000*Nst).reshape(400000,Nst).sum(axis=1); v=np.var(draw(1000000))
    P(f"   rate, {name}: |gamma| after {Nst} steps = {abs(np.mean(np.exp(2j*d))):.4f}; |p(2)|^N = {abs(chi2)**Nst:.4f}; exp(-2 v N) = {np.exp(-2*v*Nst):.4f}")

qq=rng.normal(size=(200000,4)); qq/=np.linalg.norm(qq,axis=1)[:,None]; q0,q1,q2,q3=qq.T
d1=q0*q0+q1*q1-q2*q2-q3*q3; d2=q0*q0-q1*q1+q2*q2-q3*q3; d3=q0*q0-q1*q1-q2*q2+q3*q3
wq=np.stack([1+d1+d2+d3,1+d1-d2-d3,1-d1+d2-d3,1-d1-d2+d3])/4
P(f"   frequencies of one history: max |(1 +- R11 +- R22 +- R33)/4 - q_i^2| over 2e5 random rotations = {np.abs(wq-qq.T**2).max():.1e}; smallest value {wq.min():.1e}")
Rq=np.array([[d1[0],2*(q1[0]*q2[0]-q0[0]*q3[0]),2*(q1[0]*q3[0]+q0[0]*q2[0])],[2*(q1[0]*q2[0]+q0[0]*q3[0]),d2[0],2*(q2[0]*q3[0]-q0[0]*q1[0])],[2*(q1[0]*q3[0]-q0[0]*q2[0]),2*(q2[0]*q3[0]+q0[0]*q1[0]),d3[0]]])
P(f"      the diagonal is that of a rotation: |R R^T - 1| = {np.abs(Rq@Rq.T-np.eye(3)).max():.1e}, det = {np.linalg.det(Rq):.6f}")
vq=np.kron(su2([0,1,0],pi),np.eye(2))@psi; vq2=np.kron(su2([0,1,0],pi),su2([0,1,0],pi))@psi
P(f"   fidelity with the mean turn left in: every history at delta = pi/2 (gamma = -1) gives {abs(psi.conj()@vq)**2:.6f}; with the mean turn removed, {abs(psi.conj()@vq2)**2:.6f}")

P("== 9. Numbers of the text")
hbar=1.054571817e-34; c=299792458.0; G=6.67430e-11
ker=lambda D_: -cos(D_); tri=lambda D_: -1+2*abs(D_)/pi
P(f"   Bell 1964 at clamps 0, pi/4, pi/2: kernel {abs(ker(pi/4)-ker(pi/2)):.4f} vs {1+ker(pi/4):.4f}; triangle {abs(tri(pi/4)-tri(pi/2)):.4f} vs {1+tri(pi/4):.4f}")
Fmax=c**4/(4*G); Eph=2*pi*hbar*c/810e-9
P(f"   F_max = {Fmax:.4e} N; 810 nm stroke {Eph:.4e} J; own window at 1 m {Eph/(2*Fmax):.3e}; Earth alpha_ext at the surface {2*3.986004418e14/c**2/6.371e6:.3e}")
neg=np.array([0.4925,0.4533,0.3829,0.3097,0.2368,0.1843,0.1432,0.1152])
P("   sweep, 2 sqrt(1+|gamma|^2) from the reported negativity:",np.round(2*sqrt(1+(2*neg)**2),3))
