"""Marked real SU(2) periods and one shrinking SU(3) period.

Standard Python 3. All calculations use Lambda = 1, closed cycles (two
sheets), and the differentials specified in the respective articles.
"""

from math import cos, pi, sin, sqrt


def simpson(func, start, end, intervals):
    if intervals <= 0 or intervals % 2:
        raise ValueError("Use a positive, even number of intervals.")
    step = (end - start) / intervals
    total = func(start) + func(end)
    for j in range(1, intervals):
        total += (4 if j % 2 else 2) * func(start + j * step)
    return total * step / 3


def marked_periods(modulus, intervals):
    """Return a and Im(a_D) on the U > 1 branch of the marked cubic."""
    if modulus <= 1:
        raise ValueError("These real intervals require U > 1.")
    delta = modulus - 1
    electric = simpson(lambda theta: sqrt(modulus - cos(theta)),
                       0, pi, intervals)

    def magnetic_integrand(theta):
        return 2 * delta * cos(theta)**2 / sqrt(2 + delta * sin(theta)**2)

    magnetic = simpson(magnetic_integrand, 0, pi / 2, intervals)
    return sqrt(2) * electric / pi, sqrt(2) * magnetic / pi


def scaled_cusp_period(delta, intervals):
    """Return |integral dS| / delta**(5/6) for the two-sheet short cycle.

    At u=0 and v=1+delta, take the scaled branch roots 1 and exp(2*pi*i/3).
    Integrate between them along radii through zero on one sheet, return on
    the second, and use r=1-s**2 to remove the endpoint singularity.
    """
    def regular_integrand(s):
        r = 1 - s**2
        return 2 * r**3 / sqrt((1 + r + r*r) * (2 + delta * (1 - r**3)))

    return 6 * sqrt(3) * simpson(regular_integrand, 0, 1, intervals)


def main():
    for modulus in (1.1, 3, 8):
        a, magnetic = marked_periods(modulus, 512)
        coarse = marked_periods(modulus, 256)
        assert max(abs(a - coarse[0]), abs(magnetic - coarse[1])) < 1e-10
        h = 1e-5
        below, above = (marked_periods(modulus + shift, 512)
                        for shift in (-h, h))
        da, dm = [(high - low) / (2*h) for low, high in zip(below, above)]
        wronskian = a * dm - magnetic * da
        assert abs(wronskian - 2/pi) < 3e-9
        if modulus == 3:
            assert abs(dm/da - 1) < 1e-9
        print(f"U={modulus}: a={a:.9f}, Im(a_D)={magnetic:.9f}, "
              f"Im(tau)={dm/da:.9f}, Im(W)={wronskian:.9f}")

    for delta in (0.1, 0.01, 0.001, 0.0):
        value = scaled_cusp_period(delta, 256)
        assert abs(value - scaled_cusp_period(delta, 512)) < 3e-9
        print(f"delta={delta:g}: scaled short period = {value:.8f}")


if __name__ == "__main__":
    main()
