import os
from pathlib import Path

# --8<-- [start:code]
"""Variable-coefficient Poisson, -div(kappa grad u) = f on the unit square: a PINN, kappa jumping by 5 along a diagonal."""

import foundax
import jax
import numpy as np
import optax

import jno

run = jno.setup(__file__)
π, sin, tanh = jno.np.pi, jno.np.sin, jno.np.tanh
EPOCHS = 10_000

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

κ = 1 + 4 * (0.5 + 0.5 * tanh((x + y - 1) / 0.02))  # 1 below the diagonal x + y = 1, 5 above it, a ~0.03 wide step
kink = jno.np.sqrt((x + y - 1) ** 2 + 0.01**2)  # |x + y - 1| rounded over 0.01: a ridge along the jump in κ
u_exact = sin(π * x) * sin(π * y) + 0.2 * sin(4 * π * x) * sin(3 * π * y) + 0.3 * kink * x * (1 - x) * y * (1 - y)
ue = u_exact.scalar.bind(x=x, y=y)
f = -jno.np.vector(κ * ue.x, κ * ue.y).div(x, y)  # -div(κ grad u_exact)
# --8<-- [end:setup]

# --8<-- [start:residual]
net = jno.nn(foundax.mlp(in_features=2, hidden_dims=64, num_layers=4, key=jax.random.PRNGKey(13)))
net.optimizer(optax.adam(optax.exponential_decay(2e-3, 2000, 0.6, end_value=1e-5)))

u = (net(x, y) * x * (1 - x) * y * (1 - y)).scalar.bind(x=x, y=y)  # hard u = 0 on the boundary
pde = -jno.np.vector(κ * u.x, κ * u.y).div(x, y) - f  # -div(κ grad u) = f
# --8<-- [end:residual]

# --8<-- [start:solve]
crux = jno.core([pde.mse])
fine = jno.shape.rect(0, 0, 1, 1, size=0.0125).domain()  # the network is a function: draw it on a finer mesh
epochs = np.unique(np.round(np.geomspace(1, EPOCHS, 100)).astype(int))
frames = [np.asarray(crux.eval([u], domain=fine)[0]).ravel()]  # the untrained network
for done, upto in zip([0, *epochs[:-1]], epochs):  # train in chunks, a snapshot after each
    crux.solve(int(upto - done), log=False)
    frames.append(np.asarray(crux.eval([u], domain=fine)[0]).ravel())

xs, ys, u_ref = (np.asarray(v).ravel() for v in crux.eval([x, y, u_exact], domain=fine))
rel_l2 = float(np.linalg.norm(frames[-1] - u_ref) / np.linalg.norm(u_ref))  # reference: the u_exact above
near = np.abs(xs + ys - 1) < 0.1 * 2**0.5  # within 0.1 of the diagonal where κ jumps
rel_jump = float(np.linalg.norm((frames[-1] - u_ref)[near]) / np.linalg.norm(u_ref[near]))
print(f"Relative L2 error: {rel_l2:.4e} everywhere, {rel_jump:.4e} within 0.1 of the jump in κ")
assert rel_l2 < 0.1, f"relative L2 error too large: {rel_l2:.3e}"
# --8<-- [end:solve]
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/variable_coefficient_poisson_2d.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "variable_coefficient_poisson_2d.npz",
        x=xs,
        y=ys,
        u=np.array(frames, dtype=np.float32),
        exact=u_ref,
        epochs=np.array([0, *epochs]),
        rel_l2=rel_l2,
        rel_jump=rel_jump,
    )
