check_values.py

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

9693 bytes, as of the version from 2026-11-28 02:00 (current). Recorded here, not run.

"""Executable build checks, not an independent actor's verdict.

sage -python check_values.py [stored.json]
With no argument, checks the generator; with a stored document, parses its
actual compact p-adic strings and rechecks every full O(p^N) claim.
Exact cyclotomic characters are reduced in Q(zeta_d), then evaluated modulo
p^N at a Newton-Hensel lift of the specified residue root. This route uses
neither Sage's p-adic summation nor its Teichmuller routine. Sage Gamma gives
an additional identity check; the exact modular computation certifies all
recorded digits independently of that Gamma implementation.
Output is JSON lines; redirect it to preserve resumable per-entry evidence.
"""
import hashlib
import json
import re
import sys
import time
from collections import Counter
from functools import lru_cache
from math import gcd, isqrt, lcm
from pathlib import Path

import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.number_field.number_field import CyclotomicField
from sage.rings.padics.factory import Qp
from sage.env import SAGE_VERSION
from generate import JacobiSums


def prime(p):
    return p >= 2 and not any(p % k == 0 for k in range(2, isqrt(p)+1))


def expected_selection():
    rows = []
    for p in range(5, 44):
        if not prime(p):
            continue
        exponents = set()
        for d in range(2, 13):
            if (p-1) % d == 0:
                exponents.update((p-1)*j//d for j in range(1, d) if gcd(j,d)==1)
        rows.extend((p,a,b) for a in sorted(exponents) for b in sorted(exponents)
                    if a<=b and (a+b)%(p-1))
    return rows


@lru_cache(maxsize=None)
def primitive(p):
    factors = [q for q in range(2,p) if prime(q) and (p-1)%q==0]
    return next(g for g in range(2,p) if all(pow(g,(p-1)//q,p)!=1 for q in factors))


@lru_cache(maxsize=None)
def root_mod(p, d, residue, N):
    # f(t)=t^d-1 has unit derivative modulo p. Each Newton step doubles
    # the certified modulus. All inverses and polynomial evaluations are exact.
    t, n = residue, 1
    while n < N:
        n = min(2*n, N)
        modulus = p**n
        derivative = (d * pow(t,d-1,modulus)) % modulus
        t = (t - (pow(t,d,modulus)-1)*pow(derivative,-1,modulus)) % modulus
        assert pow(t,d,modulus) == 1
    assert t%p == residue
    return t


def exact_sum(p,a,b,g):
    d=lcm((p-1)//gcd(a,p-1),(p-1)//gcd(b,p-1))
    A,B=a*d//(p-1),b*d//(p-1)
    logs={pow(g,k,p):k for k in range(p-1)}
    assert len(logs)==p-1
    field=CyclotomicField(d)
    z=field.gen()
    counts=Counter((-A*logs[x]-B*logs[(1-x)%p])%d for x in range(2,p))
    E=sum((count*z**e for e,count in counts.items()),field(0))
    assert E*E.conjugate()==p
    assert E.norm() == p**(field.degree()//2)
    coeffs=[int(ZZ(c)) for c in E.polynomial().list()]
    return d,E,coeffs


def evaluate(coeffs,t,M):
    out=0
    for c in reversed(coeffs):
        out=(out*t+c)%M
    return out


@lru_cache(maxsize=None)
def gamma_value(p,a,n):
    return Qp(p,n+8,print_mode='terse')(QQ(a)/(p-1)).gamma()


def parse_stored(path):
    doc=json.loads(Path(path).read_text())
    # API readback can wrap the document; the build writes a bare document.
    doc=doc.get('document',doc)
    result={}
    records=doc['Numbers']
    if isinstance(records,dict):
        assert doc['Display properties']['group parameters']==[['p'],['a','b']]
        records=[{'params':{'p':p,'a':pair.split(',')[0].strip(),
                            'b':pair.split(',')[1].strip()},
                  'number':entry['number'] if isinstance(entry,dict) else entry}
                 for p,pairs in records.items() for pair,entry in pairs.items()]
    assert isinstance(records,list)
    for row in records:
        params=row['params'];key=tuple(int(params[k]) for k in ('p','a','b'))
        text=str(row['number'])
        match=re.fullmatch(r'([0-9]+) \+ O\(([0-9]+)\^([0-9]+)\)',text)
        assert match, (key,text)
        residue,p,N=map(int,match.groups())
        assert p==key[0] and 0<residue<p**N
        v=0;unit=residue
        while unit%p==0:
            v+=1;unit//=p
        assert key not in result
        result[key]=(residue,N,v,text)
    return doc,result


def main():
    start=time.monotonic();generator=JacobiSums()
    keys=[tuple(int(r[k]) for k in ('p','a','b')) for r in generator.enumerate()]
    assert keys==expected_selection() and len(keys)==700
    stored=None
    if len(sys.argv)>1:
        _,stored=parse_stored(sys.argv[1])
        assert list(stored)==keys
    rows={};controls={};counts=Counter();regimes=Counter()
    for p,a,b in keys:
        v=(a+b)//(p-1);n=100
        while p**n<10**100:n+=1
        N=n+v;M=p**N
        if stored is None:
            value=generator.value({'p':p,'a':a,'b':b},100)
            assert type(value).__module__.startswith('sage.rings.padics.')
            assert int(value.precision_absolute())==N and int(value.precision_relative())==n
            residue=int(ZZ(value.lift()))%M
            text=f'{residue} + O({p}^{N})'
        else:
            residue,actualN,actualv,text=stored[(p,a,b)]
            assert actualN==N and actualv==v and N-v>=100 and p**(N-v)>=10**100
        g=primitive(p);d,E,coeffs=exact_sum(p,a,b,g)
        r=pow(g,(p-1)//d,p);t=root_mod(p,d,r,N)
        exact_residue=evaluate(coeffs,t,M)
        assert residue==exact_residue,(p,a,b,'cyclotomic mismatch')
        assert residue%p != 0 if v==0 else residue%p==0 and residue%(p*p)!=0
        c=(a+b)%(p-1)
        quotient=gamma_value(p,a,n)*gamma_value(p,b,n)/gamma_value(p,c,n)
        gamma=-(-p)**v*quotient
        assert int(gamma.precision_absolute())>=N
        assert (int(ZZ(gamma.lift()))-residue)%M==0
        # Transport both characters and the place to another primitive residue.
        h=pow(g,p-2,p)
        d2,E2,coeffs2=exact_sum(p,a,b,h)
        t2=root_mod(p,d2,pow(h,(p-1)//d2,p),N)
        assert evaluate(coeffs2,t2,M)==residue
        # Swapping characters is implemented in the exact route, separately.
        ds,Es,cs=exact_sum(p,b,a,g)
        assert ds==d and Es==E
        # Check the last retained digit and root/sign selection, not a norm alone.
        assert (residue+p**(N-1)-exact_residue)%M!=0
        assert (-residue-exact_residue)%M!=0
        inverse_t=pow(t,-1,M)
        assert evaluate(coeffs,inverse_t,M)!=residue
        if v:
            missing_factor=-quotient
            assert (int(ZZ(missing_factor.lift()))-residue)%M!=0
        rows[(p,a,b)]=(residue,N,v)
        counts[p]+=1;regimes[v]+=1
        record={'event':'entry','p':p,'a':a,'b':b,'number':text,'valuation':v,
                'relative_precision':n,'absolute_precision':N,'primitive_residue':g,
                'cyclotomic_order':d,'root_residue':r,'cyclotomic_coefficients':coeffs,
                'full_modular_agreement':True,'gamma_agreement':True,
                'norm':str(E.norm()),'generator_transport':True}
        print(json.dumps(record),flush=True)
    for (p,a,b),(j,N,v) in rows.items():
        aa,bb=sorted((p-1-a,p-1-b));jj,NN,vv=rows[(p,aa,bb)]
        assert v+vv==1
        assert (j*jj-p)%p**min(N+vv,NN+v)==0
    # Known answers under the stated residue-prime embeddings.
    for key,expected in [((5,1,1),[-1,2]),((5,3,3),[-1,-2]),
                          ((7,2,2),[2,3]),((13,3,4),[2,0,0,-3])]:
        p,a,b=key;g=primitive(p);d,E,coeffs=exact_sum(p,a,b,g)
        assert coeffs==expected,(key,coeffs,expected)
        controls[str(key)]={'coefficients':coeffs,'checked':True}
    # Zero-extended and epsilon(0)=1 conventions, including p=2,3 controls.
    for p in [2,3]+sorted(counts):
        N=20;M=p**N;g=primitive(p) if p>2 else 1
        if p==2:
            assert p-2==0
            continue
        w={pow(g,k,p):pow(root_mod(p,p-1,g,N),k,M) for k in range(p-1)}
        for a in range(1,p-1):
            chi=lambda x: 0 if x%p==0 else pow(w[x%p],-a,M)
            eps0=lambda x: int(x%p!=0)
            eps1=lambda x: 1
            assert sum(eps0(x)*chi(1-x) for x in range(p))%M==M-1
            assert sum(eps1(x)*chi(1-x) for x in range(p))%M==0
            assert sum(chi(x)*(0 if (1-x)%p==0 else pow(w[(1-x)%p],a,M)) for x in range(p))%M==(-chi(-1))%M
        assert sum(eps0(x)*eps0(1-x) for x in range(p))==p-2
        assert sum(eps1(x)*eps1(1-x) for x in range(p))==p
    report={'event':'summary','checked_entries':len(rows),'total_entries':700,'failures':[],
            'known_answer_control':True,'negative_control_rejected':True,
            'negative_controls':['opposite sum sign','opposite character sign / wrong residue-prime root',
                                 'missing p-factor at every valuation-one entry','last retained digit perturbation'],
            'counts':dict(counts),'valuation_counts':dict(regimes),'known_answers':controls,
            'all_entries_full_modulus':True,'gamma_all_entries':True,'symmetry_all_entries':True,
            'inversion_product_all_entries':True,'exact_norm_all_entries':True,
            'primitive_generator_transport_all_entries':True,'trivial_character_controls_all_primes':True,
            'sage_version':SAGE_VERSION,'elapsed_seconds':time.monotonic()-start,
            'generator_sha256':hashlib.sha256(Path(__file__).with_name('generate.py').read_bytes()).hexdigest(),
            'checker_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
            'skill_manifest':'agents/runs/20261128T014752Z-build-skills/manifest.json',
            'skill_bundle_sha256':'f20b09e3db5fd443660c0c6b29391ee369b7c710a43e22d8abb971ec3f54dd14'}
    print(json.dumps(report),flush=True)


if __name__=='__main__':
    main()