# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Fit once and compare two-stage methods on new quadratic IVPs."""

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "reference"))
from learned_rk import step
from train_rk import train


def square_rhs(rate):
    def rhs(y):
        return (-rate * y[0] ** 2,)

    return rhs


def endpoint(rate, y0, h, n_steps, a, b):
    rhs = square_rhs(rate)
    state = (y0,)
    for _ in range(n_steps):
        state = step(rhs, state, h, a, b)
    return state[0]


if __name__ == "__main__":
    training = [dict(rhs=square_rhs(rate), state=(y0,))
                for rate in (0.15, 0.30, 0.45) for y0 in (1.2, 2.0, 2.8)]
    a, b, loss = train(training, ((), (0.8,)), (0.0, 0.0), order=3, fit_weight=0.0)
    print(f"Fitted a21={a[1][0]:.6f}, b=({b[0]:.6f}, {b[1]:.6f})")
    print(f"Taylor objective below 1e-16: {loss < 1e-16}")

    h, n_steps = 0.05, 40
    for rate, y0 in ((0.20, 1.5), (0.40, 2.5)):
        exact = y0 / (1 + rate * y0 * h * n_steps)
        learned = endpoint(rate, y0, h, n_steps, a, b)
        heun = endpoint(rate, y0, h, n_steps, ((), (1.0,)), (0.5, 0.5))
        print(f"rate={rate:.2f}, y0={y0:.1f}: learned error={abs(learned - exact):.3e}, "
              f"Heun error={abs(heun - exact):.3e}")
