# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Jointly learn a nonlinear closure correction, a decoder residual, drift and noise.

The observed q and hidden h evolve as a rotating linear diffusion. Instruments record
(q, h - 0.4*tanh(q), h/4). Start the closure with a calibrated projection on channel 2.
The four balanced innovations per start exactly match the first two normal moments.
"""
from math import exp, sqrt, tanh
from random import Random
from fit import minimize
from stochastic import coordinates, drift, joint_loss, reconstruct


def micro(q,h):
    return [q, h-0.4*tanh(q), h/4]


def samples(seed, count, dt=0.1):
    rng = Random(seed)
    pairs = []
    for _ in range(count):
        q,h = rng.uniform(-1,1),rng.uniform(-1.5,1.5)
        for a,b in ((sqrt(2),0),(-sqrt(2),0),(0,sqrt(2)),(0,-sqrt(2))):
            q1 = q + dt*(-0.6*q+1.3*h) + sqrt(dt)*0.12*a
            h1 = h + dt*(-1.3*q-0.6*h) + sqrt(dt)*0.19*b
            pairs.append((micro(q,h),micro(q1,h1),dt))
    return pairs


def model(theta):
    enc, dec, log_damping, spin, log_s1, log_s2, log_curvature = theta
    def encoder(x):
        z = coordinates(x,[x[0]],[[0,1,0]],[enc*tanh(x[0])])
        return z[:1],z[1:]
    def decoder(hidden):
        return reconstruct(hidden,[[0],[1],[0]],[0.,0.,dec*tanh(hidden[0])])
    def baseline(x):
        return [0.,x[1],0.]
    lower = [[exp(log_damping/2),0.],[0.,exp(log_damping/2)]]
    skew = [[0.,-spin],[spin,0.]]
    sigma = [[exp(log_s1),0.],[0.,exp(log_s2)]]
    def dynamics(z):
        grad_v = [z[0], exp(log_curvature)*z[1]]
        return drift(grad_v,lower,skew), sigma
    return encoder,decoder,baseline,dynamics


def train(pairs):
    initial = [0.,0.,-0.1,0.8,-1.5,-1.5,0.]
    joint, _ = minimize(lambda p: joint_loss(pairs,*model(p),weight=.01,penalty=.1),
                        initial,steps=60,tol=2e-6)
    # Fix both coordinate maps and refine only the drift, potential and diffusion heads.
    frozen = joint[:2]
    dynamics, loss = minimize(lambda p: joint_loss(pairs,*model(frozen+p),weight=0.),
                              joint[2:],steps=30,tol=2e-6)
    return frozen+dynamics, loss
