"""Symbolic checks of the Lax and zero-curvature pairs quoted in four model records.

Each check expands a compatibility condition with SymPy and compares it with the field or
lattice equation in the record's own convention. Each deliberately altered pair must fail.
Run with Python 3 and SymPy:  python3 lax_pairs.py
"""
import sympy as sp

lam, mu, z = sp.symbols('lambda mu z')


def is_zero(expr):
    return sp.simplify(sp.expand(expr)) == 0


def zero_curvature(U, V, a, b):
    """U_b - V_a + [U, V] for the linear problems Psi_a = U Psi and Psi_b = V Psi."""
    return (U.diff(b) - V.diff(a) + U * V - V * U).applyfunc(sp.expand)


def nls(sigma, broken=False):
    """i q_t + q_xx + 2 sigma |q|^2 q = 0, with qbar treated as an independent field."""
    x, t = sp.symbols('x t')
    q, qbar = sp.Function('q')(x, t), sp.Function('qbar')(x, t)
    r = -sigma * qbar
    sign = -1 if broken else 1
    U = sp.Matrix([[-sp.I * lam, q], [r, sp.I * lam]])
    V = sp.Matrix([[-2 * sp.I * lam**2 - sp.I * q * r, 2 * lam * q + sign * sp.I * q.diff(x)],
                   [2 * lam * r - sp.I * r.diff(x), 2 * sp.I * lam**2 + sp.I * q * r]])
    Z = zero_curvature(U, V, x, t)
    equation = sp.I * q.diff(t) + q.diff(x, 2) + 2 * sigma * q**2 * qbar
    conjugate = -sp.I * qbar.diff(t) + qbar.diff(x, 2) + 2 * sigma * q * qbar**2
    return (is_zero(Z[0, 0]) and is_zero(Z[1, 1])
            and is_zero(sp.I * Z[0, 1] - equation)
            and is_zero(sp.I * sigma * Z[1, 0] - conjugate))


def sine_gordon(broken=False):
    """phi_{xi eta} = sin(phi), with x = xi + eta and t = xi - eta."""
    xi, eta = sp.symbols('xi eta')
    phi = sp.Function('phi')(xi, eta)
    sign = -1 if broken else 1
    U = sp.Matrix([[-sp.I * lam, -phi.diff(xi) / 2], [phi.diff(xi) / 2, sp.I * lam]])
    V = sp.I / (4 * lam) * sp.Matrix([[sp.cos(phi), sign * sp.sin(phi)], [sign * sp.sin(phi), -sp.cos(phi)]])
    Z = zero_curvature(U, V, xi, eta)
    equation = phi.diff(xi, eta) - sp.sin(phi)
    pair_ok = (sp.simplify(Z - sp.Matrix([[0, -equation / 2], [equation / 2, 0]])) == sp.zeros(2, 2))
    # Chain rule on a sample field: d_xi d_eta f(xi+eta, xi-eta) = f_xx - f_tt.
    X, T = sp.symbols('X T')
    f = sp.sin(2 * X + 3 * T) + X**3 * T**2 + sp.exp(X - T)
    lhs = f.subs({X: xi + eta, T: xi - eta}).diff(xi, eta)
    rhs = (f.diff(X, 2) - f.diff(T, 2)).subs({X: xi + eta, T: xi - eta})
    return pair_ok and is_zero(lhs - rhs)


def operator_terms(expr, psi):
    """Split a linear differential expression in psi into coefficients of psi and its derivatives."""
    derivatives = sorted((d for d in expr.atoms(sp.Derivative) if d.expr == psi), key=sp.default_sort_key)
    coefficients = {d: expr.coeff(d) for d in derivatives}
    rest = sp.expand(expr - sum(c * d for d, c in coefficients.items()))
    return coefficients, rest.coeff(psi), sp.expand(rest - rest.coeff(psi) * psi)


def kp(s_value, broken=False):
    """sigma psi_y + psi_xx + u psi = 0 and the t problem, with sigma^2 = s and w_x = -sigma u_y."""
    x, y, t = sp.symbols('x y t')
    sigma = sp.sqrt(s_value)
    u, w, psi = (sp.Function(name)(x, y, t) for name in ('u', 'w', 'psi'))
    c = 5 if broken else 6

    def A(f):
        return sigma * f.diff(y) + f.diff(x, 2) + u * f

    def B(f):
        return f.diff(t) + 4 * f.diff(x, 3) + c * u * f.diff(x) + 3 * (u.diff(x) + w) * f

    commutator = sp.expand(A(B(psi)) - B(A(psi)))
    constraint = {w.diff(x, 2): -sigma * u.diff(x, y), w.diff(x): -sigma * u.diff(y)}
    commutator = sp.expand(commutator.subs(constraint))
    derivative_terms, psi_coefficient, remainder = operator_terms(commutator, psi)
    if remainder != 0 or any(not is_zero(c) for c in derivative_terms.values()):
        return False
    # The surviving multiplier is u_t + 6 u u_x + u_xxx = 3 sigma w_y; its x-derivative is KP.
    system = -(u.diff(t) + 6 * u * u.diff(x) + u.diff(x, 3)) + 3 * sigma * w.diff(y)
    kp_equation = (u.diff(t) + 6 * u * u.diff(x) + u.diff(x, 3)).diff(x) + 3 * s_value * u.diff(y, 2)
    differentiated = sp.expand(system.diff(x).subs({w.diff(x, y): -sigma * u.diff(y, 2)}))
    return is_zero(psi_coefficient - system) and is_zero(differentiated + kp_equation)


def periodic_toda(n, broken=False):
    """L-dot = [B, L] for the periodic Jacobi matrix L(z) of the record's Toda cell."""
    a = sp.symbols(f'a1:{n + 1}', positive=True)
    b = sp.symbols(f'b1:{n + 1}', real=True)
    L, B = sp.zeros(n, n), sp.zeros(n, n)
    for j in range(n):
        L[j, j] += b[j]
    for j in range(n - 1):
        L[j, j + 1] += a[j]
        L[j + 1, j] += a[j]
        B[j, j + 1] += -a[j] / 2
        B[j + 1, j] += a[j] / 2
    # The closing bond joins site n to site 1 and carries the Floquet multiplier z.
    L[n - 1, 0] += a[n - 1] * z
    L[0, n - 1] += a[n - 1] / z
    B[n - 1, 0] += -a[n - 1] * z / 2
    B[0, n - 1] += (-1 if broken else 1) * a[n - 1] / (2 * z)
    adot = {a[j]: a[j] * (b[j] - b[(j + 1) % n]) / 2 for j in range(n)}
    bdot = {b[j]: a[j - 1]**2 - a[j]**2 for j in range(n)}
    rates = {**adot, **bdot}
    Ldot = L.applyfunc(lambda e: sum(sp.diff(e, v) * rate for v, rate in rates.items()))
    lax_ok = sp.simplify(Ldot - (B * L - L * B)) == sp.zeros(n, n)
    if broken or n != 2:
        return lax_ok
    # Two-site cell: det(mu - L(z)) = a1 a2 (Delta(mu) - z - 1/z), Delta as in the record.
    Delta = ((mu - b[0]) * (mu - b[1]) - a[0]**2 - a[1]**2) / (a[0] * a[1])
    return lax_ok and is_zero((mu * sp.eye(2) - L).det() - a[0] * a[1] * (Delta - z - 1 / z))


def main():
    checks = {
        'NLS, focusing sign': nls(1),
        'NLS, defocusing sign': nls(-1),
        'sine-Gordon, light-cone pair and coordinate change': sine_gordon(),
        'KP-II, heat-type operator (s = +1)': kp(1),
        'KP-I, nonstationary Schrodinger operator (s = -1)': kp(-1),
        'periodic Toda, N = 2, with the discriminant identity': periodic_toda(2),
        'periodic Toda, N = 3': periodic_toda(3),
        'periodic Toda, N = 4': periodic_toda(4),
    }
    controls = {
        'NLS with a reversed q_x term': nls(1, broken=True),
        'sine-Gordon with reversed off-diagonal sines': sine_gordon(broken=True),
        'KP with coefficient 5 in front of u psi_x': kp(1, broken=True),
        'periodic Toda with a wrong closing sign in B': periodic_toda(3, broken=True),
    }
    for name, ok in checks.items():
        print(f"{'PASS' if ok else 'FAIL'}  {name}")
    for name, ok in controls.items():
        print(f"{'PASS' if not ok else 'FAIL'}  altered pair rejected: {name}")
    if not all(checks.values()) or any(controls.values()):
        raise SystemExit(1)
    print('All quoted Lax representations reproduce their equations; every altered pair fails.')


if __name__ == '__main__':
    main()
