# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Explicit RK, the paper's one-step objective, and a quadratic-family fit."""

from math import fsum, sqrt


def step(rhs, state, h, a, b):
    """Step an autonomous vector ODE with compact strictly lower-triangular rows."""
    state = tuple(state)
    stages = []
    for i, row in enumerate(a):
        if len(row) != i:
            raise ValueError("A row i must contain i coefficients (zero-based)")
        stage_state = tuple(
            value + h * sum(weight * slope[k] for weight, slope in zip(row, stages))
            for k, value in enumerate(state)
        )
        slope = tuple(rhs(stage_state))
        if len(slope) != len(state):
            raise ValueError("RHS and state dimensions differ")
        stages.append(slope)
    weighted_stages = tuple(zip(b, stages, strict=True))
    if not weighted_stages:
        raise ValueError("at least one stage is required")
    return tuple(value + h * sum(weight * slope[k] for weight, slope in weighted_stages)
                 for k, value in enumerate(state))


def squared_distance(left, right):
    return fsum((a - b) ** 2 for a, b in zip(left, right, strict=True))


def _sample_residuals(sample, fit_weight, order_weight, order_weights=None):
    """Weighted residuals whose squares sum to one sample's objective.

    order_weights optionally multiplies the residual of derivative k by order_weights[k-1];
    the paper's Eq. (16) is the default of all ones.
    """
    if fit_weight:
        target = sample["target"]
        scale = squared_distance(target, sample["baseline"])
        if scale == 0.0:
            raise ValueError("scaled loss needs a nonzero baseline error")
        factor = sqrt(fit_weight) / sqrt(scale)
        for exact, model in zip(target, sample["prediction"], strict=True):
            yield factor * (model - exact)
    if order_weight:
        pairs = tuple(zip(sample["target_derivatives"], sample["prediction_derivatives"], strict=True))
        weights = (1.0,) * len(pairs) if order_weights is None else tuple(order_weights)
        if len(weights) != len(pairs):
            raise ValueError("order_weights needs one weight per derivative order")
        for (exact, model), weight in zip(pairs, weights):
            factor = sqrt(order_weight * weight)
            for x, y in zip(exact, model, strict=True):
                yield factor * (y - x)


def objective(samples, fit_weight=1.0, order_weight=1.0):
    """Average Eq. (14) plus Eq. (16) from one-step states and derivatives at h=0."""
    samples = tuple(samples)
    if not samples:
        raise ValueError("objective needs at least one sample")
    return fsum(r * r for sample in samples for r in _sample_residuals(sample, fit_weight, order_weight)) / len(samples)


def fit_square(samples):
    """Fit two stages to y'=-rate*y**2 using Eq. (16) through derivative 3.

    Each (rate, initial state) supplies two linear least-squares observations.
    Enforce b1+b2=1 and solve for u=b2*a21 and v=b2*a21**2, then recover A and b.
    The finite-h loss has weight zero for this fit.
    """
    second, third = [], []
    for rate, y in samples:
        f, fp, fpp = -rate * y**2, -2 * rate * y, -2 * rate
        second.append((2 * fp * f, fp * f))
        third.append((3 * fpp * f**2, fpp * f**2 + fp**2 * f))

    def least_squares(observations):
        norm = fsum(feature**2 for feature, _ in observations)
        if norm == 0.0:
            raise ValueError("need nonzero quadratic dynamics to fit the tableau")
        return fsum(feature * target for feature, target in observations) / norm

    u, v = least_squares(second), least_squares(third)
    a21 = v / u
    b2 = u / a21
    return ((), (a21,)), (1.0 - b2, b2)
