#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
# Copyright (c) 2026 Anthropic, PBC. Part of BootLoops 1.0; see LICENSE and NOTICE beside this file.
"""eec-nnlo-evaluate.py - the elliptic remainder of the NNLO energy-energy
correlator in N=4 super Yang-Mills, evaluated from its closed form.

The paper "The hidden sunrise in the energy-energy correlator" (Schwartz and
Zhang) writes the finite two-fold integral left over from the 2019 NNLO
calculation of Henn, Sokatchev, Yan and Zhiboedov as (its eq. 42)

    F_R(zeta) = 2 F_K1(zeta) + P(zeta),      F_K1 = c1 S0 + c2 S0' + Psi,

with P and Psi harmonic polylogarithms of zeta over the letters {0, 1} up to
weight five (the paper's printed expressions for P and Psi), S0 the
thirteen-word combination of iterated Eisenstein integrals of Gamma_1(6)
printed in the paper, S0' = dS0/dzeta, and the rational prefactors
c1 = zeta (zeta-1) (8 zeta-5) / 3 and c2 = zeta (8 zeta+1) (zeta-1)^2 / 3.
The complete NNLO correlator is F_NNLO = F_HPL + F_R, with F_HPL the
polylogarithmic part given in the 2019 paper; this script evaluates F_R.

Everything is computed in one frame, the one the paper uses for S0: the
variable q of the elliptic curve, with zeta, psi_1 and the four letters
omega_0, omega_1, psi_1 omega_0 and zeta psi_1 omega_0 as exact rational
q-series built from the paper's eta quotients, and every iterated integral,
the harmonic polylogarithms included (H_u(zeta) = I(omega_u1, ..., omega_un; q)
with the same tangential-base-point regularization), as a polynomial in
L = log q whose coefficients are exact rational q-series.  Nothing is rounded
before the final substitution of q_0, L, pi^2, zeta_3, pi^4 and zeta_5 at the
working precision.  The number of q-terms N follows the paper's estimate
D = N log10(1/q_0) - 3 for D correct digits, plus a margin; the printed
truncation report measures what the last 20 terms contribute and gives a
conservative estimate of the dropped tail.  The point q_0 is found from zeta_0 by bisection and Newton's method
on the q-series of psi_1 (zeta - zeta_0), a holomorphic form whose
coefficients stay bounded.  The series converge for 0 < zeta < 1, more slowly
as zeta approaches 1 (q_0 -> 1): fifty digits take about 95 terms and one
second at zeta = 3/11, 120 terms and two seconds at 1/2, 160 terms and three
seconds at 3/4, 300 terms and sixteen seconds at 99/100; two hundred digits
at 3/11 take 290 terms and a quarter of a minute.

Usage
-----
    python3 eec-nnlo-evaluate.py 3/11                # F_R at zeta = 3/11, 30 digits
    python3 eec-nnlo-evaluate.py 1/2 --digits 60     # 60 digits
    python3 eec-nnlo-evaluate.py --check             # self-test

--check verifies, in order: the q-expansions of zeta, psi_1 and psi_1 omega_0
against the series printed in the paper and the identities between them;
the two iterated integrals the paper prints as an example; the values of
q_0 at the paper's two reference angles 3/11 and 1/2; seven harmonic
polylogarithms against mpmath's polylog and log; and F_R at the two
reference angles and at two further angles (1/3 and 5/13) against the
values of the two-fold integral itself, computed for this work by the
authors' independent evaluator (numerical quadrature plus transport of the
differential system of the two-fold integral) and quoted below to the
number of digits that evaluator guarantees.  It takes a few seconds.

Requires Python 3 and mpmath (https://mpmath.org/); nothing else.
"""
import argparse
import sys
import time
from fractions import Fraction as Fr
from math import comb, factorial

import mpmath as mp
from mpmath import mpf

# ----------------------------------------------------------------------------
# The three printed expressions, transcribed mechanically from the paper's
# LaTeX source.  Keys are HPL index vectors with one entry per letter (the
# paper's condensed indices of P are expanded here, H_3 = H_{0,0,1}); the
# values are the coefficients as functions of zeta (z), pi^2, zeta_3, pi^4 and
# zeta_5.  For S0/psi_1 the keys are the letter words of the iterated
# Eisenstein integrals and the values (rational number, constant).
# ----------------------------------------------------------------------------

P_TABLE = {
    (): lambda z, pi2, z3, pi4, z5: -(mpf(5)*pi2*z**3*z3 - mpf(120)*pi2*z**3 - mpf(10)*pi2*z**2*z3 + mpf(80)*pi2*z**2 + mpf(15)*pi2*z*z3 + mpf(100)*pi2*z - mpf(80)*pi2 + mpf(8)*pi4*z - mpf(360)*z**3*z3 + mpf(420)*z**3*z5 + mpf(1860)*z**2*z3 - mpf(840)*z**2*z5 - mpf(480)*z**2 - mpf(2820)*z*z3 - mpf(570)*z*z5 + mpf(960)*z + mpf(1260)*z3 - mpf(480))/(mpf(120)*(z - mpf(1))),
    (0,): lambda z, pi2, z3, pi4, z5: (mpf(20)*pi2*z**2 - mpf(50)*pi2*z + mpf(20)*pi2 + pi4*z**3 - mpf(2)*pi4*z**2 - pi4*z + mpf(360)*z**3*z3 - mpf(840)*z**2*z3 + mpf(660)*z*z3 - mpf(120)*z3)/(mpf(60)*(z - mpf(1))),
    (1,): lambda z, pi2, z3, pi4, z5: (-mpf(260)*pi2*z**2 + mpf(420)*pi2*z - mpf(140)*pi2 + mpf(4)*pi4*z**3 - mpf(8)*pi4*z**2 - mpf(11)*pi4*z + mpf(1440)*z**3*z3 - mpf(3000)*z**2*z3 - mpf(960)*z**2 + mpf(1800)*z*z3 + mpf(1920)*z - mpf(960))/(mpf(240)*(z - mpf(1))),
    (0, 0): lambda z, pi2, z3, pi4, z5: -(mpf(3)*pi2*z**3 - mpf(7)*pi2*z**2 + mpf(5)*pi2*z - pi2 + mpf(3)*z**3*z3 - mpf(24)*z**3 - mpf(6)*z**2*z3 + mpf(48)*z**2 - mpf(3)*z*z3 - mpf(36)*z + mpf(12))/(mpf(12)*(z - mpf(1))),
    (0, 1): lambda z, pi2, z3, pi4, z5: (mpf(12)*pi2*z**3 - mpf(28)*pi2*z**2 + mpf(14)*pi2*z - mpf(4)*pi2 + mpf(3)*z**3*z3 + mpf(24)*z**3 - mpf(6)*z**2*z3 - mpf(120)*z**2 + mpf(15)*z*z3 + mpf(108)*z - mpf(24))/(mpf(12)*(z - mpf(1))),
    (1, 0): lambda z, pi2, z3, pi4, z5: -(mpf(3)*pi2*z**3 - mpf(6)*pi2*z**2 + mpf(3)*pi2*z - mpf(2)*pi2 + mpf(3)*z**3*z3 - mpf(24)*z**3 - mpf(6)*z**2*z3 + mpf(84)*z**2 - mpf(15)*z*z3 - mpf(84)*z + mpf(24))/(mpf(12)*(z - mpf(1))),
    (1, 1): lambda z, pi2, z3, pi4, z5: (mpf(12)*pi2*z**3 - mpf(27)*pi2*z**2 + mpf(13)*pi2*z - mpf(2)*pi2 + mpf(3)*z**3*z3 + mpf(24)*z**3 - mpf(6)*z**2*z3 - mpf(84)*z**2 + mpf(9)*z*z3 + mpf(96)*z - mpf(36))/(mpf(12)*(z - mpf(1))),
    (0, 0, 1): lambda z, pi2, z3, pi4, z5: -(pi2*z**3 - mpf(2)*pi2*z**2 + mpf(7)*pi2*z - mpf(72)*z**3 + mpf(96)*z**2 - mpf(24)*z - mpf(12))/(mpf(24)*(z - mpf(1))),
    (0, 1, 0): lambda z, pi2, z3, pi4, z5: -(-pi2*z + mpf(10)*z**2 - mpf(18)*z + mpf(4))/(mpf(4)*(z - mpf(1))),
    (1, 0, 0): lambda z, pi2, z3, pi4, z5: z*(-pi2 + mpf(6)*z - mpf(6))/(mpf(12)*(z - mpf(1))),
    (0, 1, 1): lambda z, pi2, z3, pi4, z5: -(pi2*z**3 - mpf(2)*pi2*z**2 + mpf(3)*pi2*z - mpf(72)*z**3 + mpf(204)*z**2 - mpf(204)*z + mpf(72))/(mpf(24)*(z - mpf(1))),
    (1, 1, 0): lambda z, pi2, z3, pi4, z5: pi2*z/(mpf(6)*(z - mpf(1))),
    (1, 0, 1): lambda z, pi2, z3, pi4, z5: -(pi2*z**3 - mpf(2)*pi2*z**2 + mpf(13)*pi2*z - mpf(72)*z**3 + mpf(84)*z**2 + mpf(12)*z - mpf(12))/(mpf(24)*(z - mpf(1))),
    (1, 1, 1): lambda z, pi2, z3, pi4, z5: -(pi2*z**3 - mpf(2)*pi2*z**2 + mpf(7)*pi2*z - mpf(72)*z**3 + mpf(240)*z**2 - mpf(264)*z + mpf(96))/(mpf(24)*(z - mpf(1))),
    (0, 0, 0, 1): lambda z, pi2, z3, pi4, z5: -z*(mpf(5)*z**2 - mpf(11)*z + mpf(4))/(mpf(2)*(z - mpf(1))),
    (0, 0, 1, 0): lambda z, pi2, z3, pi4, z5: (mpf(3)*z**3 - mpf(7)*z**2 + mpf(2)*z - mpf(1))/(z - mpf(1)),
    (0, 0, 1, 1): lambda z, pi2, z3, pi4, z5: (mpf(5)*z**2 - mpf(7)*z + mpf(4))/mpf(2),
    (0, 1, 0, 0): lambda z, pi2, z3, pi4, z5: -(z**2 - mpf(2)*z + mpf(2))/mpf(2),
    (0, 1, 0, 1): lambda z, pi2, z3, pi4, z5: -mpf(2)*(mpf(2)*z**3 - mpf(4)*z**2 - z + mpf(1))/(z - mpf(1)),
    (0, 1, 1, 0): lambda z, pi2, z3, pi4, z5: z*(z - mpf(1))/mpf(2),
    (0, 1, 1, 1): lambda z, pi2, z3, pi4, z5: mpf(3)*z**2 - mpf(5)*z + mpf(4),
    (1, 0, 0, 1): lambda z, pi2, z3, pi4, z5: -(mpf(5)*z**3 - mpf(8)*z**2 + mpf(1))/(mpf(2)*(z - mpf(1))),
    (1, 0, 1, 0): lambda z, pi2, z3, pi4, z5: (mpf(6)*z**3 - mpf(15)*z**2 + mpf(9)*z - mpf(2))/(mpf(2)*(z - mpf(1))),
    (1, 0, 1, 1): lambda z, pi2, z3, pi4, z5: (mpf(5)*z**2 - mpf(11)*z + mpf(5))/mpf(2),
    (1, 1, 0, 0): lambda z, pi2, z3, pi4, z5: -(z - mpf(1))**2/mpf(2),
    (1, 1, 0, 1): lambda z, pi2, z3, pi4, z5: -(mpf(8)*z**3 - mpf(15)*z**2 + z + mpf(2))/(mpf(2)*(z - mpf(1))),
    (1, 1, 1, 0): lambda z, pi2, z3, pi4, z5: (z - mpf(1))**2/mpf(2),
    (1, 1, 1, 1): lambda z, pi2, z3, pi4, z5: mpf(3)*(z - mpf(1))**2,
    (0, 0, 0, 0, 1): lambda z, pi2, z3, pi4, z5: z*(z - mpf(1))/mpf(2),
    (0, 0, 0, 1, 0): lambda z, pi2, z3, pi4, z5: mpf(3)*z*(z**2 - mpf(2)*z - mpf(1))/(mpf(4)*(z - mpf(1))),
    (0, 0, 0, 1, 1): lambda z, pi2, z3, pi4, z5: z*(mpf(5)*z**2 - mpf(10)*z + mpf(1))/(mpf(4)*(z - mpf(1))),
    (0, 0, 1, 0, 0): lambda z, pi2, z3, pi4, z5: -z*(z**2 - mpf(2)*z - mpf(1))/(mpf(4)*(z - mpf(1))),
    (0, 0, 1, 0, 1): lambda z, pi2, z3, pi4, z5: mpf(3)*z*(z - mpf(1))/mpf(4),
    (0, 0, 1, 1, 0): lambda z, pi2, z3, pi4, z5: z*(z - mpf(1))/mpf(2),
    (0, 0, 1, 1, 1): lambda z, pi2, z3, pi4, z5: z*(mpf(3)*z**2 - mpf(6)*z - mpf(1))/(mpf(2)*(z - mpf(1))),
    (0, 1, 0, 0, 1): lambda z, pi2, z3, pi4, z5: z*(z**2 - mpf(2)*z + mpf(2))/(z - mpf(1)),
    (0, 1, 0, 1, 0): lambda z, pi2, z3, pi4, z5: mpf(3)*z*(z - mpf(1))/mpf(4),
    (0, 1, 0, 1, 1): lambda z, pi2, z3, pi4, z5: z*(mpf(7)*z**2 - mpf(14)*z + mpf(9))/(mpf(4)*(z - mpf(1))),
    (0, 1, 1, 0, 0): lambda z, pi2, z3, pi4, z5: -z*(z - mpf(1))/mpf(4),
    (0, 1, 1, 0, 1): lambda z, pi2, z3, pi4, z5: z*(mpf(5)*z**2 - mpf(10)*z + mpf(7))/(mpf(4)*(z - mpf(1))),
    (0, 1, 1, 1, 0): lambda z, pi2, z3, pi4, z5: z*(z - mpf(1))/mpf(2),
    (0, 1, 1, 1, 1): lambda z, pi2, z3, pi4, z5: mpf(2)*z*(z - mpf(1)),
    (1, 0, 0, 0, 1): lambda z, pi2, z3, pi4, z5: z*(z**2 - mpf(2)*z + mpf(5))/(mpf(2)*(z - mpf(1))),
    (1, 0, 0, 1, 0): lambda z, pi2, z3, pi4, z5: z*(mpf(3)*z**2 - mpf(6)*z - mpf(7))/(mpf(4)*(z - mpf(1))),
    (1, 0, 0, 1, 1): lambda z, pi2, z3, pi4, z5: z*(mpf(5)*z**2 - mpf(10)*z + mpf(9))/(mpf(4)*(z - mpf(1))),
    (1, 0, 1, 0, 0): lambda z, pi2, z3, pi4, z5: -z*(z**2 - mpf(2)*z - mpf(1))/(mpf(4)*(z - mpf(1))),
    (1, 0, 1, 0, 1): lambda z, pi2, z3, pi4, z5: mpf(3)*z*(z**2 - mpf(2)*z + mpf(5))/(mpf(4)*(z - mpf(1))),
    (1, 0, 1, 1, 0): lambda z, pi2, z3, pi4, z5: z*(z - mpf(1))/mpf(2),
    (1, 0, 1, 1, 1): lambda z, pi2, z3, pi4, z5: mpf(3)*z*(z - mpf(1))/mpf(2),
    (1, 1, 0, 0, 1): lambda z, pi2, z3, pi4, z5: z*(mpf(2)*z**2 - mpf(4)*z + mpf(3))/(mpf(2)*(z - mpf(1))),
    (1, 1, 0, 1, 0): lambda z, pi2, z3, pi4, z5: z*(mpf(3)*z**2 - mpf(6)*z - mpf(1))/(mpf(4)*(z - mpf(1))),
    (1, 1, 0, 1, 1): lambda z, pi2, z3, pi4, z5: mpf(7)*z*(z - mpf(1))/mpf(4),
    (1, 1, 1, 0, 0): lambda z, pi2, z3, pi4, z5: -z*(z - mpf(1))/mpf(4),
    (1, 1, 1, 0, 1): lambda z, pi2, z3, pi4, z5: z*(mpf(5)*z**2 - mpf(10)*z + mpf(11))/(mpf(4)*(z - mpf(1))),
    (1, 1, 1, 1, 0): lambda z, pi2, z3, pi4, z5: z*(z - mpf(1))/mpf(2),
    (1, 1, 1, 1, 1): lambda z, pi2, z3, pi4, z5: mpf(2)*z*(z - mpf(1)),
}

PSI_TABLE = {
    (): lambda z, pi2, z3, pi4, z5: -(mpf(60)*pi2*z**2 + mpf(30)*pi2*z - mpf(60)*pi2 - mpf(8)*pi4*z**2 + mpf(10)*pi4*z - mpf(2)*pi4 + mpf(540)*z**2*z3 - mpf(1350)*z*z3 + mpf(360)*z + mpf(945)*z3 - mpf(360))/mpf(180),
    (1,): lambda z, pi2, z3, pi4, z5: -(-mpf(10)*pi2*z + mpf(7)*pi2 + mpf(80)*z**2*z3 - mpf(100)*z*z3 - mpf(48)*z + mpf(20)*z3 + mpf(48))/mpf(24),
    (0, 0): lambda z, pi2, z3, pi4, z5: (z - mpf(1))*(mpf(4)*pi2*z - pi2 + mpf(12))/mpf(24),
    (0, 1): lambda z, pi2, z3, pi4, z5: -(mpf(4)*pi2*z**2 - mpf(5)*pi2*z + pi2 + mpf(24)*z**2 - mpf(48)*z + mpf(12))/mpf(12),
    (1, 0): lambda z, pi2, z3, pi4, z5: (z - mpf(1))*(mpf(4)*pi2*z - pi2 + mpf(12))/mpf(24),
    (1, 1): lambda z, pi2, z3, pi4, z5: -(z - mpf(1))*(mpf(4)*pi2*z - pi2 + mpf(24)*z - mpf(24))/mpf(12),
    (0, 0, 1): lambda z, pi2, z3, pi4, z5: -(mpf(12)*z**2 - mpf(8)*z - mpf(1))/mpf(4),
    (0, 1, 0): lambda z, pi2, z3, pi4, z5: (z - mpf(1))/mpf(2),
    (0, 1, 1): lambda z, pi2, z3, pi4, z5: -mpf(3)*(z - mpf(1))*(mpf(2)*z - mpf(1))/mpf(2),
    (1, 0, 0): lambda z, pi2, z3, pi4, z5: -(z - mpf(1))/mpf(2),
    (1, 0, 1): lambda z, pi2, z3, pi4, z5: -(mpf(12)*z**2 - mpf(14)*z + mpf(5))/mpf(4),
    (1, 1, 1): lambda z, pi2, z3, pi4, z5: -mpf(3)*(z - mpf(1))**2,
    (0,): lambda z, pi2, z3, pi4, z5: -(z - mpf(1))*(pi2 + mpf(28)*z*z3 - mpf(7)*z3)/mpf(6),
    (0, 0, 0, 1): lambda z, pi2, z3, pi4, z5: (z - mpf(1))*(mpf(4)*z - mpf(1))/mpf(3),
    (0, 0, 1, 1): lambda z, pi2, z3, pi4, z5: -(z - mpf(1))*(mpf(4)*z - mpf(1))/mpf(6),
    (0, 1, 0, 1): lambda z, pi2, z3, pi4, z5: (z - mpf(1))*(mpf(4)*z - mpf(1))/mpf(6),
    (0, 1, 1, 1): lambda z, pi2, z3, pi4, z5: -(z - mpf(1))*(mpf(4)*z - mpf(1))/mpf(3),
    (1, 0, 0, 1): lambda z, pi2, z3, pi4, z5: mpf(2)*(z - mpf(1))*(mpf(4)*z - mpf(1))/mpf(3),
    (1, 0, 1, 1): lambda z, pi2, z3, pi4, z5: (z - mpf(1))*(mpf(4)*z - mpf(1))/mpf(6),
    (1, 1, 0, 1): lambda z, pi2, z3, pi4, z5: (z - mpf(1))*(mpf(4)*z - mpf(1))/mpf(2),
}

S0_TABLE = {   # letters: '1', 'k3' = psi_1 omega_0, 'zk3' = zeta psi_1 omega_0, 'w0' = omega_0, 'w1' = omega_1
    ('1', 'zk3', 'w0', 'w0', 'w1'): (Fr(-4, 1), '1'),
    ('1', 'zk3', 'w0', 'w1', 'w1'): (Fr(-4, 1), '1'),
    ('1', 'zk3', 'w1', 'w0', 'w1'): (Fr(-4, 1), '1'),
    ('1', 'zk3', 'w1', 'w1', 'w1'): (Fr(-4, 1), '1'),
    ('1', 'k3', 'w0', 'w0', 'w1'): (Fr(-1, 1), '1'),
    ('1', 'k3', 'w0', 'w1', 'w1'): (Fr(-5, 2), '1'),
    ('1', 'k3', 'w1', 'w0', 'w1'): (Fr(-7, 2), '1'),
    ('1', 'k3', 'w1', 'w1', 'w1'): (Fr(-5, 1), '1'),
    ('1', 'k3', 'w0', 'w1', 'w0'): (Fr(-3, 2), '1'),
    ('1', 'k3', 'w1', 'w0', 'w0'): (Fr(3, 2), '1'),
    ('1', 'k3', 'w1'): (Fr(-1, 4), 'pi2'),
    ('1', 'zk3'): (Fr(-4, 1), 'z3'),
    ('1', 'k3'): (Fr(1, 2), 'z3'),
}
# S0/psi_1 = 33/4 zeta_5 - pi^2 zeta_3/12 - pi^4 L/30 + sum over S0_TABLE of (rational x constant) I(word; q)

def c1(z): return z * (z - 1) * (8 * z - 5) / 3
def c2(z): return z * (8 * z + 1) * (z - 1) ** 2 / 3

# Values of F_R, i.e. of the two-fold integral, computed independently of
# this script by the authors' evaluator (numerical quadrature plus transport
# of the differential system of the two-fold integral), quoted to the number
# of digits that evaluator guarantees.  Used by --check.
REFERENCE = {
    '3/11': ('0.445432102802142338275259912920870533101432', 42),
    '1/2': ('0.602454960123346394560306461760558539506351', 42),
    '1/3': ('0.50394093034869997522468855454610352079836031710327', 50),
    '5/13': ('0.544595324271032286493189414750360821298170', 42),
}

# ----------------------------------------------------------------------------
# exact truncated q-series over Q (lists of Fractions, index = power of q)
# ----------------------------------------------------------------------------

def smul(a, b, N):
    out = [Fr(0)] * (N + 1)
    for i in range(min(len(a), N + 1)):
        ai = a[i]
        if ai:
            for j in range(min(len(b), N + 1 - i)):
                if b[j]:
                    out[i + j] += ai * b[j]
    return out

def sinv(a, N):
    out = [Fr(0)] * (N + 1); out[0] = 1 / a[0]
    for n in range(1, N + 1):
        out[n] = -sum(a[k] * out[n - k] for k in range(1, min(n, len(a) - 1) + 1) if a[k]) / a[0]
    return out

def spow(a, n, N):
    r = [Fr(1)] + [Fr(0)] * N
    for _ in range(n): r = smul(r, a, N)
    return r

def sadd(*fs):
    out = [Fr(0)] * max(len(f) for f in fs)
    for f in fs:
        for i, c in enumerate(f): out[i] += c
    return out

def sscale(a, c): return [c * x for x in a]

def eta_product(d, N):
    """prod_{n>=1} (1 - qt^{dn}) with qt = -q, as a series in q."""
    f = [Fr(1)] + [Fr(0)] * N; n = 1
    while d * n <= N:
        g = [Fr(0)] * (N + 1); g[0] = Fr(1); g[d * n] = -Fr(-1) ** (d * n)
        f = smul(f, g, N); n += 1
    return f

def frame(N):
    """zeta, psi_1 and the letters as q-series through q^N, from the paper's eta quotients (q = -qt)."""
    E = {d: eta_product(d, N) for d in (1, 2, 3, 6)}
    I = {d: sinv(E[d], N) for d in (1, 2, 3, 6)}
    zeta = [Fr(0)] + smul(smul(spow(E[1], 3, N), spow(E[6], 9, N), N), smul(spow(I[2], 3, N), spow(I[3], 9, N), N), N)[:N]
    psi1 = smul(smul(E[2], spow(E[3], 6, N), N), smul(spow(I[1], 2, N), spow(I[6], 3, N), N), N)
    one = [Fr(1)] + [Fr(0)] * N
    onem = sadd(one, sscale(zeta, Fr(-1))); onep8 = sadd(one, sscale(zeta, Fr(8)))
    psi2 = smul(psi1, psi1, N); psi3 = smul(psi2, psi1, N)
    w0 = smul(psi2, smul(onem, onep8, N), N)            # omega_0 = psi_1^2 (1 - zeta)(1 + 8 zeta)
    w1 = smul(psi2, smul(zeta, onep8, N), N)            # omega_1 = psi_1^2 zeta (1 + 8 zeta)
    k3 = smul(psi3, smul(onem, onep8, N), N)            # psi_1 omega_0
    zk3 = smul(zeta, k3, N)                             # zeta psi_1 omega_0
    return {'1': one, 'w0': w0, 'w1': w1, 'k3': k3, 'zk3': zk3}, zeta, psi1

# ----------------------------------------------------------------------------
# polynomials in L = log q with q-series coefficients: dict {power of L: series}
# ----------------------------------------------------------------------------

def theta_inv(poly, N):
    """theta^{-1}: q^m L^j -> sum_i (-1)^i j!/(j-i)! q^m L^{j-i} / m^{i+1} (m >= 1);  L^j -> L^{j+1}/(j+1)."""
    out = {}
    for j, s in poly.items():
        if s[0]:
            out.setdefault(j + 1, [Fr(0)] * (N + 1))[0] += s[0] / (j + 1)
        for i in range(j + 1):
            t = out.setdefault(j - i, [Fr(0)] * (N + 1)); f = Fr((-1) ** i * (factorial(j) // factorial(j - i)))
            for m in range(1, N + 1):
                if s[m]: t[m] += f * s[m] / Fr(m) ** (i + 1)
    return out

def theta(poly, N):
    """theta = q d/dq:  q^m L^j -> m q^m L^j + j q^m L^{j-1}."""
    out = {}
    for j, s in poly.items():
        t = out.setdefault(j, [Fr(0)] * (N + 1))
        for m in range(1, N + 1): t[m] += m * s[m]
        if j:
            u = out.setdefault(j - 1, [Fr(0)] * (N + 1))
            for m in range(N + 1): u[m] += j * s[m]
    return out

def pmul(poly, series, N):
    return {j: smul(s, series, N) for j, s in poly.items()}

def padd(a, b, N, cb=Fr(1)):
    """a + cb * b"""
    out = {j: list(s) for j, s in a.items()}
    for j, s in b.items():
        t = out.setdefault(j, [Fr(0)] * (N + 1))
        for m in range(N + 1):
            if s[m]: t[m] += cb * s[m]
    return out

def iterated_integral(word, letters, N, memo):
    """I(f_1, ..., f_n; q) = theta^{-1}(f_1 I(f_2, ..., f_n; q)), built from the inside out, memoised on suffixes."""
    if word not in memo:
        if not word: memo[word] = {0: [Fr(1)] + [Fr(0)] * N}
        else: memo[word] = theta_inv(pmul(iterated_integral(word[1:], letters, N, memo), letters[word[0]], N), N)
    return memo[word]

def value(poly, q0, L0, upto):
    """substitute q_0 and L_0 = log q_0, keeping the terms through q^upto."""
    tot = mpf(0)
    for j, s in poly.items():
        acc = mpf(0)
        for m in range(upto, -1, -1):
            acc = acc * q0 + (mpf(s[m].numerator) / s[m].denominator if s[m] else 0)
        tot += acc * L0 ** j
    return tot

# ----------------------------------------------------------------------------
# the evaluation
# ----------------------------------------------------------------------------

def q_of_zeta(zeta_series, psi1_series, zeta0, N):
    """the unique q_0 in (0, 1) with zeta(q_0) = zeta_0, found as the root of the holomorphic weight-one form
    psi_1 (zeta - zeta_0), whose q-coefficients stay bounded (those of zeta itself do not) and which has the same
    root since psi_1 > 0 on 0 < q < 1: bracket by walking up while the truncated series still increases, bisect,
    then Newton's method.  Raises ValueError when the N-term series cannot reach zeta_0."""
    zp = smul(zeta_series, psi1_series, N)
    c = [mpf(zp[n].numerator) / zp[n].denominator - zeta0 * mpf(psi1_series[n].numerator) / psi1_series[n].denominator for n in range(N + 1)]
    f = lambda q: mp.polyval(c[::-1], q)
    fp = lambda q: mp.polyval([n * c[n] for n in range(N, 0, -1)], q)
    lo, hi, step = mpf(0), mpf('0.05'), mpf('0.05')
    while f(hi) < 0:
        if fp(hi) <= 0 or hi >= 1:
            raise ValueError('the %d-term series does not reach zeta = %s; use more terms' % (N, zeta0))
        lo, hi = hi, hi + step
    for _ in range(60):
        mid = (lo + hi) / 2
        if f(mid) < 0: lo = mid
        else: hi = mid
    q = (lo + hi) / 2
    for _ in range(8): q = q - f(q) / fp(q)
    if not (lo - step <= q <= hi + step) or abs(f(q)) > mpf(10) ** (6 - mp.mp.dps):
        raise ValueError('q_0 did not converge for zeta = %s with %d terms' % (zeta0, N))
    return q

def terms_needed(digits, q0):
    return int(mp.ceil((digits + 10) / mp.log10(1 / q0))) + 15

def evaluate(zeta0, digits, N=None):
    """F_R and its pieces at the rational zeta0, aiming at `digits` correct digits.  Returns a dict of mpf values."""
    t0 = time.time()
    wdps = digits + 12
    with mp.workdps(wdps):
        z = mpf(zeta0.numerator) / zeta0.denominator
        if N is None:
            n0 = 60
            while True:
                try:
                    _, zeta_lo, psi1_lo = frame(n0)
                    N = terms_needed(digits, q_of_zeta(zeta_lo, psi1_lo, z, n0)); break
                except ValueError:
                    n0 *= 2
        if N < 40: raise ValueError('N must be at least 40')
        letters, zeta_s, psi1_s = frame(N)
        q0 = q_of_zeta(zeta_s, psi1_s, z, N); L0 = mp.log(q0)
        K = dict(z=z, pi2=mp.pi ** 2, z3=mp.zeta(3), pi4=mp.pi ** 4, z5=mp.zeta(5))
        memo = {}
        def hpl_sum(table, upto):
            terms = [coeff(**K) * value(iterated_integral(tuple('w%d' % i for i in key), letters, N, memo), q0, L0, upto)
                     for key, coeff in table.items()]
            return mp.fsum(terms), mp.fsum(abs(t) for t in terms)
        # S0 = psi_1 [ 33/4 zeta_5 - pi^2 zeta_3/12 - pi^4 L/30 + sum_channels constant x G_channel ],  G = sum rational x I(word)
        G = {}
        for word, (r, ch) in S0_TABLE.items():
            G[ch] = padd(G.get(ch, {}), iterated_integral(word, letters, N, memo), N, r)
        S0poly = {ch: pmul(g, psi1_s, N) for ch, g in G.items()}
        S0poly['pi4'] = {1: sscale(psi1_s, Fr(-1, 30))}
        S0poly['z5pi2z3'] = {0: psi1_s}
        thetaS0poly = {ch: theta(p, N) for ch, p in S0poly.items()}
        CH = {'1': mpf(1), 'pi2': K['pi2'], 'z3': K['z3'], 'pi4': K['pi4'], 'z5pi2z3': mpf(33) / 4 * K['z5'] - K['pi2'] * K['z3'] / 12}
        def assemble(upto):
            P, Pabs = hpl_sum(P_TABLE, upto); Psi, Psiabs = hpl_sum(PSI_TABLE, upto)
            S0terms = [CH[ch] * value(p, q0, L0, upto) for ch, p in S0poly.items()]
            thetaterms = [CH[ch] * value(p, q0, L0, upto) for ch, p in thetaS0poly.items()]
            den = value({0: psi1_s}, q0, L0, upto) ** 2 * z * (1 - z) * (1 + 8 * z)      # theta zeta
            S0, S0p = mp.fsum(S0terms), mp.fsum(thetaterms) / den                         # S0' = theta S0 / theta zeta
            FK1 = c1(z) * S0 + c2(z) * S0p + Psi
            # the sum of the magnitudes of everything that was added up, which sets the scale of the rounding error
            absum = Pabs + 2 * (abs(c1(z)) * mp.fsum(abs(t) for t in S0terms) + abs(c2(z)) * mp.fsum(abs(t) for t in thetaterms) / abs(den) + Psiabs)
            return dict(P=P, Psi=Psi, S0=S0, S0p=S0p, FK1=FK1, FR=2 * FK1 + P, absum=absum)
        full, less = assemble(N), assemble(N - 20)
        # rounding: the working precision times the magnitudes added; truncation: the terms q^(N-19) .. q^N move F_R by
        # `block`.  A geometric tail would put the dropped part beyond q^N near block * q0^20; the series converge more
        # slowly than that as zeta -> 1, so the estimate uses q0^10 instead.
        rnd = full['absum'] * mpf(10) ** (1 - wdps)
        moved = abs(full['FR'] - less['FR'])
        block = moved + rnd
        est = block * q0 ** 10 + rnd
        out = dict(zeta=z, q0=q0, L=L0, N=N, block_digits=float(-mp.log10(block / abs(full['FR']))), below_rounding=bool(moved < rnd),
                   est_digits=float(-mp.log10(est / abs(full['FR']))), rounding_digits=float(-mp.log10(rnd / abs(full['FR']))),
                   wdps=wdps, sec=time.time() - t0, **full)
    return out

# ----------------------------------------------------------------------------
# self-test
# ----------------------------------------------------------------------------

def check():
    ok = [True]
    def gate(name, cond, detail=''):
        ok[0] = ok[0] and bool(cond); print('  [%s] %s%s' % ('ok' if cond else 'FAIL', name, '  ' + detail if detail else ''))
    def F(*xs): return [Fr(x) for x in xs]
    t0 = time.time()
    print('1. the frame: q-series against the series printed in the paper, and the identities between them')
    N = 40; letters, zeta, psi1 = frame(N); one = [Fr(1)] + [Fr(0)] * N
    gate('zeta = q + 3q^2 + 3q^3 - 5q^4 - 18q^5 + ...', zeta[:6] == F(0, 1, 3, 3, -5, -18))
    gate('psi_1 = 1 - 2q + 4q^2 - 2q^3 + ...', psi1[:4] == F(1, -2, 4, -2))
    gate('psi_1 omega_0 = 1 + q - 5q^2 + q^3 + 11q^4 - 24q^5 + ...', letters['k3'][:6] == F(1, 1, -5, 1, 11, -24))
    thz = [n * zeta[n] for n in range(N + 1)]
    gate('theta zeta = zeta omega_0 = psi_1^2 zeta (1-zeta)(1+8 zeta), order by order', thz == smul(zeta, letters['w0'], N))
    gate('theta zeta = (1-zeta) omega_1', thz == smul(sadd(one, sscale(zeta, Fr(-1))), letters['w1'], N))
    gate('zeta psi_1 omega_0 = psi_1 theta zeta', letters['zk3'] == smul(psi1, thz, N))
    fr = [Fr((-1) ** n * sum(comb(n, k) ** 3 for k in range(n + 1))) for n in range(N + 1)]
    comp, zp = [Fr(0)] * (N + 1), list(one)
    for n in range(N + 1): comp = sadd(comp, sscale(zp, fr[n])); zp = smul(zp, zeta, N)
    gate('psi_1 = sum_n (-1)^n (sum_k C(n,k)^3) zeta^n  (Franel numbers)', comp == psi1)
    memo = {}
    I1 = iterated_integral(('k3',), letters, N, memo); I2 = iterated_integral(('1', 'k3'), letters, N, memo)
    gate('I(psi_1 omega_0; q) = L + q - 5/2 q^2 + 1/3 q^3 + 11/4 q^4 - 24/5 q^5 + ...',
         I1[1][:2] == F(1, 0) and I1[0][:6] == F(0, 1, Fr(-5, 2), Fr(1, 3), Fr(11, 4), Fr(-24, 5)))
    gate('I(1, psi_1 omega_0; q) = L^2/2 + q - 5/4 q^2 + 1/9 q^3 + 11/16 q^4 - 24/25 q^5 + ...',
         I2[2][:2] == F(Fr(1, 2), 0) and I2[0][:6] == F(0, 1, Fr(-5, 4), Fr(1, 9), Fr(11, 16), Fr(-24, 25)) and not any(I2.get(1, [0])))
    print('2. q_0 at the reference angles (the paper: q_0 = 0.1739 and L = -1.7493 at zeta = 3/11; q_0 = 0.2724 at zeta = 1/2)')
    with mp.workdps(30):
        q = q_of_zeta(zeta, psi1, mpf(3) / 11, N); gate('q_0(3/11) = %s' % mp.nstr(q, 8), abs(q - mpf('0.1739')) < mpf('5e-5'))
        gate('L(3/11) = %s' % mp.nstr(mp.log(q), 8), abs(mp.log(q) + mpf('1.7493')) < mpf('5e-5'))
        q = q_of_zeta(zeta, psi1, mpf(1) / 2, N); gate('q_0(1/2) = %s' % mp.nstr(q, 8), abs(q - mpf('0.2724')) < mpf('5e-5'))
    print('3. harmonic polylogarithms at zeta = 1/3 by the q-series against mpmath (bar: 28 digits)')
    with mp.workdps(40):
        N = 90; letters, zeta, psi1 = frame(N); q0 = q_of_zeta(zeta, psi1, mpf(1) / 3, N); L0 = mp.log(q0); z = mpf(1) / 3; memo = {}
        H = lambda *u: value(iterated_integral(tuple('w%d' % i for i in u), letters, N, memo), q0, L0, N)
        tests = [('H_0 = log zeta', H(0), mp.log(z)), ('H_1 = -log(1-zeta)', H(1), -mp.log(1 - z)),
                 ('H_{0,1} = Li_2', H(0, 1), mp.polylog(2, z)), ('H_{0,0,1} = Li_3', H(0, 0, 1), mp.polylog(3, z)),
                 ('H_{0,0,0,0,1} = Li_5', H(0, 0, 0, 0, 1), mp.polylog(5, z)), ('H_{1,1} = log^2(1-zeta)/2', H(1, 1), mp.log(1 - z) ** 2 / 2),
                 ('H_{1,0} = H_1 H_0 - H_{0,1} (shuffle)', H(1, 0), -mp.log(1 - z) * mp.log(z) - mp.polylog(2, z))]
        for name, a, b in tests:
            d = min(float(-mp.log10(abs(a - b) / abs(b) + mpf(10) ** -40)), 40.0); gate(name, d >= 28, '%.1f digits' % d)
    print('4. F_R at the reference angles against the two-fold integral computed independently')
    for zk, (ref, cert) in REFERENCE.items():
        target = min(cert, 45); r = evaluate(Fr(zk), target + 4)
        with mp.workdps(60):
            d = float(-mp.log10(abs(r['FR'] - mpf(ref)) / abs(mpf(ref))))
        gate('F_R(%s) = %s' % (zk, mp.nstr(r['FR'], target)), d >= target - 1,
             'agrees with %s... to %.1f digits (reference good to %d; N = %d, %.1f s)' % (ref[:12], d, cert, r['N'], r['sec']))
    print('%s  (%.0f s)' % ('ALL CHECKS PASSED' if ok[0] else 'CHECK FAILED', time.time() - t0))
    return 0 if ok[0] else 1

def main():
    ap = argparse.ArgumentParser(description='F_R(zeta) = 2 F_K1 + P of the NNLO N=4 energy-energy correlator from its closed form')
    ap.add_argument('zeta', nargs='?', help='rational angle variable, e.g. 3/11 (0 < zeta < 1)')
    ap.add_argument('--digits', type=int, default=30, help='target digits (default 30)')
    ap.add_argument('--N', type=int, default=None, help='override the number of q-terms (at least 40)')
    ap.add_argument('--check', action='store_true', help='run the self-test')
    a = ap.parse_args()
    if a.check: return check()
    if a.zeta is None: ap.error('give zeta (e.g. 3/11) or --check')
    try: z0 = Fr(a.zeta)
    except (ValueError, ZeroDivisionError): ap.error('zeta must be a rational number such as 3/11 or 0.27')
    if not 0 < z0 < 1: ap.error('zeta must lie in (0, 1)')
    if a.digits < 1: ap.error('--digits must be a positive integer')
    if a.N is not None and a.N < 40: ap.error('--N must be at least 40')
    try: r = evaluate(z0, a.digits, a.N)
    except ValueError as e: ap.error(str(e))
    print('zeta = %s   q_0 = %s   L = log q_0 = %s   N = %d terms' % (z0, mp.nstr(r['q0'], 12), mp.nstr(r['L'], 12), r['N']))
    for k, lab in (('P', 'P'), ('Psi', 'Psi'), ('S0', 'S0'), ('S0p', "S0'"), ('FK1', 'F_K1'), ('FR', 'F_R = 2 F_K1 + P')):
        print('%-18s = %s' % (lab, mp.nstr(r[k], a.digits + 2)))
    if r['est_digits'] < 2:
        print('WARNING: the series is not converged with N = %d terms (fewer than two digits); use more terms' % r['N'])
    if r['below_rounding']:
        print('truncation: the last 20 terms move F_R by less than the rounding error, which is at the %.1f-th digit (working precision %d digits); %.1f s'
              % (r['rounding_digits'], r['wdps'], r['sec']))
    else:
        print('truncation: the last 20 terms move F_R at the %.1f-th digit; the dropped tail is estimated below the %.1f-th; rounding error at the %.1f-th (working precision %d digits); %.1f s'
              % (r['block_digits'], r['est_digits'], r['rounding_digits'], r['wdps'], r['sec']))
    return 0

if __name__ == '__main__':
    sys.exit(main())
