"""Exact KdV, Yang–Baxter, Jacobi and Volterra checks. Requires SymPy."""

from itertools import product

import sympy as sp


def kdv():
    x, t, z = sp.symbols("x t z")
    u = sp.Function("u")(x, t)
    b = 4*z - 2*u
    U = sp.Matrix([[0, 1], [-z-u, 0]])
    V = sp.Matrix([[u.diff(x), b], [u.diff(x, 2)-b*(z+u), -u.diff(x)]])

    def curvature(space, time):
        return (space.diff(t) - time.diff(x) + space*time - time*space).applyfunc(sp.expand)

    K = u.diff(t) + 6*u*u.diff(x) + u.diff(x, 3)
    original = curvature(U, V)
    assert original == sp.Matrix([[0, 0], [-K, 0]])
    G = sp.Matrix([[1, x], [0, 1]])
    inverse = G.inv()
    space = (G.diff(x) + G*U)*inverse
    time = (G.diff(t) + G*V)*inverse
    transformed = curvature(space, time)
    expected = -K * sp.Matrix([[x, -x**2], [1, -x]])
    assert (transformed - expected).applyfunc(sp.expand) == sp.zeros(2)

    wrong = V.copy()
    wrong[1, 0] -= 2*u.diff(x, 2)
    defect = curvature(U, wrong) - original
    assert defect == sp.Matrix([[-2*u.diff(x, 2), 0], [2*u.diff(x, 3), 2*u.diff(x, 2)]])
    sample = defect.subs(u, x**3).doit().subs(x, 1)
    assert sample == sp.Matrix([[-12, 0], [12, 12]])
    print("KdV changed-sign defect minus original:", defect)
    print("Changed sign at the cubic profile:", sample)


def swaps():
    words = list(product((0, 1), repeat=3))

    def exchange(i, j):
        matrix = sp.zeros(8)
        for column, word in enumerate(words):
            outgoing = list(word)
            outgoing[i], outgoing[j] = outgoing[j], outgoing[i]
            row = words.index(tuple(outgoing))
            matrix[row, column] = 1
        return matrix

    a, b, c, x, y = sp.symbols("a b c x y")
    left = a*sp.eye(8) + exchange(0, 1)
    middle = b*sp.eye(8) + exchange(0, 2)
    right = c*sp.eye(8) + exchange(1, 2)
    forward = left*middle*right
    reverse = right*middle*left
    row, column = words.index((0, 0, 1)), words.index((0, 1, 0))
    assert sp.expand(forward[row, column] - (a+1)*b) == 0
    assert sp.expand(reverse[row, column] - (a*(b+1)+c)) == 0
    defect = forward - reverse

    # Check the exact, separately quadratic matrix on a 3-by-3 grid as well
    # as checking all coefficients. No inverse is taken at the rank changes.
    rational = defect.subs({a: x, b: x+y, c: y})
    for first, second in product((-1, 0, 1), repeat=2):
        assert rational.subs({x: first, y: second}) == sp.zeros(8)
    assert rational.applyfunc(sp.expand) == sp.zeros(8)
    wrong = defect.subs({a: x*x, b: (x+y)**2, c: y*y}).applyfunc(sp.factor)
    assert sum(value != 0 for value in wrong) == 12
    assert wrong[row, column] == 2*x*y
    assert wrong[:, 0] == sp.zeros(8, 1)
    print("Tensor test, nonzero entries and example: 0, 0 (rational);",
          "12,", wrong[row, column], "(squared differences)")


def jacobi():
    x, y, z = coordinates = sp.symbols("x y z")
    for field, expected in [((x, y, z), 0), ((-y, x, 1), -2)]:
        a, b, c = field
        P = sp.Matrix([[0, c, -b], [-c, 0, a], [b, -a, 0]])
        coefficient = sum(P[i, ell]*P[j, k].diff(coordinates[ell])
                          for i, j, k in [(0, 1, 2), (1, 2, 0), (2, 0, 1)]
                          for ell in range(3))
        assert coefficient == expected
        print("Jacobi coefficient:", coefficient)
        if expected == 0:
            assert P*sp.Matrix(coordinates) == sp.zeros(3, 1)
            assert P[:2, :2].det().subs(z, 3) == 9
        else:
            # X_H acts by {.,H}, so the fields for x and y are columns.
            X, Y = P[:, 0], P[:, 1]
            commutator = Y.jacobian(coordinates)*X - X.jacobian(coordinates)*Y
            assert P[0, 1] == 1
            assert commutator == sp.Matrix([0, 0, -2])
            print("Commutator of the x and y fields:", list(commutator))


def volterra():
    a, b, c, d = sp.symbols("u_m1 u_0 u_1 u_2")
    A, B = sp.symbols("A B")
    rho = A*b*b + B*b*c
    dot = rho.diff(b)*b*(c-a) + rho.diff(c)*c*(d-b)
    flux = b*c*(c+d)
    prev = a*b*(b+c)
    local = dot.subs({A: sp.Rational(1, 2), B: 1})
    assert sp.expand(local-flux+prev) == 0

    ring = (1, 2, 3, 5, 7)
    stencils = [dict(zip((a, b, c, d), [ring[(i+j) % len(ring)] for j in (-1, 0, 1, 2)]))
                for i in range(len(ring))]
    charge_rate = sum(dot.subs(values) for values in stencils)
    assert sp.expand(charge_rate + 66*(2*A-B)) == 0
    fluxes = [flux.subs(values) for values in stencils]
    local_rates = [local.subs(values) for values in stencils]
    assert local_rates[:2] == [-11, 38]
    assert sum(local_rates[:2]) == fluxes[1] - fluxes[-1] == 27
    print("Quadratic density coefficient factor:", 2*A-B, "ring test:", -66)
    print("Five local rates:", local_rates, "net into first two sites:", sum(local_rates[:2]))


if __name__ == "__main__":
    kdv()
    swaps()
    jacobi()
    volterra()
