# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Use fixed-step BDF2 with a single backward Euler startup step."""

from math import fsum, isfinite, ulp


def _solve(matrix, rhs):
    """Small dense linear solve with partial pivoting."""
    n = len(rhs)
    rows = [list(row) + [r] for row, r in zip(matrix, rhs, strict=True)]
    for j in range(n):
        pivot = max(range(j, n), key=lambda i: abs(rows[i][j]))
        rows[j], rows[pivot] = rows[pivot], rows[j]
        if not isfinite(rows[j][j]) or rows[j][j] == 0:
            raise RuntimeError("singular Newton matrix")
        for row in rows[j+1:]:
            scale = row[j] / rows[j][j]
            for k in range(j+1, n+1):
                row[k] -= scale*rows[j][k]
    for i in reversed(range(n)):
        rhs[i] = (rows[i][-1] - fsum(rows[i][j]*rhs[j] for j in range(i+1, n))) / rows[i][i]
    return rhs


def _endpoint(fun, jac, time, base, coefficient, guess, tol, max_iter):
    initial = tuple(guess)
    state = initial
    if not state or not all(map(isfinite, (time, coefficient, tol, *base, *state))):
        raise ValueError("need a finite, nonempty problem")
    if coefficient == 0 or tol <= 0 or max_iter < 1:
        raise ValueError("need nonzero step, positive tolerance and at least one Newton update")
    for _ in range(max_iter):
        residual = [y-a-coefficient*f for y, a, f in zip(state, base, fun(time, state), strict=True)]
        if not all(map(isfinite, residual)):
            raise RuntimeError("nonfinite Newton residual")
        jacobian = tuple(tuple(row) for row in jac(time, state))
        if len(jacobian) != len(state) or any(len(row) != len(state) for row in jacobian):
            raise ValueError("Jacobian size does not match the state")
        matrix = [[float(i == j) - coefficient*df for j, df in enumerate(row)]
                  for i, row in enumerate(jacobian)]
        correction = _solve(matrix, residual)
        updated = tuple(y-d for y, d in zip(state, correction, strict=True))
        if not all(map(isfinite, updated)):
            raise RuntimeError("nonfinite Newton iterate")
        scales = (max(abs(start), abs(old), abs(new))
                  for start, old, new in zip(initial, state, updated, strict=True))
        if all(abs(delta) <= max(tol*scale, 4*ulp(scale))
               for delta, scale in zip(correction, scales, strict=True)):
            return updated
        state = updated
    raise RuntimeError("Newton correction did not converge")


def start(fun, jac, t, y, h, *, tol=1e-13, max_iter=20):
    """Obtain y(t+h) by a backward Euler step."""
    y = tuple(y)
    return _endpoint(fun, jac, t+h, y, h, y, tol, max_iter)


def step(fun, jac, t, previous, current, h, *, tol=1e-13, max_iter=20):
    """Advance from adjacent states at t-h and t to t+h."""
    current = tuple(current)
    base = tuple(y + (y-old)/3 for old, y in zip(previous, current, strict=True))
    return _endpoint(fun, jac, t+h, base, 2*h/3, current, tol, max_iter)


def integrate(fun, jac, t0, y0, h, n_steps, **solve_options):
    """Yield (time, state) on one fixed grid, including the initial state."""
    if n_steps < 0:
        raise ValueError("need a nonnegative number of steps")
    previous = tuple(y0)
    yield t0, previous
    if n_steps == 0:
        return
    current = start(fun, jac, t0, previous, h, **solve_options)
    yield t0+h, current
    for n in range(1, n_steps):
        previous, current = current, step(fun, jac, t0+n*h, previous, current, h, **solve_options)
        yield t0+(n+1)*h, current
