import os
from pathlib import Path

import numpy as np

# --8<-- [start:code]
"""Fredholm integral equation of the second kind, u(x) = f(x) + x ∫₀¹ t u(t) dt, solved with a PINN."""

import foundax
import jax
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.01).domain()
x, _ = d.variable("interior")
f = sin(π * x) - x / π  # chosen so that u = sin(πx) solves it
# --8<-- [end:setup]

# --8<-- [start:model]
net = jno.nn(foundax.mlp(in_features=1, hidden_dims=64, num_layers=4, activation=jax.nn.tanh, key=jax.random.PRNGKey(0)))
net.optimizer(optax.adam(optax.exponential_decay(1e-3, 5_000, 0.5, end_value=1e-5)))
# --8<-- [end:model]

# --8<-- [start:residual]
u = net(x)
C = (x * u).integrate()  # ∫₀¹ t u(t) dt: one number, whatever x is
residual = u - f - x * C
# --8<-- [end:residual]

# --8<-- [start:solve]
crux = jno.core([residual.mse])
crux.solve(50_000)

u_h, u_ref = crux.eval([u, sin(π * x)])
rel_l2 = float(jax.numpy.linalg.norm(u_h - u_ref) / jax.numpy.linalg.norm(u_ref))  # reference: sin(πx)
print(f"Relative L2 error: {rel_l2:.4e}")
assert rel_l2 < 0.05, f"relative L2 error too large: {rel_l2:.3e}"
# --8<-- [end:solve]
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/fredholm_integral_equation.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):  # the same training again, in chunks, for the animation
    fine = jno.Path(0.0, 0.0).line_to(1.0, 0.0).curve(size=0.002).domain()
    single = np.asarray(crux.eval([u], domain=fine)[0]).ravel()  # the single call, on the fine grid
    net = jno.nn(
        foundax.mlp(in_features=1, hidden_dims=64, num_layers=4, activation=jax.nn.tanh, key=jax.random.PRNGKey(0))
    )
    net.optimizer(optax.adam(optax.exponential_decay(1e-3, 5_000, 0.5, end_value=1e-5)))
    u = net(x)
    crux = jno.core([(u - f - x * (x * u).integrate()).mse])
    epochs = np.unique(np.round(np.geomspace(1, 50_000, 100)).astype(int))
    frames = [np.asarray(crux.eval([u], domain=fine)[0]).ravel()]  # the untrained network
    xs = np.asarray(crux.eval([x], domain=fine)[0]).ravel()
    for done, upto in zip([0, *epochs[:-1]], epochs):
        crux.solve(int(upto - done), log=False)
        frames.append(np.asarray(crux.eval([u], domain=fine)[0]).ravel())
    print(f"chunked run vs single call on the fine grid: max |difference| = {np.abs(frames[-1] - single).max():.2e}")
    np.savez_compressed(
        Path(out) / "fredholm_integral_equation.npz", x=xs, u=np.array(frames), epochs=np.array([0, *epochs])
    )
