# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Small autonomous RK trainer for right-hand sides that accept Taylor series."""

import math
import warnings

from learned_rk import _sample_residuals, step
from taylor_series import Series, coefficients

# Highest classical order an explicit RK method with s stages can have (Butcher's barriers).
# A higher target is reachable only through special structure of the family.
GENERIC_ORDER = {1: 1, 2: 2, 3: 3, 4: 4, 5: 4, 6: 5, 7: 6, 8: 6, 9: 7, 10: 7, 11: 8}
MAX_ITERS = 2000
GRADIENT_TOL = 1e-8  # (projected) gradient relative to the loss
STALL_TOL = 1e-4  # accepted when no step helps: limit of the finite-difference gradient


def _derivatives(series, order):
    vectors = [coefficients(value, order + 1) for value in series]
    return tuple(tuple(math.factorial(k) * c[k] for c in vectors) for k in range(1, order + 1))


def rk_derivatives(rhs, state, a, b, order):
    """Return the h derivatives of the given tableau's step, of orders 1 through order."""
    h = Series((0.0, 1.0) + (0.0,) * (order - 1))
    return _derivatives(step(rhs, state, h, a, b), order)


def _flow_series(rhs, state, order):
    """Use [h^(k+1)] y = [h^k] f(y)/(k+1) to expand the exact local flow."""
    series = [Series((value,) + (0.0,) * order) for value in state]
    for k in range(order):
        slopes = rhs(tuple(series))
        series = [Series(y.coefficients[:k + 1] + (coefficients(f, order + 1)[k] / (k + 1),)
                         + (0.0,) * (order - k - 1)) for y, f in zip(series, slopes, strict=True)]
    return series


def flow_derivatives(rhs, state, order):
    """Return the exact local flow's h derivatives, of orders 1 through order."""
    return _derivatives(_flow_series(rhs, state, order), order)


def order_residuals(samples, a, b, order):
    """Scale-free derivative residual of each order 1..order on the given tasks.

    Entry k-1 is the mean over samples of ||D_k(exact) - D_k(RK)||^2 / ||D_k(exact)||^2,
    so it does not depend on the units of the states at ordinary magnitudes. A value near
    1e-30 means the tableau matches order k on these tasks to rounding.
    """
    totals = [0.0] * order
    for sample in samples:
        exact = flow_derivatives(sample["rhs"], sample["state"], order)
        model = rk_derivatives(sample["rhs"], sample["state"], a, b, order)
        for k, (x, y) in enumerate(zip(exact, model, strict=True)):
            error = math.fsum((p - q) ** 2 for p, q in zip(x, y, strict=True))
            size = math.fsum(p * p for p in x)
            value = error / size if size > 0.0 else (0.0 if error == 0.0 else math.inf)
            totals[k] += value if math.isfinite(value) else math.inf  # NaN counts as a mismatch
    return [total / len(samples) for total in totals]


def _softmax(logits):
    shift = max(logits)
    unnormalized = [math.exp(x - shift) for x in logits]
    total = math.fsum(unnormalized)
    return tuple(weight / total for weight in unnormalized)


def _dot(left, right):
    return math.fsum(x * y for x, y in zip(left, right, strict=True))


def _solve_positive_definite(matrix, rhs):
    """Solve with a Cholesky factorization of the small damped normal matrix."""
    lower = []
    forward = []
    for i, row in enumerate(matrix):
        entries = []
        for j in range(i):
            entries.append((row[j] - _dot(entries, lower[j][:j])) / lower[j][j])
        diagonal = math.sqrt(row[i] - _dot(entries, entries))
        lower.append(entries + [diagonal])
        forward.append((rhs[i] - _dot(entries, forward)) / diagonal)
    answer = [0.0] * len(rhs)
    for i in reversed(range(len(rhs))):
        tail = math.fsum(lower[j][i] * answer[j] for j in range(i + 1, len(rhs)))
        answer[i] = (forward[i] - tail) / lower[i][i]
    return answer


def _solve(matrix, rhs):
    """Solve a small dense linear system by Gaussian elimination with partial pivoting."""
    n = len(rhs)
    rows = [list(row) + [value] for row, value in zip(matrix, rhs, strict=True)]
    for col in range(n):
        pivot = max(range(col, n), key=lambda i: abs(rows[i][col]))
        if rows[pivot][col] == 0.0:
            raise ZeroDivisionError("singular system")
        rows[col], rows[pivot] = rows[pivot], rows[col]
        for i in range(col + 1, n):
            factor = rows[i][col] / rows[col][col]
            if factor:
                rows[i] = [x - factor * y for x, y in zip(rows[i], rows[col], strict=True)]
    answer = [0.0] * n
    for i in reversed(range(n)):
        answer[i] = (rows[i][-1] - math.fsum(rows[i][j] * answer[j] for j in range(i + 1, n))) / rows[i][i]
    return answer


def classical_order_conditions(a, b, order):
    """Residuals of the classical order conditions of orders 2 through order (at most 4).

    These hold for every smooth ODE, with c = A 1: b.c = 1/2; b.c^2 = 1/3, b.Ac = 1/6;
    b.c^3 = 1/4, b.(c*Ac) = 1/8, b.Ac^2 = 1/12, b.AAc = 1/24. Order 1 (sum b = 1)
    always holds through the softmax.
    """
    if not 2 <= order <= 4:
        raise ValueError("classical conditions are provided for orders 2 to 4")
    s = len(b)
    full = [[a[i][j] if j < i else 0.0 for j in range(s)] for i in range(s)]
    c = [math.fsum(row) for row in full]

    def times_a(vector):
        return [math.fsum(row[j] * vector[j] for j in range(s)) for row in full]

    def with_b(vector):
        return _dot(b, vector)

    out = [with_b(c) - 1 / 2]
    if order >= 3:
        c2, ac = [x * x for x in c], times_a(c)
        out += [with_b(c2) - 1 / 3, with_b(ac) - 1 / 6]
    if order >= 4:
        out += [with_b([x**3 for x in c]) - 1 / 4, with_b([x * y for x, y in zip(c, ac)]) - 1 / 8,
                with_b(times_a(c2)) - 1 / 12, with_b(times_a(ac)) - 1 / 24]
    return out


def _jacobian(function, values):
    columns = []
    for j, value in enumerate(values):
        delta = 1e-6 * max(1.0, abs(value))
        plus, minus = list(values), list(values)
        plus[j], minus[j] = value + delta, value - delta
        columns.append([(u - v) / (2 * delta) for u, v in zip(function(plus), function(minus), strict=True)])
    return columns  # one column per parameter


def _null_space(rows, n):
    """Orthonormal basis of the vectors orthogonal to rows (the tangent space)."""
    basis = []
    for row in rows:
        v = list(row)
        for q in basis:
            v = [x - _dot(q, v) * y for x, y in zip(v, q)]
        norm = math.sqrt(_dot(v, v))
        if norm > 1e-12:
            basis.append([x / norm for x in v])
    normal, tangent = len(basis), []
    for i in range(n):
        v = [1.0 if j == i else 0.0 for j in range(n)]
        for q in basis:
            v = [x - _dot(q, v) * y for x, y in zip(v, q)]
        norm = math.sqrt(_dot(v, v))
        if norm > 1e-8:
            q = [x / norm for x in v]
            basis.append(q)
            tangent.append(q)
        if len(basis) == n:
            break
    return tangent if normal + len(tangent) == n else tangent


def _tangent(vector, rows):
    """Component of vector orthogonal to the constraint gradients (rows)."""
    gram = [[_dot(u, v) for v in rows] for u in rows]
    try:
        weights = _solve(gram, [_dot(row, vector) for row in rows])
    except ZeroDivisionError:
        return vector
    return [x - math.fsum(w * row[j] for w, row in zip(weights, rows)) for j, x in enumerate(vector)]


def _project(constraints, values, max_steps=50):
    """Newton steps onto constraints(values) = 0, continued to floating-point accuracy.

    Stopping early would leave a small normal displacement, and the loss can be very
    sensitive to it. Returns None if the steps fail or leave finite numbers."""
    values = list(values)
    best, best_size = None, math.inf
    try:
        for _ in range(max_steps):
            g = constraints(values)
            if not all(map(math.isfinite, g)):
                return None
            size = max(map(abs, g))
            if size < best_size:
                best, best_size = list(values), size
            elif size <= 1e-13:  # no further progress at rounding level
                break
            if size == 0.0:
                break
            rows = list(zip(*_jacobian(constraints, values)))  # constraint gradients
            gram = [[_dot(u, v) for v in rows] for u in rows]
            multipliers = _solve(gram, [-x for x in g])
            values = [x + math.fsum(m * row[j] for m, row in zip(multipliers, rows))
                      for j, x in enumerate(values)]
            if not all(map(math.isfinite, values)):
                return None
    except (ZeroDivisionError, OverflowError, ValueError):
        return None
    return best if best_size <= 1e-12 else None


def train(samples, a0, logits0, order, fit_weight=1.0, order_weight=1.0, max_iters=None, *,
          order_weights=None, keep_order=None):
    """Fit one tableau to raw tasks with deterministic damped Gauss–Newton.

    Each sample has rhs and state, and for an active finite-h loss also h, target
    and baseline. Derive the order targets from rhs. Return (A, b, mean loss).
    max_iters=0 evaluates the initial tableau. max_iters=None iterates until the
    (projected) gradient is small relative to the loss, up to MAX_ITERS. If it uses all
    iterations, or no step lowers the loss while the gradient is not yet small, it warns
    that the fit did not converge. The paper's scaled loss can be too badly conditioned
    for the finite-difference Jacobian; then try other starting tableaus.

    keep_order=q (2 to 4) holds the classical order conditions up to order q exactly,
    to rounding, during the whole fit, optimising along that set (an addition to the
    paper's method). Use it whenever the tableau must keep order q at steps smaller
    than those trained on: a finite-step term, or a target order beyond what the stage
    count can reach, otherwise trades exact order for accuracy at the training steps.
    Results depend on the starting tableau; try several. order_weights (one per
    derivative order, default all ones as in Eq. (16)) only weights the penalty.

    After training, a heuristic RuntimeWarning reports derivative orders up to
    min(order, reachable order) (the reachable order if the Taylor term is off) that the
    fitted tableau matches only approximately on the training tasks. Keep the states at
    ordinary magnitudes (nondimensionalise them), and check the convergence slope at
    small steps in any case.
    """
    stages = len(logits0)
    if not logits0 or tuple(map(len, a0)) != tuple(range(stages)):
        raise ValueError("initial rows must have lengths 0, 1, ..., s-1 with s logits")
    if order < 1 or min(fit_weight, order_weight) < 0 or fit_weight + order_weight <= 0:
        raise ValueError("use positive derivative order and nonnegative weights with an active term")
    budget = MAX_ITERS if max_iters is None else max_iters
    if budget < 0:
        raise ValueError("iteration budget cannot be negative")
    if order_weights is not None and (len(order_weights) != order or min(order_weights) < 0):
        raise ValueError("order_weights needs one nonnegative weight per derivative order")
    reach = GENERIC_ORDER.get(stages, order)
    keep_limit = min(4, reach, order) if order_weight else min(4, reach)
    if keep_order is not None and not (2 <= keep_order <= keep_limit):
        raise ValueError(f"keep_order must be between 2 and {keep_limit} for {stages} stages"
                         + (f" and order {order}" if order_weight else ""))
    prepared = [dict(sample) for sample in samples]
    if not prepared:
        raise ValueError("need at least one training task")
    if order_weight:
        for sample in prepared:
            sample["target_derivatives"] = flow_derivatives(sample["rhs"], sample["state"], order)

    row_starts = [i * (i - 1) // 2 for i in range(stages + 1)]
    offset = row_starts[-1]
    # Fix the final logit at zero since a common shift leaves the softmax unchanged.
    parameters = [x for row in a0 for x in row] + [z - logits0[-1] for z in logits0[:-1]]

    def unpack(values):
        a = tuple(tuple(values[i:j]) for i, j in zip(row_starts, row_starts[1:]))
        return a, _softmax([*values[offset:], 0.0])

    def residuals(values):
        a, b = unpack(values)
        errors = []
        for sample in prepared:
            rhs, state = sample["rhs"], sample["state"]
            if fit_weight:
                sample["prediction"] = step(rhs, state, sample["h"], a, b)
            if order_weight:
                sample["prediction_derivatives"] = rk_derivatives(rhs, state, a, b, order)
            errors.extend(_sample_residuals(sample, fit_weight, order_weight, order_weights))
        return errors

    def trial_residuals(values):
        try:
            errors = residuals(values)
        except (OverflowError, ValueError, ZeroDivisionError):
            return None, math.inf
        loss = _dot(errors, errors)
        return (errors, loss) if math.isfinite(loss) else (None, math.inf)

    constraints = None
    if keep_order:
        def constraints(values):
            return classical_order_conditions(*unpack(values), keep_order)

        projected = _project(constraints, parameters)
        if projected is None:
            raise ValueError(f"could not move the starting tableau onto the order-{keep_order} conditions; "
                             f"start from a classical tableau of order {keep_order}")
        parameters = projected

    errors = residuals(parameters)
    loss = _dot(errors, errors)
    if not math.isfinite(loss):
        raise ValueError("initial loss must be finite")
    # Levenberg–Marquardt with per-parameter (Marquardt) damping. The fit counts as converged
    # only when the gradient, projected onto the order-condition set under keep_order, is
    # small relative to the loss; a small step alone is not convergence. If no step lowers
    # the loss even with heavy damping, the fit stops and warns.
    initial = max(loss, 1e-300)
    damping, converged, stalled = 1e-3, budget == 0, False
    for _ in range(budget):
        if constraints is None:
            columns = _jacobian(residuals, parameters)
        else:
            # Work in an orthonormal basis of the tangent space of the order conditions, with
            # derivatives taken along the set itself (perturb, project back, difference): the
            # loss is often far more sensitive across the set than along it.
            tangent = _null_space(list(zip(*_jacobian(constraints, parameters))), len(parameters))
            columns = []
            delta = 1e-6 * max(1.0, *map(abs, parameters))
            for t in tangent:
                ends = [_project(constraints, [p + sign * delta * x for p, x in zip(parameters, t)])
                        for sign in (1.0, -1.0)]
                ends = [e if e is not None else [p + sign * delta * x for p, x in zip(parameters, t)]
                        for e, sign in zip(ends, (1.0, -1.0))]
                plus, minus = residuals(ends[0]), residuals(ends[1])
                columns.append([(u - v) / (2 * delta) for u, v in zip(plus, minus, strict=True)])
        gradient = [_dot(column, errors) for column in columns]
        if max(map(abs, gradient), default=0.0) <= GRADIENT_TOL * loss or loss <= 1e-28 * initial:
            converged = True
            break
        # Marquardt damping with a floor, so that flat directions (the optimum is often a
        # valley along the order-condition set) are damped as well.
        diagonal = [_dot(u, u) for u in columns]
        floor = 1e-12 * max(max(diagonal, default=0.0), 1e-300)
        normal = [[_dot(u, v) + (damping * max(diagonal[i], floor) if i == j else 0.0)
                   for j, v in enumerate(columns)] for i, u in enumerate(columns)]
        try:
            update = _solve_positive_definite(normal, [-g for g in gradient])
        except (ValueError, ZeroDivisionError):
            update = None
        trial = None
        if update is not None and all(map(math.isfinite, update)):
            if constraints is not None:  # back to coefficient space
                update = [math.fsum(u * t[j] for u, t in zip(update, tangent)) for j in range(len(parameters))]
            size, largest = max(1.0, *map(abs, parameters)), max(map(abs, update), default=0.0)
            if largest > size:  # keep each step within the scale of the coefficients
                update = [d * size / largest for d in update]
            trial = [p + d for p, d in zip(parameters, update, strict=True)]
            if constraints is not None:
                trial = _project(constraints, trial)
        trial_errors, trial_loss = trial_residuals(trial) if trial is not None else (None, math.inf)
        if trial_loss < loss:
            parameters, errors, loss = trial, trial_errors, trial_loss
            damping = max(damping / 3.0, 1e-12)
        else:
            damping *= 10.0
            if damping > 1e12:
                # No step lowers the loss. That is convergence to the accuracy of the
                # finite-difference gradient if the gradient is already small.
                converged = max(map(abs, gradient), default=0.0) <= STALL_TOL * loss
                stalled = not converged
                break
    a, b = unpack(parameters)
    if not converged:
        reason = ("no step lowered the loss any further" if stalled
                  else f"it used all {budget} iterations")
        warnings.warn(f"training stopped without converging ({reason}); the tableau and the numbers "
                      "derived from it are not final. Try other starting tableaus or raise max_iters.",
                      RuntimeWarning, stacklevel=2)
    _warn_on_unmatched_orders(prepared, (a, b), min(order, reach) if order_weight else reach, reach)
    return a, b, loss / len(prepared)


def _warn_on_unmatched_orders(samples, tableau, checked, reach, lost=1e-16):
    """Warn about orders 1..checked that the fitted tableau does not match on the tasks.

    A heuristic: order_residuals above 1e-16 (a relative derivative error above 1e-8, well
    beyond what the optimizer leaves in an exact fit). It does not replace checking the
    convergence slope at small steps.
    """
    if checked < 2:
        return
    after = order_residuals(samples, *tableau, checked)
    dropped = [k for k in range(1, checked + 1) if after[k - 1] > lost]
    if dropped:
        stages = len(tableau[1])
        warnings.warn(
            f"the fitted tableau matches derivative order(s) {dropped} on the training tasks only "
            f"approximately, although {stages} explicit stages can match order {reach} on any ODE. "
            f"Its convergence order then drops at steps smaller than those trained on, and it can be "
            f"far less accurate there than a classical tableau with the same stages. Use keep_order to "
            f"hold the orders you need exactly, and compare held-out rollouts with a classical tableau "
            f"of the same stage count, including smaller steps.", RuntimeWarning, stacklevel=3)
