import os
from pathlib import Path

import numpy as np

# --8<-- [start:code]
"""2-D Fokker-Planck equation of an Ornstein-Uhlenbeck process on a disc, solved with a PINN."""

import foundax
import jax
import optax

import jno

run = jno.setup(__file__)
π, exp = jno.np.pi, jno.np.exp

# --8<-- [start:setup]
d = jno.shape.disk(0, 0, 3.0, size=0.25).domain()  # radius 3 holds the Gaussian's support
x, y, _ = d.variable("interior")
xb, yb, _ = d.variable("boundary")

p_exact = exp(-(x**2 + y**2)) / π
# --8<-- [end:setup]

# --8<-- [start:residual]
net = jno.nn(foundax.mlp(in_features=2, hidden_dims=64, num_layers=5, key=jax.random.PRNGKey(0)))
net.optimizer(
    optax.chain(  # clipping caps the occasional gradient spike of the stiff residual
        optax.clip_by_global_norm(1.0),
        optax.adam(optax.exponential_decay(1e-3, 2000, 0.5, end_value=1e-5)),
    )
)

p = net(x, y).scalar.bind(x=x, y=y)
drift = jno.np.vector(x * p, y * p).div(x, y)  # ∇·(b p) with drift b = (x, y)
fp = drift + 0.5 * (p.xx + p.yy)  # = 0
# --8<-- [end:residual]

# --8<-- [start:constraints]
norm = p.integrate() - 1.0  # ∬ p dx dy = 1
bc = net(xb, yb) - (exp(-(xb**2 + yb**2)) / π + jno.noise.gaussian(std=1e-4))  # noisy boundary data
# --8<-- [end:constraints]

# --8<-- [start:solve]
crux = jno.core([fp.mse, norm.mse, bc.mse])
crux.solve(15_000)

p_h, p_ref = crux.eval([p, p_exact])
rel_l2 = float(jax.numpy.linalg.norm(p_h - p_ref) / jax.numpy.linalg.norm(p_ref))  # reference: e^-(x²+y²) / π
print(f"Relative L2 error: {rel_l2:.4e}")
assert rel_l2 < 3e-1, f"relative L2 error too large: {rel_l2:.3e}"
# --8<-- [end:solve]
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/fokker_planck_2d.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):  # the same training again, in chunks, for the animation
    fine = jno.shape.disk(0, 0, 3.0, size=0.03).domain()
    single = np.asarray(crux.eval([p], domain=fine)[0]).ravel()  # the single call, on the fine grid
    net = jno.nn(foundax.mlp(in_features=2, hidden_dims=64, num_layers=5, key=jax.random.PRNGKey(0)))
    net.optimizer(
        optax.chain(optax.clip_by_global_norm(1.0), optax.adam(optax.exponential_decay(1e-3, 2000, 0.5, end_value=1e-5)))
    )
    p = net(x, y).scalar.bind(x=x, y=y)
    fp = jno.np.vector(x * p, y * p).div(x, y) + 0.5 * (p.xx + p.yy)
    bc = net(xb, yb) - (exp(-(xb**2 + yb**2)) / π + jno.noise.gaussian(std=1e-4))
    crux = jno.core([fp.mse, (p.integrate() - 1.0).mse, bc.mse])
    epochs = np.unique(np.round(np.geomspace(1, 15_000, 100)).astype(int))
    frames = [np.asarray(crux.eval([p], domain=fine)[0]).ravel()]  # the untrained network
    xs, ys = (np.asarray(crux.eval([c], domain=fine)[0]).ravel() for c in (x, y))
    for done, upto in zip([0, *epochs[:-1]], epochs):
        crux.solve(int(upto - done), log=False)
        frames.append(np.asarray(crux.eval([p], domain=fine)[0]).ravel())
    ref = np.exp(-(xs**2 + ys**2)) / np.pi
    print(f"chunked run vs single call on the fine grid: max |difference| = {np.abs(frames[-1] - single).max():.2e}")
    np.savez_compressed(
        Path(out) / "fokker_planck_2d.npz",
        x=xs,
        y=ys,
        p=np.array(frames, dtype=np.float32),
        exact=ref,
        epochs=np.array([0, *epochs]),
    )
