# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Fixed-step ABM43 with classical RK4 startup and one correction."""

from math import fsum, isfinite


def _add(y, h, slope):
    return tuple(a+h*b for a,b in zip(y,slope,strict=True))


def _weighted(y, h, weights, slopes, divisor):
    return tuple(a+h*fsum(w*f for w,f in zip(weights,col,strict=True))/divisor
                 for a,col in zip(y,zip(*slopes,strict=True),strict=True))


def predict(y, h, history):
    """Use AB4 with four cached slopes, newest first."""
    return _weighted(y, h, (55,-59,37,-9), history, 24)


def step(fun, t, y, h, history):
    """Return the corrected state, its slope, and the signed Milne estimate."""
    y = tuple(y)
    history = tuple(tuple(slope) for slope in history)
    if len(history) != 4:
        raise ValueError("ABM43 needs four slopes, newest first")
    if not y or not isfinite(t) or not isfinite(h) or h == 0:
        raise ValueError("need a nonempty state and a finite nonzero step")
    prediction = predict(y, h, history)
    forward_slope = tuple(fun(t+h, prediction))
    corrected = _weighted(y, h, (9,19,-5,1), (forward_slope,*history[:3]), 24)
    slope = tuple(fun(t+h, corrected))
    estimate = tuple((p-c)*19/270 for p,c in zip(prediction,corrected,strict=True))
    if len(slope) != len(y) or not all(map(isfinite, (*corrected,*slope,*estimate))):
        raise ValueError("RHS dimension or finite state requirement violated")
    return corrected, slope, estimate


def _rk4(fun, t, y, h, k1):
    k2 = tuple(fun(t+h/2, _add(y,h/2,k1)))
    k3 = tuple(fun(t+h/2, _add(y,h/2,k2)))
    k4 = tuple(fun(t+h, _add(y,h,k3)))
    return _weighted(y,h,(1,2,2,1),(k1,k2,k3,k4),6)


def integrate(fun, t0, y0, h, n_steps):
    """Yield (t, y, estimate); estimate is None initially and during startup."""
    if n_steps < 0 or not isfinite(t0) or not isfinite(h) or h == 0:
        raise ValueError("need a finite initial time, nonzero fixed step and nonnegative step count")
    y = tuple(y0)
    yield t0,y,None
    if n_steps == 0:
        return
    history = (tuple(fun(t0,y)),)
    for n in range(n_steps):
        t = t0+n*h
        if n < 3:
            y = _rk4(fun,t,y,h,history[0])
            slope, estimate = tuple(fun(t+h,y)), None
        else:
            y, slope, estimate = step(fun,t,y,h,history)
        history = (slope,*history[:3])
        yield t0+(n+1)*h,y,estimate
