from pathlib import Path
import re, math, random

HERE=Path(__file__).resolve().parent
PAPER=HERE/"CSM_RH_Paper_88_Polynomial_Threshold_Inertia_and_Extremal_Family_TypeII_Gate_v0.1_2026-09-09.md"

def interval_multiple_count(a,H,d):
    return (a+H)//d - a//d

def check_family_divisor():
    random.seed(88)
    H=137
    starts=sorted(random.sample(range(10000,20000),37))
    J=len(starts)
    vals=[]
    for d in [2,3,5,7,11,17,31,67,149,251]:
        Ad=sum(interval_multiple_count(a,H,d) for a in starts)
        err=abs(Ad-J*H/d)
        assert err<=J+1e-12,(d,err,J)
        vals.append((d,err))
    return vals

def check_inertia_bound():
    X=10**12
    tau=0.2
    nu=0.1
    H=X**(1-tau)
    T=H*X**(-nu)
    L=T/(8*math.log(4*X))-1
    change=2*(L+1)*math.log(4*X)
    assert change<=T/4*(1+1e-12)
    return T,L,change

def check_center_exponents():
    for tau,nu,c in [(0.3,0.12,0.08),(0.4,0.15,0.2),(0.2,0.05,0.1)]:
        L_exp=1-tau-nu
        J_exp=(1-c)-L_exp
        assert abs(J_exp-(tau+nu-c))<1e-14
        K_exp=J_exp-nu
        assert abs(K_exp-(tau-c))<1e-14
    return True

def check_family_window():
    for d in [0.05,0.2,0.32]:
        if d<1/3:
            tau=(d+(1-2*d))/2
            assert d<tau<1-2*d
            nu=(d+(1-tau)/2)/2
            assert d<nu<(1-tau)/2
    for d in [0.34,0.4]:
        assert not (d < 1-2*d)
    return True

def check_grid_complexity():
    for tau,nu,c in [(0.3,0.1,0.07),(0.4,0.12,0.2)]:
        B_exp=tau+nu
        J_exp=tau+nu-c
        assert abs(B_exp-J_exp-c)<1e-14
    return True

def check_threshold_typeI():
    for tau,nu in [(0.2,0.1),(0.4,0.15),(0.1,0.3)]:
        D_exp=1-tau-nu
        assert abs((1-D_exp)-(tau+nu))<1e-14
    return True

def check_linear_sieve_constant():
    gamma=0.5772156649015329
    for tau in [0.1,0.3,0.45]:
        theta=1-tau
        s=2*theta
        if 1<=s<=3:
            F=2*math.exp(gamma)/s
            Vcoeff=2*math.exp(-gamma)
            coeff=F*Vcoeff
            target=2/theta
            assert abs(coeff-target)<1e-12,(tau,coeff,target)
    return True

def check_source():
    s=PAPER.read_text(encoding="utf-8")
    for pat in [r"(?<!\\)\\\(",r"(?<!\\)\\\)",r"(?<!\\)\\\[",r"(?<!\\)\\\]"]:
        assert re.search(pat,s) is None
    assert s.count("$$")%2==0
    tmp=re.sub(r"\$\$.*?\$\$","",s,flags=re.S)
    assert len(re.findall(r"(?<!\\)\$",tmp))%2==0
    return True

if __name__=="__main__":
    print("family_divisor",check_family_divisor())
    print("inertia_bound",check_inertia_bound())
    print("center_exponents",check_center_exponents())
    print("family_window",check_family_window())
    print("grid_complexity",check_grid_complexity())
    print("threshold_typeI",check_threshold_typeI())
    print("linear_sieve_constant",check_linear_sieve_constant())
    print("source_delimiters",check_source())
    print("PASS")
