import os
from pathlib import Path

# --8<-- [start:code]
"""A learned time-stepper: an FNO that advances 1-D viscous Burgers by one step, rolled out against the solver.

    u_t + u u_x = nu u_xx   on a periodic box, so that  mean(u)  is conserved exactly.

Data: trajectories of jno.spectral (Fourier, 3/2 dealiasing, ETDRK4) from random smooth initial states. The FNO learns
u(t) -> u(t + DT) from pairs of consecutive states inside the window t <= T_TRAIN, and is then applied to its own output for
many more steps than it was trained on. Checks on held-out initial states: the one-step error, the error growth along the
rollout, and the drift of the conserved mean.
"""

import foundax
import jax
import jax.numpy as jnp
import numpy as np
import optax

import jno

run = jno.setup(__file__)
L, N, NU, T, STEPS = 2 * np.pi, 256, 0.02, 8.0, 1600  # periodic box, grid, viscosity, final time, ETDRK4 steps
DT, T_TRAIN = 0.05, 3.0  # the network's step; it is trained on states with t <= T_TRAIN and rolled out to T
N_TRAIN, N_TEST, EPOCHS, KEY = 256, 32, 6000, jax.random.PRNGKey(0)
ts = np.arange(0.0, T + DT / 2, DT)  # the snapshots: 161 states per trajectory

# 1. Data: one jno.spectral solve per random initial state, snapshots every DT.
d = jno.Path(0.0, 0.0).line_to(L, 0.0).curve(size=L / N).domain(time=(0.0, T, STEPS + 1))
U = d.unknown(space=("fourier",), order=(N,), name="u")
x, t = d.variable("interior", split=True)
x0, _ = d.variable("initial", split=True)
(xl, _), (xr, _) = d.variable("left", split=True), d.variable("right", split=True)
u = U.bind(x=x, t=t, scheme=jno.sp(dealias=3 / 2))
grid = U.basis.nodes[:, 0]


def initial_state(seed):  # a random mean plus four random modes with amplitudes ~ k^(-1/2), peak value 1.5
    r = np.random.default_rng(seed)
    u0 = sum(r.normal() * np.sin(k * grid + r.uniform(0, 2 * np.pi)) / np.sqrt(k) for k in range(1, 5))
    return 1.5 * u0 / np.abs(u0).max() + 0.3 * r.normal()


def trajectory(u0):  # (len(ts), N)
    return np.asarray(
        jno.spectral([u.t + u * u.x - NU * u.xx, U(x0) - jnp.asarray(u0.reshape(-1, 1)), U(xl) - U(xr)]).solve(
            time=jno.solve.etdrk4(), save_ts=ts
        )
    )


traj = np.stack([trajectory(initial_state(s)) for s in range(N_TRAIN + N_TEST)]).astype(np.float32)
train, test = traj[:N_TRAIN], traj[N_TRAIN:]
pairs = train[:, : int(T_TRAIN / DT) + 1]  # (N_TRAIN, 61, N): consecutive states inside the training window
now, nxt = (pairs[:, :-1].reshape(-1, N, 1), pairs[:, 1:].reshape(-1, N, 1))


def rows(a):  # a batch of states as a jNO domain: one row per state
    dom = len(a) * jno.shape.rect(0.0, 0.0, 1.0, 1.0).structured(n=3).domain()
    dom.variable("interior")
    dom.variable("u", a[:, None])
    return dom


# 2. The stepper u -> u + net(u) and its one-step loss; the FNO predicts the increment.
batch = rows(now)
batch.variable("u_next", nxt[:, None])
u_now, u_next = batch.variable("u"), batch.variable("u_next")
net = jno.nn(foundax.fno1d(in_features=1, hidden_channels=32, n_modes=24, n_layers=4, key=KEY))
net.optimizer(optax.adam(optax.cosine_decay_schedule(2e-3, EPOCHS, 0.01)))
crux = jno.core([(u_next - (u_now + net(u_now))).mse])
crux.solve(epochs=EPOCHS, batchsize=256)

# 3. One step on held-out states, then the rollout: feed the network its own output for 160 steps.
step = u_now + net(u_now)  # the same expression, evaluated on whatever rows it is handed


def advance(a):
    return np.asarray(crux.eval([step], domain=rows(a)))[:, 0, :, 0]


one = advance(test[:, :-1].reshape(-1, N, 1))  # every held-out state, one step
one_step = np.linalg.norm(one - test[:, 1:].reshape(-1, N), axis=1) / np.linalg.norm(test[:, 1:].reshape(-1, N), axis=1)

roll = [test[:, 0]]
for _ in range(len(ts) - 1):
    roll.append(advance(roll[-1][:, :, None]))
roll = np.stack(roll, 1)  # (N_TEST, len(ts), N)

err = np.linalg.norm(roll - test, axis=2) / np.linalg.norm(test, axis=2)  # relative L2 error per state and time
mean_drift = np.abs(roll.mean(2) - test.mean(2)).max(0)  # the conserved mean: |mean(rollout) - mean(solver)|
i3, i8 = int(T_TRAIN / DT), len(ts) - 1
print(f"one-step relative error {np.median(one_step):.2e} (median), {one_step.max():.2e} (max)")
print(
    f"rollout error, median over states: {np.median(err[:, 20]):.3f} at t=1, {np.median(err[:, i3]):.3f} at t={T_TRAIN}, {np.median(err[:, i8]):.3f} at t={T}"
)
print(
    f"mean drift: {mean_drift[i3]:.2e} at t={T_TRAIN}, {mean_drift[i8]:.2e} at t={T}  (solver: {np.abs(test.mean(2) - test[:, :1].mean(2)).max():.1e})"
)
assert np.median(one_step) < 2e-3 and np.median(err[:, i8]) < 0.1 and mean_drift[i8] < 0.1
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "learned_time_stepper_burgers.npz",
        truth=test.astype(np.float32),
        rollout=roll.astype(np.float32),
        err=err,
        mean_drift=mean_drift,
        one_step=one_step,
        ts=ts,
        params=np.array([L, NU, DT, T_TRAIN]),
    )
