# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Three-stage Radau IIA with coupled Newton, dense cubic and step doubling."""

from bisect import bisect_left
from math import fsum, isfinite, sqrt, ulp

s = sqrt(6)
C = ((4-s)/10, (4+s)/10, 1.0)
A = (
    ((88-7*s)/360, (296-169*s)/1800, (-2+3*s)/225),
    ((296+169*s)/1800, (88+7*s)/360, (-2-3*s)/225),
    ((16-s)/36, (16+s)/36, 1/9),
)


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, error_weights):
    """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
    if error_weights is None:
        correction_rtol, correction_atol = tol, 0.0
    else:
        rtol, atol = error_weights
        correction_rtol, correction_atol = 0.01*rtol, 0.01*atol
    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(correction_atol+correction_rtol*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):
    """Return the endpoint state and dense(theta) for theta in [0, 1]."""
    return _step(fun, jac, t, y, h, tol=tol, max_iter=max_iter)


def _step(fun, jac, t, y, h, *, tol=2e-14, max_iter=12, error_weights=None):
    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")
    stages = _stages(fun, jac, t, y, h, C, A, tol, max_iter, error_weights)
    points = (y, *stages)
    nodes = (0.0, *C)

    def dense(theta):
        if not 0 <= theta <= 1:
            raise ValueError("dense output is confined to the step")
        weights = []
        for i, node in enumerate(nodes):
            weight = 1.0
            for j, other in enumerate(nodes):
                if i != j:
                    weight *= (theta-other)/(node-other)
            weights.append(weight)
        return tuple(fsum(w*point[k] for w, point in zip(weights, points))
                     for k in range(len(y)))

    return stages[-1], dense


def _dense_error(full, left, right, split, rtol, atol):
    """Compare the trial cubics at the split and twice inside each half."""
    samples = (
        (split/3, left(1/3)),
        (2*split/3, left(2/3)),
        (split, left(1)),
        (split + (1-split)/3, right(1/3)),
        (split + 2*(1-split)/3, right(2/3)),
    )
    return max(
        abs(a-b)/(atol+rtol*max(abs(a), abs(b)))
        for theta, fine in samples
        for a, b in zip(full(theta), fine, strict=True)
    )


def solve(fun, jac, t0, y0, t_end, *, h0, rtol=1e-7, atol=1e-10, max_trials=10000):
    """Integrate forward. Return (y_end, evaluate(time), accepted, rejected)."""
    if not all(map(isfinite, (t0, t_end, h0, rtol, atol))) or (
            not t0 < t_end or min(h0, rtol, atol) <= 0 or max_trials < 1):
        raise ValueError("need a forward interval and positive adaptive controls")
    y, t, h = tuple(y0), t0, h0
    error_weights = (rtol, atol)
    ends, segments = [], []
    rejected = 0
    for _ in range(max_trials):
        right = min(t+h, t_end)
        middle = t + (right-t)/2
        if not t < middle < right:
            raise RuntimeError("step too small to advance")
        try:
            full, dense_full = _step(fun, jac, t, y, right-t, error_weights=error_weights)
            half, dense0 = _step(fun, jac, t, y, middle-t, error_weights=error_weights)
            refined, dense1 = _step(fun, jac, middle, half, right-middle, error_weights=error_weights)
        except RuntimeError:
            rejected += 1
            h = (right-t)/2
            continue
        endpoint_error = max(abs(a-b)/(31*(atol+rtol*max(abs(x), abs(a))))
                             for x, a, b in zip(y, refined, full, strict=True))
        interior_error = _dense_error(dense_full, dense0, dense1, (middle-t)/(right-t), rtol, atol)
        # The smooth local errors scale as h**6 at the endpoint and h**4 inside.
        relative_step = max(endpoint_error**(1/6), interior_error**(1/4))
        factor = min(4, max(0.2, 0.9/relative_step)) if relative_step else 4
        h = (right-t)*factor
        if relative_step > 1:
            rejected += 1
            continue
        ends.extend((middle, right))
        segments.extend(((t, middle, dense0), (middle, right, dense1)))
        t, y = right, refined
        if t == t_end:
            break
    else:
        raise RuntimeError("adaptive trial limit reached")

    def evaluate(time):
        if not t0 <= time <= t_end:
            raise ValueError("output time outside the solved interval")
        left, right, polynomial = segments[bisect_left(ends, time)]
        return polynomial((time-left)/(right-left))

    return y, evaluate, len(ends)//2, rejected
