import os
from pathlib import Path

import numpy as np

# --8<-- [start:code]
"""Variational PINN: a network trial function tested against the finite-element basis, -Δu = f on the unit square."""

import foundax
import jax
import optax

import jno

jax.config.update("jax_enable_x64", True)  # the assembler builds in float64
run = jno.setup(__file__)

# --8<-- [start:setup]
d = jno.shape.rect(0, 0, 1, 1, size=0.07).domain()
xi, yi, _ = d.variable("interior", split=True)
xb, yb, _ = d.variable("boundary", split=True)
u = d.unknown()  # only to declare the Dirichlet condition: it tells the loss which test functions to drop
v = u.test()

net = jno.nn(foundax.mlp(2, hidden_dims=32, num_layers=3, activation=jax.nn.tanh, key=jax.random.PRNGKey(0)))
net.optimizer(optax.adam(1e-2))

bubble = xi * (1 - xi) * yi * (1 - yi)
u_net = net(xi, yi) * bubble  # hard u = 0 on the boundary
grad = lambda w: jno.np.jacobian(w, [xi, yi])
f = 2 * (xi * (1 - xi) + yi * (1 - yi))  # -Δ[x(1-x)y(1-y)]
# --8<-- [end:setup]

# --8<-- [start:weak]
pde = jno.fem([jno.np.inner(grad(u_net), grad(v)) - f * v, u(xb, yb) - 0.0])  # ∫ ∇u_net·∇v - f v, v in the P1 basis
# --8<-- [end:weak]

# --8<-- [start:solve]
crux = jno.core([pde.mse], domain=d)
crux.solve(2500)

fine = jno.shape.rect(0, 0, 1, 1, size=0.04).domain()
u_h, u_ref = crux.eval([u_net, bubble], domain=fine)  # reference: x(1-x)y(1-y)
rel_l2 = float(np.linalg.norm(u_h - u_ref) / np.linalg.norm(u_ref))
print(f"Relative L2 error: {rel_l2:.4e}")
assert rel_l2 < 1e-2, f"VPINN did not solve Poisson: rel-L2={rel_l2:.3e}"
# --8<-- [end:solve]
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/vpinn_poisson_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.rect(0, 0, 1, 1, size=0.0125).domain()
    single = np.asarray(crux.eval([u_net], domain=fine)[0]).ravel()  # the single call, on the fine grid
    net = jno.nn(foundax.mlp(2, hidden_dims=32, num_layers=3, activation=jax.nn.tanh, key=jax.random.PRNGKey(0)))
    net.optimizer(optax.adam(1e-2))
    u_net = net(xi, yi) * bubble
    crux = jno.core([jno.fem([jno.np.inner(grad(u_net), grad(v)) - f * v, u(xb, yb) - 0.0]).mse], domain=d)
    epochs = np.unique(np.round(np.geomspace(1, 2500, 100)).astype(int))
    frames = [np.asarray(crux.eval([u_net], domain=fine)[0]).ravel()]  # the untrained network
    xs, ys, ref = (np.asarray(crux.eval([c], domain=fine)[0]).ravel() for c in (xi, yi, bubble))
    for done, upto in zip([0, *epochs[:-1]], epochs):
        crux.solve(int(upto - done), log=False)
        frames.append(np.asarray(crux.eval([u_net], domain=fine)[0]).ravel())
    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) / "vpinn_poisson_2d.npz",
        x=xs,
        y=ys,
        u=np.array(frames, dtype=np.float32),
        exact=ref,
        epochs=np.array([0, *epochs]),
    )
