generate-early.py

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

6769 bytes, as of the version from 2026-11-28 22:17 (current). Recorded here, not run.

"""Generate T864, geodesic lengths of hyperbolic knots.

Install in SageMath: sage -pip install snappy==3.3.2 numberdb
Run: sage -python generate.py --compute   (offline computation)
     sage -python generate.py             (verify all stored entries)
     sage -python generate.py --publish   (fill the existing authorized draft)
Keep knotinfo-inputs.json alongside this source. Default enumeration is the
first four real length order statistics, with geometric multiplicity, on all
243 hyperbolic prime knots through ten crossings in corrected KnotInfo order.
Curvature is -1; geodesics are primitive and unoriented. Mirrors agree.

SnapPy 3.3.2's verified length_spectrum_alt_gen uses certified shapes and
interval tiling. Stop only at an emitted lower length bound above the fourth
smallest upper endpoint already seen. Sort lower and upper endpoints
separately; never assign an overlapping interval to a permanent rank by word.
Start at 540 bits; reject nonfinite, nonpositive or insufficiently narrow bounds.
Word witnesses, unsimplified presentation, triangulation, shape enclosures,
trace enclosures and stopping bound are retained in the computation packet.
All uncertainty propagates; no approximate result becomes an exact number.

An opt-in cache, NUMBERDB_USE_CHECKPOINTS=1, reads spectrum-checkpoints.json
bound to the input SHA-256 and this algorithm version. Omit it to recompute.
Cache packets are computational evidence, not an independent oracle.
"""
import numberdb.sage as numberdb
from numberdb._write import to_text
from sage.rings.rational_field import QQ
from sage.rings.real_mpfi import RealIntervalField
import snappy
from snappy.len_spec import mcomplex_for_len_spec
import ast,json,os,hashlib,time
from pathlib import Path
ROOT=Path(__file__).resolve().parent
ALGORITHM='verified-stream-endpoint-order-v1'
INPUT_PATH=ROOT/'knotinfo-inputs.json'
INPUT_HASH=hashlib.sha256(INPUT_PATH.read_bytes()).hexdigest()
TORUS={(3,1),(5,1),(7,1),(8,19),(9,1),(10,124)}
KNOTS={(d['n'],d['k']):d for d in json.loads(INPUT_PATH.read_text())['knots'] if (d['n'],d['k']) not in TORUS}
assert len(KNOTS)==243

def endpoints(x):return [str(x.lower().exact_rational()),str(x.upper().exact_rational())]
def complex_endpoints(z):return [endpoints(z.real()),endpoints(z.imag())]
def from_endpoints(e,R):return R(QQ(e[0]),QQ(e[1]))
def geometric(M):
    for _ in range(50):
        if M.solution_type()=='all tetrahedra positively oriented':return M
        M.randomize()
    raise ArithmeticError('No positive ideal triangulation in 50 attempts')
def manifold(d):
    word=ast.literal_eval(d['braid_notation'])
    if word and isinstance(word[0],list):word=word[0]  # documented 10_136 alternatives
    return geometric(snappy.Link(braid_closure=word).exterior())
def word_matrix(word,matrices):
    A=matrices[0]
    if not all(c.isalpha() and c.isascii() for c in word):raise ValueError('Unsupported word spelling')
    for c in word:
        i=ord(c.lower())-ord('a')+1
        A=A*matrices[i if c.islower() else -i]
    return A

def compute_packet(n,k,prec=540):
    if snappy.__version__!='3.3.2':raise RuntimeError('This archived implementation requires SnapPy 3.3.2')
    start=time.monotonic();M=manifold(KNOTS[n,k]);R=RealIntervalField(prec)
    witnesses=[];stop=None;previous=None
    stream=M.length_spectrum_alt_gen(verified=True,bits_prec=prec)
    for g in stream:
        r=g.length.real()
        assert r.lower()>0 and r.upper()<10**6
        if previous is not None:assert r.lower()>=previous
        previous=r.lower()
        if len(witnesses)>=4 and r.lower()>sorted(QQ(t['real'][1]) for t in witnesses)[3]:
            stop={'word':g.word,'real':endpoints(r),'complex':complex_endpoints(g.length)};break
        witnesses.append({'word':g.word,'real':endpoints(r),'complex':complex_endpoints(g.length)})
        if len(witnesses)>500:raise ArithmeticError('Unexpectedly large tied prefix')
    assert stop is not None
    lo=sorted(QQ(t['real'][0]) for t in witnesses)
    hi=sorted(QQ(t['real'][1]) for t in witnesses)
    values=[R(lo[j],hi[j]) for j in range(4)]
    assert all(v.lower()>0 and v.absolute_diameter()<QQ(1)/10**115 for v in values)
    # A separately evaluated representation supplies trace witnesses for checks.
    mc=mcomplex_for_len_spec(M,bits_prec=prec,verified=True)
    assert mc.num_generators<=26
    for t in witnesses+[stop]:
        A=word_matrix(t['word'],mc.GeneratorMatrices)
        assert (1 in A.det().real()) and A.det().imag().contains_zero()
        t['trace']=complex_endpoints(A.trace())
    G=M.fundamental_group(simplify_presentation=False)
    return {'n':n,'k':k,'bits':prec,'triangulation':M._to_string(),'isosig':M.triangulation_isosig(),
            'presentation':{'generators':G.generators(),'relators':G.relators()},
            'shapes':[complex_endpoints(t.ShapeParameters[3]) for t in mc.Tetrahedra],
            'witnesses':witnesses,'stop':stop,'values':[endpoints(v) for v in values],
            'numbers':[to_text(v,digits=100) for v in values],'seconds':time.monotonic()-start}

class Geodesics(numberdb.Generator):
    table='T864';parameters=('n','k','j');type='R';digits=100;rigour='proven'
    files=('generate.py','knotinfo-inputs.json','spectrum-checkpoints.json')
    def __init__(self):
        self.packets={}
        if os.environ.get('NUMBERDB_USE_CHECKPOINTS')=='1':
            p=json.loads((ROOT/'spectrum-checkpoints.json').read_text())
            assert p['input_sha256']==INPUT_HASH and p['algorithm']==ALGORITHM
            self.packets={(d['n'],d['k'],d['bits']):d for d in p['knots']}
    def packet(self,n,k,digits=100):
        prec=max(540,numberdb.bits(digits,losing=128));key=(n,k,prec)
        if key not in self.packets:self.packets[key]=compute_packet(n,k,prec)
        return self.packets[key]
    def enumerate(self):
        for n,k in sorted(KNOTS):
            for j in range(1,5):yield {'n':n,'k':k,'j':j}
    def value(self,params,digits):
        n,k,j=(int(params[s]) for s in self.parameters)
        if j<1:raise ValueError('Rank starts at one')
        if j>4:raise ValueError('Extend the certified prefix before requesting this rank')
        p=self.packet(n,k,digits);R=RealIntervalField(p['bits'])
        v=from_endpoints(p['values'][j-1],R)
        assert v.lower()>0 and v.upper()<10**6 and v.absolute_diameter()<QQ(1)/10**(digits+10)
        return v

if __name__=='__main__':
    import sys
    g=Geodesics()
    if '--publish' in sys.argv:print(g.publish(message='Fill checked geodesic lengths; proposal https://github.com/numberdb/numberdb-data/issues/408'))
    elif '--compute' in sys.argv:
        for n,k in sorted(KNOTS):print(json.dumps({'event':'knot',**g.packet(n,k)}),flush=True)
    else:print(g.verify(sample=None))