"""Verify the exact Sawada–Kotera and Kaup–Kupershmidt solitary waves.

Run with Python 3 and SymPy. The model convention has coefficients 5 and 5
in front of u*u_xxx and u**2*u_x, respectively. The mixed term is the
coefficient under test. No spatial grids or floating-point tolerances enter.
"""

import sympy as sp


def travelling_residual(field, exponential, mixed_coefficient):
    """Evaluate the unit-scale PDE at s = exp(x-t) with exact arithmetic."""
    derivatives = [field]
    for _ in range(5):
        derivatives.append(sp.factor(exponential * sp.diff(derivatives[-1], exponential)))
    _, first, second, third, _, fifth = derivatives
    return sp.factor(
        -first + fifth + 5 * field * third
        + mixed_coefficient * first * second + 5 * field**2 * first
    )


def main():
    exponential = sp.Symbol("s", positive=True)
    sk_tau = 1 + exponential
    kk_tau = 1 + exponential + exponential**2 / 16

    def log_curvature(tau):
        slope = exponential * sp.diff(sp.log(tau), exponential)
        return sp.factor(exponential * sp.diff(slope, exponential))

    sk = 6 * log_curvature(sk_tau)
    kk = 3 * log_curvature(kk_tau)
    assert travelling_residual(sk, exponential, 5) == 0
    assert travelling_residual(kk, exponential, sp.Rational(25, 2)) == 0
    mismatch = travelling_residual(sk, exponential, sp.Rational(25, 2))
    assert mismatch.subs(exponential, 2) == sp.Rational(40, 27)
    assert kk.subs(exponential, 1) == sp.Rational(112, 121)
    assert kk.subs(exponential, 2) == sp.Rational(168, 169)
    assert sp.factor(kk.subs(exponential, 16 / exponential) - kk) == 0
    print("Both solitary waves have identically zero residual in their own equations.")
    print("Sawada–Kotera pulse in the Kaup–Kupershmidt equation at s=2:", mismatch.subs(exponential, 2))
    print("Kaup–Kupershmidt pulse at s=1 and s=2:", kk.subs(exponential, 1), kk.subs(exponential, 2))


if __name__ == "__main__":
    main()
