import os
from pathlib import Path

# --8<-- [start:code]
"""Four optimisers, one PINN: Poisson -Δu = f on the unit square with a thin ring layer and a fast ripple in u."""

import foundax
import jax
import numpy as np
import optax

import jno

jax.config.update("jax_enable_x64", True)  # the quasi-Newton phases need float64
run = jno.setup(__file__)
π, sin, tanh = jno.np.pi, jno.np.sin, jno.np.tanh
STEPS, WARM, CHUNK = 4000, 3200, 80  # the same budget for every optimiser; a snapshot every CHUNK steps

# --8<-- [start:setup]
d = jno.shape.rect(0, 0, 1, 1).structured(n=80).domain()
x, y, _ = d.variable("interior", split=True)
bubble = x * (1 - x) * y * (1 - y)

ring = tanh((0.09 - ((x - 0.5) ** 2 + (y - 0.5) ** 2)) / 0.01)  # a step across the circle r = 0.3, about 0.017 wide
u_exact = sin(π * x) * sin(π * y) * (0.6 + 0.4 * ring) + 0.05 * sin(8 * π * x) * sin(8 * π * y)
ue = u_exact.scalar.bind(x=x, y=y)
f = -(ue.xx + ue.yy)  # the forcing that makes u_exact the solution
# --8<-- [end:setup]

# --8<-- [start:runs]
rate = lambda n: optax.exponential_decay(3e-3, n // 3, 0.5, end_value=1e-5)
runs = {  # name -> [(optimizer, steps), ...]
    "Adam": [(optax.adam(rate(STEPS)), STEPS)],
    "SOAP": [(jno.optimizers.soap(rate(STEPS)), STEPS)],
    "SS-ESOAP": [(jno.optimizers.ss_esoap(rate(STEPS)), STEPS)],
    "Adam, then SSBroyden": [(optax.adam(rate(WARM)), WARM), (jno.optimizers.ssbroyden(), STEPS - WARM)],
}

fine = jno.shape.rect(0, 0, 1, 1).structured(n=128).domain()  # where the snapshots are drawn
snapshots, errors = {}, {}
for name, stages in runs.items():
    net = jno.nn(foundax.mlp(2, hidden_dims=40, num_layers=3, activation=jax.nn.tanh, key=jax.random.PRNGKey(0)))
    u = (net(x, y) * bubble).scalar.bind(x=x, y=y)  # hard u = 0 on the boundary
    crux = jno.core([(-(u.xx + u.yy) - f).mse], domain=d)
    snapshots[name] = []
    for optimizer, steps in stages:
        net.optimizer(optimizer)
        for _ in range(steps // CHUNK):
            crux.solve(CHUNK, log=False)
            snapshots[name].append(np.asarray(crux.eval([u], domain=fine)[0]).ravel())
    u_h, u_ref = (np.asarray(v).ravel() for v in crux.eval([u, u_exact]))
    errors[name] = float(np.linalg.norm(u_h - u_ref) / np.linalg.norm(u_ref))  # reference: the u_exact above
    print(f"{name:22s} rel-L2 = {errors[name]:.2e}")
# --8<-- [end:runs]

assert max(errors["SS-ESOAP"], errors["Adam, then SSBroyden"]) < 0.5 * errors["Adam"]  # the curvature-aware ones win
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/optimizer_comparison_2d.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):
    xs, ys, ref = (np.asarray(v).ravel() for v in crux.eval([x, y, u_exact], domain=fine))
    np.savez_compressed(
        Path(out) / "optimizer_comparison_2d.npz",
        x=xs,
        y=ys,
        exact=ref,
        names=list(runs),
        frames=np.array([snapshots[n] for n in runs], dtype=np.float32),  # (optimiser, snapshot, node)
        steps=CHUNK * (1 + np.arange(STEPS // CHUNK)),
        errors=[errors[n] for n in runs],
    )
