# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Implicit trapezoid on the time variable of an ordinary differential equation."""

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 step(fun, jac, t, y, h, *, tol=1e-13, max_iter=20):
    """Advance one signed step with the average of the old and new slopes."""
    y = tuple(y)
    if not y or not all(map(isfinite, (*y, t, h, tol))) or tol <= 0 or max_iter < 1:
        raise ValueError("need finite input and positive Newton controls")
    if h == 0:
        return y
    base = tuple(a+h*f/2 for a,f in zip(y,fun(t,y),strict=True))
    return _endpoint(fun,jac,t+h,base,h/2,y,tol,max_iter)
