# --8<-- [start:code]
"""A struck drum: the 2-D wave equation on a disk, second order in time.

A round membrane clamped on its rim, struck off-centre with a narrow smooth bump and released from rest:

    u_tt = c^2 Delta u ,   u = 0 on the rim ,   u(t=0) = exp(-|x - x0|^2 / (2 s^2)) ,   u_t(t=0) = 0 .

Many modes ring at once, so ripples travel, reflect off the rim and interfere. The exact solution is the
Bessel series  u = sum J_m(k_mn r) a_mn cos(m theta) cos(c k_mn t),  J_m(k_mn) = 0, with a_mn the projection
of the bump onto the modes. The second time derivative ``u.tt`` is reduced to the first-order system
[u, u_t] and marched with the energy-conserving trapezoidal rule (backward Euler would damp the waves).
"""

import jax
import numpy as np
from scipy.special import jn_zeros, jv

import jno

jax.config.update("jax_enable_x64", True)  # u_tt: float32 gets the wave frequencies wrong
run = jno.setup(__file__)
C, S, R0 = 1.0, 0.1, 0.45  # wave speed, width of the strike, its distance from the centre
T, STEPS = 2.0, 476  # two diameters of travel: reflections and interference

d = jno.shape.disk(0, 0, 1, size=0.015).domain(time=(0.0, T, STEPS + 1))
x, y, t = d.variable("interior", split=True)
b = d.variable("boundary", split=True)
ci = d.variable("initial", split=True)
u = d.unknown()
v = u.test()
ub, vb = u.bind(x=x, y=y, t=t), v.bind(x=x, y=y, t=t)
grad = lambda w: jno.np.jacobian(w, [x, y])

fem = jno.fem(
    [
        ub.tt * vb + C**2 * jno.np.inner(grad(u), grad(v)),  # int u_tt phi + c^2 grad u . grad phi = 0
        u(*b) - 0.0,
        u(*ci) - jno.np.exp(-((ci[0] - R0) ** 2 + ci[1] ** 2) / (2 * S**2)),  # the strike
        u.bind(x=ci[0], y=ci[1], t=ci[2]).t - 0.0,  # released from rest
    ]
)
assert fem.is_transient and fem.is_linear

N = fem.offsets[1]  # the state is [u; u_t]: displacement first
sol = fem.solve()
U = np.asarray(jno.core([sol.mse]).eval([sol]))[:, :N]  # (steps + 1, N)
ts = np.linspace(fem.t0, fem.t1, len(U))
pts = np.asarray(fem.points)[:, :2]


def bessel_series(points, times, kmax=80.0):
    """The exact u at `points` and `times`: modes J_m(k r) cos(m theta), coefficients by quadrature."""
    r, th = np.hypot(*points.T), np.arctan2(points[:, 1], points[:, 0])
    rq, wq = np.polynomial.legendre.leggauss(600)  # radial quadrature on [0, 1]
    rq, wq = 0.5 * (rq + 1), 0.5 * wq
    thq = np.linspace(0, 2 * np.pi, 512, endpoint=False)
    f = np.exp(-((rq[:, None] * np.cos(thq) - R0) ** 2 + (rq[:, None] * np.sin(thq)) ** 2) / (2 * S**2))
    out = np.zeros((len(times), len(points)))
    for m in range(int(kmax * R0) + 12):
        k = jn_zeros(m, int(kmax / np.pi) + 2)
        k = k[k < kmax]
        Fm = f @ np.cos(m * thq) * (2 * np.pi / len(thq))  # int f cos(m theta) d theta, per radius
        norm = (2 * np.pi if m == 0 else np.pi) * 0.5 * jv(m + 1, k) ** 2
        a = (jv(m, k[None] * rq[:, None]) * (Fm * rq * wq)[:, None]).sum(0) / norm
        modes = jv(m, k[None] * r[:, None]) * np.cos(m * th)[:, None] * a  # (points, modes)
        out += np.cos(C * np.outer(times, k)) @ modes.T
    return out


# the reference: the series reproduces the strike itself, then the solution at a few times
ref = bessel_series(pts, ts[[0, STEPS // 4, STEPS // 2, STEPS]])
strike = np.exp(-((pts[:, 0] - R0) ** 2 + pts[:, 1] ** 2) / (2 * S**2))
trunc = np.linalg.norm(ref[0] - strike) / np.linalg.norm(strike)
errs = [np.linalg.norm(U[i] - r) / np.linalg.norm(r) for i, r in zip([0, STEPS // 4, STEPS // 2, STEPS], ref)]
print(f"Struck drum: dofs={fem.dofs}, {STEPS} steps to t={T}; series truncation (t=0): {trunc:.1e}")
print(
    "  FEM vs Bessel series, rel L2 at t = "
    + ", ".join(f"{ts[i]:.1f}: {e:.1e}" for i, e in zip([0, STEPS // 4, STEPS // 2, STEPS], errs))
)
assert trunc < 1e-4 and errs[-1] < 0.05, f"drum does not follow the Bessel series: {errs[-1]:.2e}"
# --8<-- [end:code]

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

if out := os.environ.get("JNO_FIGURE_DATA"):
    keep = np.arange(0, len(U), 4)
    np.savez_compressed(
        Path(out) / "wave_membrane_2d.npz",
        points=pts,
        triangles=np.asarray(d.mesh_connectivity["triangles"]),
        u=U[keep].astype(np.float32),
        t=ts[keep],
    )
