import os
from pathlib import Path

# --8<-- [start:code]
"""DeepONet for a parametric Poisson family, k Δu + 1 = 0 on [0, 2] x [0, 1] with u = 0 on the boundary,
learned from the PDE residual alone: the network never sees a solution."""

import foundax
import jax
import numpy as np
import optax

import jno

run = jno.setup(__file__)
KEY, N_SAMPLES, EPOCHS = jax.random.PRNGKey(0), 50, 2_000

d = N_SAMPLES * jno.shape.rect(0, 0, 2, 1, size=0.05).domain()  # one mesh, replicated per sample
x, y, _ = d.variable("interior")
k = d.variable("k", jax.random.uniform(KEY, (N_SAMPLES, 1, 1), minval=0.5, maxval=1.5))  # one k per sample

net = jno.nn(
    foundax.deeponet(n_sensors=1, coord_dim=2, basis_functions=32, hidden_dim=128, activation=jax.numpy.tanh, key=KEY)
)
net.optimizer(optax.adam(optax.cosine_decay_schedule(1e-3, EPOCHS, alpha=1e-2)))

u = (net(k, jno.np.concat([x, y], axis=-1)) * x * (2 - x) * y * (1 - y)).scalar.bind(x=x, y=y)  # u = 0 on the boundary
crux = jno.core([(k * (u.xx + u.yy) + 1.0).mse])
crux.solve(epochs=EPOCHS, batchsize=32)

# Held-out k on a mesh five times finer. Reference: k Δu + 1 = 0 is -Δw = 1 with u = w / k.
K_TEST = (0.7, 1.234, 1.4)
td = len(K_TEST) * jno.shape.rect(0, 0, 2, 1, size=0.01).domain()
xt, yt, _ = td.variable("interior")
kt = td.variable("k", np.array(K_TEST, dtype=np.float32).reshape(-1, 1, 1))
u_net = net(kt, jno.np.concat([xt, yt], axis=-1)) * xt * (2 - xt) * yt * (1 - yt)
pred = np.asarray(crux.eval([u_net], domain=td)).reshape(len(K_TEST), -1)

r = jno.shape.rect(0, 0, 2, 1, size=0.01).domain()
xr, yr, _ = r.variable("interior", split=True)
xb, yb, _ = r.variable("boundary", split=True)
w = r.unknown()
v = w.test()
grad = lambda q: jno.np.jacobian(q, [xr, yr])
fem = jno.fem([jno.np.inner(grad(w), grad(v)) - v, w(xb, yb) - 0.0], quad_degree=3)
ref = np.asarray(fem.solve(linear=jno.solve.lu())).ravel() / np.array(K_TEST)[:, None]

rel_l2 = np.linalg.norm(pred - ref, axis=1) / np.linalg.norm(ref, axis=1)
print(f"held-out k = {K_TEST}: rel-L2 vs finite elements = {np.array2string(rel_l2, precision=4)}")
assert rel_l2.max() < 0.15, rel_l2
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/deeponet_poisson_2d.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.deeponet(n_sensors=1, coord_dim=2, basis_functions=32, hidden_dim=128, activation=jax.numpy.tanh, key=KEY)
    )
    net.optimizer(optax.adam(optax.cosine_decay_schedule(1e-3, EPOCHS, alpha=1e-2)))
    u = (net(k, jno.np.concat([x, y], axis=-1)) * x * (2 - x) * y * (1 - y)).scalar.bind(x=x, y=y)
    crux = jno.core([(k * (u.xx + u.yy) + 1.0).mse])
    u_net = net(kt, jno.np.concat([xt, yt], axis=-1)) * xt * (2 - xt) * yt * (1 - yt)
    CHUNK = 20
    frames = [np.asarray(crux.eval([u_net], domain=td)).reshape(len(K_TEST), -1)]
    for _ in range(EPOCHS // CHUNK):
        crux.solve(epochs=CHUNK, batchsize=32, log=False)
        frames.append(np.asarray(crux.eval([u_net], domain=td)).reshape(len(K_TEST), -1))
    chunked = np.linalg.norm(frames[-1] - ref, axis=1) / np.linalg.norm(ref, axis=1)
    print(f"chunked run: rel-L2 = {np.array2string(chunked, precision=4)}")
    np.savez_compressed(
        Path(out) / "deeponet_poisson_2d.npz",
        points=np.asarray(td.mesh_connectivity["points"])[:, :2],
        triangles=np.asarray(td.mesh_connectivity["triangles"]),
        k=np.array(K_TEST),
        ref=ref,
        frames=np.array(frames, dtype=np.float32),
        epochs=np.arange(0, EPOCHS + 1, CHUNK),
    )
