"""Check exact identities in three Painlevé articles with Python 3 and SymPy."""
import sympy as s

t, lam = s.symbols("t lambda", nonzero=True)
X = s.Matrix([[0, 1], [1, 0]])
Y = s.Matrix([[0, -s.I], [s.I, 0]])
Z = s.diag(1, -1)


def rational_dressing():
    q = -1/t
    gauge = s.eye(2) + s.I/(2*t*lam)*s.Matrix([[-1, 1], [-1, 1]])
    spec = -s.I*(4*lam**2 + t + 2*q**2)*Z + (4*lam*q - 1/lam)*X - 2*q.diff(t)*Y
    time = -s.I*lam*Z + q*X
    vacuum_spec = -s.I*(4*lam**2+t)*Z
    vacuum_time = -s.I*lam*Z
    assert s.simplify(gauge.det()) == 1
    for variable, coefficient, vacuum in [(lam, spec, vacuum_spec), (t, time, vacuum_time)]:
        residual = gauge.diff(variable) + gauge*vacuum - coefficient*gauge
        assert residual.applyfunc(s.cancel) == s.zeros(2)


def tau_pair():
    q = 1/t - 3*t**2/(t**3+4)
    for field, alpha, polynomial in [(q, 2, t**3+4), (-q, -2, t)]:
        p = field.diff(t) + field**2 + t/2
        h = p**2/2 - (field**2+t/2)*p - (alpha+s.Rational(1, 2))*field
        assert s.factor(h - polynomial.diff(t)/polynomial + t**2/8) == 0
        assert s.factor(field.diff(t, 2)-2*field**3-t*field-alpha) == 0


def commutator(a, b):
    return a*b-b*a


def moving_residues():
    a0, at, a1 = X/4, -s.I*Y/5, Z/6
    center = s.Rational(1, 2)
    # A0'=[At,A0]/t and A1'=[At,A1]/(t-1).
    d0 = commutator(at, a0)/center
    d1 = commutator(at, a1)/(center-1)
    dt = -d0-d1
    # Differentiate the matrix equations once more at the regular point.
    dd0 = (commutator(dt, a0)+commutator(at, d0)-d0)/center
    dd1 = (commutator(dt, a1)+commutator(at, d1)-d1)/(center-1)
    h = s.Symbol("h")
    pole0 = a0 + h*d0 + h*h*dd0/2
    pole1 = a1 + h*d1 + h*h*dd1/2
    moving = at + h*dt - h*h*(dd0+dd1)/2
    actual = (pole0*moving).trace()/(center+h) + (pole1*moving).trace()/(center+h-1)
    jet = s.series(actual, h, 0, 3).removeO().expand()
    assert jet == -s.Rational(4, 15)*h*h
    assert (a0*commutator(at, a1)).trace() == s.Rational(1, 30)


if __name__ == "__main__":
    rational_dressing()
    tau_pair()
    moving_residues()
    print("Exact spectral and time residuals vanish; both rational tau derivatives match.")
    print("Direct Schlesinger jet gives log(tau) = -4 h**3/45 + O(h**4).")
