import os
from pathlib import Path

# --8<-- [start:code]
"""2-D Allen-Cahn equation, u_t = ε² Δu + u - u³ + f: a thin circular front that shrinks, a manufactured solution."""

import foundax
import jax
import numpy as np
import optax

import jno

run = jno.setup(__file__)
tanh, sqrt = jno.np.tanh, jno.np.sqrt
ε, T = 0.03, 1.0

# --8<-- [start:setup]
d = jno.shape.rect(0, 0, 1, 1, size=0.025).domain(time=(0, T, 21))
x, y, t = d.variable("interior")
x0, y0, t0 = d.variable("initial")
xb, yb, tb = d.variable("boundary")

front = lambda x, y, t: tanh((0.4 - 0.2 * t - sqrt((x - 0.5) ** 2 + (y - 0.5) ** 2 + 1e-9)) / (2**0.5 * ε))
u_exact = front(x, y, t)  # +1 inside a circle whose radius shrinks from 0.4 to 0.2, -1 outside; the front is ~0.04 wide
ue = u_exact.scalar.bind(x=x, y=y, t=t)
f = ue.t - ε**2 * (ue.xx + ue.yy) - ue + ue**3  # makes u_exact a solution
# --8<-- [end:setup]

# --8<-- [start:net]
net = jno.nn(
    foundax.deeponet(
        n_sensors=1, coord_dim=2, n_outputs=1, n_layers=4, basis_functions=64, hidden_dim=64, key=jax.random.PRNGKey(42)
    )
)
net.optimizer(optax.adam(optax.warmup_cosine_decay_schedule(0.0, 2e-3, 10, 12_000, 1e-5)))
# --8<-- [end:net]

# --8<-- [start:residual]
u = net(t, jno.np.concat([x, y])).scalar.bind(x=x, y=y, t=t)
pde = u.t - ε**2 * (u.xx + u.yy) - u + u**3 - f
ini = u(x0, y0, t0) - front(x0, y0, t0)  # the same field at t = 0
bc = u(xb, yb, tb) - front(xb, yb, tb)  # and on the sides, where the front has not arrived
# --8<-- [end:residual]

# --8<-- [start:solve]
crux = jno.core([pde.mse, ini.mse, bc.mse])
crux.solve(12_000)

# the whole space-time field on a finer grid than the collocation points, against the exact front
N_T = 41
fine = jno.shape.rect(0, 0, 1, 1, size=0.0125).domain(time=(0, T, N_T))
xs, ys, u_h, u_ref = (np.asarray(v)[0, :, :, 0] for v in crux.eval([x, y, u, u_exact], domain=fine, min_consecutive=N_T))
rel_l2 = float(np.linalg.norm(u_h - u_ref) / np.linalg.norm(u_ref))
radius = 0.4 - 0.2 * np.linspace(0, T, N_T)[:, None]
near = np.abs(np.hypot(xs - 0.5, ys - 0.5) - radius) < 0.06  # within 0.06 of the front
rel_front = float(np.linalg.norm((u_h - u_ref)[near]) / np.linalg.norm(u_ref[near]))
print(f"Relative L2 error: {rel_l2:.4e} everywhere, {rel_front:.4e} within 0.06 of the front")
assert rel_l2 < 0.3, f"relative L2 error too large: {rel_l2:.3e}"  # reference: the tanh front above
# --8<-- [end:solve]
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/allen_cahn_2d.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "allen_cahn_2d.npz",
        x=xs[0],
        y=ys[0],
        t=np.linspace(0, T, N_T),
        u=u_h.astype(np.float32),
        exact=u_ref.astype(np.float32),
        rel_l2=rel_l2,
        rel_front=rel_front,
    )
