import os
from pathlib import Path

# --8<-- [start:code]
"""Viscous Burgers equation u_t + u u_x = ν u_xx on the space-time rectangle, trained with four point strategies."""

import foundax
import jax
import numpy as np
import optax

import jno

run = jno.setup(__file__)
π, sin = jno.np.pi, jno.np.sin
ν, EPOCHS, POINTS = 0.01 / np.pi, 15_000, 4_000

# --8<-- [start:setup]
strategies = {  # the settings of the examples in docs/ml/resampling.md
    "fixed": None,  # the same uniform points the whole time
    "RAD": jno.sampler.rad(resample_every=100, resample_fraction=0.1, start_epoch=1000, k=10),
    "RAR-D": jno.sampler.rard(resample_every=100, resample_fraction=0.1, start_epoch=1000, power=2.0),
    "R3": jno.sampler.r3(resample_every=100, start_epoch=1000, threshold_mode="mean"),
}
# --8<-- [end:setup]


# --8<-- [start:problem]
def burgers(strategy):
    """The same problem, network and initialisation every time; only the way the collocation points move differs."""
    d = jno.shape.rect(-1.0, 0.0, 1.0, 1.0).domain()  # the (x, t) plane: t is the second coordinate
    x, t, _ = d.variable("interior", sample=(POINTS, None), resampling_strategy=strategy)
    x0, t0, _ = d.variable("bottom", sample=(500, None))  # t = 0

    net = jno.nn(foundax.mlp(in_features=2, hidden_dims=64, num_layers=5, key=jax.random.PRNGKey(0)))
    net.optimizer(optax.adam(optax.warmup_cosine_decay_schedule(0.0, 2e-3, 10, EPOCHS, 1e-5)))

    u = (net(x, t) * (1 - x**2)).scalar.bind(x=x, t=t)  # hard u(-1, t) = u(1, t) = 0
    pde = u.t + u * u.x - ν * u.xx
    ini = u(x0, t0) + sin(π * x0)  # u(x, 0) = -sin(πx)
    return jno.core([pde.mse, ini.mse]), u, x, t


# --8<-- [end:problem]


# --8<-- [start:solve]
runs = {}
for name, strategy in strategies.items():
    runs[name] = crux, u, x, t = burgers(strategy)
    crux.solve(EPOCHS, min_consecutive=None)
# --8<-- [end:solve]


# --8<-- [start:reference]
def cole_hopf(x, t, nu, n=100):
    """The exact solution: the Cole-Hopf transform turns Burgers into the heat equation, whose kernel is integrated
    by Gauss-Hermite quadrature."""
    z, w = np.polynomial.hermite.hermgauss(n)
    y = x[..., None] - 2 * np.sqrt(nu * t[..., None]) * z
    log_kernel = -np.cos(np.pi * y) / (2 * np.pi * nu)
    e = np.exp(log_kernel - log_kernel.max(-1, keepdims=True)) * w
    return -(np.sin(np.pi * y) * e).sum(-1) / e.sum(-1)


fine = jno.shape.rect(-1.0, 0.0, 1.0, 1.0, size=0.01).domain()  # nodes to evaluate every network on
errors = {}
for name, (crux, u, x, t) in runs.items():
    xs, ts, u_h = (np.asarray(v).ravel() for v in crux.eval([x, t, u], domain=fine))
    u_ref = cole_hopf(xs, np.maximum(ts, 1e-9), ν)
    near = (np.abs(xs) < 0.1) & (ts > 0.3)  # the shock, once it has formed
    rel = lambda m: float(np.linalg.norm((u_h - u_ref)[m]) / np.linalg.norm(u_ref[m]))
    errors[name] = rel(~near), rel(near)
    print(f"{name:>5}: relative L2 error {errors[name][0]:.3e} away from the shock, {errors[name][1]:.3e} within 0.1 of it")
    assert errors[name][0] < 0.1, f"{name}: error away from the shock too large: {errors[name][0]:.3e}"  # Cole-Hopf
# --8<-- [end:reference]
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/burgers_viscous_1d.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):  # the same four trainings again, snapshotting the net and the points
    import equinox as eqx
    import jax.numpy as jnp

    GX, GT = np.meshgrid(np.linspace(-1, 1, 201), np.linspace(0, 1, 101))
    grid = jnp.stack([GX.ravel(), GT.ravel()], -1)

    class Snapshots(jno.callbacks.Callback):
        """Every `every` epochs: the network on the grid and the interior collocation points."""

        def __init__(self, every):
            self.every, self.epochs, self.fields, self.points = every, [], [], []

        def on_solve_begin(self, **kw):
            self.frozen, self.static = kw["frozen"], kw["static"]

        def on_epoch_end(self, **kw):
            if kw["epoch"] % self.every and kw["epoch"] != EPOCHS - 1:
                return False
            (model,) = eqx.combine(kw["trainable"], self.frozen, self.static).values()
            self.fields.append(np.asarray(jax.vmap(model)(grid)[:, 0] * (1 - grid[:, 0] ** 2)).reshape(GX.shape))
            self.points.append(np.asarray(kw["context"]["interior"])[0, 0].copy())
            self.epochs.append(kw["epoch"] + 1)
            return False

    snaps = {}
    for name, strategy in strategies.items():
        if strategy is not None:
            strategy.update_epoch(-1)  # forget the last resampling of the first run
        snaps[name] = cb = Snapshots(every=250)
        burgers(strategy)[0].solve(EPOCHS, min_consecutive=None, callbacks=[cb])
    exact = cole_hopf(GX, np.maximum(GT, 1e-9), ν)
    np.savez_compressed(
        Path(out) / "burgers_viscous_1d.npz",
        names=list(snaps),
        x=GX[0],
        t=GT[:, 0],
        exact=exact.astype(np.float32),
        epochs=np.array(cb.epochs),
        fields=np.array([np.array(c.fields, np.float32) for c in snaps.values()]),
        points=np.array([np.array(c.points, np.float16) for c in snaps.values()]),
        errors=np.array([errors[n] for n in snaps]),
    )
