"""T732: Elliptic logarithm of the Heegner trace.

Install numberdb in SageMath 10.9 or later and keep heegner.py beside this file:
    sage -pip install numberdb
    sage -python generate.py            # read-only full reproduction check
    sage -python generate.py --publish  # fill the authorized private draft

(N,D,beta) uses all twelve genus-one levels and every fundamental D with
|D|<=100 satisfying the coprime Heegner condition, with every orientation.
The helper enumerates complete N-systems, obtains the full integral homology
lattice from primitive Gamma0 loops, and evaluates q-primitives in Arb balls.
Its elementary tail bound is 2*r^(M+1)/(1-r), from |a(n)|/n<=2.
480 working bits were measured on the complete selection; the saved evidence
reports the actual radii and term counts. No arbitrary Weierstrass period
normalization is substituted. Fricke/class conjugation proves the rational
real-period coordinate used to preserve exactly zero real components.

The generator submits entries additively; it never offers or publishes a draft.
"""
import numberdb.sage as numberdb
from functools import lru_cache
from heegner import Evaluator, selection
from fractions import Fraction
from sage.rings.rational_field import QQ

class HeegnerTrace(numberdb.Generator):
    table='T732'
    parameters=('N','D','beta')
    type='C'
    digits=100
    rigour='proven'
    files=('generate.py','heegner.py')
    @staticmethod
    @lru_cache(None)
    def evaluator(N,digits):
        return Evaluator(N,max(480,numberdb.bits(digits,losing=144)))
    def enumerate(self,bound=100):
        yield from selection(bound)
    def value(self,params,digits):
        N,D,beta=(int(params[k]) for k in self.parameters)
        assert N in (11,14,15,17,19,20,21,24,27,32,36,49)
        assert D<0 and (beta*beta-D)%(4*N)==0 and 0<=beta<2*N
        v=self.evaluator(N,digits).trace(D,beta)[0]
        if v.real().is_zero():
            # Preserve a proved exact component using the client's public type.
            def frac(x):
                q=QQ(x);return Fraction(int(q.numerator()),int(q.denominator()))
            return numberdb.ComplexInterval(0,numberdb.RealInterval(frac(v.imag().lower()),frac(v.imag().upper())))
        return v

if __name__=='__main__':
    import sys,os
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN')=='1':numberdb.configure(api_key=sys.stdin.read().strip())
    g=HeegnerTrace()
    if '--publish' in sys.argv or os.environ.get('NUMBERDB_PUBLISH')=='1':
        g.publish(removing=False)
    else:g.verify(sample=None)
