generate.py

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

10842 bytes, as of the version from 2026-11-17 12:35 (current). Recorded here, not run.

"""T733: Riemann zeta heat trace, in the width alpha=4*pi*t convention.

Requires SageMath 10.9 (or compatible Sage with Arb/FLINT) and numberdb.
  sage -pip install numberdb
  sage -python generate.py                 # preview only; writes nothing
  sage -python generate.py --publish       # fill the already assigned draft

The default selection retains every reduced a/b, 1<=a<=b<=12, and adds every
(a/b)*pi with coprime 1<=a,b<=6. Both are bounded exploratory reference slices;
neither height bound is canonical. The second slice corresponds to rational
heat times a/(4*b), not rational angles. Exact keys are pi, pi/b, a*pi or
a*pi/b. The function is defined for every positive real alpha; this generator
accepts exact positive rationals and positive rational multiples of pi.

Rational widths retain the prime formula below. Pi multiples use 138 certified,
consecutively indexed zeros below T=300, with the next zero above T. For the
remaining zeros, including possible off-critical-line zeros, the critical strip
and Hasanalizade-Shen-Wong, Corollary 1.2, imply the unconditional tail bound
  2*exp(t/4-t*T^2)*(T^2+1/t), t=alpha/(4*pi).
Indeed N(u)<=u^2 for u>=300, and Stieltjes integration bounds the two-sided
tail by 4*t*exp(t/4)*integral_T^infinity u^3*exp(-t*u^2)du. No global RH is
assumed. FLINT's zeta_zeros isolation and counting certify the finite prefix.
For alpha=q*pi, t=q/4 is evaluated as an exact rational, not from a rounded pi.
Finite zero errors and the tail are propagated in ball arithmetic.

Work uses at least 512 bits and retains at least digits+10 relative decimal
digits before serialization. Unsupported precision/ranges fail explicitly.
The prime route additionally uses 40 absolute guard places for quadrature.

This is the unconditional Gaussian Weil explicit formula (Suzuki, Section
3.1, (3.3); Montgomery-Vaughan, Theorem 12.13), in Connes's heat convention
(arXiv:2402.13082v1, (13)-(15), (25)), with t=alpha/(4*pi).

The integrand is expm1(x/2-pi*x*x/alpha)/(2*sinh(x)), continuously 1/4 at 0.
At balls containing 0, 1F1(1;2;z)=(exp(z)-1)/z removes the singularity
analytically. Arb encloses the finite integral. Subtract atanh(exp(-L))
exactly for the exponential tail; the remaining positive Gaussian tail is
at most exp(-pi*L^2/alpha-L/2)/(2*(pi/alpha)*L*(1-exp(-2*L))).

Prime powers p^k<=M carry log(p), not log(p^k). For c=pi/alpha, the omitted
prime contribution is at most exp(alpha/(4*pi))*erfc(z), z=sqrt(c)*
(log(M)-alpha/(2*pi)), further bounded above by exp(alpha/(4*pi)-z*z)/
(sqrt(pi)*z). This follows from Lambda(n)/sqrt(n)<=1, the decreasing
integral test, completing a square and erfc(z)<=exp(-z*z)/(sqrt(pi)*z).
The final RealBall includes rounding, input uncertainty and both tails.
M>=100000 and L=12 are used for the rational slice at 100 digits. Larger
precision/widths increase both cutoffs; workloads above 5,000,000 integers
are refused explicitly. No zero data is used by the prime route.
Checks and their respective independence are explained in check_values.py
and check_pi_values.py.
"""
import os
import sys
import re
from functools import lru_cache
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField
from sage.arith.misc import prime_range


@lru_cache(maxsize=8)
def prime_powers(M):
    terms = []
    for p in prime_range(M + 1):
        p = int(p)
        n = p
        while n <= M:
            terms.append((n, p))
            n *= p
    return tuple(sorted(terms))


def parse_width(alpha):
    text = str(alpha).replace(' ', '')
    match = re.fullmatch(r'(?:(\d+)\*)?pi(?:/(\d+))?', text)
    if match:
        coefficient = QQ(match.group(1) or 1) / QQ(match.group(2) or 1)
        kind = 'pi'
    elif re.fullmatch(r'\d+(?:/\d+)?', text):
        coefficient = QQ(text)
        kind = 'rational'
    else:
        raise ValueError('Use a positive rational or an exact key such as pi/3 or 4*pi/3')
    if coefficient <= 0:
        raise ValueError('alpha must be positive')
    return kind, coefficient


def pi_key(coefficient):
    coefficient = QQ(coefficient)
    numerator = int(coefficient.numerator())
    denominator = int(coefficient.denominator())
    text = 'pi' if numerator == 1 else str(numerator) + '*pi'
    return text if denominator == 1 else text + '/' + str(denominator)


def argument_latex(alpha):
    kind, coefficient = parse_width(alpha)
    if kind != 'pi':
        raise ValueError('The special display is only needed for pi multiples')
    numerator = int(coefficient.numerator())
    denominator = int(coefficient.denominator())
    top = r'\pi' if numerator == 1 else str(numerator) + r'\pi'
    return '$' + (top if denominator == 1 else r'\frac{' + top + '}{' + str(denominator) + '}') + '$'


def width_ball(alpha, field):
    kind, coefficient = parse_width(alpha)
    return field(coefficient) * field.pi() if kind == 'pi' else field(coefficient)


def prime_components(alpha, digits=100, work_bits=None):
    prec = work_bits or max(512, numberdb.bits(digits, losing=160))
    R = RealBallField(prec)
    C = ComplexBallField(prec)
    a = width_ball(alpha, R)
    pi = R.pi()
    c = pi / a
    goal = R(10) ** (-digits - 40)
    L = max(12, int(((digits + 90) * R(10).log() / c).sqrt().upper().ceil()))
    M = max(100000, int((((digits + 80) * R(10).log() / c).sqrt()
                         + a / (2 * pi)).exp().upper().ceil()))
    if M > 5000000:
        raise ValueError('prime cutoff exceeds documented workload limit')

    def kernel(z, analytic):
        u = z / 2 - c * z * z
        if z.contains_zero():
            # Entire quotients; no removable singularity remains at z=0.
            return ((QQ(1) / 2 - c * z) * u.hypergeometric([1], [2])
                    / (2 * (-z).exp() * (2 * z).hypergeometric([1], [2])))
        return (u.exp() - 1) / (z.exp() - (-z).exp())

    integral = C.integral(kernel, 0, L, abs_tol=goal, rel_tol=goal,
                          eval_limit=100000)
    if not (integral.real().is_finite() and integral.imag().is_finite()
            and integral.imag().contains_zero()):
        raise ArithmeticError('quadrature did not enclose a finite real integral')
    integral = integral.real() - (-R(L)).exp().arctanh()
    arch_tail = (-c * L * L - R(L) / 2).exp() / (
        2 * c * L * (1 - (-R(2 * L)).exp()))
    integral = integral.add_error(arch_tail)
    arch = ((4 * pi).log() + R.euler_constant() + 2 * integral) / a.sqrt()
    prime = R(0)
    for n, p in prime_powers(M):
        logn = R(n).log()
        prime += R(p).log() / R(n).sqrt() * (-c * logn * logn).exp()
    prime *= 2 / a.sqrt()
    z = c.sqrt() * (R(M).log() - a / (2 * pi))
    if not z > 0:
        raise ArithmeticError('prime tail inequality requires z>0')
    prime_tail = (a / (4 * pi) - z * z).exp() / (pi.sqrt() * z)
    prime = prime.add_error(prime_tail)
    pole = 2 * (a / (16 * pi)).exp()
    value = pole - arch - prime
    if not value.is_finite() or not R(value.rad()) < abs(value) * R(10) ** (-digits - 10):
        raise ArithmeticError('insufficient non-vacuous relative precision')
    return {'value': value, 'arch': arch, 'prime': prime, 'pole': pole,
            'arch_integral_tail': arch_tail, 'prime_tail': prime_tail,
            'M': M, 'L': L, 'work_bits': prec, 'method': 'prime'}


@lru_cache(maxsize=4)
def certified_zero_prefix(precision):
    field = ComplexBallField(precision)
    zeros = field.zeta_zeros(150)
    if not all(zero.real() == QQ(1)/2 and zero.imag().is_finite() for zero in zeros):
        raise ArithmeticError('The certified prefix did not have finite critical-line zeros')
    if not all(zeros[index].imag().upper() < zeros[index + 1].imag().lower()
               for index in range(len(zeros) - 1)):
        raise ArithmeticError('Certified zeros are not separated and ordered')
    if not (zeros[137].imag().upper() < 300 < zeros[138].imag().lower()):
        raise ArithmeticError('The 138-zero cutoff at T=300 was not certified')
    return tuple(zero.imag() for zero in zeros[:138])


def zero_components(alpha, digits=100, work_bits=None):
    kind, coefficient = parse_width(alpha)
    precision = work_bits or max(512, numberdb.bits(digits, losing=160))
    field = RealBallField(precision)
    heat_time = (field(coefficient / 4) if kind == 'pi'
                 else field(coefficient) / (4 * field.pi()))
    zeros = certified_zero_prefix(precision)
    finite = 2 * sum(((-heat_time * ordinate**2).exp() for ordinate in zeros), field(0))
    tail = 2 * (heat_time/4 - 90000*heat_time).exp() * (90000 + 1/heat_time)
    value = finite.add_error(tail)
    if (not value.is_finite() or value.contains_zero()
            or not field(value.rad()) < abs(value) * field(10)**(-digits - 10)):
        raise ArithmeticError('Insufficient relative precision; increase precision or the certified zero prefix')
    return {'value': value, 'finite_sum': finite, 'zero_tail': tail,
            'heat_time': heat_time, 'zero_count': len(zeros), 'cutoff': 300,
            'work_bits': precision, 'method': 'zeros'}


def components(alpha, digits=100, work_bits=None, method='auto'):
    kind, coefficient = parse_width(alpha)
    if method == 'auto':
        method = 'zeros' if kind == 'pi' else 'prime'
    if method == 'prime':
        return prime_components(alpha, digits, work_bits)
    if method == 'zeros':
        return zero_components(alpha, digits, work_bits)
    raise ValueError('method must be auto, prime or zeros')


class HeatTrace(numberdb.Generator):
    table = 'T733'
    parameters = ['alpha']
    type = 'R'
    digits = 100
    rigour = 'proven'

    def enumerate(self):
        widths = sorted({QQ(a) / b for b in range(1, 13)
                         for a in range(1, b + 1)})
        for alpha in widths:
            yield {'alpha': str(alpha)}
        multiples = sorted({QQ(numerator) / denominator
                            for numerator in range(1, 7)
                            for denominator in range(1, 7)})
        for coefficient in multiples:
            yield {'alpha': pi_key(coefficient)}

    @lru_cache(maxsize=256)
    def _value(self, alpha, digits):
        return components(alpha, digits)['value']

    def value(self, params, digits):
        alpha = str(params['alpha'])
        value = self._value(alpha, digits)
        if parse_width(alpha)[0] == 'pi':
            return {'number': value, 'param-latex': argument_latex(alpha)}
        return value


if __name__ == '__main__':
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        numberdb.configure(api_key=sys.stdin.read().strip())
    g = HeatTrace()
    if '--publish' in sys.argv:
        g.publish()
    elif '--verify' in sys.argv:
        g.verify(sample=None)
    else:
        g.preview()