generate.py

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

4654 bytes, as of the version from 2026-10-31 12:22 (current). Recorded here, not run.

"""Chandrasekhar H-function moments -- numberdb.org/T638.

Run with SageMath:
    sage -pip install numberdb mpmath    # once
    sage -python generate.py             # verify all stored entries
    sage -python generate.py --fill      # fill this draft; requires API key

This computes raw moments alpha_n(d) of the conservative isotropic H-function.
The discrete default selection is 2 <= d <= 10 and 2 <= n <= 8; see
argument-selection.md. It uses the conservative phase factorization of d'Eon
and McCormick (2019), equations (56)-(68). The exponential-series recurrence
is written explicitly. All division operands in the numerical computation
are mpmath numbers. No binary float enters the generator.

Two tanh-sinh quadratures at 150 and 200 decimal working digits use different
subdivisions. We require relative agreement of at least 120 decimal digits
before storing 100 significant digits. This is heuristic agreement, not a
rigorous quadrature error bound. Values are returned as decimal strings,
whose last place denotes NumberDB's usual uncertainty interval.
"""
import functools
import os
import sys
import numberdb.sage as numberdb
import mpmath as mp

WORKING_DIGITS = (150, 200)
AGREEMENT_DIGITS = 120


def phase(d, t):
    """Continuous argument in [0, pi], using an elementary contiguous recurrence."""
    if t == 0:
        return mp.mpf(0)
    if t == 1:
        return mp.pi / 2 if d == 2 else mp.pi
    if d % 2 == 0:
        lam = mp.mpf(1)
        start = 2
    else:
        lam = 1 - t * (mp.log1p(t) - mp.log1p(-t)) / 2
        start = 3
    for j in range(start, d, 2):
        lam = (j * (1-t) * (1+t) * lam - 1) / mp.mpf(j-1)
    im = (mp.sqrt(mp.pi) * mp.gamma(mp.mpf(d)/2)
          / mp.gamma(mp.mpf(d-1)/2) * t
          * ((1-t)*(1+t))**(mp.mpf(d-3)/2))
    return mp.atan2(im, lam)


def compute_dimension(d, order=8, working=200, refined=True):
    """Return alpha_0,...,alpha_order and phase integrals J_0,...,J_(order-2)."""
    with mp.workdps(working):
        if refined:
            breaks = [0, mp.mpf(1)/4, mp.mpf(1)/2, mp.mpf(3)/4,
                      mp.mpf(9)/10, mp.mpf(99)/100, 1]
        else:
            breaks = [0, mp.mpf(1)/2, mp.mpf(9)/10, 1]
        integrals = [mp.quad(lambda t: phase(d,t)*t**k, breaks)/mp.pi
                     for k in range(order-1)]
        # log(exp(sum (-1)^k J_k w^(k+1))/(1+w))
        log_coeff = [mp.mpf(0)] + [(-1)**(j-1)*(integrals[j-1]-mp.mpf(1)/j)
                                   for j in range(1,order)]
        coeff = [mp.mpf(1)]
        for j in range(1,order):
            coeff.append(mp.fsum(k*log_coeff[k]*coeff[j-k]
                                  for k in range(1,j+1))/j)
        alpha = [mp.mpf(2)] + [2*(-1)**(n+1)*coeff[n-1]/mp.sqrt(d)
                               for n in range(1,order+1)]
        return alpha, integrals


@functools.lru_cache(maxsize=None)
def agreed_dimension(d, order=8):
    low, _ = compute_dimension(d,order,WORKING_DIGITS[0],False)
    high, _ = compute_dimension(d,order,WORKING_DIGITS[1],True)
    with mp.workdps(WORKING_DIGITS[1]):
        for n in range(1,order+1):
            if not (mp.isfinite(high[n]) and high[n]>0):
                raise ArithmeticError('Nonpositive or nonfinite moment')
            if abs(low[n]-high[n]) > abs(high[n])*mp.mpf(10)**(-AGREEMENT_DIGITS):
                raise ArithmeticError('Insufficient agreement for d=%d n=%d' % (d,n))
        return tuple(mp.nstr(x,100,strip_zeros=False) for x in high)


class ConservativeHMoments(numberdb.Generator):
    table = 'T638'
    parameters = ('d','n')
    type = 'R'
    digits = 100
    rigour = 'heuristic (agreement-checked)'

    def enumerate(self, dimension=10, order=8):
        for d in range(2,dimension+1):
            for n in range(2,order+1):
                yield {'d':d,'n':n}

    def value(self,params,digits):
        if digits != 100:
            raise ValueError('This generator is calibrated for 100 digits')
        d,n=int(params['d']),int(params['n'])
        if d<2 or n<2:
            raise ValueError('Stored moments require d>=2 and n>=2')
        return agreed_dimension(d,max(8,n))[n]


if __name__ == '__main__':
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        numberdb.configure(api_key=sys.stdin.read().strip())
    g=ConservativeHMoments()
    if '--fill' in sys.argv or os.environ.get('NUMBERDB_PUBLISH') == '1':
        print(g.publish(message='Fill 63 conservative isotropic H-function moments',
                        assisted_by=os.environ.get('NUMBERDB_ASSISTED_BY','codex-cli')))
    else:
        r=g.verify(sample=None); print(r)
        sys.exit(0 if r.ok else 1)