"""Check local KdV and Boussinesq operator identities with exact SymPy polynomials."""

import sympy as sp


jet = sp.symbols("u0:11")
x = sp.Symbol("x")


def total_dx(polynomial):
    return sum(sp.diff(polynomial, u) * ux for u, ux in zip(jet, jet[1:]))


def vary(characteristic, polynomial):
    """Directional variation of a differential polynomial along one local flow."""
    result = 0
    variation = characteristic
    for coordinate in jet:
        result += sp.diff(polynomial, coordinate) * variation
        variation = total_dx(variation)
    return sp.expand(result)


def compose(left, right, lowest):
    """Left coefficients, generalized Leibniz rule, and a fixed output cutoff."""
    out = {}
    for i, a in left.items():
        for j, b in right.items():
            for k in range(i + j - lowest + 1):
                term = a * sp.binomial(i, k) * sp.diff(b, x, k)
                power = i + j - k
                out[power] = out.get(power, 0) + term
    return {i: sp.expand(f) for i, f in out.items() if sp.expand(f) != 0}


def commutator(left, right):
    ab, ba = compose(left, right, 0), compose(right, left, 0)
    return {i: val for i in ab.keys() | ba.keys()
            if (val := sp.expand(ab.get(i, 0) - ba.get(i, 0))) != 0}


def check():
    u, u1, u2, u3, _, u5 = jet[:6]
    a, b, c = sp.symbols("a b c")
    kd3 = u3 + 6 * u * u1
    candidate = u5 + a * u * u3 + b * u1 * u2 + c * u**2 * u1
    bracket = vary(kd3, candidate) - vary(candidate, kd3)
    coeffs = sp.Poly(bracket, *jet).coeffs()
    assert sp.solve(coeffs, (a, b, c), dict=True) == [{a: 10, b: 20, c: 30}]
    assert bracket.subs({a: 11, b: 20, c: 30}).subs(dict(zip(jet, [1]*11))) == 30
    print("unique normalized fifth-order coefficients: 10, 20, 30")

    U, V = (sp.Function(f)(x) for f in ("u", "v"))
    root = {1: 1, -1: U/2, -2: -sp.diff(U, x)/4,
            -3: (sp.diff(U, x, 2) - U**2)/8}
    assert compose(root, root, -2) == {2: 1, 0: U}
    assert compose(root, {2: 1, 0: U}, 0) == {
        3: 1, 1: 3*U/2, 0: 3*sp.diff(U, x)/4}
    print("square-root verification through D^(-2), and B3 projection: exact")

    b2 = {2: 1, 0: 2*U/3}
    lax3 = {3: 1, 1: U, 0: V}
    assert commutator(b2, lax3) == {
        1: 2*sp.diff(V, x)-sp.diff(U, x, 2),
        0: sp.diff(V, x, 2)-2*sp.diff(U, x, 3)/3-2*U*sp.diff(U, x)/3}
    print("third-order scalar Boussinesq Lax commutator: exact")


if __name__ == "__main__":
    check()
