check_lattice.py

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

8746 bytes, as of the version from 2026-11-16 04:25 (current). Recorded here, not run.

"""Independent builder checks of Fermat lattices; not a scientific verdict.

Run with SageMath, with reference-divisors.json and certificate-*.json.gz beside
this script. Optional stored-document.json checks every uploaded exact value.
All relative phase configurations are checked by cyclotomic equation-matrix
ranks; deck transformations reduce arbitrary pairs to one phase-zero plane.
This script does not import lattice.py or the product generator.
"""
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.finite_rings.finite_field_constructor import GF
from sage.rings.number_field.number_field import CyclotomicField
from sage.matrix.constructor import matrix
from pathlib import Path
from itertools import permutations,product
import json,gzip,time,sys,base64,math
from modular import smith_factors
sys.set_int_max_str_digits(100000)
work=Path(__file__).parent

def emit(name,obj):
    print('ARTIFACT '+name+' '+base64.b64encode(json.dumps(obj,indent=2).encode()).decode(),flush=True)

def exact_rank(p,q,n,z,F):
    rows=[]
    for u,v,e in p+q:
        row=[F(0)]*(n+2);row[u]=1;row[v]=-z**e;rows.append(row)
    return matrix(F,rows).rank()

def canonical_matchings(n):
    return sorted({tuple(sorted(tuple(sorted(s[i:i+2])) for i in range(0,n+2,2)))
                   for s in permutations(range(n+2))})

def variations(signs):
    signs=[int(x>0)-int(x<0) for x in signs if x]
    return sum(a!=b for a,b in zip(signs,signs[1:]))

def signature(K):
    coeff=list(reversed(K.charpoly(algorithm='flint').list()));r=K.nrows()
    positive=variations(coeff)
    negative=variations([c*(-1)**(r-i) for i,c in enumerate(coeff)])
    assert positive+negative==r
    return [positive,negative]

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

def intersection_value_from_rank(rank,n,d):
    dim=n+1-rank
    return sum((1-d)**i for i in range(dim+1)) if dim>=0 else 0

def validate_quotient(G,C,K,minor_rows=None):
    r=K.nrows()
    require(G==G.transpose() and K==K.transpose(),'symmetry')
    if minor_rows is None:minor_rows=list(C.transpose().change_ring(GF(1000003)).pivots())
    require(len(minor_rows)==r,'no candidate full-rank coordinate minor')
    minor_det=abs(C.matrix_from_rows(minor_rows).det(algorithm='flint'))
    require(minor_det!=0,'singular coordinate minor')
    factors=list(minor_det.factor(proof=True))
    require(math.prod(int(prime)**int(e) for prime,e in factors)==minor_det,'incomplete factorization')
    primes=[]
    # Row index divides this nonzero maximal minor. It is 1 exactly when
    # every prime divisor of the minor sees full row-lattice rank modulo p.
    for prime,e in factors:
        rank=C.change_ring(GF(prime)).rank()
        require(rank==r,'coordinates do not integrally span')
        primes.append({'prime':str(prime),'exponent':int(e),'rank_mod_prime':int(rank)})
    require(G==C*K*C.transpose(),'quotient factorization')
    return {'maximal_minor_rows':minor_rows,'maximal_minor_determinant':str(minor_det),'prime_rank_certificates':primes,'row_lattice_index':1}

def validate_magnitude(determinant,expected):
    require(abs(determinant)==expected,'source absolute discriminant disagrees')

def check_one(row):
    n,d=row['n'],row['d'];t=time.monotonic();name=f'certificate-{n}-{d}.json.gz'
    o=json.loads(gzip.decompress((work/name).read_bytes()));ps=[tuple(tuple(x) for x in p) for p in o['planes']]
    N=len(ps);r=o['summary']['rank'];G=matrix(ZZ,o['G']);C=matrix(ZZ,o['C']);K=matrix(ZZ,o['K'])
    expected_ps={tuple((u,v,1+2*c) for (u,v),c in zip(m,cs))
                 for m in canonical_matchings(n) for cs in product(range(d),repeat=n//2+1)}
    require(set(ps)==expected_ps and len(set(ps))==N,'plane enumeration mismatch')
    require(N==math.prod(range(1,n+2,2))*d**(n//2+1),'plane count')
    index_certificate=validate_quotient(G,C,K,o['pivot_columns'])
    # Every original ideal lies on the all-plus Fermat model, since each
    # paired odd power satisfies (z^e)^d=-1. This also checks root order.
    F=CyclotomicField(2*d);z=F.gen();require(z.multiplicative_order()==2*d,'root order')
    require(all((z**e)**d==-1 for p in ps for _,_,e in p),'not on Fermat model')
    cache={};first_by_matching={}
    for p in ps:
        m=tuple((u,v) for u,v,e in p)
        if all(e==1 for _,_,e in p):first_by_matching[m]=p
    for m,p in first_by_matching.items():
        for q in ps:
            rank=exact_rank(p,q,n,z,F)
            val=intersection_value_from_rank(rank,n,d)
            # sum_{i=0}^dim (1-d)^i equals [1-(1-d)^(dim+1)]/d
            cache[(m,q)]=int(val)
    count=0
    for i,p in enumerate(ps):
        m=tuple((u,v) for u,v,e in p);shift=[0]*(n+2)
        for u,v,e in p:shift[u]=1-e
        for j,q in enumerate(ps):
            if j>i:break
            q0=tuple((u,v,(e+shift[u]-shift[v])%(2*d)) for u,v,e in q)
            require(G[i,j]==cache[(m,q0)],f'incidence mismatch {n},{d},{i},{j}')
            count+=1
    factors=[]
    for s,m in row['factors']:factors.extend([s]*m)
    determinant=int(K.det(algorithm='flint'));expected=math.prod(factors)
    actual,local_proof=smith_factors(K,determinant)
    require(actual==factors,'source invariant factors disagree')
    validate_magnitude(determinant,expected)
    sig=signature(K);require(sig==o['summary']['signature'],'signature')
    require(determinant==(-1)**sig[1]*expected,'determinant sign')
    # Explicit polarization: sum the d planes obtained by varying the last
    # phase of one matching, fixing all earlier phases at zero.
    target=next(iter(first_by_matching));h=[0]*N
    for i,p in enumerate(ps):
        if tuple((u,v) for u,v,e in p)==target and all(e==1 for u,v,e in p[:-1]):h[i]=1
    hm=matrix(ZZ,1,N,h);hc=hm*C
    require(hm*G==matrix(ZZ,1,N,[1]*N),'polarization-plane intersections')
    require((hc*K*hc.transpose())[0,0]==d,'polarization norm')
    return {'n':n,'d':d,'rank':r,'planes':N,'checked_unordered_pairs':count,'independent_cyclotomic_ranks':len(cache),'absolute_discriminant':str(expected),'signed_determinant':str(determinant),'signature':sig,'integral_index_certificate':index_certificate,'local_smith_certificate':local_proof,'source_printed_sign':row['printed_sign'],'source_sign_matches':row['printed_sign']==(-1)**sig[1],'seconds':time.monotonic()-t}

source=json.loads((work/'reference-divisors.json').read_text());results=[]
# Nonzero, zero, and deliberately invalid controls.
F=CyclotomicField(6);z=F.gen();p=((0,1,1),(2,3,1))
known=(intersection_value_from_rank(exact_rank(p,p,2,z,F),2,3)==-1
       and intersection_value_from_rank(exact_rank(p,((0,1,3),(2,3,3)),2,z,F),2,3)==0
       and intersection_value_from_rank(exact_rank(p,((0,1,1),(2,3,3)),2,z,F),2,3)==1)
require(known,'known incidence controls failed')
I=matrix(ZZ,2,2,1);validate_quotient(I,I,I)
p4=((0,1,1),(2,3,1),(4,5,1))
require(intersection_value_from_rank(exact_rank(p4,p4,4,z,F),4,3)==3,'fourfold self-intersection control')
require(signature(I)==[2,0] and signature(matrix(ZZ,[[1,0],[0,-1]]))==[1,1],'signature controls')
control_det=matrix(ZZ,[[8,0],[0,8]]).det();validate_magnitude(control_det,64)
negative=[]
for label,test in [
 ('wrong self-intersection',lambda:require(intersection_value_from_rank(exact_rank(p,p,2,z,F),2,3)==3,'wrong self-intersection rejected')),
 ('proper sublattice',lambda:validate_quotient(I,matrix(ZZ,[[2,0],[0,1]]),I)),
 ('wrong discriminant',lambda:validate_magnitude(control_det,65))]:
    try:test()
    except AssertionError:negative.append(label)
require(len(negative)==3,'negative controls failed')
for row in source['rows']:
    print('check',row['n'],row['d'],flush=True);out=check_one(row);results.append(out);print('checked',row['n'],row['d'],round(out['seconds'],2),flush=True)
    emit('check-results.json',{'checked_entries':len(results),'total_entries':15,'failures':[],'known_answer_control':known,'negative_control_rejected':len(negative)==3,'negative_controls':negative,'results':results})
if (work/'stored-document.json').exists():
    doc=json.loads((work/'stored-document.json').read_text());records=doc['Numbers'];expected={(x['n'],x['d']):x['absolute_discriminant'] for x in results}
    require(isinstance(records,list) and len(records)==15,'stored count')
    for entry in records:
        pp=entry['params'];require(str(entry['number'])==expected[(int(pp['n']),int(pp['d']))],'stored exact value mismatch')
    emit('stored-check-results.json',{'checked_entries':15,'total_entries':15,'failures':[],'known_answer_control':known,'negative_control_rejected':True,'method':'all stored exact integers against independent cyclotomic incidence and integral quotient calculations','results':results})