# --8<-- [start:code]
"""A sound pulse in a two-layer room: Q5 spectral elements on hexahedra, marched explicitly.

The scalar wave equation  u_tt = div(c^2 grad u)  in the unit cube with rigid walls (the natural condition,
du/dn = 0). A Mexican-hat pulse (a positive core in a negative shell) starts at rest in the lower layer, where
c = 1; above z = 1/2 the sound is twice as fast. The pulse spreads as a sphere, part of it reflects at the
interface and part is refracted into the fast layer, where the wavefront runs ahead of the sphere that made it.

Q5 elements on 8 x 8 x 8 hexahedra: the Gauss-Lobatto-Legendre rule at the nodes makes the mass matrix
diagonal, so the fourth-order Runge-Kutta march needs one stiffness application per stage and solves nothing,
and ``matrix_free=True`` never stores the stiffness.
"""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
SIGMA, SRC, N, ORDER = 0.08, (0.5, 0.5, 0.36), 8, 5  # pulse width and place, cells per side, degree


def march(n, order, T, steps, c2, u0, ts):
    """Explicit march of u_tt = div(c2 grad u) on n^3 Q_order hexahedra; the state [u, u_t] at the times ts."""
    d = jno.shape.box(0, 0, 0, 1, 1, 1).structured(n=n).quad().domain(time=(0.0, T, steps))
    x, y, z, t = d.variable("interior", split=True)
    ci = d.variable("initial", split=True)
    u = d.unknown(order=order)
    v = u.test()
    ui, vi = u.bind(x=x, y=y, z=z, t=t), v.bind(x=x, y=y, z=z, t=t)
    c2 = c2(z) if callable(c2) else c2
    fem = jno.fem(
        [
            ui.tt * vi + c2 * (ui.x * vi.x + ui.y * vi.y + ui.z * vi.z),  # int u_tt phi + c^2 grad u . grad phi = 0
            u(*ci) - u0(*ci[:3]),  # the pulse ...
            u.bind(x=ci[0], y=ci[1], z=ci[2], t=ci[3]).t - 0.0,  # ... at rest
        ],
        quadrature="gll",  # diagonal mass
        matrix_free=True,  # the stiffness is applied, never stored
    )
    Y = np.asarray(fem.solve(time=jno.solve.erk("rk4"), save_ts=ts).fn())
    return np.asarray(fem.points)[:, :3], Y[:, : fem.offsets[1]], Y[:, fem.offsets[1] :]


ricker = lambda s2: (1 - s2 / SIGMA**2) * jno.np.exp(-s2 / (2 * SIGMA**2))  # the Mexican hat in s2 = s^2
pulse = lambda s: lambda x, y, z: ricker((x - s[0]) ** 2 + (y - s[1]) ** 2 + (z - s[2]) ** 2)
layers = lambda z: 1 + 1.5 * (1 + jno.np.tanh((z - 0.5) / 0.02))  # c^2: 1 below z = 1/2, 4 above, over ~0.04

# 1. Standing wave of the rigid box, cos(pi x) cos(pi y) cos(pi z) cos(sqrt(3) pi t): error against the degree
mode = lambda x, y, z: jno.np.cos(np.pi * x) * jno.np.cos(np.pi * y) * jno.np.cos(np.pi * z)
for order in (4, 6, 8):
    P, U, _ = march(2, order, 0.3, 301, 1.0, mode, np.array([0.3]))
    exact = np.prod(np.cos(np.pi * P), axis=1) * np.cos(np.sqrt(3) * np.pi * 0.3)
    print(f"standing wave, 2^3 cells, Q{order}: max error {abs(U[-1] - exact).max():.1e}")
assert abs(U[-1] - exact).max() < 1e-9  # Q8

# 2. The point-like pulse in a uniform medium against the spherical wave, before it reaches a wall
T0, C0 = 0.08, (0.45, 0.5, 0.55)
for order in (4, 5, 6):
    P, U, _ = march(N, order, T0, 201, 1.0, pulse(C0), np.array([T0]))
    r, h = np.linalg.norm(P - C0, axis=1), lambda s: (1 - s**2 / SIGMA**2) * np.exp(-(s**2) / (2 * SIGMA**2))
    exact = ((r - T0) * h(r - T0) + (r + T0) * h(r + T0)) / (2 * r)  # d'Alembert for r u in three dimensions
    err = abs(U[-1] - exact).max() / abs(exact).max()
    print(f"spherical pulse at t = {T0}, {N}^3 cells, Q{order}: max error {err:.1e} of the peak {abs(exact).max():.2f}")
assert err < 1e-3  # Q6

# 3. The two layers, 0.6 time units: energy of the explicit march
T, STEPS = 0.6, 1201
ts = np.linspace(0, T, 61)
P, U, V = march(N, ORDER, T, STEPS, layers, pulse(SRC), ts)
d = jno.shape.box(0, 0, 0, 1, 1, 1).structured(n=N).quad().domain()
x, y, z = d.variable("interior", split=True)[:3]
u = d.unknown(order=ORDER)
ui, vi = u.bind(x=x, y=y, z=z), u.test().bind(x=x, y=y, z=z)
stiffness = jno.fem([layers(z) * (ui.x * vi.x + ui.y * vi.y + ui.z * vi.z)], quadrature="gll", matrix_free=True)
mass = jno.fem([ui * vi], quadrature="gll", matrix_free=True)
(K, _), (M, _) = stiffness.operator, mass.operator
w = np.asarray(M.diag())
E = np.array([0.5 * (w * V[i] ** 2).sum() + 0.5 * U[i] @ np.asarray(K @ U[i]) for i in range(len(ts))])
drift = abs(E / E[0] - 1).max()
print(
    f"two layers: {len(P)} DOFs, energy drift over {STEPS - 1} steps {drift:.1e}, peak |u| at the end {abs(U[-1]).max():.3f}"
)
assert drift < 1e-6
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/spectral_wave_layers_3d.py), only when asked ----
import os  # noqa: E402
from pathlib import Path  # noqa: E402

from scipy.interpolate import CubicSpline  # noqa: E402

if out := os.environ.get("JNO_FIGURE_DATA"):
    axes = [np.unique(np.round(P[:, i], 12)) for i in range(3)]  # the node coordinates of the tensor grid
    ix = [np.searchsorted(a, np.round(P[:, i], 12)) for i, a in enumerate(axes)]
    grid = np.linspace(0, 1, 65)
    frames = np.empty((len(ts), 65, 65, 65), np.float32)
    for k in range(len(ts)):
        F = np.zeros([len(a) for a in axes])
        F[ix[0], ix[1], ix[2]] = U[k]
        for ax, a in enumerate(axes):  # separable cubic interpolation from the nodes to a uniform grid
            F = np.moveaxis(CubicSpline(a, F, axis=ax)(grid), ax, ax)
        frames[k] = F
    np.savez_compressed(Path(out) / "spectral_wave_layers_3d.npz", u=frames, t=ts, grid=grid, src=SRC)
