check.py

back to table · edit · history · where entries came from · files · download

9269 bytes, as of the version from 2026-12-02 04:01 (current). Recorded here, not run.

"""Checks for T867, independent of generate.py's arithmetic.

sage -python check.py [computation.json] [stored.json] [T129.json]
Default files are beside this script. Uses PARI polclass(D,0) (CRT) instead
of FLINT/Arb (complex balls), primitive reduced quadratic forms instead of
Sage class_number, elementary modular polynomial gcd/Euler criterion instead
of finite-field methods, and digit-at-a-time lifting plus PARI polrootspadic
instead of modular Newton doubling. The exact-congruence test and Hensel's
simple-root hypotheses certify each specified ball. Shared assumptions are
classical CM theory, Hensel's theorem, Sage/PARI infrastructure, and integer
arithmetic. This is builder evidence, not an independent session's verdict.
Prints JSON; redirect to check-results.json to preserve the actual outcome.
"""
import sys,json,re,math,hashlib,platform
from pathlib import Path
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.libs.pari import pari
from sage.env import SAGE_VERSION
R=PolynomialRing(ZZ,'x')

def squarefree(n):
    n=abs(n)
    return all(n%(q*q) for q in range(2,math.isqrt(n)+1))

def fundamental(D):
    return D<0 and ((D%4==1 and squarefree(D)) or
                   (D%4==0 and (D//4)%4 in (2,3) and squarefree(D//4)))

def forms(D):
    out=[]
    for a in range(1,math.isqrt((-D)//3)+1):
        for b in range(-a,a+1):
            if (b*b-D)%(4*a):continue
            c=(b*b-D)//(4*a)
            if a>c or math.gcd(math.gcd(a,b),c)!=1:continue
            if (abs(b)==a or a==c) and b<0:continue
            out.append((a,b,c))
    return out

def evaluate(c,u):
    out=0
    for v in reversed(c):out=out*u+v
    return out

def derivative(c):return [i*c[i] for i in range(1,len(c))]

def trim(c):
    while c and c[-1]==0:c.pop()
    return c

def remainder(c,d,p):
    c=trim([x%p for x in c]);d=trim([x%p for x in d])
    while len(c)>=len(d) and c:
        k=len(c)-len(d);v=c[-1]*pow(d[-1],-1,p)%p
        for j in range(len(d)):c[j+k]=(c[j+k]-v*d[j])%p
        trim(c)
    return c

def is_squarefree(c,p):
    a,b=c,derivative(c)
    while b:a,b=b,remainder(a,b,p)
    return len(trim([x%p for x in a]))==1

def lift_by_digits(c,p,a,N):
    u,modulus=a,p;dinv=pow(evaluate(derivative(c),a),-1,p)
    for n in range(1,N):
        fu=evaluate(c,u);assert fu%modulus==0
        correction=-(fu//modulus)*dinv%p
        u+=modulus*correction;modulus*=p
    return u

def precision(p):
    N,M=0,1
    while M<10**100:N+=1;M*=p
    return N,M

def parse(text):
    m=re.fullmatch(r'(?:(\d+)\^(-?\d+)\s*\*\s*)?(\d+)\s*\+\s*O\((\d+)\^(\d+)\)',text.strip())
    if not m:raise ValueError('unexpected p-adic encoding: '+text[:120])
    bp,v,u,p,N=m.groups();p,N,u=int(p),int(N),int(u)
    if bp is not None:
        assert int(bp)==p and int(v)>=0;u*=p**int(v)
    return p,N,u

def valid_ball(c,p,a,u,N):
    expected,M=precision(p)
    return (N==expected and 0<=u<M and u%p==a and
            evaluate(c,u)%M==0 and evaluate(derivative(c),a)%p!=0)

def records(document):
    params=list(document['Parameters']);out=[]
    def walk(node,idx,chosen):
        if isinstance(node,list):
            for e in node:out.append(e)
        elif idx==len(params):out.append({'params':chosen,'number':node if isinstance(node,str) else node['number']})
        else:
            for k,v in node.items():
                if k in ('comment','param-latex'):continue
                walk(v,idx+1,{**chosen,params[idx]:k})
    walk(document['Numbers'],0,{})
    return out

def main():
    base=Path(__file__).parent
    data_path=Path(sys.argv[1]) if len(sys.argv)>1 else base/'computation.json'
    data=json.loads(data_path.read_text());fail=[];comparisons=[]
    def require(ok,message):
        if not ok:fail.append(message)
    Ds=[-d for d in range(1,101) if fundamental(-d) and len(forms(-d)) in (2,3)]
    require(set(map(str,Ds))==set(data['polynomials']),'discriminant selection')
    primes=[p for p in range(5,98) if all(p%q for q in range(2,math.isqrt(p)+1))]
    coeff={D:[int(x) for x in R(pari.polclass(D,0)).list()] for D in Ds}
    for D in Ds:
        require(coeff[D]==list(map(int,data['polynomials'][str(D)])),f'polynomial {D}')
        require(len(coeff[D])-1==len(forms(D)),f'degree/class number {D}')
    expected=[];pair_checks=[]
    for D in Ds:
        for p in primes:
            symbol=0 if D%p==0 else 1 if pow(D%p,(p-1)//2,p)==1 else -1
            sq=is_squarefree(coeff[D],p)
            roots=[a for a in range(p) if evaluate(coeff[D],a)%p==0] if symbol==1 and sq else []
            status='nonsplit' if symbol!=1 else 'nonsquarefree' if not sq else 'no-linear-root' if not roots else 'included'
            pair_checks.append(dict(D=D,p=p,kronecker=symbol,squarefree=sq,roots=roots,status=status))
            expected.extend((D,p,a) for a in roots)
    require(pair_checks==data['pairs'],'all 299 pair classifications')
    entries=data['entries'];source='offline checkpoint'
    stored_path=Path(sys.argv[2]) if len(sys.argv)>2 else base/'stored.json'
    if stored_path.exists():
        entries=records(json.loads(stored_path.read_text()));source='stored website document'
    keys=[tuple(int(e['params'][k]) for k in ('D','p','a')) for e in entries]
    require(keys==expected,'ordered enumeration and every branch')
    pari_roots={}
    for D,p,a in expected:
        if (D,p) not in pari_roots:
            N,M=precision(p);pr=pari(R(coeff[D])).polrootspadic(p,N)
            pari_roots[D,p]={int(t.lift())%p:int(t.lift())%M for t in pr}
            require(set(pari_roots[D,p])=={aa for dd,pp,aa in expected if (dd,pp)==(D,p)},f'PARI root count {D},{p}')
    for e,key in zip(entries,keys):
        D,p,a=key
        pp,N,u=parse(e['number'])
        c=coeff[D];digit=lift_by_digits(c,p,a,N)
        ok=(pp==p and valid_ball(c,p,a,u,N) and u==digit and u==pari_roots[D,p][a])
        require(ok,f'root {key}')
        comparisons.append(dict(D=D,p=p,a=a,N=N,residue=str(u),modulus=str(p**N),full_congruence=evaluate(c,u)%(p**N)==0,derivative_mod_p=evaluate(derivative(c),a)%p,digit_lift_matches=u==digit,pari_matches=u==pari_roots[D,p][a]))
    control_coeff=[12771880859375,-5151296875,3491750,1]
    known=(coeff[-23]==control_coeff and [a for a in range(59) if evaluate(control_coeff,a)%59==0]==[20,42,44] and [lift_by_digits(control_coeff,59,a,2) for a in (20,42,44)]==[3147,2284,1224] and pow(-23%13,6,13)==1 and is_squarefree(control_coeff,13) and not [a for a in range(13) if evaluate(control_coeff,a)%13==0])
    rational=[]
    for D,j in [(-3,0),(-4,1728),(-7,-3375),(-8,8000),(-11,-32768),(-19,-884736),(-43,-884736000),(-67,-147197952000),(-163,-262537412640768000)]:
        c=[int(x) for x in R(pari.polclass(D,0)).list()];ok=c==[-j,1]
        for p in (5,13,59,97):
            N,M=precision(p);ok=ok and lift_by_digits(c,p,j%p,N)==j%M
        rational.append(dict(D=D,j=str(j),pass_control=ok));known=known and ok
    require(known,'known-answer controls')
    D,p,a=expected[0];N,M=precision(p);u=pari_roots[D,p][a];c=coeff[D]
    negative={
      'last_residue_digit_corruption':not valid_ball(c,p,a,(u+p**(N-1))%M,N),
      'wrong_residue_label':not valid_ball(c,p,(a+1)%p,u,N),
      'insufficient_precision':not valid_ball(c,p,a,u%(p**(N-1)),N-1),
      'wrong_polynomial':not valid_ball([c[0]+1]+c[1:],p,a,u,N),
      'repeated_root_polynomial':not is_squarefree([1,-2,1],5),
      'nonroot':evaluate(c,(a+1)%p)%p!=0 or not valid_ball(c,p,(a+1)%p,u,N)}
    require(all(negative.values()),'negative controls rejected')
    t129_check=None
    t129_path=Path(sys.argv[3]) if len(sys.argv)>3 else base/'T129.json'
    if t129_path.exists():
        doc=json.loads(t129_path.read_text());rs=records(doc);t129_check=[]
        for D in Ds:
            matches=[e for e in rs if str(D) in [str(v) for v in e['params'].values()]]
            require(len(matches)==1,f'T129 source identity {D}')
            if len(matches)==1:
                f=R(matches[0]['number'].replace('^','**'));ok=list(map(int,f.list()))==coeff[D]
                t129_check.append(dict(D=D,params=matches[0]['params'],match=ok));require(ok,f'T129 polynomial {D}')
    short=3147
    matches=[list(key) for key in expected if key[1]==59 and pari_roots[key[0],59][key[2]]%(59**2)==short]
    require([-23,59,20] in matches,'short query correct branch')
    return dict(checked_entries=len(comparisons),total_entries=len(entries),failures=fail,known_answer_control=bool(known),negative_control_rejected=all(negative.values()),source=source,polynomial_count=len(Ds),pair_count=len(pair_checks),forms={str(D):forms(D) for D in Ds},rational_controls=rational,negative_controls=negative,short_query={'text':'3147 + O(59^2)','matching_table_identities':matches,'scope':'local checkpoint; draft excluded from public lookup'},T129_checks=t129_check,comparisons=comparisons,versions={'python':platform.python_version(),'sage':SAGE_VERSION,'pari':str(pari('version()'))},skill_manifest='../20261130T094538Z-build-skills/manifest.json',check_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest())

if __name__=='__main__':
    result=main();print(json.dumps(result));sys.exit(bool(result['failures']))