independent_check.py

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

8294 bytes, as of the version from 2026-11-28 03:37 (current). Recorded here, not run.

"""Check T841 from exact units and a separate modular logarithm series.

sage -python independent_check.py [analytic-rows.json or stored-rows.json]
No analytic generator is imported. The checker uses proof-enabled Sage unit
and class groups, certifies unit minimality by Pell enumeration, and implements
Hensel lifting and the logarithm independently with integer modular arithmetic.
This builder check is evidence for a fresh independent critic, not its verdict.
"""
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.qqbar import AA
from sage.rings.number_field.number_field import QuadraticField
from sage.modular.dirichlet import kronecker_character
import os,sys,json,math,hashlib,time
from pathlib import Path


def logfloor(n,p):
    k=0
    while n>=p: n//=p;k+=1
    return k


def log_unit(e,p,A):
    # e is an exact integer representative modulo p^A. Changing it by p^A
    # changes its logarithm by p^A. Extra modular guard permits division by k.
    assert e%p
    K=1
    while K-logfloor(K,p)<A: K+=1
    guard=logfloor(K,p);large=p**(A+guard);mod=p**A
    z=(pow(e,p-1,large)-1)%large
    assert z%p==0
    power=1;total=0
    for k in range(1,K):
        power=power*z%large;q=k;v=0
        while q%p==0:q//=p;v+=1
        assert power%(p**v)==0
        term=(power//(p**v))*pow(q,-1,mod)%mod
        total=(total+(-1)**(k+1)*term)%mod
    return total*pow(p-1,-1,mod)%mod,K


def hensel(D,p,A):
    r0=min(r for r in range(1,p) if (r*r-D)%p==0);r=r0
    for k in range(1,A):
        pk=p**k;r+=((D-r*r)//pk*pow(2*r,-1,p)%p)*pk
    assert (r*r-D)%(p**A)==0 and r%p==r0 and (2*r)%p
    return r,r0


def unit_data(D):
    K=QuadraticField(D,'a');assert K.discriminant()==D
    e=K.unit_group(proof=True).gens_values()[1]
    emb=K.hom([AA(D).sqrt()],AA)
    if emb(e)<0:e=-e
    if emb(e)<1:e=1/e
    assert emb(e)>1
    t=ZZ(2*e[0]);u=ZZ(2*e[1]);n=ZZ(e.norm())
    assert t>0 and u>0 and n in (-1,1) and t*t-D*u*u==4*n
    # All smaller units >1 have positive u <= this u: even for the other
    # norm sign the possible increase is <2/(sqrt(D)*e)<1.
    candidates=[]
    for w in range(1,int(u)+1):
        for sign in (-1,1):
            square=D*w*w+4*sign
            if square<=0:continue
            z=math.isqrt(square)
            if z*z!=square:continue
            value=(AA(z)+w*AA(D).sqrt())/2
            if value>1:candidates.append((value,z,w,sign))
    best=min(candidates,key=lambda x:x[0])
    assert best[1:]==(t,u,n) and best[0]==emb(e)
    chi=kronecker_character(D)
    assert chi.is_primitive() and chi.is_even() and chi.conductor()==D and sum(chi(a) for a in range(D))==0
    # Independent elementary Kronecker/Jacobi evaluation, including 2-parts.
    def symbol(a,b):
        if b==0:return int(abs(a)==1)
        sign=1
        if b<0:b=-b;sign=-1 if a<0 else 1
        twos=0
        while b%2==0:b//=2;twos+=1
        if twos:
            if a%2==0:return 0
            if twos%2 and a%8 in (3,5):sign=-sign
        a%=b
        while a:
            while a%2==0:
                a//=2
                if b%8 in (3,5):sign=-sign
            a,b=b,a
            if a%4==b%4==3:sign=-sign
            a%=b
        return sign if b==1 else 0
    assert all(int(chi(a))==symbol(D,a) for a in range(D))
    return {'D':D,'t':int(t),'u':int(u),'norm':int(n),'h':int(K.class_number(proof=True)),'minimality_u_bound':int(u),'pell_candidates':len(candidates)}


def accept(row,expected,certified_A):
    p=int(row['params']['p']);A=int(row['A']);res=int(row['residue']);N=0;power=1
    while power<10**100:N+=1;power*=p
    if not res:return False
    v=0;n=res
    while n%p==0:v+=1;n//=p
    return A<=certified_A and A-v>=N and 0<=res<p**A and (res-expected)%(p**A)==0


def run(path,output):
    start=time.monotonic();rows=json.loads(path.read_text());work=path.parent
    fields={D:unit_data(D) for D in sorted({r['params']['D'] for r in rows})}
    # Separate exhaustive parameter census, with discriminant condition and
    # splitting evaluated through Dirichlet characters rather than generator.
    expected_pairs=[]
    for D in range(5,101):
        d=D if D%4==1 else D//4
        if not ((D%4==1 and ZZ(D).is_squarefree()) or (D%4==0 and d%4 in (2,3) and ZZ(d).is_squarefree())):continue
        chi=kronecker_character(D)
        for p in range(3,32):
            if ZZ(p).is_prime() and chi(p)==1:expected_pairs.append((D,p))
    assert [(r['params']['D'],r['params']['p']) for r in rows]==expected_pairs and len(rows)==107
    assert fields[5]==dict(D=5,t=1,u=1,norm=-1,h=1,minimality_u_bound=1,pell_candidates=2)
    assert fields[12]['norm']==1 and fields[40]['h']==2 and (fields[40]['t'],fields[40]['u'])==(6,1)
    evidence=[];controls={};failures=[]
    for p in sorted({r['params']['p'] for r in rows}):
        controls[f'log-controls-{p}']=log_unit(1,p,8)[0]==0 and log_unit(-1,p,8)[0]==0 and log_unit(1+p,p,8)[0]%(p*p)==p
    negatives={};wrong_modulus=False
    for row in rows:
        D=row['params']['D'];p=row['params']['p'];A=row['A'];M=A+12;mod=p**M;f=fields[D]
        r,r0=hensel(D,p,M);e=(f['t']+f['u']*r)*pow(2,-1,mod)%mod
        assert e%p
        ell,K=log_unit(e,p,M);assert ell%p==0
        prediction=(ell//p)*2*f['h']*(p-1)*pow(r,-1,p**(M-1))%(p**(M-1))
        good=accept(row,prediction,M-1)
        if not good:failures.append({'D':D,'p':p,'kind':'class-number formula'})
        econj=(f['t']-f['u']*r)*pow(2,-1,mod)%mod
        ellconj,_=log_unit(econj,p,M)
        assert econj*e%mod==f['norm']%mod and (ell+ellconj)%mod==0
        other=(ellconj//p)*2*f['h']*(p-1)*pow((-r)%mod,-1,p**(M-1))%(p**(M-1))
        assert (other-prediction)%(p**(M-1))==0
        corrupt=dict(row,residue=str((int(row['residue'])+p**(A-1))%(p**A)))
        assert not accept(corrupt,prediction,M-1)
        widened=dict(row,A=0,residue='0');assert not accept(widened,prediction,M-1)
        if not wrong_modulus:
            narrow=dict(row,A=A+1)
            if prediction%(p**(A+1))!=int(row['residue']):
                wrong_modulus=not accept(narrow,prediction,M-1)
                negatives['overclaimed_modulus']={'D':D,'p':p,'declared_A':A+1,'rejected':wrong_modulus}
        if (D,p)==(5,11):
            negatives.update(omit_Euler_factor=not accept(row,(ell*2*f['h']*pow(r,-1,mod))%mod,M),
              square_norm_minus_one_unit=not accept(row,2*prediction,M-1),
              reverse_root_sign_only=not accept(row,-prediction,M-1))
            # Invert the conversion at the precision implied by stored L.
            inverse=int(row['residue'])*p*r*pow(2*f['h']*(p-1),-1,p**(A+1))%(p**(A+1))
            assert (inverse-ell)%(p**(A+1))==0
            negatives['round_trip']=True
        if (D,p)==(40,3):negatives['omit_class_number']=not accept(row,prediction*pow(2,-1,p**(M-1)),M-1)
        evidence.append({'D':D,'p':p,'matched':good,'stored_A':A,'check_A':M-1,'root_residue':r0,'unit_residue':e%p,'root':str(r),'log_unit_residue':str(ell),'log_A':M,'log_cutoff':K,'prediction':str(prediction),'conjugation_checked':True})
    assert all(controls.values()) and all(v for v in negatives.values() if isinstance(v,bool)) and wrong_modulus and not failures
    result={'checked_entries':len(rows),'total_entries':len(rows),'failures':failures,'known_answer_control':all(controls.values()),'negative_control_rejected':True,'controls':controls,'negative_controls':negatives,'fields':list(fields.values()),'comparisons':evidence,'input_file':path.name,'input_sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'elapsed_s':time.monotonic()-start}
    output.write_text(json.dumps(result,indent=2))
    print('ARTIFACT',output.name,json.dumps(result),flush=True)
    print('ARTIFACT arithmetic.json',json.dumps(list(fields.values())),flush=True)
    print('independent check',len(rows),'entries; all matched; controls passed; seconds',result['elapsed_s'],flush=True)
    return result


if __name__=='__main__':
    w=Path(os.environ.get('NUMBERDB_WORKDIR',str(Path.cwd())));w.mkdir(parents=True,exist_ok=True)
    path=Path(sys.argv[1]) if len(sys.argv)>1 else Path(__file__).with_name('analytic-rows.json')
    output=w/('stored-check-results.json' if path.name.startswith('stored') else 'check-results.json')
    run(path,output)