{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Axisymmetric cavity resonator\n",
    "\n",
    "A closed metal can of radius $R=50$ mm and height $H=80$ mm (a pillbox cavity) is a body of\n",
    "revolution: its fields are sums of azimuthal modes\n",
    "$\\mathbf E(r,\\varphi,z)=\\big(E_r,E_\\varphi,E_z\\big)(r,z)\\,e^{im\\varphi}$, and each order $m$ is a\n",
    "2D problem on the meridian plane $(r,z)$, a rectangle. The resonances solve\n",
    "\n",
    "$$\\nabla\\times\\nabla\\times\\mathbf E=k^2\\mathbf E,\\qquad k=\\omega/c,\\qquad \\mathbf n\\times\\mathbf E=0\\ \\text{on the walls}.$$\n",
    "\n",
    "Two formulations of `FrequencyDomainMaxwell` are used:\n",
    "\n",
    "* for $m=0$ the field splits into TE$_{0np}$ modes with only $E_\\varphi$ (polarization `Ephi`)\n",
    "  and TM$_{0np}$ modes with only $H_\\varphi$ (polarization `Hphi`), one scalar each on Lagrange\n",
    "  elements;\n",
    "* for any $m$ the polarization `Erphiz` solves all three components: Nédélec elements for\n",
    "  $(E_r,E_z)$ and Lagrange elements for $rE_\\varphi$. The gradient fields of zero frequency are\n",
    "  exact in this pair of spaces and `electromagnetic_modes` projects them out, so every computed\n",
    "  mode is a physical one.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| `walls` (side wall, end plates) | perfect electric conductor, $\\mathbf n\\times\\mathbf E=0$ |\n",
    "| axis $r=0$ | regular: $rE_\\varphi=0$, and $E_z=0$ for $m\\neq0$ |\n",
    "\n",
    "**Reference.** J. D. Jackson, *Classical Electrodynamics*, 3rd ed., §8.7; D. M. Pozar, *Microwave\n",
    "Engineering*, 4th ed., §6.3. The modes of the cylinder resonate at\n",
    "\n",
    "$$f_{mnp}=\\frac{c}{2\\pi}\\sqrt{\\Big(\\frac{x_{mn}}{R}\\Big)^2+\\Big(\\frac{p\\pi}{H}\\Big)^2},$$\n",
    "\n",
    "with $x_{mn}=j'_{mn}$, the zeros of $J_m'$, and $p\\geq1$ for TE$_{mnp}$, and $x_{mn}=j_{mn}$, the\n",
    "zeros of $J_m$, and $p\\geq0$ for TM$_{mnp}$. The lowest are TM$_{010}$ at 2.295 GHz and TE$_{111}$\n",
    "at 2.569 GHz; TE$_{0np}$ and TM$_{1np}$ share their frequencies ($j'_{0n}=j_{1n}$)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials.electromagnetic import IsotropicElectromagneticMaterial\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange, Nedelec, RevolvedH1SpaceFactory\n",
    "from onesim.numerics.linear import ComplexSparseDirect\n",
    "from onesim.physics.electromagnetics import (\n",
    "    FrequencyDomainMaxwell,\n",
    "    PerfectElectricConductor,\n",
    "    electromagnetic_modes,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.special import j0, jn_zeros, jnp_zeros\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "The STEP file holds half of the cavity as a solid of revolution; `section` with the plane $y=0$\n",
    "returns the meridian rectangle with its metal sides named `walls`. Triangles of 5 mm, a tenth of\n",
    "the radius."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "part = load(\"axisymmetric_cavity_resonator.step\")\n",
    "plane = part.section((0, 1, 0))\n",
    "radius, height = plane.size[:2]\n",
    "mesh = TriangularMesher(target_size=radius / 10).generate(plane)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 6.5))\n",
    "plots.geometry(\n",
    "    part,\n",
    "    selection={\"metal walls\": part.boundaries.walls},\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=20, azimuth=-150),\n",
    "    title=\"Pillbox cavity, half (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Meridian plane: {mesh.cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Eigenfrequency study\n",
    "\n",
    "Five models on the same mesh: the scalar TE$_0$ and TM$_0$ families (quadratic Lagrange\n",
    "elements) and the vector field for $m=0,1,2$ (second-order Nédélec elements). Each is solved\n",
    "once and `electromagnetic_modes` returns every resonance between 1 and 6 GHz."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "light = 299792458.0\n",
    "lagrange = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2), provider=RevolvedH1SpaceFactory()),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "nedelec = lambda order: Numerics(\n",
    "    spatial=FiniteElement(\n",
    "        element=Nedelec(order=order), provider=RevolvedH1SpaceFactory()\n",
    "    ),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "model = lambda polarization, m=None: FrequencyDomainMaxwell(\n",
    "    domain=plane.domain(),\n",
    "    frequency=3e9,\n",
    "    material=IsotropicElectromagneticMaterial(),\n",
    "    polarization=polarization,\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    "    **({} if m is None else {\"azimuthal_mode\": m}),\n",
    ")\n",
    "study = lambda mm, numerics, grid=mesh, window=(1e9, 6e9): electromagnetic_modes(\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Pillbox cavity\",\n",
    "            geometry=plane,\n",
    "            physics=(mm,),\n",
    "            boundary_conditions=(\n",
    "                PerfectElectricConductor(physics=mm, boundary=plane.boundaries.walls),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=grid,\n",
    "        numerics=numerics,\n",
    "    ).solve_stationary(),\n",
    "    mm,\n",
    "    frequency_range=window,\n",
    ")\n",
    "models = {\n",
    "    \"TE0 (E_phi)\": model(\"Ephi\"),\n",
    "    \"TM0 (H_phi)\": model(\"Hphi\"),\n",
    "    **{f\"m = {m}\": model(\"Erphiz\", m) for m in (0, 1, 2)},\n",
    "}\n",
    "modes = {\n",
    "    name: study(models[name], lagrange if name.startswith(\"T\") else nedelec(2))\n",
    "    for name in models\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Every family against the closed-form list of its window: TE$_0$ and TM$_0$ take the Bessel zeros\n",
    "of order zero; the vector model of order $m$ holds both, TE$_{mnp}$ and TM$_{mnp}$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "resonance = lambda x, p: light / (2 * np.pi) * np.hypot(x / radius, p * np.pi / height)\n",
    "te = lambda m: [\n",
    "    (f\"TE{m}{n + 1}{p}\", resonance(x, p))\n",
    "    for n, x in enumerate(jnp_zeros(m, 4))\n",
    "    for p in range(1, 6)\n",
    "]\n",
    "tm = lambda m: [\n",
    "    (f\"TM{m}{n + 1}{p}\", resonance(x, p))\n",
    "    for n, x in enumerate(jn_zeros(m, 4))\n",
    "    for p in range(0, 6)\n",
    "]\n",
    "analytic = {\n",
    "    \"TE0 (E_phi)\": te(0),\n",
    "    \"TM0 (H_phi)\": tm(0),\n",
    "    **{f\"m = {m}\": te(m) + tm(m) for m in (0, 1, 2)},\n",
    "}\n",
    "analytic = {\n",
    "    name: sorted(\n",
    "        [item for item in values if 1e9 <= item[1] <= 6e9], key=lambda item: item[1]\n",
    "    )\n",
    "    for name, values in analytic.items()\n",
    "}\n",
    "print(\n",
    "    f\"{'family':12s} {'modes found':>11s} {'expected':>9s} {'largest deviation':>18s}\"\n",
    ")\n",
    "for name in models:\n",
    "    exact = np.array([f for _, f in analytic[name]])\n",
    "    found = modes[name].resonance_frequencies\n",
    "    print(\n",
    "        f\"{name:12s} {modes[name].mode_count:11d} {len(exact):9d} {np.max(np.abs(found / exact - 1)) if len(found) == len(exact) else np.nan:18.1e}\"\n",
    "    )\n",
    "print()\n",
    "print(\n",
    "    f\"{'mode':8s} {'f computed [GHz]':>17s} {'f exact [GHz]':>14s} {'deviation':>10s}   (vector model, m = 0 and 1)\"\n",
    ")\n",
    "for name in (\"m = 0\", \"m = 1\"):\n",
    "    for (label, f0), f in list(zip(analytic[name], modes[name].resonance_frequencies))[\n",
    "        :7\n",
    "    ]:\n",
    "        print(f\"{label:8s} {f / 1e9:17.6f} {f0 / 1e9:14.6f} {f / f0 - 1:10.1e}\")\n",
    "print(\n",
    "    \"TE0 from E_phi against the TE modes of the vector model (m = 0):\",\n",
    "    f\"{np.max(np.abs(np.array(sorted(modes['TE0 (E_phi)'].resonance_frequencies)) / np.array(sorted(f for (label, _), f in zip(analytic['m = 0'], modes['m = 0'].resonance_frequencies) if label.startswith('TE'))) - 1)):.1e}\",\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Convergence of the elements\n",
    "\n",
    "The lowest TM$_{010}$ and TE$_{111}$ resonances on four meshes with first- and second-order\n",
    "Nédélec elements: the frequency error falls as $h^{2}$ and $h^{4}$, twice the order of the field\n",
    "error, the property of a Galerkin eigenvalue method."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "sizes = radius / np.array([2, 4, 8, 16])\n",
    "grids = {h: TriangularMesher(target_size=h).generate(plane) for h in sizes}\n",
    "errors = {\n",
    "    f\"{label}, Nedelec order {order}\": np.array(\n",
    "        [\n",
    "            abs(\n",
    "                study(\n",
    "                    model(\"Erphiz\", m), nedelec(order), grids[h], (0.9 * f0, 1.1 * f0)\n",
    "                ).resonance_frequencies[0]\n",
    "                / f0\n",
    "                - 1\n",
    "            )\n",
    "            for h in sizes\n",
    "        ]\n",
    "    )\n",
    "    for label, m, f0 in (\n",
    "        (\"TM010\", 0, resonance(jn_zeros(0, 1)[0], 0)),\n",
    "        (\"TE111\", 1, resonance(jnp_zeros(1, 1)[0], 1)),\n",
    "    )\n",
    "    for order in (1, 2)\n",
    "}\n",
    "for label, values in errors.items():\n",
    "    print(\n",
    "        f\"{label:24s} errors {' '.join(f'{v:.2e}' for v in values)}   observed order {np.polyfit(np.log(sizes), np.log(values), 1)[0]:.2f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Top: the electric field of four modes in the meridian plane (stored energy 1 J): TM$_{010}$, a\n",
    "uniform $E_z$ with the Bessel profile $J_0(j_{01}r/R)$; TE$_{011}$, an azimuthal $E_\\varphi$\n",
    "that vanishes on the axis and the walls; TM$_{011}$; and TE$_{111}$ ($m=1$), the mode with the\n",
    "field across the axis. Bottom: the computed frequencies of all families against the closed\n",
    "form, and the convergence of the elements."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "shown = [\n",
    "    (\"m = 0\", \"TM010\", 2),\n",
    "    (\"m = 0\", \"TE011\", 1),\n",
    "    (\"m = 0\", \"TM011\", None),\n",
    "    (\"m = 1\", \"TE111\", None),\n",
    "]\n",
    "nodes = np.asarray(mesh.coordinates)\n",
    "across = np.linspace(0, 1, 41)\n",
    "profile = np.abs(\n",
    "    modes[\"m = 0\"]\n",
    "    .mode(0)\n",
    "    .field(models[\"m = 0\"].electric_field)\n",
    "    .evaluate(\n",
    "        np.column_stack((0.999 * radius * across, np.full_like(across, height / 2)))\n",
    "    )[:, 2]\n",
    ")\n",
    "fig = plots.figure(2, 4, size=(24, 12))\n",
    "for panel, (name, label, component) in enumerate(shown):\n",
    "    index = [item[0] for item in analytic[name]].index(label)\n",
    "    field = modes[name].mode(index).field(models[name].electric_field).evaluate(nodes)\n",
    "    values = (\n",
    "        np.abs(field[:, component])\n",
    "        if component is not None\n",
    "        else np.sqrt(np.sum(np.abs(field) ** 2, axis=1))\n",
    "    )\n",
    "    plots.heatmap(\n",
    "        nodes[:, 0],\n",
    "        nodes[:, 1],\n",
    "        values,\n",
    "        triangles=np.asarray(mesh.cells),\n",
    "        length_unit=\"mm\",\n",
    "        xlabel=\"r [m]\",\n",
    "        ylabel=\"z [m]\",\n",
    "        label=(\n",
    "            (\"|E_r|\", \"|E_phi|\", \"|E_z|\")[component] + \" [V/m]\"\n",
    "            if component is not None\n",
    "            else \"|E| [V/m]\"\n",
    "        ),\n",
    "        title=f\"{label}, {modes[name].resonance_frequencies[index] / 1e9:.3f} GHz\",\n",
    "        ax=fig[panel],\n",
    "    )\n",
    "plots.line(\n",
    "    points={\n",
    "        name: (\n",
    "            np.array([f for _, f in analytic[name]]) / 1e9,\n",
    "            modes[name].resonance_frequencies / 1e9,\n",
    "        )\n",
    "        for name in models\n",
    "    },\n",
    "    reference={\"computed = exact\": (np.array([1.0, 6.0]), np.array([1.0, 6.0]))},\n",
    "    markers=True,\n",
    "    xlabel=\"closed-form frequency [GHz]\",\n",
    "    ylabel=\"computed frequency [GHz]\",\n",
    "    title=\"Every mode from 1 to 6 GHz\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[4],\n",
    ")\n",
    "plots.convergence(\n",
    "    sizes * 1e3,\n",
    "    errors,\n",
    "    order=(2, 4),\n",
    "    xlabel=\"element size h [mm]\",\n",
    "    ylabel=\"relative frequency error\",\n",
    "    title=\"Convergence of the elements\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[5],\n",
    ")\n",
    "plots.bars(\n",
    "    [name.replace(\" (\", \"\\n(\") for name in models],\n",
    "    {\"modes found\": [modes[name].mode_count for name in models]},\n",
    "    reference={\"closed form\": [len(analytic[name]) for name in models]},\n",
    "    ylabel=\"modes between 1 and 6 GHz\",\n",
    "    title=\"No spurious modes\",\n",
    "    ax=fig[6],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"TM010 |E_z|, computed\": (across, profile / profile[0])},\n",
    "    reference={\"J0(j01 r / R)\": (across, j0(jn_zeros(0, 1)[0] * across))},\n",
    "    xlabel=\"r / R\",\n",
    "    ylabel=\"E_z / E_z(axis)\",\n",
    "    title=\"TM010 radial profile at mid-height\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[7],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise `azimuthal_mode` to follow the families of higher $m$ (each 3D mode with $m\\neq0$ is a\n",
    "pair, $\\cos m\\varphi$ and $\\sin m\\varphi$), or add a dielectric puck on the axis to the STEP\n",
    "file: the TM$_{010}$ mode is pulled down most, since its electric field is strongest there."
   ]
  }
 ]
}
