"""T850: Steklov spectral determinants of Euclidean balls.

Install numberdb in SageMath; run sage -python generate.py for offline values,
--verify to compare every stored value, or --publish to add values to the
explicitly authorized draft. Configure credentials and provenance externally.

For the radius-one Euclidean d-ball, the scalar Dirichlet-to-Neumann spectrum
is n=0,1,... with homogeneous harmonic multiplicities. Omit n=0. With exact
P_d(n)=sum a_j n^j, logdet=-sum a_j*zeta'(-j) and det=exp(logdet).
GP arXiv:1411.6567v1, Examples 1.3.1-1.3.2, gives the spectrum; KL
arXiv:2404.14562v1 (1.10) gives the modified zeta determinant convention.
All coefficients are exact rationals. Arb uses bits(100,losing=128)=461 bits
for 100 significant decimal digits, including exponential error propagation.
Dimensions 2..20 form a contiguous finite prefix of the natural d>=2 family;
20 is a practical coverage bound, not a mathematical restriction. Both det
and logdet are inexpensive invertible conventions of this same determinant.
"""
import argparse,os,sys
from functools import lru_cache
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField

def coefficients(d):
    """Product formula for the dimension of degree-n harmonic polynomials."""
    if d<2:raise ValueError('d must be an integer >=2')
    if d==2:return (QQ(2),)
    p=[QQ(d-2),QQ(2)]
    for k in range(1,d-2):
        r=[QQ(0)]*(len(p)+1)
        for j,a in enumerate(p):r[j]+=k*a;r[j+1]+=a
        p=r
    fac=ZZ(1)
    for k in range(2,d-1):fac*=k
    return tuple(a/fac for a in p)

@lru_cache(maxsize=None)
def zeta_derivative(j,digits):
    C=ComplexBallField(numberdb.bits(digits,losing=128))
    return C(-j).zetaderiv(1).real()

@lru_cache(maxsize=None)
def logdet(d,digits=100):
    R=RealBallField(numberdb.bits(digits,losing=128))
    result=-sum((a*zeta_derivative(j,digits) for j,a in enumerate(coefficients(d))),R(0))
    if not result.is_finite():raise ArithmeticError('Nonfinite enclosure')
    return result

class BallSteklov(numberdb.Generator):
    table='T850'
    parameters=('d','convention')
    type='R'
    digits=100
    rigour='proven'
    files=('generate.py','checks.py','argument-selection.md','research.md',
           'validation-method.md','skill-manifest.json','versions.json',
           'check-results.json','numerical-evidence.json')
    def enumerate(self,limit=20):
        if not isinstance(limit,int) or limit<2:raise ValueError('limit must be integer >=2')
        for d in range(2,limit+1):
            for convention in ('det','logdet'):yield {'d':d,'convention':convention}
    def value(self,params,digits):
        d=ZZ(params['d']);c=params['convention']
        if d<2 or c not in ('det','logdet'):raise ValueError('d>=2; convention det or logdet')
        v=logdet(int(d),digits)
        return v.exp() if c=='det' else v

if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--publish',action='store_true');p.add_argument('--verify',action='store_true');a=p.parse_args()
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN')=='1':numberdb.configure(api_key=sys.stdin.read().strip())
    g=BallSteklov()
    if a.publish or os.environ.get('NUMBERDB_PUBLISH')=='1':print(g.publish(message=os.environ.get('NUMBERDB_EDIT_MESSAGE','Fill checked Steklov determinants')))
    elif a.verify:print(g.verify(sample=None))
    else:
        for par in g.enumerate():print(par,g.value(par,g.digits))
