character_check.py

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

8055 bytes, as of the version from 2026-11-18 23:06 (current). Recorded here, not run.

"""Independent BCM finite-character-sum check of T762's stored/offline cubics.

Run with full Sage and numberdb, as:
  sage -python character_check.py entries.json
The input is either the builder's flat entries or an exported live document.
This code does not import the generator, Sage HGM, or PARI HGM. It uses BCM
Theorem 1.3/Assumption 1.4 directly, with finite-field absolute traces and
complex Arb balls. Exact integrality of the rational-data H_q and unique
integer containment recover the exact trace; balls must be finite, contain
zero in the imaginary part, and have both radii <1/4. 512 working bits give
ample room even before integer recovery. All three power traces independently
check every coefficient of every cubic, without the functional-equation sign.
Each completed finite field emits a resumable CHARACTER_CHECKPOINT line.
"""
import sys,json,time,hashlib,itertools
from fractions import Fraction
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.symbolic.ring import SR
from sage.rings.complex_arb import ComplexBallField
from sage.rings.finite_rings.finite_field_constructor import GF
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.env import SAGE_VERSION

CBF=ComplexBallField(512)
GAMMA={'2.2.2':([2,2,2],[1,1,1,1,1,1]),'2.3':([2,3],[1,1,1,1,1]),
       '2.4':([4],[1,1,1,1]),'2.6':([6],[3,1,1,1])}
T_RING=PolynomialRing(ZZ,'T')

def primitive_powers(n):
    root=(CBF(0,2)*CBF.pi()/n).exp()
    out=[CBF(1)]
    for j in range(1,n):out.append(out[-1]*root)
    return out


def setup(q):
    f=GF(q,'a');p=int(f.characteristic());n=q-1;a=f.multiplicative_generator()
    omega=primitive_powers(n);psi=primitive_powers(p)
    buckets=[[] for _ in range(p)];logs={};x=f.one()
    for j in range(n):
        buckets[int(x.trace())].append(j);logs[x]=j;x*=a
    assert x==f.one() and len(logs)==n
    gauss=[CBF(-1)]
    for m in range(1,n):
        v=CBF(0)
        for tr,js in enumerate(buckets):
            subtotal=CBF(0)
            for j in js:subtotal+=omega[(m*j)%n]
            v+=psi[tr]*subtotal
        assert (v.real().is_finite() and v.imag().is_finite());gauss.append(v)
    return {'q':q,'n':n,'field':f,'omega':omega,'gauss':gauss,'logs':logs}


def character_coefficients(ctx,positive,negative):
    q,n=ctx['q'],ctx['n'];g=ctx['gauss'];s0=min(len(positive),len(negative))
    coefficients=[]
    for m in range(n):
        sm=min(sum((m*d)%n==0 for d in positive),sum((m*d)%n==0 for d in negative))
        v=CBF(QQ(q)**(sm-s0))
        for d in positive:v*=g[(d*m)%n]
        for d in negative:v*=g[(-d*m)%n]
        coefficients.append(v)
    M=QQ(1)
    for d in positive:M*=ZZ(d)**d
    for d in negative:M/=ZZ(d)**d
    epsilon=ZZ(-1)**sum(negative)
    return coefficients,M,epsilon,QQ((-1)**(len(positive)+len(negative)))/(1-q)


def finite_trace(ctx,coeffs,z):
    coefficients,M,epsilon,scale=coeffs
    f,n,omega=ctx['field'],ctx['n'],ctx['omega']
    x=f(epsilon/M*QQ(z));ell=ctx['logs'][x]
    v=CBF(0)
    for m,c in enumerate(coefficients):v+=c*omega[(ell*m)%n]
    v*=scale
    assert (v.real().is_finite() and v.imag().is_finite()) and v.imag().contains_zero()
    assert v.real().rad()<QQ(1)/4 and v.imag().rad()<QQ(1)/4
    integer=v.real().lower().ceil()
    assert integer == v.real().upper().floor()
    return int(integer),str(v.real().rad()),str(v.imag().rad())


def cubics_agree(coeff,s):
    c0,c1,c2,c3=map(int,coeff)
    return c0==1 and [-c1,c1*c1-2*c2,-c1**3+3*c1*c2-3*c3]==s


def unit(n):
    n=abs(n)
    if n==0:return False
    for p in (2,3):
        while n%p==0:n//=p
    return n==1


def independent_arguments():
    by_fractions={Fraction(u,v) for u in range(-9,10) for v in range(1,10)
                  if unit(u) and unit(v) and unit(u-v)}
    by_orbits=set()
    for x in map(Fraction,['1/2','1/3','1/4','1/9']):
        by_orbits.update([x,1-x,1/x,1/(1-x),x/(x-1),(x-1)/x])
    assert by_fractions==by_orbits and len(by_fractions)==21
    return sorted(by_fractions)


def read_records(path):
    raw=json.load(open(path))
    if isinstance(raw,list):return raw
    # Local pure flatten conversion is not needed by an external contributor:
    # exported documents in this build use flat Numbers.
    block=raw.get('Numbers',raw.get('Data'))
    if isinstance(block,list):return block
    from numberdb_app.flatten import to_records
    return to_records(raw)


def main(path):
    started=time.monotonic();rows=read_records(path);zs=independent_arguments()
    expected={(a,str(z),p) for a in GAMMA for z in zs for p in (5,7,11,13)}
    got={(str(x['params']['template']),str(x['params']['z']),int(x['params']['p'])) for x in rows}
    assert expected==got and len(rows)==336
    all_traces={};checkpoints=[];controls=[]
    for p in (5,7,11,13):
        for e in (1,2,3):
            q=p**e;t=time.monotonic();ctx=setup(q);traces={}
            for template,pn in GAMMA.items():
                coeffs=character_coefficients(ctx,*pn)
                for z in zs:
                    value,rr,ir=finite_trace(ctx,coeffs,str(z))
                    traces[template+','+str(z)]={'trace':value,'real_radius':rr,'imag_radius':ir}
                    all_traces[(template,str(z),p,e)]=value
            if e==1:
                # BCM Corollary 1.6: N(x^3+3*x^2-4*t)=1+H_q.
                c=character_coefficients(ctx,[3],[2,1]);f=ctx['field']
                for t0 in (2,3):
                    roots=sum(x**3+3*x*x-4*f(t0)==0 for x in f)
                    value,_,_=finite_trace(ctx,c,str(t0));assert value==roots-1
                    controls.append({'p':p,'t':t0,'cubic_roots':roots,'finite_sum':value})
                # BCM Corollary 1.7: #E=q+1-H_q for y^2+xy+y=(t/27)x^3.
                c=character_coefficients(ctx,[3],[1,1,1]);t0=f(2)
                count=1+sum(y*y+x*y+y==t0/f(27)*x**3 for x in f for y in f)
                value,_,_=finite_trace(ctx,c,'2');assert value==q+1-count
                controls.append({'p':p,'t':2,'elliptic_points':count,'finite_sum':value})
            cp={'p':p,'e':e,'q':q,'seconds':time.monotonic()-t,'traces':traces,
                'checker_sha256':hashlib.sha256(open(__file__,'rb').read()).hexdigest()}
            checkpoints.append(cp);print('CHARACTER_CHECKPOINT '+json.dumps(cp),flush=True)
    failures=[];checked=[]
    for row in rows:
        a,z,p=str(row['params']['template']),str(row['params']['z']),int(row['params']['p'])
        coeff=list(T_RING(str(row['number'])))
        traces=[all_traces[(a,z,p,e)] for e in (1,2,3)]
        if not cubics_agree(coeff,traces):failures.append({'params':row['params'],'coeff':list(map(int,coeff)),'traces':traces})
        checked.append({'params':row['params'],'coefficients':list(map(int,coeff)),'traces':traces})
    known={5:[1,4,20,125],7:[1,-6,-42,343],11:[1,2,-22,-1331],13:[1,12,-156,-2197]}
    known_ok=all(cubics_agree(c,[all_traces[('2.6','1/4',p,e)] for e in (1,2,3)]) for p,c in known.items())
    c=known[5];s=[all_traces[('2.6','1/4',5,e)] for e in (1,2,3)]
    corrupt=[c[0],c[1]+1,c[2],c[3]];wrong_sign=[c[0],c[1],-c[2],-c[3]]
    rejected=not cubics_agree(corrupt,s) and not cubics_agree(wrong_sign,s)
    assert known_ok and rejected and not failures
    result={'checked_entries':len(rows),'total_entries':len(rows),'failures':failures,
            'known_answer_control':known_ok,'negative_control_rejected':rejected,
            'controls':controls,'negative_controls':{'coefficient_perturbation':corrupt,'wrong_even_weight_sign':wrong_sign,'expected_traces':s},
            'method':'BCM Theorem 1.3 finite character sums at p,p^2,p^3; unique integer from 512-bit Arb balls; Newton identities',
            'working_bits':512,'max_q':2197,'checked':checked,'seconds':time.monotonic()-started,
            'sage':SAGE_VERSION,'skill_manifest':'skill-manifest.json'}
    print('CHARACTER_RESULTS '+json.dumps(result),flush=True)

if __name__=='__main__':main(sys.argv[1] if len(sys.argv)>1 else '/work/offline-entries.json')