import os
from pathlib import Path

# --8<-- [start:code]
"""A lossy load in a microwave oven: the 2.45 GHz field heats it, the heat raises its loss, hot spots run away."""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
C0, EPS0, MU0 = 299792458.0, 8.8541878128e-12, 4e-7 * np.pi  # SI units: m, s, W, J, K
W = 2 * np.pi * 2.45e9  # the source: time dependence exp(-i W t)
K0 = W / C0
LC, HC, A_G, L_G = 0.30, 0.26, 0.086, 0.10  # cavity (x, y), guide width and length (m)
XL, YL, RL = 0.15, 0.13, 0.04  # the load, a disk (m)
E0 = 1.0e4  # amplitude of the guide mode that the port launches (V/m)
T0 = 293.15  # initial temperature and temperature of the air around the load (K)
RHO_C, K_TH, H_LOSS = (
    3.5e6,
    0.5,
    10.0,
)  # load: heat capacity (J/(m^3 K)), conductivity (W/(m K)); loss to the air (W/(m^2 K))
EPS_R0, DEPS_R, EPS_I0, DT_E = 40.0, 0.05, 0.3, 60.0  # eps' = EPS_R0 - DEPS_R dT, eps'' = EPS_I0 exp(dT / DT_E)
T_END, STEPS, SIZE_AIR, SIZE_LOAD = 480.0, 80, 0.006, 0.003
KX = np.sqrt(K0**2 - (np.pi / A_G) ** 2)  # propagation constant of the guide's one mode
mode = lambda y, y0: jno.np.sin(np.pi * (y - y0) / A_G)  # E_z of that mode across the guide, which starts at y0

cavity = jno.shape.rect(0, 0, LC, HC) | jno.shape.rect(-L_G, (HC - A_G) / 2, 0, (HC + A_G) / 2)
load = jno.shape.disk(XL, YL, RL, size=SIZE_LOAD)
d = (load.name("load").attach(chi=1.0) + (cavity - load).sized(SIZE_AIR).name("air").attach(chi=0.0)).domain(
    time=(0.0, T_END, STEPS + 1)
)
x, y, t = d.variable("interior", split=True)
port, wet, ci = (
    d.variable("port", where=lambda x, y: x < -L_G + 1e-9, split=True),
    d.variable("air|load", split=True),
    d.variable("initial", split=True),
)
Y0, Y1, TOL = (HC - A_G) / 2, (HC + A_G) / 2, 1e-9
on = lambda a, b: abs(a - b) < TOL
metal = lambda x, y: (
    (on(x, 0) & ((y < Y0 - TOL) | (y > Y1 + TOL)))
    | on(y, 0)
    | on(y, HC)
    | on(x, LC)
    | ((x < TOL) & (on(y, Y0) | on(y, Y1)))
)
wall = d.variable("wall", where=metal, split=True)  # the metal: cavity outline and guide sides

Er, Ei = d.unknown.scalar(order=2, name="Er"), d.unknown.scalar(order=2, name="Ei")  # E_z = Er + i Ei, everywhere
T = d.unknown.scalar(name="T", region="load")  # the temperature, in the load only
vr, vi, s = Er.test(), Ei.test(), T.test()
Erb, Eib, vrb, vib = (f.bind(x=x, y=y) for f in (Er, Ei, vr, vi))
Erp, Eip, vrp, vip = (f.bind(x=port[0], y=port[1]) for f in (Er, Ei, vr, vi))
Tb, sb, Tw, sw = T.bind(x=x, y=y, t=t), s.bind(x=x, y=y), T.bind(x=wet[0], y=wet[1]), s.bind(x=wet[0], y=wet[1])
dot = lambda f, g: f.x * g.x + f.y * g.y

dT = Tb - T0
eps_r = 1 + d.chi * (EPS_R0 - 1 - DEPS_R * dT)  # eps': 1 in the air
eps_i = d.chi * EPS_I0 * jno.np.exp(dT / DT_E)  # eps'': the loss, only in the load, growing with temperature
Q = 0.5 * W * EPS0 * eps_i * (Erb**2 + Eib**2)  # absorbed power density, W/m^3
E_in = E0 * mode(port[1], Y0)

fem = jno.fem(
    [
        dot(Erb, vrb) - K0**2 * (eps_r * Erb - eps_i * Eib) * vrb,  # div grad E + k0^2 (eps' + i eps'') E = 0,
        dot(Eib, vib) - K0**2 * (eps_r * Eib + eps_i * Erb) * vib,  # real and imaginary parts
        KX * Eip * vrp,  # the port, matched to the guide mode: dE/dn - i kx E = -2 i kx E_in
        -KX * (Erp - 2 * E_in) * vip,
        Er(*wall) - 0.0,  # metal: E_z = 0
        Ei(*wall) - 0.0,
        d.chi * (RHO_C * Tb.t * sb + K_TH * dot(Tb, sb)) - Q * sb,  # rho c T_t = div(k grad T) + Q, in the load
        H_LOSS * (Tw - T0) * sw,  # heat lost through the load's surface
        T(*ci) - T0,
    ],
    quad_degree=4,
)
traj = np.asarray(fem.solve(nonlinear=jno.solve.newton(direct=True), linear=jno.solve.lu(backend="host")).eval())
Ere, Eim, temp = (traj[:, fem.blocks[fem.block_index(f)]] for f in (Er, Ei, T))

# the checks: rows of a weak term sum to its integral (the test functions sum to one)
row = lambda e, k: np.asarray(fem.eval(e, traj[k])).sum()
P_in = E0**2 * KX * A_G / (4 * W * MU0)  # W per metre of height: the guide mode's power
absorbed = lambda k: row(Q * sb, k)
stored = lambda k: row(d.chi * RHO_C * (Tb - T0) * sb, k)
lost = lambda k: row(H_LOSS * (Tw - T0) * sw, k)
reflected = lambda k: (
    (row((Erp - E_in) * mode(port[1], Y0) * vrp, k) ** 2 + row(Eip * mode(port[1], Y0) * vrp, k) ** 2)
    / (E0 * A_G / 2) ** 2
    * P_in
)
dt = T_END / STEPS
heat_err = max(abs(absorbed(k) - (stored(k) - stored(k - 1)) / dt - lost(k)) / absorbed(k) for k in range(1, STEPS + 1))
port_err = max(abs(absorbed(k) + reflected(k) - P_in) / P_in for k in range(1, STEPS + 1))
print(f"{fem.dofs} DOFs, {STEPS} steps of {dt:g} s; incident {P_in:.0f} W/m")
print(
    f"absorbed {absorbed(1):.0f} -> {absorbed(STEPS):.0f} W/m; hottest node {temp[0].max() - 273.15:.0f} -> {temp[STEPS].max() - 273.15:.0f} C"
)
print(f"heat balance {heat_err:.1e}, port balance {port_err:.1e}")
assert heat_err < 1e-6 and port_err < 5e-3
# the reference: the same terms in a straight guide that ends in a metal wall behind a lossy slab. The field is a
# sine in the slab (complex wavenumber k1) and two travelling waves before it, so it is known exactly, and so is the reflection
L_AIR, L_SLAB, EPS_SLAB = 0.10, 0.04, 35.0 + 6.0j
slab, air = jno.shape.rect(L_AIR, 0, L_AIR + L_SLAB, A_G), jno.shape.rect(0, 0, L_AIR, A_G)
g = (slab.name("slab").attach(chi=1.0) + air.name("air").attach(chi=0.0)).sized(0.004).domain()
gx, gy, _ = g.variable("interior", split=True)
gp = g.variable("port", where=lambda x, y: x < TOL, split=True)
gw = g.variable("wall", where=lambda x, y: on(y, 0) | on(y, A_G) | on(x, L_AIR + L_SLAB), split=True)
a, b = g.unknown.scalar(order=2, name="Ar"), g.unknown.scalar(order=2, name="Ai")
va, vb = a.test(), b.test()
ab, bb, vab, vbb = (f.bind(x=gx, y=gy) for f in (a, b, va, vb))
ap, bp, vap, vbp = (f.bind(x=gp[0], y=gp[1]) for f in (a, b, va, vb))
er, ei = 1 + g.chi * (EPS_SLAB.real - 1), g.chi * EPS_SLAB.imag
ref = jno.fem(
    [
        dot(ab, vab) - K0**2 * (er * ab - ei * bb) * vab,
        dot(bb, vbb) - K0**2 * (er * bb + ei * ab) * vbb,
        KX * bp * vap,
        -KX * (ap - 2 * E0 * mode(gp[1], 0.0)) * vbp,
        a(*gw) - 0.0,
        b(*gw) - 0.0,
    ],
    quad_degree=4,
)
sol = np.asarray(ref.solve(linear=jno.solve.lu(backend="host")))
pts, Eh = np.asarray(ref.field_points[0])[:, :2], sol[ref.blocks[0]] + 1j * sol[ref.blocks[1]]
k1 = np.sqrt(K0**2 * EPS_SLAB - (np.pi / A_G) ** 2)
rho = (1j * KX + k1 / np.tan(k1 * L_SLAB)) / (1j * KX - k1 / np.tan(k1 * L_SLAB))  # reflection, from E'/E at the slab
inc, refl = (
    np.exp(1j * KX * (pts[:, 0] - L_AIR)) * np.exp(1j * KX * L_AIR),
    rho * np.exp(-1j * KX * (pts[:, 0] - L_AIR)) * np.exp(1j * KX * L_AIR),
)
first = inc + refl
Ex = np.where(
    pts[:, 0] <= L_AIR + TOL,
    first,
    (1 + rho) * np.exp(1j * KX * L_AIR) * np.sin(k1 * (L_AIR + L_SLAB - pts[:, 0])) / np.sin(k1 * L_SLAB),
)
Ex = E0 * Ex * np.sin(np.pi * pts[:, 1] / A_G)
slab_row = lambda e: np.asarray(ref.eval(e, sol)).sum()
slab_abs = slab_row(0.5 * W * EPS0 * ei * (ab**2 + bb**2) * vab)
guide_err = np.linalg.norm(Eh - Ex) / np.linalg.norm(Ex)
absorbed_err = abs(slab_abs / (P_in * (1 - abs(rho) ** 2)) - 1)
print(
    f"straight guide with a lossy slab, {ref.dofs} DOFs: field error {guide_err:.1e}, absorbed power vs P_in(1 - |R|^2) {absorbed_err:.1e}"
)
assert guide_err < 2e-3 and absorbed_err < 5e-3
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/microwave_oven_runaway.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):
    mesh = d.built_mesh
    np.savez_compressed(
        Path(out) / "microwave_oven_runaway.npz",
        points=np.asarray(fem.field_points[fem.block_index(Er)])[:, :2],  # the P2 nodes of E
        mesh_points=mesh.points[:, :2],
        triangles=mesh.cells_dict["triangle"],
        points_T=np.asarray(fem.field_points[fem.block_index(T)])[:, :2],
        Er=Ere.astype(np.float32),
        Ei=Eim.astype(np.float32),
        T=temp.astype(np.float32),
        t=np.linspace(0.0, T_END, STEPS + 1),
        geometry=[LC, HC, A_G, L_G, XL, YL, RL, T0],
        absorbed=[absorbed(k) for k in range(1, STEPS + 1)],
        incident=P_in,
    )
