# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Verify the closed-form arXiv v3 square tableau and test transfer."""

import math
import random
import sys
from pathlib import Path

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

HEUN = ((), (1.0,)), (0.5, 0.5)
T_FINAL = 2.0


def samples(seed, count):
    rng = random.Random(seed)
    return [(rng.uniform(0.1, 0.5), rng.uniform(1.0, 3.0)) for _ in range(count)]


def mean_max_error(tasks, n_steps, tableau, rhs_at, exact, final_time=T_FINAL):
    h = final_time / n_steps
    errors = []
    for rate, y0 in tasks:
        state, max_error = (y0,), 0.0

        def rhs(y):
            return (rhs_at(rate, y[0]),)

        for n in range(1, n_steps + 1):
            state = step(rhs, state, h, *tableau)
            error = abs(state[0] - exact(rate, y0, n * h))
            if not math.isfinite(error):
                return math.inf
            max_error = max(max_error, error)
        errors.append(max_error)
    return math.fsum(errors) / len(errors)


if __name__ == "__main__":
    tableau = fit_square(samples(731, 64))
    a, b = tableau
    expected = (2.0, 0.75, 0.25)
    coeff_error = max(abs(x - y) for x, y in zip((a[1][0], *b), expected))
    assert coeff_error <= 1e-12, "fitted coefficients differ from Eq. (24)"
    print(f"PASS Eq. (24): a21={a[1][0]:.12f}, b=({b[0]:.12f}, {b[1]:.12f}) "
          f"(max difference {coeff_error:.2e})")

    held_out = samples(814, 16)
    steps = (25, 50, 100, 200, 400, 800)
    rhs_at = lambda rate, y: -rate * y**2
    exact = lambda rate, y0, t: y0 / (1 + rate * y0 * t)
    learned = [mean_max_error(held_out, n, tableau, rhs_at, exact) for n in steps]
    heun = [mean_max_error(held_out, n, HEUN, rhs_at, exact) for n in steps]
    for n, model, baseline in zip(steps, learned, heun):
        print(f"h={T_FINAL / n:.4f} learned E={model:.6e} Heun E={baseline:.6e}")
    assert all(model < baseline for model, baseline in zip(learned, heun)), "lost Fig. 4 accuracy improvement"
    model_slope = math.log2(learned[-2] / learned[-1])
    heun_slope = math.log2(heun[-2] / heun[-1])
    assert abs(model_slope - 3.0) <= 0.15, "slope differs from Fig. 4"
    assert abs(heun_slope - 2.0) <= 0.15, "Heun baseline is not second order"
    print(f"PASS Fig. 4: learned slope {model_slope:.4f}, Heun slope {heun_slope:.4f}")

    linear = [(1.3, 2.0)]
    linear_rhs = lambda rate, y: -rate * y
    linear_exact = lambda rate, y0, t: y0 * math.exp(-rate * t)
    errors = [mean_max_error(linear, n, tableau, linear_rhs, linear_exact) for n in (100, 200)]
    linear_heun = [mean_max_error(linear, n, HEUN, linear_rhs, linear_exact) for n in (100, 200)]
    transfer_slope = math.log2(errors[0] / errors[1])
    assert abs(transfer_slope - 2.0) <= 0.15, "square tableau has unexpected linear-family order"
    assert max(abs(a - b) for a, b in zip(errors, linear_heun)) <= 1e-12
    print(f"PASS shift to linear decay: slope {transfer_slope:.4f}, same errors as Heun within 1e-12")

    sine = [(1.0, 1.0)]
    sine_rhs = lambda rate, y: math.sin(y)
    sine_exact = lambda rate, y0, t: 2 * math.atan(math.exp(t) * math.tan(y0 / 2))
    ratios = []
    for n in (50, 100, 200, 400):
        model = mean_max_error(sine, n, tableau, sine_rhs, sine_exact, final_time=1.0)
        baseline = mean_max_error(sine, n, HEUN, sine_rhs, sine_exact, final_time=1.0)
        ratios.append(model / baseline)
    assert min(ratios) > 3.0, "expected higher error than Heun on y'=sin(y)"
    print("PASS nonlinear shift y'=sin(y): learned/Heun error ratios " + ", ".join(f"{r:.3f}" for r in ratios))
