"""Two formulations for a regular pair of real XXX roots on a five-site ring."""
from math import atan, pi

import numpy as np


def phase_equations(roots):
    values = []
    G = np.zeros((2, 2))
    for j, (u, branch) in enumerate(zip(roots, (1,-1))):
        d = u - roots[1-j]
        values.append(10*atan(0.5/u) - 2*atan(1/d) - 2*pi*branch)
        G[j,j] = -5/(u*u+0.25) + 2/(1+d*d)
        G[j,1-j] = -2/(1+d*d)
    return np.array(values), G


def polynomial_equations(roots):
    # For real roots, the cleared equation is twice i times the imaginary
    # part of (u+i/2)^5 (u-v-i); use that real polynomial and its Jacobian.
    values = []
    G = np.zeros((2,2))
    for j,u in enumerate(roots):
        q = u+0.5j
        d = u-roots[1-j]-1j
        values.append((q**5*d).imag)
        G[j,j] = (5*q**4*d + q**5).imag
        G[j,1-j] = -(q**5).imag
    return np.array(values), G


def solve(equations):
    roots = np.array([0.55,-0.47])
    for iteration in range(12):
        residual,G = equations(roots)
        if np.linalg.norm(residual, ord=np.inf)<2e-14:
            print("Steps, roots, equation error, condition:",iteration,roots,
                  max(abs(residual)),np.linalg.cond(G))
            return roots
        roots -= np.linalg.solve(G,residual)
    raise ArithmeticError("Newton solve did not converge")


if __name__ == "__main__":
    for equations in (phase_equations,polynomial_equations):
        u = solve(equations)
        np.testing.assert_allclose(u,[0.5,-0.5],rtol=0,atol=2e-14)
        energy = sum(0.5/(u*u+0.25))
        print("Energy in units of J:",energy)
