import os
from pathlib import Path

import numpy as np

# --8<-- [start:code]
"""The residual measured in H^-1: a better-conditioned PINN loss with one changed line.

Poisson -Δu = f on the unit square with the exact solution of the SV-PINN paper's experiment 2 (Marcondes 2026,
arXiv:2605.03542): the same network, optimiser and step budget are trained on ``r.mse`` and on ``r.norm("H-1")**2``.
"""

import foundax
import jax
import optax

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
π, sin, cos = jno.np.pi, jno.np.sin, jno.np.cos
a, STEPS = 10.0, 2000

# --8<-- [start:setup]
d = jno.shape.rect(0, 0, 1, 1).structured(n=(32, 32)).domain()  # a lattice: the norm takes its sine-transform backend
x, y, _ = d.variable("interior", split=True)
bubble = x * (1 - x) * y * (1 - y)
u_exact = sin(π * x) * sin(π * y) * (sin(a * (x + y)) + sin(2 * π * x) + cos(3 * π * y))
ue = u_exact.scalar.bind(x=x, y=y)
f = -(ue.xx + ue.yy)
# --8<-- [end:setup]


# --8<-- [start:train]
def train(loss):
    """Train a fresh network on ``loss(residual)``; return the relative L2 error against the exact solution."""
    net = jno.nn(foundax.mlp(2, 1, hidden_dims=128, num_layers=4, key=jax.random.PRNGKey(0)))
    net.optimizer(optax.adam(optax.exponential_decay(1e-3, 100, 0.9)))  # the SV-PINN paper's schedule
    u = (net(x, y) * bubble).scalar.bind(x=x, y=y)  # hard u = 0 on the boundary
    r = -(u.xx + u.yy) - f  # the strong residual
    crux = jno.core([loss(r)], domain=d)
    crux.solve(STEPS)
    u_h, u_ref = (np.asarray(v).reshape(-1) for v in crux.eval([u, u_exact]))
    return float(np.linalg.norm(u_h - u_ref) / np.linalg.norm(u_ref))


err_l2 = train(lambda r: r.mse)  # the usual loss
err_h1 = train(lambda r: r.norm("H-1") ** 2)  # the same residual, measured in H^-1
print(f"r.mse             rel-L2 = {err_l2:.3e}")
print(f"r.norm('H-1')**2  rel-L2 = {err_h1:.3e}")
assert err_h1 < 0.5 * err_l2, (err_l2, err_h1)
# --8<-- [end:train]
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/h_minus_1_residual_loss.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):  # both trainings again, in chunks, evaluated on a fine lattice
    fine = jno.shape.rect(0, 0, 1, 1).structured(n=(160, 160)).domain()
    epochs = np.unique(np.round(np.geomspace(1, STEPS, 100)).astype(int))

    def snapshots(loss):
        net = jno.nn(foundax.mlp(2, 1, hidden_dims=128, num_layers=4, key=jax.random.PRNGKey(0)))
        net.optimizer(optax.adam(optax.exponential_decay(1e-3, 100, 0.9)))
        u = (net(x, y) * bubble).scalar.bind(x=x, y=y)
        crux = jno.core([loss(-(u.xx + u.yy) - f)], domain=d)
        frames = [np.asarray(crux.eval([u], domain=fine)[0]).ravel()]  # the untrained network
        for done, upto in zip([0, *epochs[:-1]], epochs):
            crux.solve(int(upto - done), log=False)
            frames.append(np.asarray(crux.eval([u], domain=fine)[0]).ravel())
        grid = [np.asarray(crux.eval([c], domain=fine)[0]).ravel() for c in (x, y, u_exact)]
        return np.array(frames, dtype=np.float32), grid

    mse, (xs, ys, exact) = snapshots(lambda r: r.mse)
    h1, _ = snapshots(lambda r: r.norm("H-1") ** 2)
    err = [np.linalg.norm(s[-1] - exact) / np.linalg.norm(exact) for s in (mse, h1)]
    print(f"chunked runs on the fine lattice: rel L2 {err[0]:.3e} (r.mse), {err[1]:.3e} (H-1)")
    np.savez_compressed(
        Path(out) / "h_minus_1_residual_loss.npz",
        x=xs,
        y=ys,
        exact=exact.astype(np.float32),
        mse=mse,
        h1=h1,
        epochs=np.array([0, *epochs]),
    )
