"""Check the Painlevé-II similarity reduction using ordinary Python 3.

Run: python3 mkdv_similarity_clock.py
"""
from fractions import Fraction
from math import log2


def rk4_error(steps):
    """Maximum mesh-point error in w on [1, 2] for alpha=1."""
    h = 1.0 / steps
    w, velocity = -1.0, 1.0
    error = 0.0

    def acceleration(z, value):
        return 2 * value**3 + z * value + 1

    for j in range(steps):
        z = 1 + j * h
        k1, a1 = velocity, acceleration(z, w)
        k2 = velocity + h * a1 / 2
        a2 = acceleration(z + h / 2, w + h * k1 / 2)
        k3 = velocity + h * a2 / 2
        a3 = acceleration(z + h / 2, w + h * k2 / 2)
        k4 = velocity + h * a3
        a4 = acceleration(z + h, w + h * k3)
        w += h * (k1 + 2*k2 + 2*k3 + k4) / 6
        velocity += h * (a1 + 2*a2 + 2*a3 + a4) / 6
        error = max(error, abs(w + 1 / (z + h)))
    return error


def quotient_series(numerator, denominator, degree):
    """Taylor coefficients obtained by multiplying back by the denominator."""
    result = []
    for k in range(degree + 1):
        known = sum(denominator[j] * result[k-j]
                    for j in range(1, min(k, len(denominator)-1) + 1))
        value = numerator[k] if k < len(numerator) else 0
        result.append(Fraction(value - known, denominator[0]))
    return result


def field_terms(clock, x=1, t=Fraction(1, 3)):
    """Return (u_t, -6 u² u_x, u_xxx) via exact Taylor division in x."""
    denominator = [x**3 + clock * t, 3*x*x, 3*x, 1]
    reciprocal = quotient_series([1], [x, 1], 3)
    pulse = quotient_series([3*x*x, 6*x, 3], denominator, 3)
    u, ux, _, cubic = [a - b for a, b in zip(reciprocal, pulse)]
    ut = 3 * clock * x*x / denominator[0]**2
    return ut, -6 * u*u * ux, 6 * cubic


if __name__ == "__main__":
    previous = None
    for steps in (10, 20, 40, 80):
        error = rk4_error(steps)
        rate = "" if previous is None else f", observed order {log2(previous/error):.3f}"
        print(f"RK4, {steps:2d} steps: max profile error {error:.6e}{rate}")
        previous = error
    assert error < 1e-8
    for clock in (12, 4):
        terms = field_terms(clock)
        print(f"Clock {clock}: PDE terms", *map(str, terms), "sum", sum(terms))
    assert sum(field_terms(12)) == 0
    assert sum(field_terms(4)) == Fraction(-216, 49)
