# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Two-stage Gauss–Legendre collocation with coupled Newton."""

from math import fsum, isfinite, sqrt, ulp

d = sqrt(3)/6
C = (0.5-d, 0.5+d)
A = ((0.25, 0.25-d), (0.25+d, 0.25))


def linear_solve(matrix, rhs):
    rows = [list(row) + [r] for row, r in zip(matrix, rhs, strict=True)]
    n = len(rows)
    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 rows[j][j] == 0 or not isfinite(rows[j][j]):
            raise RuntimeError("singular stage 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 _stages(fun, jac, t, y, h, c, a, tol, max_iter):
    """Solve collocation stages, with stage-major ordering for block Newton."""
    n, m = len(y), len(c)
    times = [t+ci*h for ci in c]
    stages = [y]*m
    for _ in range(max_iter):
        slopes = [tuple(fun(ti, yi)) for ti, yi in zip(times, stages)]
        js = [tuple(tuple(row) for row in jac(ti, yi)) for ti, yi in zip(times, stages)]
        if any(len(f) != n for f in slopes) or any(
                len(j) != n or any(len(row) != n for row in j) for j in js):
            raise ValueError("RHS and Jacobian must match the state dimension")
        residual = [stages[i][k]-y[k]-h*fsum(a[i][j]*slopes[j][k] for j in range(m))
                    for i in range(m) for k in range(n)]
        if not all(map(isfinite, residual)):
            raise RuntimeError("nonfinite stage residual")
        matrix = [
            [float(i == j and k == ell) - h*a[i][j]*js[j][k][ell]
             for j in range(m) for ell in range(n)]
            for i in range(m) for k in range(n)
        ]
        delta = linear_solve(matrix, residual)
        updated = [tuple(stages[i][k]-delta[i*n+k] for k in range(n)) for i in range(m)]
        if not all(isfinite(x) for stage in updated for x in stage):
            raise RuntimeError("nonfinite Newton iterate")
        scales = (max(abs(start), abs(old), abs(new))
                  for before, after in zip(stages, updated, strict=True)
                  for start, old, new in zip(y, before, after, strict=True))
        if all(abs(change) <= max(tol*scale, 4*ulp(scale))
               for change, scale in zip(delta, scales, strict=True)):
            return updated
        stages = updated
    raise RuntimeError("stage Newton iteration did not converge")


def step(fun, jac, t, y, h, *, tol=2e-14, max_iter=12):
    """Advance one signed fixed step using two Gauss collocation stages."""
    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 state, time and step, with positive Newton controls")
    if h == 0:
        return y
    stages = _stages(fun, jac, t, y, h, C, A, tol, max_iter)
    f1, f2 = (fun(t+c*h, stage) for c, stage in zip(C, stages, strict=True))
    endpoint = tuple(x+h*(a+b)/2 for x, a, b in zip(y, f1, f2, strict=True))
    if not all(map(isfinite, endpoint)):
        raise RuntimeError("nonfinite endpoint")
    return endpoint
