import os
from pathlib import Path

import numpy as np

# --8<-- [start:code]
"""1-D Laplace equation, u'' = 0 on [0, 1] with u(0) = 0, u(1) = 1: the smallest PINN."""

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

import jno

run = jno.setup(__file__)
d = jno.Path(0.0, 0.0).line_to(1.0, 0.0).curve(size=0.1).domain()
x, _ = d.variable("interior")

net = jno.nn(foundax.mlp(in_features=1, hidden_dims=32, num_layers=3, key=jax.random.PRNGKey(0)))
net.optimizer(optax.adam(optax.exponential_decay(1e-3, 10, 0.5, end_value=1e-5)))

u = (x + x * (1 - x) * net(x)).scalar.bind(x=x)  # hard boundary values: line + bubble * net
crux = jno.core([u.xx.mse])  # u'' = 0
crux.solve(5000)

u_h, u_ex = crux.eval([u, x])  # exact solution u = x
rel_l2 = float(jnp.linalg.norm(u_h - u_ex) / jnp.linalg.norm(u_ex))
print(f"Relative L2 error: {rel_l2:.4e}")
assert rel_l2 < 1e-1, f"relative L2 error too large: {rel_l2:.3e}"
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/laplace_1d.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):  # the same training again, in chunks, for the animation
    net = jno.nn(foundax.mlp(in_features=1, hidden_dims=32, num_layers=3, key=jax.random.PRNGKey(0)))
    net.optimizer(optax.adam(optax.exponential_decay(1e-3, 10, 0.5, end_value=1e-5)))
    u = (x + x * (1 - x) * net(x)).scalar.bind(x=x)
    crux = jno.core([u.xx.mse])
    dense = jno.Path(0.0, 0.0).line_to(1.0, 0.0).curve(size=0.005).domain()
    epochs = np.unique(np.round(np.geomspace(1, 5000, 100)).astype(int))
    frames = [np.asarray(crux.eval([u], domain=dense)[0]).ravel()]  # the untrained network
    xs = np.asarray(crux.eval([x], domain=dense)[0]).ravel()
    for done, upto in zip([0, *epochs[:-1]], epochs):
        crux.solve(int(upto - done), log=False)
        frames.append(np.asarray(crux.eval([u], domain=dense)[0]).ravel())
    np.savez_compressed(Path(out) / "laplace_1d.npz", x=xs, u=np.array(frames), epochs=np.array([0, *epochs]))
