import os
from pathlib import Path

# --8<-- [start:code]
"""Transient heat equation, u_t = ν Δu on the unit square with u = 0 on the boundary, by finite differences.

The initial temperature is a rough patchwork of hot and cold spots: a sum of 64 sine modes with random
amplitudes. Each mode decays on its own, sin(mπx) sin(nπy) at the rate νπ²(m² + n²), so the exact solution
is the same sum with every amplitude multiplied by its exponential: the fine modes die first and the field
smooths into a single bump. A problem is transient when its term list carries an initial condition
``u(xi, yi) - u0``; ``jno.fdm`` then marches the semi-discrete system (method of lines) over the domain's
time window and returns the trajectory.
"""

import jax

jax.config.update("jax_enable_x64", True)

import numpy as np

import jno

run = jno.setup(__file__)
nu, T, steps = 0.02, 0.8, 400
modes = [(m, n) for m in range(1, 9) for n in range(1, 9)]
amp = 0.6 * np.random.default_rng(3).normal(size=len(modes)) / np.hypot(*np.array(modes).T) ** 0.5  # finer modes smaller
amp[0] = 3.0  # the slowest mode, (1, 1), is the bump that survives

d = jno.shape.rect(0, 0, 1, 1, size=0.02).domain(time=(0.0, T, steps))
x, y, t = d.variable("interior", split=True)
xb, yb, _ = d.variable("boundary", split=True)
xi, yi, _ = d.variable("initial", split=True)  # the t = 0 slice

u = d.unknown()
ui = u.bind(x=x, y=y, t=t)
u0 = sum(a * jno.np.sin(m * np.pi * xi) * jno.np.sin(n * np.pi * yi) for a, (m, n) in zip(amp, modes))

traj = np.asarray(jno.fdm([ui.t - nu * (ui.xx + ui.yy), u(xb, yb) - 0.0, u(xi, yi) - u0]).solve())  # (steps, nodes)


def exact(px, py, time):
    """The same sum of modes, each decayed by exp(-ν π² (m² + n²) t)."""
    return sum(
        a * np.exp(-nu * np.pi**2 * (m * m + n * n) * time) * np.sin(m * np.pi * px) * np.sin(n * np.pi * py)
        for a, (m, n) in zip(amp, modes)
    )


p = np.asarray(d.mesh_connectivity["points"])[:, :2]
times = np.linspace(0.0, T, steps)
for k in (steps // 40, steps - 1):  # early, while the fine modes still matter, and at the end
    ref = exact(p[:, 0], p[:, 1], times[k])
    rel_l2 = float(np.linalg.norm(traj[k] - ref) / np.linalg.norm(ref))
    print(f"Transient heat via jno.fdm: t = {times[k]:.2f}  rel_L2 = {rel_l2:.3e}")
    assert rel_l2 < 2e-2, f"relative L2 error too large at t = {times[k]:.2f}: {rel_l2:.3e}"
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/heat_2d_fdm.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):
    frames = np.unique(np.geomspace(1, steps, 90).astype(int) - 1)  # dense early, where the field changes fast
    np.savez_compressed(
        Path(out) / "heat_2d_fdm.npz",
        points=p,
        triangles=np.asarray(d.mesh_connectivity["triangles"]),
        u=traj[frames].astype(np.float32),
        t=times[frames],
    )
