# --8<-- [start:code]
"""Time-harmonic 2D Maxwell for the in-plane electric field E = (Ex, Ey): a complex curl-curl equation.

    curl(curl E) - k^2 E = J ,   k^2 = 30 + 4i   (complex: a lossy medium)

``complex=True`` makes E one complex symbol, so the weak form is written once with ordinary complex
algebra; ``weak.real`` lowers it onto two coupled real fields. A nodal discretisation needs a grad-div
penalty to remove the spurious curl kernel, consistent here because the exact field is divergence-free.
The check is a manufactured divergence-free E with Re(E) != Im(E): J = curl(curl E) - k^2 E in closed form.
"""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)  # the coupled real system is float64
run = jno.setup(__file__)
pi, KR, KI = np.pi, 30.0, 4.0
k2 = KR + 1j * KI

# manufactured divergence-free fields: Re(E) a curl eigenfield (2 pi^2), Im(E) a higher mode (8 pi^2);
# m is the namespace they are evaluated in: jno.np inside the weak form, numpy for the reference
E_re = lambda X, Y, m: (pi * m.sin(pi * X) * m.cos(pi * Y), -pi * m.cos(pi * X) * m.sin(pi * Y))
E_im = lambda X, Y, m: (2 * pi * m.sin(2 * pi * X) * m.cos(2 * pi * Y), -2 * pi * m.cos(2 * pi * X) * m.sin(2 * pi * Y))

d = jno.shape.rect(0, 0, 1, 1, size=0.025).domain()
x, y, _ = d.variable("interior", split=True)
xb, yb, _ = d.variable("boundary", split=True)
E = d.unknown.vector(2, order=2, complex=True)
v = E.test()
Eb, vb = E.bind(x=x, y=y), v.bind(x=x, y=y)

curl = lambda F: F.x[1] - F.y[0]  # dFy/dx - dFx/dy (grad-then-index)
div = lambda F: F.x[0] + F.y[1]

# J = curl(curl E) - k^2 E, component by component, as complex data
J = [
    jno.complex((2 * pi**2 - KR) * a + KI * c, (8 * pi**2 - KR) * c - KI * a)
    for a, c in zip(E_re(x, y, jno.np), E_im(x, y, jno.np))
]
weak = curl(Eb) * curl(vb) + KR * div(Eb) * div(vb) - k2 * Eb.dot(vb) - (J[0] * vb[0] + J[1] * vb[1])
er, ei = E_re(xb, yb, jno.np), E_im(xb, yb, jno.np)  # E = the exact field on the wall
fem = jno.fem(
    [
        weak.real,
        E.real(xb, yb) - er,
        E.imag(xb, yb) - ei,
    ],
    quad_degree=6,
)

sol = np.asarray(fem.solve()).reshape(-1)  # coupled real fields (Re E, Im E)
pts, n = np.asarray(fem.field_points[0]), int(fem.offsets[1])
E_h = sol[:n].reshape(-1, 2) + 1j * sol[n:].reshape(-1, 2)  # E at every node
E_ex = np.stack(E_re(pts[:, 0], pts[:, 1], np), 1) + 1j * np.stack(E_im(pts[:, 0], pts[:, 1], np), 1)
rel = np.linalg.norm(E_h - E_ex) / np.linalg.norm(E_ex)
print(f"Maxwell 2D: {fem.dofs} DOFs (4 real per node), L2 rel error vs manufactured E: {rel:.2e}")
assert rel < 2e-3, f"manufactured Maxwell not recovered: {rel:.2e}"
# --8<-- [end:code]

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

if out := os.environ.get("JNO_FIGURE_DATA"):
    mesh = d.built_mesh
    np.savez_compressed(
        Path(out) / "maxwell_2d_vector.npz",
        points=pts[:, :2],  # the P2 nodes
        mesh_points=mesh.points[:, :2],  # the P1 vertices of the triangulation
        triangles=mesh.cells_dict["triangle"],
        E=E_h.astype(np.complex64),
    )
