"""Verify Toda corners and H1 surface closure with exact rational data."""
from fractions import Fraction as Q
from math import log


def momenta(x, y, h):
    """x, y are exponentials of the initial and final particle positions."""
    a, b = [(t/s-1)/h for s, t in zip(x, y)]
    bond = h*x[1]/y[0]
    return (a, b+bond), (a+bond, b)


def step(x, p, h):
    e1 = 1+h*p[0]
    e2 = 1+h*p[1]-h*h*x[1]/(x[0]*e1)
    assert min(e1,e2) > 0
    end = (x[0]*e1, x[1]*e2)
    before, after = momenta(x, end, h)
    assert before == p
    return end, after


def action(x, y, h):
    ratios = [t/s for s,t in zip(x,y)]
    return sum((r-1-log(r))/h for r in ratios)-h*x[1]/y[0]


def toda():
    h, k = Q(1,4), Q(1,5)
    x, p = (Q(1),Q(2)), (Q(1),Q(-1))
    xh, ph = step(x,p,h)
    xk, pk = step(x,p,k)
    finish, pf = step(xh,ph,k)
    assert (finish,pf) == step(xk,pk,h)
    assert momenta(x,xh,h)[0] == momenta(x,xk,k)[0]
    assert momenta(x,xh,h)[1] == momenta(xh,finish,k)[0]
    assert momenta(x,xk,k)[1] == momenta(xk,finish,h)[0]
    assert momenta(xh,finish,k)[1] == momenta(xk,finish,h)[1]
    print("Exp positions:",xh,xk,finish,"final p:",pf)
    defect = action(x,xh,h)+action(xh,finish,k)-action(x,xk,k)-action(xk,finish,h)
    assert abs(defect)<1e-14
    print("Square action defect (floating logarithms):",defect)


def h1():
    a,b,c = (Q(1),Q(3),Q(6))
    p,q,r = (Q(2),Q(5),Q(11))
    # The base field is zero.
    ab,ac,bc = -(p-q)/(a-b), -(p-r)/(a-c), -(q-r)/(b-c)
    low = (b-c,c-a,a-b)
    def closure(ab):
        upper = (ab-ac,bc-ab,ac-bc)
        ratios = [y/x for x,y in zip(low,upper)]
        linear = sum(u*d for u,d in zip((a,b,c),upper))
        value = linear-sum(d*log(abs(v)) for d,v in zip((q-r,r-p,p-q),ratios))
        return ratios, value
    ratios, defect = closure(ab)
    assert ratios == [Q(-1,10)]*3 and abs(defect)<1e-14
    print("H1 common signed ratio:",ratios[0],"closure and changed-face defect:",
          defect,closure(ab+Q(1,10))[1])


if __name__ == "__main__":
    toda()
    h1()
