"""Relative electric period of the rank-two-sheeted adjoint curve and its Toda limit.

Python 3, standard library. The calculation uses rho=1, u=4 and t=exp(i*theta).
"""

from cmath import exp, sqrt
from math import pi


def relative_period(mass, points, modes):
    samples = []
    for j in range(points):
        t = exp(2j * pi * j / points)
        if mass is None:
            samples.append(sqrt(4 + t + 1 / t).real)
            continue
        w, q = t / mass**2, mass**-4
        a = b = c = 0j
        for n in range(-modes, modes + 1):
            factor = (-1)**n * q**(n * (n - 1) // 2) * w**n
            a += factor
            b -= 2 * n * mass * factor
            c += (n**2 * mass**2 - 4) * factor
        # Half the root separation, chosen continuously with positive real part.
        root = sqrt((b / (2 * a))**2 - c / a)
        assert root.real > 1
        samples.append(root.real)
    return sum(samples) / points


if __name__ == "__main__":
    for mass in (10, 20, 40, 80, None):
        coarse = relative_period(mass, 128, 3)
        fine = relative_period(mass, 256, 4)
        assert abs(coarse - fine) < 2e-12
        print(f"{str(mass or 'Toda'):>4}  {fine:.11f}  {abs(coarse-fine):.1e}")
