import os
from pathlib import Path

import numpy as np

# --8<-- [start:code]
"""Deep Ritz: minimise the energy J[u] = ∫ ½|∇u|² - f u of -Δu = f on the unit square with a network."""

import foundax
import jax
import optax

import jno

jax.config.update("jax_enable_x64", True)  # the mesh integral accumulates in float64
run = jno.setup(__file__)

# --8<-- [start:energy]
d = jno.shape.rect(0, 0, 1, 1, size=0.05).domain()
x, y, _ = d.variable("interior", split=True)

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

bubble = x * (1 - x) * y * (1 - y)
w = net(x, y) * bubble  # hard u = 0 on the boundary
u = w.scalar.bind(x=x, y=y)
f = 2 * (x * (1 - x) + y * (1 - y))  # -Δ[x(1-x)y(1-y)]

energy = (0.5 * (u.x**2 + u.y**2) - f * u).integrate(quadrature="gauss")  # J[u], element Gauss points
# --8<-- [end:energy]

# --8<-- [start:solve]
crux = jno.core([energy], domain=d)  # the signed energy is the loss; it converges to J_min < 0
crux.solve(4000)

fine = jno.shape.rect(0, 0, 1, 1, size=0.035).domain()
u_h, u_ref = crux.eval([w, 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-3, f"Deep Ritz did not solve Poisson: rel-L2={rel_l2:.3e}"
# --8<-- [end:solve]
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/deep_ritz_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([w], domain=fine)[0]).ravel()  # the single call, on the fine grid
    net = jno.nn(foundax.mlp(2, hidden_dims=48, num_layers=4, activation=jax.nn.tanh, key=jax.random.PRNGKey(0)))
    net.optimizer(optax.adam(3e-3))
    w = net(x, y) * bubble
    u = w.scalar.bind(x=x, y=y)
    crux = jno.core([(0.5 * (u.x**2 + u.y**2) - f * u).integrate(quadrature="gauss")], domain=d)
    epochs = np.unique(np.round(np.geomspace(1, 4000, 100)).astype(int))
    frames = [np.asarray(crux.eval([w], domain=fine)[0]).ravel()]  # the untrained network
    xs, ys, ref = (np.asarray(crux.eval([c], domain=fine)[0]).ravel() for c in (x, y, bubble))
    for done, upto in zip([0, *epochs[:-1]], epochs):
        crux.solve(int(upto - done), log=False)
        frames.append(np.asarray(crux.eval([w], 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) / "deep_ritz_poisson_2d.npz",
        x=xs,
        y=ys,
        u=np.array(frames, dtype=np.float32),
        exact=ref,
        epochs=np.array([0, *epochs]),
    )
