import os
from pathlib import Path

# --8<-- [start:code]
"""Fourier neural operator for -Δu = f on the unit square with u = 0 on the boundary, trained on (f, u) pairs:
a regression, no PDE residual."""

import foundax
import jax
import numpy as np
import optax
from poisson_data import build_domain_from_arrays, generate_poisson_data

import jno

run = jno.setup(__file__)
KEY, GRID, SAMPLES, EPOCHS = jax.random.PRNGKey(0), 64, 256, 600

forcing, solution = generate_poisson_data(SAMPLES, GRID, n_modes=5, alpha=1.5, seed=42)
d = build_domain_from_arrays(forcing, solution, GRID)
f, u_data = d.variable("_f"), d.variable("_u")

net = jno.nn(
    foundax.fno2d(
        in_features=1,
        hidden_channels=16,
        n_modes=6,
        d_vars=1,
        n_layers=2,
        n_steps=1,
        d_model=(GRID, GRID),
        norm="layer",
        linear_conv=True,
        key=KEY,
    )
)
net.optimizer(
    optax.chain(
        optax.clip_by_global_norm(1e-3),
        optax.adamw(optax.cosine_decay_schedule(5e-4, EPOCHS, alpha=1e-7 / 5e-4), weight_decay=1e-6),
    )
)

crux = jno.core([(u_data - net(f)).mse])
crux.solve(epochs=EPOCHS, batchsize=32)

# Eight held-out forcings from another seed: the operator's own output against the exact solutions.
N_TEST = 8
f_test, u_test = generate_poisson_data(N_TEST, GRID, n_modes=5, alpha=1.5, seed=123)
test = build_domain_from_arrays(f_test, u_test, GRID)
pred = np.asarray(crux.eval([net(test.variable("_f"))], domain=test)).reshape(N_TEST, -1)
truth = u_test.reshape(N_TEST, -1)

rel = np.linalg.norm(pred - truth, axis=1) / np.linalg.norm(truth, axis=1)
print(f"held-out per-sample rel-L2: {np.array2string(rel, precision=3)}")
print(f"held-out mean rel-L2 = {rel.mean():.4f}")
assert rel.mean() < 0.2, rel.mean()
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/fno_poisson_2d.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "fno_poisson_2d.npz",
        pred=pred.reshape(N_TEST, GRID, GRID),
        truth=truth.reshape(N_TEST, GRID, GRID),
        rel=rel,
    )
