# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Three-stage third-order strong-stability-preserving Runge–Kutta."""

from math import isfinite


def _euler(fun, t, y, h):
    result = tuple(a+h*b for a,b in zip(y,fun(t,y),strict=True))
    if not all(map(isfinite,result)):
        raise RuntimeError("nonfinite Euler substep")
    return result


def step(fun, t, y, h):
    """Advance one nonnegative step; the caller supplies a suitable CFL bound."""
    y = tuple(y)
    if not y or not all(map(isfinite,(t,h,*y))) or h < 0:
        raise ValueError("need finite nonempty state, finite time and nonnegative step")
    if h == 0:
        return y
    first = _euler(fun,t,y,h)
    second_fe = _euler(fun,t+h,first,h)
    second = tuple(0.75*a+0.25*b for a,b in zip(y,second_fe,strict=True))
    third_fe = _euler(fun,t+h/2,second,h)
    return tuple(a/3+(2/3)*b for a,b in zip(y,third_fe,strict=True))
