# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Fit the squared energy lift and friction head to paired spring observations."""
from math import cos, exp, sin, sqrt
from random import Random

from fit import gradient, minimize
from onsager import model_loss


def exact(x, v, t, stiffness=4.0, friction=3.0):
    decay = friction / 2
    omega = sqrt(stiffness - decay**2)
    c, s = cos(omega*t), sin(omega*t)/omega
    return [exp(-decay*t) * (x*c + (v+decay*x)*s),
            exp(-decay*t) * (v*c - (stiffness*x+decay*v)*s)]


def pairs(seed, count, dt=0.001):
    rng = Random(seed)
    rows = []
    for _ in range(count):
        x, v = rng.uniform(-1, 1), rng.uniform(-1, 1)
        for t in (0., 0.25, 0.7):
            rows.append((exact(x, v, t), exact(x, v, t+dt), dt))
    return rows


def spring_model(weights):
    stiffness_root, nonlinear, friction_root = weights
    return dict(hidden=[[1, 0]], hidden_bias=[0], lift=[[nonlinear], [0]],
                lift_bias=[0, 0], skip=[[stiffness_root, 0], [0, 1]],
                matrix=[[0], [0], [0], [0]], matrix_bias=[0, -1, 0, friction_root],
                drive=[[0, 0], [0, 0]], drive_bias=[0, 0], alpha=0., beta=0.)


def train_spring(training):
    def objective(weights):
        return model_loss(spring_model(weights), training)
    return minimize(objective, [1.45, 0.25, 1.2], tol=2e-9)


def spring_loss_gradient(weights, pairs, substeps=1):
    """Return the trajectory loss and its derivatives in spring_model weight order."""
    def objective(w):
        return model_loss(spring_model(w), pairs, substeps)

    return [objective(weights), gradient(objective, list(weights))]
