"""Processed leapfrog (processed drift-kick-drift) with a potential trained by MEAL.

processed-dkd-meal v0.1.0, Jiang, Guo, Zhu & Li, Accelerating Dynamical Systems
Simulation via Modified-Equation-Aware Learning (2026)

Separable Hamiltonian H(q, p) = sum p_i^2 / (2 m_i) + V(q) with constant masses.

Conventions
- `grad(q)` returns +grad V(q), the gradient of the potential (the force is -grad V).
  `hvp(q, v)` returns the Hessian-vector product (grad^2 V)(q) v; only training uses it.
- States are (q, p) with canonical momentum p_i = m_i * v_i; `mass` holds one
  positive mass per coordinate (repeat an atom's mass for x, y and z).
- Vectors are tuples of floats so the file runs on the standard library alone.
  Port the arithmetic to NumPy, JAX or PyTorch unchanged; in an autodiff framework,
  get grad and hvp from the scalar model instead of writing them by hand.

Training (paper Eqs. (41)-(42)): fit V so that the corrected gradient
    g~(q) = grad V + (h^2 / 12) (grad^2 V) M^-1 grad V
matches the force labels, g~(q_i) ~ -F_i.
Simulation (paper Algorithm 2): preprocess once, ordinary DKD steps with grad V,
postprocess a copy of the state at each output. Never use g~ in simulation.
"""

from math import ceil, isfinite, sqrt
from typing import Callable, Iterable, Sequence

Vector = tuple[float, ...]
Gradient = Callable[[Vector], Sequence[float]]
HessianProduct = Callable[[Vector, Vector], Sequence[float]]


# ---------------------------------------------------------------- training ----

def modified_gradient(q: Vector, h: float, mass: Vector, grad: Gradient, hvp: HessianProduct) -> Vector:
    """Corrected gradient g~ = grad V + (h^2/12) (grad^2 V) M^-1 grad V (paper Eq. (41)).

    Equal to the gradient of V + (h^2/24) (grad V)^T M^-1 (grad V), paper Eq. (40).
    """
    g = tuple(grad(q))
    correction = hvp(q, tuple(gi / mi for gi, mi in zip(g, mass, strict=True)))
    return tuple(gi + (h * h / 12) * ci for gi, ci in zip(g, correction, strict=True))


def force_loss(samples: Iterable[tuple[Vector, Vector]], h: float, mass: Vector, grad: Gradient, hvp: HessianProduct) -> float:
    """MEAL loss for processed leapfrog, paper Eq. (42).

    Mean over configurations of the squared Euclidean norm of g~(q_i) + F_i, where
    F_i is the force label (minus the potential gradient) at q_i.
    """
    total, count = 0.0, 0
    for q, force in samples:
        g_mod = modified_gradient(q, h, mass, grad, hvp)
        total += sum((gi + fi) ** 2 for gi, fi in zip(g_mod, force, strict=True))
        count += 1
    if count == 0:
        raise ValueError("force_loss needs at least one sample")
    return total / count


# -------------------------------------------------------------- simulation ----

def drift(q: Vector, p: Vector, dt: float, mass: Vector) -> Vector:
    """Position update q <- q + dt M^-1 p."""
    return tuple(qi + dt * pi / mi for qi, pi, mi in zip(q, p, mass, strict=True))


def kick(q: Vector, p: Vector, dt: float, grad: Gradient) -> Vector:
    """Momentum update p <- p - dt grad V(q). One gradient evaluation."""
    return tuple(pi - dt * gi for pi, gi in zip(p, grad(q), strict=True))


def dkd_step(q: Vector, p: Vector, h: float, mass: Vector, grad: Gradient) -> tuple[Vector, Vector]:
    """One ordinary drift-kick-drift (position Verlet) step. One gradient evaluation."""
    q = drift(q, p, h / 2, mass)
    p = kick(q, p, h, grad)
    return drift(q, p, h / 2, mass), p


def postprocessor_shears(h: float) -> tuple[tuple[str, float], ...]:
    """The eight shears of the postprocessor, in the order they are applied (paper Eq. (68)).

    s = |h| / sqrt(48): D(s), K(s), D(-s), K(-s), D(-s), K(-s), D(s), K(s).
    """
    s = abs(h) / sqrt(48)
    return (("D", s), ("K", s), ("D", -s), ("K", -s), ("D", -s), ("K", -s), ("D", s), ("K", s))


def process(q: Vector, p: Vector, h: float, mass: Vector, grad: Gradient, *, post: bool) -> tuple[Vector, Vector]:
    """Apply the postprocessor (auxiliary -> physical, post=True) or the preprocessor
    (physical -> auxiliary, post=False), its exact inverse: the same shears in
    reverse order with every duration negated. Four gradient evaluations either way.
    """
    shears = postprocessor_shears(h)
    if not post:
        shears = tuple((kind, -dt) for kind, dt in reversed(shears))
    for kind, dt in shears:
        if kind == "D":
            q = drift(q, p, dt, mass)
        else:
            p = kick(q, p, dt, grad)
    return q, p


def rollout(q0, p0, h: float, n_steps: int, mass, grad: Gradient, *, every: int = 1):
    """Simulate n_steps processed-leapfrog steps of size h from the physical state (q0, p0).

    Returns a list of (step, q, p) of PHYSICAL states at step 0, every `every` steps,
    and at the final step (paper Algorithm 2); step n is time t0 + n h. Negative h
    integrates backwards. Gradient evaluations: n_steps + 4 + 4 * ceil(n_steps / every)
    for n_steps > 0 (paper Eq. (43)), none for n_steps = 0. Output never changes the
    trajectory: the auxiliary state is carried forward, outputs are copies.
    """
    q, p, mass = tuple(q0), tuple(p0), tuple(mass)
    if not q or len(q) != len(p) or len(q) != len(mass):
        raise ValueError("q, p and mass must have the same nonzero length")
    if any(not isfinite(m) or m <= 0 for m in mass):
        raise ValueError("masses must be finite and positive")
    if not isfinite(h) or h == 0:
        raise ValueError("h must be finite and nonzero")
    if type(n_steps) is not int or n_steps < 0 or type(every) is not int or every < 1:
        raise ValueError("need an integer n_steps >= 0 and an integer every >= 1")
    out = [(0, q, p)]
    if n_steps == 0:
        return out
    xq, xp = process(q, p, h, mass, grad, post=False)  # auxiliary state
    for n in range(1, n_steps + 1):
        xq, xp = dkd_step(xq, xp, h, mass, grad)
        if n % every == 0 or n == n_steps:
            yq, yp = process(xq, xp, h, mass, grad, post=True)
            if not all(isfinite(x) for x in yq + yp):
                raise FloatingPointError(f"non-finite physical state at step {n}")
            out.append((n, yq, yp))
    return out


def gradient_evaluations(n_steps: int, every: int) -> int:
    """Gradient evaluations used by rollout (paper Eq. (43)); excludes training."""
    return 0 if n_steps == 0 else n_steps + 4 + 4 * ceil(n_steps / every)


def kinetic_energy(p: Vector, mass: Vector) -> float:
    return sum(pi * pi / (2 * mi) for pi, mi in zip(p, mass, strict=True))
