import os
from pathlib import Path

# --8<-- [start:code]
"""Gradient and sensitivity analysis of a PINN with jno.callbacks: gradient conflict, neural tangent kernel, scale."""

import foundax
import jax
import numpy as np
import optax

import jno

run = jno.setup(__file__)
π, sin = jno.np.pi, jno.np.sin

# --8<-- [start:setup]
d = jno.Path(0.0, 0.0).line_to(1.0, 0.0).curve(size=0.001).domain()
x, _ = d.variable("interior")
xl, _ = d.variable("left", where=lambda x: x < 0.5)  # the two halves of the domain, as two loss terms
xr, _ = d.variable("right", where=lambda x: x >= 0.5)
u_exact = sin(π * x) / π**2  # for the check only, not used in training

u_net = jno.nn(foundax.mlp(in_features=1, hidden_dims=32, num_layers=3, key=jax.random.PRNGKey(0)))
u_net.optimizer(optax.adam(1e-3))
field = lambda x: (u_net(x) * x * (1 - x)).scalar.bind(x=x)  # hard u(0) = u(1) = 0
u = field(x)
pde = lambda x: -field(x).xx - sin(π * x)  # -u'' = sin(πx)
# --8<-- [end:setup]

# --8<-- [start:callbacks]
conflict = jno.callbacks.cos_similarity(interval=100)  # cosine similarity between the gradients of the loss terms
alignment = jno.callbacks.gradient_alignment(interval=100)  # and the total alignment of all of them
ntk = jno.callbacks.ntk_spectrum(u.grad(u_net), n_points=512, top_k=10, interval=500)  # K = J Jᵀ of the network

crux = jno.core([pde(xl).mse, pde(xr).mse])
crux.solve(5000, log=1000, callbacks=[conflict, alignment, ntk])
# --8<-- [end:callbacks]

u_h, u_ref = crux.eval([u, u_exact])
rel_l2 = float(np.linalg.norm(u_h - u_ref) / np.linalg.norm(u_ref))
print(f"Relative L² error: {rel_l2:.3e}")
assert rel_l2 < 1e-1, f"solution error too large: {rel_l2:.3e}"

# --8<-- [start:ntk]
cos_track = conflict.result["cos_sim_matrix"][:, 0, 1]  # left gradient vs right gradient, every 100 epochs
cos_sim = float(cos_track[-1])
print(f"cos_sim (left vs right gradient) = {cos_sim:.4f}, total alignment = {alignment.result['alignment'][-1]:.4f}")
assert -1.0 <= cos_sim <= 1.0

eigs = np.sort(ntk.result["all_eigvals"][-1])[::-1].clip(0)  # the NTK spectrum at the last sample
eff_rank = float(eigs.sum() ** 2 / ((eigs**2).sum() + 1e-12))  # participation ratio
cond = float(ntk.result["condition_number"][-1])
print(
    f"NTK {eigs.size}×{eigs.size}: λ_max = {eigs[0]:.4f}, λ_min = {eigs[-1]:.4f}, eff. rank = {eff_rank:.2f}, cond = {cond:.1e}"
)
# --8<-- [end:ntk]

# --8<-- [start:scale]
# Scale conflict, the twin: the terms of ONE residual on a thin domain (Lx = 1, Ly = 1/20) differ by (Lx/Ly)².
Lx, Ly, U = 1.0, 0.05, 3.0
ad = jno.shape.rect(0.0, 0.0, Lx, Ly, size=0.1).domain()
ax, ay, _ = ad.variable("interior", split=True)
ax, ay = ax.unit("m").scale(Lx), ay.unit("m").scale(Ly)  # characteristic lengths
au = jno.nn(foundax.mlp(in_features=2, hidden_dims=8, num_layers=2, key=jax.random.PRNGKey(1)))(ax, ay)
au = au.unit("K").scale(U).scalar.bind(x=ax, y=ay)  # and a characteristic temperature
aniso = au.xx + au.yy

assert not jno.units.check(aniso).warnings  # both terms are K·m⁻²
terms = jno.units.nondimensionalize(aniso).residuals[0].terms
scale_sep = terms[1].pi / terms[0].pi
print(f"scale separation = {scale_sep:.0f}×   (= (Lx/Ly)² = {(Lx / Ly) ** 2:.0f})")
assert abs(scale_sep - (Lx / Ly) ** 2) < 1e-6

transformed, rescaler = jno.units.rescale(aniso)  # the residual in O(1) form, and the map back to physical units
assert rescaler.field_scale == U
assert float(rescaler.to_physical(1.0)) == U
# --8<-- [end:scale]
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/gradient_conflict.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):
    xs, us = (np.asarray(v).ravel() for v in crux.eval([x, u]))
    np.savez_compressed(
        Path(out) / "gradient_conflict.npz",
        x=xs,
        u=us,
        u_exact=np.asarray(u_ref).ravel(),
        eigs=np.asarray(eigs),
        cos_track=cos_track,
        cos_epochs=conflict.result["epochs"],
        cos_sim=cos_sim,
        eff_rank=eff_rank,
        cond=cond,
        rel_l2=rel_l2,
    )
