independent_check.py

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

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

"""Independent pure-integer/Fraction checks; no Sage, PARI, or generator imports.

python3 independent_check.py computation.json [stored-document.json]
Writes check-results.json beside the input. Gaussian periods in Z[x]/Phi_q
identify each conductor polynomial. Integer digit-Hensel lifting and an
explicit log-series with a tail bound check the full retained moduli.
Field/unit certification is independently rerunnable via generate.py but
ultimately relies on PARI bnfcertify(flag=0); this script does not replace it.
"""
import sys,json,hashlib
from pathlib import Path
from fractions import Fraction as F
from itertools import product
from math import isqrt


def require(ok, message):
    if not ok: raise AssertionError(message)


def valuation(a,p):
    require(a != 0, 'valuation of unresolved zero')
    v=0
    while a % p == 0: a//=p;v+=1
    return v


def floorlog(n,p):
    k=0
    while p**(k+1)<=n:k+=1
    return k


def evaluate(c,x,m=None):
    z=0
    for a in reversed(c):
        a=F(a)
        if m:
            z=(z*x+a.numerator*pow(a.denominator,-1,m))%m
        else:z=z*x+a
    return z


def hensel(c,r,p,N):
    derivative=[i*c[i] for i in range(1,len(c))]
    require(evaluate(c,r,p)==0 and evaluate(derivative,r,p)!=0,'not a simple branch')
    x=r; modulus=p
    for n in range(1,N):
        fx=evaluate(c,x)
        require(fx.denominator==1 and fx.numerator%modulus==0,'Hensel residual')
        digit=(-int(fx)//modulus * pow(int(evaluate(derivative,x,p)),-1,p))%p
        x+=digit*modulus
        modulus*=p
    require(evaluate(c,x,modulus)==0 and x%p==r,'root lift failed')
    return x


def log_mod(x,p,B):
    # x is known modulo p^(B+G). k-floorlog_p(k) is nondecreasing;
    # K=2B+10 ensures the entire k>=K tail vanishes modulo p^B.
    K=2*B+10;G=floorlog(K,p)
    require(K-floorlog(K,p)>=B,'tail bound')
    high=p**(B+G);mod=p**B
    require(x%p != 0,'log input not a unit')
    z=(pow(x,p-1,high)-1)%high
    require(z%p==0,'Fermat reduction')
    power=1;total=0
    for k in range(1,K):
        power=power*z%high
        e=0;unit=k
        while unit%p==0:e+=1;unit//=p
        require(power%p**e==0,'division precision')
        term=(power//p**e)*pow(unit,-1,mod)%mod
        total=(total+term if k%2 else total-term)%mod
    return total*pow(p-1,-1,mod)%mod


def mul(a,b,f):
    c=[F(0)]*5
    for i,x in enumerate(a):
        for j,y in enumerate(b): c[i+j]+=x*y
    for k in [4,3]:
        for j in range(3): c[k-3+j]-=c[k]*f[j]
    return c[:3]


def algebra_eval(c,a,f):
    z=[F(0)]*3
    for x in reversed(c):
        z=mul(z,a,f);z[0]+=F(x)
    return z


def inverse(a,f):
    cols=[mul(a,[int(i==j) for i in range(3)],f) for j in range(3)]
    M=[[cols[j][i] for j in range(3)]+[F(int(i==0))] for i in range(3)]
    for j in range(3):
        pivot=next(i for i in range(j,3) if M[i][j])
        M[j],M[pivot]=M[pivot],M[j]
        scale=M[j][j];M[j]=[v/scale for v in M[j]]
        for i in range(3):
            if i!=j:
                scale=M[i][j];M[i]=[x-scale*y for x,y in zip(M[i],M[j])]
    return [M[i][3] for i in range(3)]


def power(a,n,f):
    if n<0:a=inverse(a,f);n=-n
    z=[F(1),F(0),F(0)]
    while n:
        if n%2:z=mul(z,a,f)
        a=mul(a,a,f);n//=2
    return z


def norm(a,f):
    cols=[mul(a,[int(i==j) for i in range(3)],f) for j in range(3)]
    return det([[cols[j][i] for j in range(3)] for i in range(3)])


def det(M):
    if len(M)==2:return M[0][0]*M[1][1]-M[1][0]*M[0][1]
    return sum((-1)**j*M[0][j]*det([[M[i][k] for k in range(3) if k!=j] for i in [1,2]]) for j in range(3))


def cyclic_product(a,b,q):
    c=[0]*q
    for i,x in enumerate(a):
        if x:
            for j,y in enumerate(b):
                if y:c[(i+j)%q]+=x*y
    return c


def gaussian_polynomial(q):
    H={pow(a,3,q) for a in range(1,q)}
    remain=set(range(1,q));periods=[]
    while remain:
        g=min(remain);coset={g*h%q for h in H}
        periods.append([int(i in coset) for i in range(q)])
        remain-=coset
    require(len(periods)==3,'wrong cubic cosets')
    def rational(c):
        # Mod Phi_q=1+x+...+x^(q-1), constant iff all nonconstant
        # coefficients are equal. Its integer value is c0-c1.
        require(len(set(c[1:]))==1,'period symmetric function not rational')
        return c[0]-c[1]
    e1=[sum(t[i] for t in periods) for i in range(q)]
    e2=[0]*q
    for a,b in [(0,1),(0,2),(1,2)]:
        ab=cyclic_product(periods[a],periods[b],q)
        e2=[x+y for x,y in zip(e2,ab)]
    e3=cyclic_product(cyclic_product(periods[0],periods[1],q),periods[2],q)
    return [-rational(e3),rational(e2),-rational(e1),1]


def compare(record,residue,p):
    N=record['N'];v=record['valuation']
    require(record['p']==p and N>v>=0,'invalid precision')
    require(int(record['residue'])%p**N==residue%p**N,'wrong residue')
    require(valuation(int(record['residue']),p)==v,'wrong valuation')
    require(int(record['unit'])*p**v%p**N==int(record['residue']),'wrong unit part')


def run(data,stored=None):
    require(len(data['fields'])==9 and len(data['rows'])==54,'wrong coverage')
    fields={r['q']:r for r in data['fields']}
    for q,field in fields.items():
        f=field['coefficients']
        require(f==gaussian_polynomial(q),'field is not the Gaussian-period field')
        require(field['discriminant']==q*q and field['bnfcertify_flag']==0 and field['bnfcertify_result']==1,'missing full certification')
        require(field['torsion_order']==2,'wrong torsion')
        for u in field['units']:
            require(abs(norm(list(map(F,u)),f))==1,'unit norm')
        sigma=list(map(F,field['galois_generator']));a=[F(0),F(1),F(0)]
        require(algebra_eval(f,sigma,f)==[0,0,0],'sigma not an automorphism')
        require(algebra_eval(sigma,algebra_eval(sigma,sigma,f),f)==a,'sigma order not 3')
        M=field['galois_unit_matrix']
        require(det(M)==1 and sum(M[i][i] for i in range(2))==-1,'Galois unit representation')
        for j,u in enumerate(field['units']):
            image=algebra_eval(u,sigma,f)
            product_unit=mul(power(list(map(F,field['units'][0])),M[0][j],f),
                             power(list(map(F,field['units'][1])),M[1][j],f),f)
            sign=(-1)**field['galois_unit_torsion_exponents'][j]
            require(image==[sign*c for c in product_unit],'wrong exact Galois unit matrix')
    ps=[p for p in range(5,98) if all(p%d for d in range(2,isqrt(p)+1))]
    qs=[q for q in range(7,74) if q%3==1 and all(q%d for d in range(2,isqrt(q)+1))]
    census=[(q,p) for q in qs for p in ps if p!=q and pow(p,(q-1)//3,q)==1]
    require(census==[(r['q'],r['p']) for r in data['rows']],'selection census mismatch')
    require(fields[7]['coefficients']==[-1,-2,1,1],'known conductor-seven polynomial')
    results=[]
    for row in data['rows']:
        q,p=row['q'],row['p'];field=fields[q];f=field['coefficients'];s=row['square']
        require(field['order_index']%p!=0,'bad power order')
        require(row['ramification_and_residue_degrees']==[[1,1]]*3,'not completely split')
        labels=[r for r in range(p) if evaluate(f,r,p)==0]
        require(labels==row['root_labels'] and len(labels)==3,'residue labels')
        wrong_label=next(i for i in range(p) if evaluate(f,i,p)!=0)
        try:hensel(f,wrong_label,p,5)
        except AssertionError:pass
        else:raise AssertionError('wrong root control accepted')
        B=max(t['N'] for t in row['signed_minors'])+4
        G=floorlog(2*B+10,p);high=p**(B+G);mod=p**B
        roots=[hensel(f,r,p,B+G) for r in labels]
        L=[]
        units=[list(map(F,u)) for u in field['units']]
        transforms=[(units[1],units[0]),
                    (mul(units[0],units[1],f),units[1]),
                    (mul(units[0],units[0],f),units[1])]
        for i,x in enumerate(roots):
            compare(row['roots'][i],x,p)
            L.append([log_mod(evaluate(u,x,high),p,B) for u in units])
            for j in range(2):compare(row['logarithms'][i][j],L[i][j],p)
        require(all(sum(L[i][j] for i in range(3))%mod==0 for j in range(2)),'column sum')
        minors=[(L[i][0]*L[j][1]-L[j][0]*L[i][1])%mod for i,j in [(1,2),(0,2),(0,1)]]
        for r,d in zip(row['signed_minors'],minors):compare(r,d,p)
        require((minors[0]-minors[2])%mod==0 and (minors[0]+minors[1])%mod==0,'minor signs')
        square=minors[2]**2%mod
        compare(s,square,p)
        require(all((d*d-square)%mod==0 for d in minors),'omitted embedding')
        require(s['valuation']>=4 and s['valuation']%2==0,'square valuation')
        require(p**(s['N']-s['valuation'])>=10**100,'insufficient relative accuracy')
        require(p**(s['N']-s['valuation']-1)<10**100,'nonminimal requested modulus')
        # Re-evaluate transformed exact units, not just transformed log columns.
        for (u,v),factor in zip(transforms,[1,1,4]):
            LL=[[log_mod(evaluate(w,x,high),p,B) for w in [u,v]] for x in roots]
            d=det(LL[:2])
            require((d*d-factor*square)%mod==0,'exact basis transformation')
        # Unit inversion is evaluated by modular inversion of the exact unit image.
        invL=[[log_mod(pow(evaluate(units[0],x,high),-1,high),p,B),
               log_mod(evaluate(units[1],x,high),p,B)] for x in roots]
        require((det(invL[:2])**2-square)%mod==0,'unit inversion')
        appended=det([[1,1,1],[L[i][0] for i in range(3)],[L[i][1] for i in range(3)]])
        require((appended-3*minors[2])%mod==0,'appended row factor')
        # Hofmann-Zhang-style p-maximal orbit pair. Determine the exact integer
        # exponent matrix from the certified Galois action; its determinant
        # is the exact subgroup index, not an assumed saturation statement.
        M=field['galois_unit_matrix'];orbit=None
        for ex in product(range(p),repeat=2):
            sex=[sum(M[i][j]*ex[j] for j in range(2)) for i in range(2)]
            index=abs(ex[0]*sex[1]-ex[1]*sex[0])
            if index%p!=0:
                orbit=(list(ex),sex,index);break
        require(orbit is not None,'no p-maximal orbit pair')
        ex,sex,index=orbit
        # Exact automorphism maps each labelled embedding to one of the three.
        sigma=field['galois_generator']
        perm=[next(j for j,y in enumerate(roots) if (evaluate(sigma,x,high)-y)%high==0) for x in roots]
        eimages=[pow(evaluate(units[0],x,high),ex[0],high)*pow(evaluate(units[1],x,high),ex[1],high)%high for x in roots]
        elogs=[log_mod(x,p,B) for x in eimages]
        a,b=elogs[0],elogs[perm[0]]
        quadratic=(a*a+a*b+b*b)%mod
        require(valuation(quadratic,p)*2==s['valuation'],'orbit quadratic valuation')
        require((quadratic**2-index**2*square)%mod==0,'orbit exact index square')
        # For each p, controls also exercise the logarithm's nonzero behavior.
        require(log_mod(1,p,B)==0 and log_mod(high-1,p,B)==0,'torsion controls')
        control=log_mod(1+p,p,B)
        require(control%p**2==p and valuation(control,p)==1,'known nonzero log')
        for wrong in [dict(s,residue=str(int(s['residue'])+p**s['valuation'])),dict(s,unit=str(int(s['unit'])+1))]:
            try:compare(wrong,square,p)
            except AssertionError:pass
            else:raise AssertionError('negative residue control accepted')
        require((4*square-square)%p**s['N']!=0 and (9*square-square)%p**s['N']!=0,'scaling control inconclusive')
        require(p**(s['N']-1-s['valuation'])<10**100,'shortened precision control')
        results.append({'q':q,'p':p,'valuation':s['valuation'],'modulus_exponent':s['N'],
                        'log_check_absolute_digits':B,'embedding_permutation':perm,
                        'orbit_exponents':ex,'sigma_exponents':sex,'exact_orbit_index':index,
                        'full_residue_check':True,'all_basis_controls':True,
                        'wrong_root_rejected':True,'wrong_residue_rejected':True,
                        'wrong_scaling_rejected':True,'shortened_precision_rejected':True,
                        'known_log_1_plus_p_mod_p_squared':int(control%p**2)})
    pilot=next(r for r in results if (r['q'],r['p'])==(7,13))
    require(pilot['valuation']==4,'reported pilot valuation')
    if stored is not None:
        # Website nested entries. No comparison to freshly produced library logs.
        numbers=stored.get('Numbers',stored.get('Data'))
        if isinstance(numbers,list):
            records={(int(r['params']['q']),int(r['params']['p'])):r for r in numbers}
            require(len(records)==len(numbers)==54,'duplicate or missing stored rows')
        else:
            require(isinstance(numbers,dict),'unexpected stored entries shape')
            records={(int(q),int(p)):r for q,group in numbers.items() for p,r in group.items()}
        require(set(records)==set(census),'stored selected arguments differ')
        for row in data['rows']:
            q,p=row['q'],row['p'];rec=records[q,p]
            text=rec['number'] if isinstance(rec,dict) else rec
            require(isinstance(text,str),'stored p-adic must carry explicit modulus')
            import re
            match=re.fullmatch(r'(\d+)\^(\d+)\s*\*\s*(\d+)\s*\+\s*O\((\d+)\^(\d+)\)',text)
            require(match is not None,'unsupported stored p-adic encoding: '+text[:50])
            pp,v,u,pp2,N=map(int,match.groups())
            s=row['square']
            require(pp==pp2==p and v==s['valuation'] and N==s['N'],'stored precision mismatch')
            require((p**v*u-int(s['residue']))%p**N==0,'stored residue mismatch')
    return {'checked_entries':len(results),'total_entries':len(census),'failures':[],
            'known_answer_control':True,'negative_control_rejected':True,
            'stored_readback_checked':stored is not None,'fields_gaussian_period_checked':9,
            'results':results,'limitations':'PARI full-unit certification is shared with the generator; no separate unit-lattice enumeration is claimed.'}


if __name__=='__main__':
    path=Path(sys.argv[1]);data=json.loads(path.read_text())
    stored=json.loads(Path(sys.argv[2]).read_text()) if len(sys.argv)>2 else None
    try:
        result=run(data,stored)
    except Exception as e:
        result={'checked_entries':0,'total_entries':len(data['rows']),'failures':[str(e)],
                'known_answer_control':False,'negative_control_rejected':False}
        (path.parent/'check-results.json').write_text(json.dumps(result,indent=2))
        raise
    result['input_sha256']=hashlib.sha256(path.read_bytes()).hexdigest()
    (path.parent/'check-results.json').write_text(json.dumps(result,indent=2))
    print(json.dumps({k:v for k,v in result.items() if k!='results'},indent=2))