"""Exact checks for the KdV hierarchy built from fractional powers of L = D^2 + u.

The script implements formal pseudodifferential operators with left coefficients, computes the
monic square root of L, and verifies through the seventh-order flow that
  1. [(L^{n/2})_+, L] is multiplication by K_n = 2 (res L^{n/2})_x,
  2. the flows K_3, K_5, K_7 commute on arbitrary jets,
  3. every density res L^{m/2} is conserved by every flow, while u^3 alone is not,
  4. the gradient of the integral of res L^{n/2} is (n/2) res L^{(n-2)/2},
  5. the Lenard relation (D^3 + 4uD + 2u_x) res L^{(n-2)/2} = 4 D res L^{n/2} holds,
  6. one soliton depends on every time through x + kappa^2 t3 + kappa^4 t5 + kappa^6 t7.
Run with Python 3 and SymPy:  python3 kdv_hierarchy.py
"""
from functools import reduce
import sympy as sp

x = sp.symbols('x')
u = sp.Function('u')(x)
ORDER = 9          # retain the root down to D^{-ORDER}
JET = 20           # number of jet variables used for differential polynomials
U = sp.symbols(f'u0:{JET}')


def binom(m, r):
    """Generalized binomial coefficient m(m-1)...(m-r+1)/r! for integer m, r >= 0."""
    return reduce(lambda acc, i: acc * (m - i), range(r), sp.Integer(1)) / sp.factorial(r)


def mul(A, B, low=-ORDER):
    """Product of formal operators {power: coefficient}, keeping powers >= low."""
    out = {}
    for i, a in A.items():
        for j, b in B.items():
            r = 0
            while i + j - r >= low:
                c = binom(i, r)
                if c == 0 and i >= 0:
                    break
                if c != 0:
                    term = sp.expand(a * sp.diff(b, x, r) * c)
                    if term != 0:
                        out[i + j - r] = sp.expand(out.get(i + j - r, 0) + term)
                r += 1
    return {k: v for k, v in out.items() if v != 0}


def add(A, B, sign=1):
    keys = set(A) | set(B)
    out = {k: sp.expand(A.get(k, 0) + sign * B.get(k, 0)) for k in keys}
    return {k: v for k, v in out.items() if v != 0}


L = {2: sp.Integer(1), 0: u}


def square_root():
    """Monic S with S^2 = L, determined one coefficient at a time."""
    S = {1: sp.Integer(1)}
    for m in range(1, ORDER + 1):
        coefficient = mul(S, S).get(1 - m, 0)
        target = u if m == 1 else 0
        S[-m] = sp.expand((target - coefficient) / 2)
    return S


S = square_root()
assert add(mul(S, S, low=-ORDER + 2), L, -1) == {} or all(k < -ORDER + 2 for k in add(mul(S, S, low=-ORDER + 2), L, -1))


def power(n):
    """L^{n/2} for odd n = 2k + 1, as L^k S."""
    P = S
    for _ in range((n - 1) // 2):
        P = mul(L, P)
    return P


def to_jet(expr):
    """Replace u and its derivatives by jet symbols u0, u1, ..."""
    expr = sp.expand(expr)
    for k in range(JET - 1, 0, -1):
        expr = expr.subs(sp.Derivative(u, (x, k)), U[k])
    return sp.expand(expr.subs(u, U[0]))


def total_d(P):
    return sp.expand(sum(U[k + 1] * sp.diff(P, U[k]) for k in range(JET - 1)))


def euler(P):
    """Variational derivative sum_k (-D)^k dP/du_k of a differential polynomial."""
    out = 0
    for k in range(JET):
        term = sp.diff(P, U[k])
        for _ in range(k):
            term = -total_d(term)
        out += term
    return sp.expand(out)


def flow(F, P):
    """Derivative of P along u_t = F, with u_{k,t} = D^k F."""
    out, DF = 0, F
    for k in range(JET - 6):
        out += DF * sp.diff(P, U[k])
        DF = total_d(DF)
    return sp.expand(out)


res = {n: to_jet(power(n).get(-1, 0)) for n in (1, 3, 5, 7, 9)}
K = {}
for n in (3, 5, 7):
    B = {k: v for k, v in power(n).items() if k >= 0}
    commutator = add(mul(B, L, low=0), mul(L, B, low=0), -1)
    assert set(commutator) <= {0}, f'[B_{n}, L] has derivative terms {sorted(commutator)}'
    K[n] = to_jet(commutator.get(0, 0))
    assert sp.expand(K[n] - 2 * total_d(res[n])) == 0, f'K_{n} differs from 2 D res'

expected_res = {
    1: U[0] / 2,
    3: (U[2] + 3 * U[0]**2) / 8,
    5: (U[4] + 10 * U[0] * U[2] + 5 * U[1]**2 + 10 * U[0]**3) / 32,
}
expected_K7 = (U[7] + 14 * U[0] * U[5] + 42 * U[1] * U[4] + 70 * U[2] * U[3] + 70 * U[0]**2 * U[3]
               + 280 * U[0] * U[1] * U[2] + 70 * U[1]**3 + 140 * U[0]**3 * U[1]) / 64
expected_K5 = (U[5] + 10 * U[0] * U[3] + 20 * U[1] * U[2] + 30 * U[0]**2 * U[1]) / 16
checks = {}
checks['residues of L^(1/2), L^(3/2), L^(5/2)'] = all(sp.expand(res[n] - e) == 0 for n, e in expected_res.items())
checks['K3 = (u3 + 6 u u1)/4'] = sp.expand(K[3] - (U[3] + 6 * U[0] * U[1]) / 4) == 0
checks['K5 = (u5 + 10uu3 + 20u1u2 + 30u^2u1)/16'] = sp.expand(K[5] - expected_K5) == 0
checks['K7 matches the seventh-order KdV polynomial / 64'] = sp.expand(K[7] - expected_K7) == 0
for m, n in ((3, 5), (3, 7), (5, 7)):
    checks[f'flows {m} and {n} commute on jets'] = sp.expand(flow(K[m], K[n]) - flow(K[n], K[m])) == 0
for m in (3, 5, 7):
    for n in (1, 3, 5, 7):
        checks[f'res L^({n}/2) conserved by t{m}'] = euler(flow(K[m], res[n])) == 0
for n in (3, 5, 7, 9):
    checks[f'gradient of int res L^({n}/2) = ({n}/2) res L^({n - 2}/2)'] = sp.expand(euler(res[n]) - sp.Rational(n, 2) * res[n - 2]) == 0
for n in (3, 5, 7, 9):
    P1 = total_d(total_d(total_d(res[n - 2]))) + 4 * U[0] * total_d(res[n - 2]) + 2 * U[1] * res[n - 2]
    checks[f'Lenard relation for n = {n}'] = sp.expand(P1 - 4 * total_d(res[n])) == 0
checks['int (2u^3 - u1^2) conserved by t3'] = euler(flow(K[3], 2 * U[0]**3 - U[1]**2)) == 0
# Integrating by parts: the quoted densities differ from the residues by total derivatives.
checks['res L^(5/2) ~ (5/32)(2u^3 - u1^2)'] = euler(res[5] - sp.Rational(5, 32) * (2 * U[0]**3 - U[1]**2)) == 0
checks['res L^(7/2) ~ (7/128)(5u^4 - 10u u1^2 + u2^2)'] = euler(res[7] - sp.Rational(7, 128) * (5 * U[0]**4 - 10 * U[0] * U[1]**2 + U[2]**2)) == 0
# Both brackets generate each flow: K_n = (1/n) P1 grad H_n = 4/(n+2) D grad H_{n+2}.
for n in (3, 5, 7):
    gradient_n, gradient_next = euler(res[n]), euler(res[n + 2])
    P1 = total_d(total_d(total_d(gradient_n))) + 4 * U[0] * total_d(gradient_n) + 2 * U[1] * gradient_n
    checks[f'K{n} from both Hamiltonian operators'] = (sp.expand(P1 / n - K[n]) == 0
                                                       and sp.expand(sp.Rational(4, n + 2) * total_d(gradient_next) - K[n]) == 0)

controls = {
    'int u^3 is not conserved by t3': euler(flow(K[3], U[0]**3)) != 0,
    'changing 10 to 11 in K5 breaks commutation': sp.expand(flow(K[3], K[5] + U[0] * U[3] / 16) - flow(K[5] + U[0] * U[3] / 16, K[3])) != 0,
}

# One soliton in three times, checked at sample points with 30-digit arithmetic.
kappa, t3, t5, t7 = sp.symbols('kappa t3 t5 t7')
phase = x + kappa**2 * t3 + kappa**4 * t5 + kappa**6 * t7
Q = 2 * kappa**2 * sp.sech(kappa * phase)**2
derivs = [Q] + [sp.diff(Q, x, k) for k in range(1, 8)]
values = {U[k]: derivs[k] for k in range(8)}
soliton_ok = True
for n, t in ((3, t3), (5, t5), (7, t7)):
    residual = sp.diff(Q, t) - K[n].subs(values)
    for point in ((sp.Rational(3, 10), sp.Rational(7, 10), sp.Rational(-1, 5), sp.Rational(1, 3), sp.Rational(1, 7)),
                  (sp.Rational(6, 5), sp.Rational(-2, 3), sp.Rational(1, 2), sp.Rational(-1, 4), sp.Rational(2, 5))):
        value = residual.subs(dict(zip((kappa, x, t3, t5, t7), point))).evalf(30)
        soliton_ok &= abs(value) < sp.Float('1e-25')
checks['one soliton solves t3, t5 and t7 with phase x + k^2 t3 + k^4 t5 + k^6 t7'] = soliton_ok


def main():
    print('res L^(7/2) =', sp.factor(res[7]))
    print('K7 =', sp.factor(K[7]))
    for name, ok in checks.items():
        print(f"{'PASS' if ok else 'FAIL'}  {name}")
    for name, ok in controls.items():
        print(f"{'PASS' if ok else 'FAIL'}  control: {name}")
    if not all(checks.values()) or not all(controls.values()):
        raise SystemExit(1)
    print('All hierarchy identities hold through the seventh-order flow; both controls fail as required.')


if __name__ == '__main__':
    main()
