# --8<-- [start:code]
"""2D Helmholtz with a perfectly matched layer: a point source radiating into open space.

    -div(S grad u) - k^2 det(S) u = f ,   S = diag(Sy/Sx, Sx/Sy) ,   Sx = 1 + i sx/k ,   Sy = 1 + i sy/k

The PML is a complex coordinate stretch (sigma ramps up in a frame, 0 in the core), so the weak form has
complex coefficients and ``jno.fem`` solves its real-equivalent block. A converged PML leaves the core
field independent of the absorber strength sigma0: that is the check.
"""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)  # the real-equivalent block is float64
run = jno.setup(__file__)
L, w, k = 1.0, 0.25, 25.0  # box, PML frame width, wavenumber (~4 wavelengths across the core)
relu = lambda z: jno.np.maximum(z, 0.0)


def solve_pml(sigma0):  # sigma0 = 0: no PML, a u = 0 cavity
    d = jno.shape.rect(0, 0, L, L, size=0.01).domain()
    x, y, _ = d.variable("interior", split=True)
    b = d.variable("boundary", split=True)
    u = d.unknown.scalar()
    v = u.test()
    ub, vb = u.bind(x=x, y=y), v.bind(x=x, y=y)
    sx = sigma0 * (relu(w - x) ** 2 + relu(x - (L - w)) ** 2) / w**2  # quadratic profile, per axis
    sy = sigma0 * (relu(w - y) ** 2 + relu(y - (L - w)) ** 2) / w**2
    Sx, Sy = 1 + 1j * sx / k, 1 + 1j * sy / k  # the complex coordinate stretch
    f = jno.np.exp(-((x - 0.5) ** 2 + (y - 0.5) ** 2) / (2 * 0.025**2))  # a narrow Gaussian source
    weak = (Sy / Sx) * ub.x * vb.x + (Sx / Sy) * ub.y * vb.y - k**2 * Sx * Sy * ub * vb - f * vb
    fem = jno.fem([weak, u(*b) - 0.0], quad_degree=3)
    return fem, np.asarray(fem.solve())


fem, u_pml = solve_pml(40.0)
_, u_strong = solve_pml(60.0)  # 1.5x the absorber: the core must not change
_, u_off = solve_pml(0.0)  # no PML: the wave reflects off the walls
pts = np.asarray(fem.points)

core = (pts[:, 0] > w) & (pts[:, 0] < L - w) & (pts[:, 1] > w) & (pts[:, 1] < L - w)
sigma_insens = np.linalg.norm(u_pml[core] - u_strong[core]) / np.linalg.norm(u_pml[core])
print(f"Helmholtz + PML: dofs={fem.dofs}  core change, sigma0 40 -> 60: {sigma_insens:.3e}")
assert fem.is_complex and not np.isnan(u_pml).any()
assert sigma_insens < 1e-2, f"PML not reflection-free: {sigma_insens:.3e}"
# --8<-- [end:code]

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

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "helmholtz_pml_2d.npz",
        points=pts[:, :2],
        triangles=np.asarray(fem.domain.mesh_connectivity["triangles"]),
        u_pml=u_pml.astype(np.complex64),
        u_off=u_off.astype(np.complex64),
        geometry=np.array([L, w, k]),
    )
