{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Resonances of a rectangular PEC cavity\n",
    "\n",
    "A closed, air-filled box of size $a\\times b\\times d$ bounded on all six faces\n",
    "by perfect electric conductors is excited by a short current pulse. After the\n",
    "pulse has ended the field rings freely; the electric field at a probe point is\n",
    "recorded and Fourier transformed, and the spectral peaks are the cavity\n",
    "resonances.\n",
    "\n",
    "The time-domain Maxwell equations are advanced with OneSimulation's Yee\n",
    "scheme (electric field on edges, magnetic flux on faces, second-order\n",
    "leapfrog in time):\n",
    "\n",
    "$$\\varepsilon_0\\,\\partial_t\\mathbf{E}=\\nabla\\times\\mathbf{H}-\\mathbf{J},\\qquad\n",
    "  \\mu_0\\,\\partial_t\\mathbf{H}=-\\nabla\\times\\mathbf{E}.$$\n",
    "\n",
    "**Reference.** The resonances of a rectangular cavity are\n",
    "\n",
    "$$f_{mnp}=\\frac{c}{2}\\sqrt{\\Big(\\frac{m}{a}\\Big)^2+\\Big(\\frac{n}{b}\\Big)^2+\\Big(\\frac{p}{d}\\Big)^2},$$\n",
    "\n",
    "where at most one index may vanish. With $b<a<d$ the fundamental is TE$_{101}$,\n",
    "followed by TE$_{102}$ and TE$_{201}$. We check the first resonances of the\n",
    "spectrum against these closed forms and confirm that the discrete scheme\n",
    "conserves the electromagnetic energy during the ring-down."
   ],
   "id": "a001df9c"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "from math import pi, sqrt\n",
    "\n",
    "import numpy as np\n",
    "from onesim.materials import VACUUM_PERMEABILITY, VACUUM_PERMITTIVITY\n",
    "from onesim.meshing.meshes import staggered\n",
    "from onesim.numerics.discretization import StaggeredLocation\n",
    "from onesim.numerics.time import StaggeredVerlet\n",
    "from onesim.physics.electromagnetics import DEFAULT_ELECTROMAGNETICS_PROVIDER_REGISTRY\n",
    "from onesim.physics.electromagnetics.waves import YeeDiscretization\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.signal import find_peaks\n",
    "\n",
    "theme.set()"
   ],
   "id": "d8fae555"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Parameters\n",
    "\n",
    "The cavity is 50 mm x 20 mm x 60 mm, so TE101 resonates at about 3.90 GHz,\n",
    "TE102 at 5.83 GHz and TE201 at 6.50 GHz. The grid spacing of 2.5 mm resolves\n",
    "the shortest wavelength of interest (46 mm at 6.5 GHz) with 18 cells."
   ],
   "id": "21b06510"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "a = 0.050\n",
    "b = 0.020\n",
    "d = 0.060\n",
    "cells = (20, 8, 24)\n",
    "c0 = 1.0 / sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)\n",
    "\n",
    "\n",
    "def f_mnp(m, n, p):\n",
    "    return 0.5 * c0 * sqrt((m / a) ** 2 + (n / b) ** 2 + (p / d) ** 2)\n",
    "\n",
    "\n",
    "modes = sorted(\n",
    "    (f_mnp(m, n, p), f\"{m}{n}{p}\")\n",
    "    for m in range(3)\n",
    "    for n in range(2)\n",
    "    for p in range(4)\n",
    "    if sum(index > 0 for index in (m, n, p)) >= 2\n",
    ")\n",
    "reference = modes[:3]\n",
    "for f_ref, label in reference:\n",
    "    print(f\"f_{label} = {f_ref / 1e9:.4f} GHz\")\n",
    "\n",
    "node_axes = tuple(\n",
    "    np.linspace(0.0, extent, count + 1) for extent, count in zip((a, b, d), cells)\n",
    ")\n",
    "time_step = 4e-12\n",
    "pulse_duration = 0.5e-9\n",
    "sample_interval = 20e-12\n",
    "samples = 2000\n",
    "\n",
    "\n",
    "def yee_solver(final_time):\n",
    "    return DEFAULT_ELECTROMAGNETICS_PROVIDER_REGISTRY.create(\n",
    "        \"electromagnetics.maxwell_time_domain\",\n",
    "        mesh=staggered(node_axes=node_axes, periodic=False),\n",
    "        spatial=YeeDiscretization(),\n",
    "        time_integrator=StaggeredVerlet(),\n",
    "        permittivity=VACUUM_PERMITTIVITY,\n",
    "        permeability=VACUUM_PERMEABILITY,\n",
    "        final_time=final_time,\n",
    "        time_step=time_step,\n",
    "    )"
   ],
   "id": "fd21a9b4"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Excitation and ring-down\n",
    "\n",
    "A Gaussian-derivative current pulse (centre 0.2 ns, width 40 ps, spectrum\n",
    "peaking near 4 GHz) is injected as J_y in a small blob off the symmetry planes\n",
    "of the cavity so that several low modes are excited. The field state after the\n",
    "pulse is then advanced in short segments of 20 ps and E_y is sampled at a probe\n",
    "point after each segment."
   ],
   "id": "12df5329"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "pulse_centre, pulse_width = 0.2e-9, 0.04e-9\n",
    "source_x, source_z = 0.3 * a, 0.3 * d\n",
    "\n",
    "\n",
    "def current_density_y(time, points):\n",
    "    envelope = (\n",
    "        -(time - pulse_centre)\n",
    "        / pulse_width\n",
    "        * np.exp(-0.5 * ((time - pulse_centre) / pulse_width) ** 2)\n",
    "    )\n",
    "    blob = np.exp(\n",
    "        -((points[..., 0] - source_x) ** 2 + (points[..., 2] - source_z) ** 2)\n",
    "        / 0.004**2\n",
    "    )\n",
    "    return envelope * blob\n",
    "\n",
    "\n",
    "pulse = yee_solver(pulse_duration)\n",
    "state = pulse.run(current_density=(0.0, current_density_y, 0.0))\n",
    "print(f\"Pulse: {state.step_count} steps, injected energy {state.source_work:.3e} J\")\n",
    "\n",
    "segment = yee_solver(sample_interval)\n",
    "ey_axes = segment.grid.axes(StaggeredLocation(\"edge\", 1))\n",
    "probe = tuple(\n",
    "    int(np.argmin(np.abs(axis - target)))\n",
    "    for axis, target in zip(ey_axes, (0.65 * a, 0.5 * b, 0.7 * d))\n",
    ")\n",
    "print(\n",
    "    \"Probe at x = {:.1f} mm, y = {:.2f} mm, z = {:.1f} mm\".format(\n",
    "        *(1e3 * axis[index] for axis, index in zip(ey_axes, probe))\n",
    "    )\n",
    ")\n",
    "\n",
    "electric, magnetic, charge = state.electric, state.magnetic, state.charge_density\n",
    "signal = np.empty(samples)\n",
    "energy_start = None\n",
    "for i in range(samples):\n",
    "    state = segment.run(\n",
    "        initial_electric=electric, initial_magnetic=magnetic, initial_charge=charge\n",
    "    )\n",
    "    electric, magnetic, charge = state.electric, state.magnetic, state.charge_density\n",
    "    signal[i] = electric[1][probe]\n",
    "    energy_start = state.initial_energy if energy_start is None else energy_start\n",
    "energy_drift = abs(state.final_energy / energy_start - 1.0)\n",
    "times = pulse_duration + sample_interval * np.arange(1, samples + 1)\n",
    "print(\n",
    "    f\"Ring-down: {samples} samples over {sample_interval * samples * 1e9:.0f} ns, relative energy drift {energy_drift:.1e}\"\n",
    ")"
   ],
   "id": "652cb16c"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the closed-form resonances\n",
    "\n",
    "The ring-down is Hann-windowed and zero-padded; the spectral peaks below\n",
    "7 GHz are compared with f_101, f_102 and f_201 in order of frequency."
   ],
   "id": "36b12baa"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "padding = 16 * samples\n",
    "spectrum = np.abs(np.fft.rfft(signal * np.hanning(samples), padding))\n",
    "frequencies = np.fft.rfftfreq(padding, sample_interval)\n",
    "spectrum /= spectrum.max()\n",
    "band = frequencies < 7e9\n",
    "peaks, _ = find_peaks(spectrum[band], prominence=0.05)\n",
    "f_peaks = frequencies[band][peaks]\n",
    "print(\"Spectral peaks below 7 GHz:\", \", \".join(f\"{f / 1e9:.4f} GHz\" for f in f_peaks))\n",
    "\n",
    "errors = []\n",
    "for (f_ref, label), f_num in zip(reference, f_peaks):\n",
    "    errors.append(abs(f_num / f_ref - 1.0))\n",
    "    print(\n",
    "        f\"TE{label}: computed {f_num / 1e9:.4f} GHz, reference {f_ref / 1e9:.4f} GHz, deviation {100 * errors[-1]:.2f} %\"\n",
    "    )"
   ],
   "id": "0791ffd2"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ],
   "id": "9982e389"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "show = frequencies < 9e9\n",
    "fig = plots.figure(1, 2, size=(12, 4.8))\n",
    "plots.line(\n",
    "    times * 1e9,\n",
    "    signal / np.max(np.abs(signal)),\n",
    "    xlimits=(0, 8),\n",
    "    xlabel=\"time [ns]\",\n",
    "    ylabel=\"E_y at the probe / max\",\n",
    "    title=\"Ring-down of the cavity after the current pulse\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    frequencies[show] / 1e9,\n",
    "    {\"OneSimulation probe spectrum\": spectrum[show]},\n",
    "    vlines={f\"closed form {label}\": f_ref / 1e9 for f_ref, label in modes[:6]},\n",
    "    xlimits=(2, 9),\n",
    "    ylimits=(0, 1.1),\n",
    "    xlabel=\"frequency [GHz]\",\n",
    "    ylabel=\"|FFT| / max\",\n",
    "    title=\"Resonance spectrum and closed-form mode frequencies\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "id": "73bd6a1c"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Move the source off the mid-plane in y to excite the TE011 and TE111 modes as\n",
    "well, halve the grid spacing to shrink the small numerical red shift of the\n",
    "peaks, or fill the cavity with a dielectric (`permittivity=eps_r*eps_0`) and\n",
    "watch every resonance scale with $1/\\sqrt{\\varepsilon_r}$."
   ],
   "id": "c3c79cfc"
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 }
}
