{
 "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": [
    "# Q factors of axisymmetric cavity resonators\n",
    "\n",
    "The field of a body of revolution separates into azimuthal modes\n",
    "$\\mathbf E(r,\\varphi,z)=\\big(E_r,E_\\varphi,E_z\\big)(r,z)\\,e^{im\\varphi}$. For each whole number $m$\n",
    "the three components live on the meridian plane ($r$, $z$): `FrequencyDomainMaxwell` with the\n",
    "polarization `Erphiz` and `azimuthal_mode=m` solves them with Nédélec elements for $(E_r,E_z)$\n",
    "and Lagrange elements for $rE_\\varphi$, so that the gradient fields of zero frequency are exactly\n",
    "represented and projected out of the eigenvalue problem. A 3D mode with $m\\neq0$ appears twice\n",
    "($\\cos m\\varphi$ and $\\sin m\\varphi$); the meridian returns it once.\n",
    "\n",
    "The copper walls are a surface impedance $Z_s=(1-i)\\sqrt{\\omega\\mu_0/(2\\sigma)}$\n",
    "(`SurfaceImpedanceBoundary`), taken at the frequency of each resonance; the complex eigenfrequency\n",
    "gives the quality factor $Q=\\operatorname{Re}f/(2|\\operatorname{Im}f|)$.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| `walls` | surface impedance of copper, $\\sigma=5.8\\cdot10^7$ S/m |\n",
    "| axis $r=0$ | regular: $rE_\\varphi=0$, and $E_z=0$ for $m\\neq0$ |\n",
    "\n",
    "**Reference.** D. M. Pozar, *Microwave Engineering*, 4th ed., §6.3: a cylinder of radius $R$ and\n",
    "length $L$ resonates at $f_0=\\tfrac{c}{2\\pi}\\sqrt{(x/R)^2+(p\\pi/L)^2}$ with the Bessel zeros\n",
    "$x=j_{mn}$ (TM$_{mnp}$) and $x=j'_{mn}$ (TE$_{mnp}$, $p\\geq1$); for TM$_{010}$\n",
    "$Q_c=\\eta j_{01}/\\big(2R_s(1+R/L)\\big)$ and for TE$_{011}$\n",
    "\n",
    "$$Q_c=\\frac{(kR)^3\\,\\eta RL}{4\\,{j'_{01}}^2R_s}\\;\\frac{1}{RL/2+(\\beta R^2/j'_{01})^2},\\qquad\\beta=\\pi/L.$$\n",
    "\n",
    "R. F. Harrington, *Time-Harmonic Electromagnetic Fields*, §6-12: a sphere of radius $a$ resonates\n",
    "at the roots of $j_n(ka)=0$ (TE$_n$) and $[x\\,j_n(x)]'_{x=ka}=0$ (TM$_n$), $2n+1$ modes\n",
    "($m=-n\\ldots n$) at each, with $Q_c\\,\\delta/a=1$ (TE) and $1-n(n+1)/(ka)^2$ (TM). The walls lower\n",
    "each resonance to $f_0(1-1/(2Q_c))$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import VACUUM_PERMEABILITY, VACUUM_PERMITTIVITY\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, Nedelec, RevolvedH1SpaceFactory\n",
    "from onesim.numerics.linear import ComplexSparseDirect\n",
    "from onesim.physics.electromagnetics import (\n",
    "    FrequencyDomainMaxwell,\n",
    "    SurfaceImpedanceBoundary,\n",
    "    electromagnetic_modes,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.optimize import brentq\n",
    "from scipy.special import jn_zeros, jnp_zeros, spherical_jn\n",
    "\n",
    "theme.set()\n",
    "\n",
    "light = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)\n",
    "eta = np.sqrt(VACUUM_PERMEABILITY / VACUUM_PERMITTIVITY)\n",
    "copper = 5.8e7"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "The STEP files hold half of each cavity as a solid of revolution; `section` with the plane $y=0$\n",
    "returns the meridian planes, a rectangle and a half disc, with the face name `walls` on their\n",
    "metal sides. Triangles of 2.5 mm (cylinder) and 1 mm (sphere, to follow the circle closely)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "names = (\"cylindrical\", \"spherical\")\n",
    "parts = {name: load(f\"axisymmetric_cavity_q_factors_{name}.step\") for name in names}\n",
    "planes = {name: parts[name].section((0, 1, 0)) for name in names}\n",
    "meshes = {\n",
    "    \"cylindrical\": TriangularMesher(target_size=2.5e-3).generate(planes[\"cylindrical\"]),\n",
    "    \"spherical\": TriangularMesher(target_size=1e-3).generate(planes[\"spherical\"]),\n",
    "}\n",
    "\n",
    "fig = plots.figure(2, 2, size=(13, 12))\n",
    "for column, name in enumerate(names):\n",
    "    plots.geometry(\n",
    "        parts[name],\n",
    "        selection={\"copper walls\": parts[name].boundaries.walls},\n",
    "        labels=False,\n",
    "        camera=plots.Camera(elevation=20, azimuth=-150),\n",
    "        title=f\"{name.capitalize()} cavity, half (STEP)\",\n",
    "        ax=fig[column],\n",
    "    )\n",
    "    plots.mesh(\n",
    "        meshes[name],\n",
    "        groups=(\"all\",),\n",
    "        legend=False,\n",
    "        title=f\"Meridian plane: {meshes[name].cell_count} triangles\",\n",
    "        ax=fig[2 + column],\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Eigenfrequency study\n",
    "\n",
    "For each cavity and each order $m=0,1$: one model on the meridian, solved once, and every\n",
    "resonance between 4 and 9 GHz from `electromagnetic_modes`."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Nedelec(order=2), provider=RevolvedH1SpaceFactory()),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "model = lambda plane, m: FrequencyDomainMaxwell(\n",
    "    domain=plane.domain(),\n",
    "    frequency=6e9,\n",
    "    material=IsotropicElectromagneticMaterial(),\n",
    "    polarization=\"Erphiz\",\n",
    "    azimuthal_mode=m,\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    ")\n",
    "solve = lambda name, mm: Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"Copper cavity\",\n",
    "        geometry=planes[name],\n",
    "        physics=(mm,),\n",
    "        boundary_conditions=(\n",
    "            SurfaceImpedanceBoundary(\n",
    "                physics=mm, boundary=planes[name].boundaries.walls, conductivity=copper\n",
    "            ),\n",
    "        ),\n",
    "    ),\n",
    "    mesh=meshes[name],\n",
    "    numerics=numerics,\n",
    ").solve_stationary()\n",
    "models = {(name, m): model(planes[name], m) for name in names for m in (0, 1)}\n",
    "modes = {\n",
    "    key: electromagnetic_modes(\n",
    "        solve(key[0], models[key]), models[key], frequency_range=(4e9, 9e9)\n",
    "    )\n",
    "    for key in models\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Each computed mode is named by the nearest closed-form resonance of its family. Where a closed\n",
    "form of $Q_c$ is known, the frequency reference includes the shift by the walls."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "radius, length = planes[\"cylindrical\"].size[:2]\n",
    "sphere = planes[\"spherical\"].size[0]\n",
    "resistance = lambda f: np.sqrt(np.pi * f * VACUUM_PERMEABILITY / copper)\n",
    "cylinder = lambda x, p: light / (2 * np.pi) * np.hypot(x / radius, p * np.pi / length)\n",
    "te_root = {n: brentq(lambda x: spherical_jn(n, x), n + 2.5, n + 3.8) for n in (1, 2)}\n",
    "tm_root = {\n",
    "    n: brentq(\n",
    "        lambda x: spherical_jn(n, x) + x * spherical_jn(n, x, derivative=True),\n",
    "        n + 1.2,\n",
    "        n + 2.4,\n",
    "    )\n",
    "    for n in (1, 2)\n",
    "}\n",
    "j01, jp01 = jn_zeros(0, 1)[0], jnp_zeros(0, 1)[0]\n",
    "te011 = cylinder(jp01, 1)\n",
    "k011, beta = 2 * np.pi * te011 / light, np.pi / length\n",
    "families = {\n",
    "    (\"cylindrical\", 0): {\n",
    "        \"TM010\": (\n",
    "            cylinder(j01, 0),\n",
    "            eta * j01 / (2 * resistance(cylinder(j01, 0)) * (1 + radius / length)),\n",
    "        ),\n",
    "        \"TM011\": (cylinder(j01, 1), None),\n",
    "        \"TE011\": (\n",
    "            te011,\n",
    "            (k011 * radius) ** 3\n",
    "            * eta\n",
    "            * radius\n",
    "            * length\n",
    "            / (4 * jp01**2 * resistance(te011))\n",
    "            / (radius * length / 2 + (beta * radius**2 / jp01) ** 2),\n",
    "        ),\n",
    "        \"TM012\": (cylinder(j01, 2), None),\n",
    "    },\n",
    "    (\"cylindrical\", 1): {\n",
    "        \"TE111\": (cylinder(jnp_zeros(1, 1)[0], 1), None),\n",
    "        \"TM110\": (cylinder(jn_zeros(1, 1)[0], 0), None),\n",
    "        \"TM111\": (cylinder(jn_zeros(1, 1)[0], 1), None),\n",
    "        \"TE112\": (cylinder(jnp_zeros(1, 1)[0], 2), None),\n",
    "    },\n",
    "    **{\n",
    "        (\"spherical\", m): {\n",
    "            f\"TM n=1, m={m}\": (\n",
    "                light * tm_root[1] / (2 * np.pi * sphere),\n",
    "                tm_root[1]\n",
    "                * eta\n",
    "                / (2 * resistance(light * tm_root[1] / (2 * np.pi * sphere)))\n",
    "                * (1 - 2 / tm_root[1] ** 2),\n",
    "            ),\n",
    "            f\"TM n=2, m={m}\": (\n",
    "                light * tm_root[2] / (2 * np.pi * sphere),\n",
    "                tm_root[2]\n",
    "                * eta\n",
    "                / (2 * resistance(light * tm_root[2] / (2 * np.pi * sphere)))\n",
    "                * (1 - 6 / tm_root[2] ** 2),\n",
    "            ),\n",
    "            f\"TE n=1, m={m}\": (\n",
    "                light * te_root[1] / (2 * np.pi * sphere),\n",
    "                te_root[1]\n",
    "                * eta\n",
    "                / (2 * resistance(light * te_root[1] / (2 * np.pi * sphere))),\n",
    "            ),\n",
    "        }\n",
    "        for m in (0, 1)\n",
    "    },\n",
    "}\n",
    "print(\n",
    "    f\"{'cavity':12s} {'m':>2s} {'mode':14s} {'f computed [GHz]':>17s} {'f exact [GHz]':>14s} {'deviation':>10s} {'Q computed':>11s} {'Q exact':>9s} {'deviation':>10s}\"\n",
    ")\n",
    "for key, family in families.items():\n",
    "    for label, (f0, q0) in family.items():\n",
    "        index = int(np.argmin(np.abs(modes[key].resonance_frequencies - f0)))\n",
    "        f, q = (\n",
    "            modes[key].resonance_frequencies[index],\n",
    "            modes[key].quality_factors[index],\n",
    "        )\n",
    "        reference = f0 if q0 is None else f0 * (1 - 1 / (2 * q0))\n",
    "        print(\n",
    "            f\"{key[0]:12s} {key[1]:2d} {label:14s} {f / 1e9:17.5f} {reference / 1e9:14.5f} {f / reference - 1:10.1e} {q:11.0f} \"\n",
    "            + (f\"{q0:9.0f} {q / q0 - 1:10.1e}\" if q0 else f\"{'-':>9s} {'-':>10s}\")\n",
    "        )\n",
    "print(\n",
    "    \"modes found from 4 to 9 GHz:\",\n",
    "    {f\"{name} m={m}\": modes[name, m].mode_count for name, m in modes},\n",
    ")\n",
    "print(\n",
    "    \"sphere, m = 1 against m = 0, largest relative frequency difference:\",\n",
    "    f\"{np.max(np.abs(modes['spherical', 1].resonance_frequencies / modes['spherical', 0].resonance_frequencies - 1)):.1e}\",\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The magnitude of the electric field in the meridian plane (stored energy 1 J): TM$_{010}$ with\n",
    "$E_z$ along the axis, TE$_{011}$ with $E_\\varphi$ only, vanishing on the axis, and the $m=1$\n",
    "mode TE$_{111}$, the lowest-but-one resonance of the cylinder (sampled at the mesh nodes, pulled\n",
    "inside by 0.1 % so that nodes on the arc lie within the straight-sided triangles); the sphere's TM$_{n=1}$ mode for\n",
    "$m=0$ and $m=1$ (one frequency, two field patterns of the same family) and its TE$_{n=1}$ mode."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "shown = [\n",
    "    (\"cylindrical\", 0, \"TM010\"),\n",
    "    (\"cylindrical\", 0, \"TE011\"),\n",
    "    (\"cylindrical\", 1, \"TE111\"),\n",
    "    (\"spherical\", 0, \"TM n=1, m=0\"),\n",
    "    (\"spherical\", 1, \"TM n=1, m=1\"),\n",
    "    (\"spherical\", 0, \"TE n=1, m=0\"),\n",
    "]\n",
    "fig = plots.figure(2, 3, size=(18, 12))\n",
    "for panel, (name, m, label) in enumerate(shown):\n",
    "    index = int(\n",
    "        np.argmin(\n",
    "            np.abs(modes[name, m].resonance_frequencies - families[name, m][label][0])\n",
    "        )\n",
    "    )\n",
    "    nodes = np.asarray(meshes[name].coordinates)\n",
    "    field = modes[name, m].mode(index).field(models[name, m].electric_field)\n",
    "    plots.heatmap(\n",
    "        nodes[:, 0],\n",
    "        nodes[:, 1],\n",
    "        np.sqrt(np.sum(np.abs(field.evaluate((1 - 1e-3) * nodes)) ** 2, axis=1)),\n",
    "        triangles=np.asarray(meshes[name].cells),\n",
    "        label=\"|E| [V/m]\",\n",
    "        xlabel=\"r [m]\",\n",
    "        ylabel=\"z [m]\",\n",
    "        length_unit=\"mm\",\n",
    "        title=f\"{label}: {modes[name, m].resonance_frequencies[index] / 1e9:.3f} GHz, Q {modes[name, m].quality_factors[index]:.0f}\",\n",
    "        ax=fig[panel],\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise `azimuthal_mode` to 2 or 3 for the next families, or replace `SurfaceImpedanceBoundary` by\n",
    "`PerfectElectricConductor` on part of the walls to see how the losses of the end plates and the\n",
    "side wall add up: $1/Q_c$ is the sum of the contributions of each wall."
   ]
  }
 ]
}
