{
 "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 and resonant frequencies of cavity resonators\n",
    "\n",
    "A closed metal cavity stores electromagnetic energy at discrete resonance frequencies. In a\n",
    "real cavity the walls are not perfect conductors: the field penetrates a skin depth\n",
    "$\\delta=\\sqrt{2/(\\omega\\mu_0\\sigma)}$ into the metal and the wall currents dissipate power. The\n",
    "quality factor\n",
    "\n",
    "$$Q=\\omega\\,\\frac{\\text{stored energy}}{\\text{power lost per second}}=\\frac{\\operatorname{Re}f}{2\\,|\\operatorname{Im}f|}$$\n",
    "\n",
    "measures how many radians the field oscillates before its energy has dropped by $1/e$.\n",
    "\n",
    "For a good conductor the wall can be replaced by a boundary condition, the Leontovich surface\n",
    "impedance $\\mathbf E_t=Z_s\\,\\mathbf n\\times\\mathbf H$ with $Z_s=(1-i)R_s$, $R_s=\\sqrt{\\omega\\mu_0/(2\\sigma)}$\n",
    "(for the phasor convention $e^{-i\\omega t}$). `SurfaceImpedanceBoundary` applies it at the\n",
    "frequency of each resonance, and `electromagnetic_modes` solves the eigenvalue problem\n",
    "\n",
    "$$\\nabla\\times\\mu_0^{-1}\\nabla\\times\\mathbf E-\\omega^2\\varepsilon_0\\mathbf E=0,$$\n",
    "\n",
    "discretized with second-order Nédélec elements, by shift-invert about a target frequency. The\n",
    "gradient fields of zero frequency are projected out, so no spurious modes appear; because the\n",
    "surface impedance depends on $\\omega$, each complex resonance is refined by a fixed-point\n",
    "iteration in $\\omega$.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| `walls` of every cavity | surface impedance of copper, $\\sigma=5.8\\cdot10^7$ S/m |\n",
    "\n",
    "**Reference.** D. M. Pozar, *Microwave Engineering*, 4th ed., §6.3 and §6.4: the TE$_{101}$\n",
    "mode of an $a\\times b\\times d$ box resonates at $f=\\tfrac{c}{2}\\sqrt{a^{-2}+d^{-2}}$ with\n",
    "\n",
    "$$Q_c=\\frac{(kad)^3\\,b\\,\\eta}{2\\pi^2R_s}\\,\\frac{1}{2a^3b+2bd^3+a^3d+ad^3},$$\n",
    "\n",
    "the TM$_{010}$ mode of a cylinder of radius $R$ and length $L$ at $f=c\\,j_{01}/(2\\pi R)$ with\n",
    "$Q_c=\\eta\\,j_{01}/\\big(2R_s(1+R/L)\\big)$, $j_{01}=2.40483$. R. F. Harrington, *Time-Harmonic\n",
    "Electromagnetic Fields*, §6-12: the lowest mode of a sphere of radius $a$, TM$_{101}$ (three\n",
    "modes of the same frequency), has $ka=2.74371$, the root of $[x\\,j_1(x)]'=0$, and\n",
    "$Q_c\\,\\delta/a=1-2/(ka)^2$. The wall reactance, equal to the wall resistance, lowers every\n",
    "resonance of the perfectly conducting cavity, $f_0$, to $f=f_0\\,(1-1/(2Q_c))$ (Pozar §6.7,\n",
    "perturbation of the walls)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\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 TetrahedralMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Nedelec\n",
    "from onesim.numerics.linear import ComplexSparseDirect\n",
    "from onesim.physics.electromagnetics import (\n",
    "    FrequencyDomainMaxwell,\n",
    "    PerfectElectricConductor,\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 j0, jn_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",
    "`load` reads the air volume of each cavity. The box is meshed with straight tetrahedra; the\n",
    "cylinder and the sphere with curved (quadratic) tetrahedra whose edge midpoints lie on the CAD\n",
    "surface, so that the round walls are followed and not cut by chords."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "names = (\"rectangular\", \"cylindrical\", \"spherical\")\n",
    "cavities = {name: load(f\"cavity_resonator_q_factors_{name}.step\") for name in names}\n",
    "sizes = {\"rectangular\": 5e-3, \"cylindrical\": 6.25e-3, \"spherical\": 6.25e-3}\n",
    "meshes = {\n",
    "    name: TetrahedralMesher(\n",
    "        target_size=sizes[name], geometry_order=1 if name == \"rectangular\" else 2\n",
    "    ).generate(cavities[name])\n",
    "    for name in names\n",
    "}\n",
    "\n",
    "fig = plots.figure(2, 3, size=(18, 11))\n",
    "for column, name in enumerate(names):\n",
    "    plots.geometry(\n",
    "        cavities[name],\n",
    "        selection={\"copper walls\": cavities[name].boundaries.walls},\n",
    "        labels=False,\n",
    "        camera=plots.Camera(elevation=25, azimuth=-60),\n",
    "        title=f\"{name.capitalize()} cavity (STEP)\",\n",
    "        ax=fig[column],\n",
    "    )\n",
    "    plots.mesh(\n",
    "        meshes[name],\n",
    "        groups=(\"all\",),\n",
    "        legend=False,\n",
    "        title=f\"{meshes[name].cell_count} tetrahedra\",\n",
    "        ax=fig[3 + column],\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model and eigenfrequency study\n",
    "\n",
    "One `FrequencyDomainMaxwell` model per cavity, solved once near its expected resonance; the solved\n",
    "result carries the operator from which `electromagnetic_modes` builds the eigenvalue problem.\n",
    "The sphere is asked for three modes: TM$_{101}$ is threefold degenerate. Each cavity is solved\n",
    "with copper walls and, for comparison on the same mesh, with perfectly conducting walls."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "a, b, d = cavities[\"rectangular\"].size\n",
    "radius, length = cavities[\"cylindrical\"].size[0] / 2, cavities[\"cylindrical\"].size[2]\n",
    "sphere = cavities[\"spherical\"].size[0] / 2\n",
    "j01 = jn_zeros(0, 1)[0]\n",
    "x101 = brentq(\n",
    "    lambda x: spherical_jn(1, x) + x * spherical_jn(1, x, derivative=True), 2, 3.5\n",
    ")\n",
    "exact = {\n",
    "    \"rectangular\": light / 2 * np.hypot(1 / a, 1 / d),\n",
    "    \"cylindrical\": light * j01 / (2 * np.pi * radius),\n",
    "    \"spherical\": light * x101 / (2 * np.pi * sphere),\n",
    "}\n",
    "resistance = lambda f: np.sqrt(np.pi * f * VACUUM_PERMEABILITY / copper)\n",
    "k = {name: 2 * np.pi * exact[name] / light for name in names}\n",
    "quality = {\n",
    "    \"rectangular\": (k[\"rectangular\"] * a * d) ** 3\n",
    "    * b\n",
    "    * eta\n",
    "    / (2 * np.pi**2 * resistance(exact[\"rectangular\"]))\n",
    "    / (2 * a**3 * b + 2 * b * d**3 + a**3 * d + a * d**3),\n",
    "    \"cylindrical\": eta\n",
    "    * j01\n",
    "    / (2 * resistance(exact[\"cylindrical\"]) * (1 + radius / length)),\n",
    "    \"spherical\": x101 * eta / (2 * resistance(exact[\"spherical\"])) * (1 - 2 / x101**2),\n",
    "}\n",
    "\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Nedelec(order=2)), linear_solver=ComplexSparseDirect()\n",
    ")\n",
    "model = lambda part, frequency: FrequencyDomainMaxwell(\n",
    "    domain=part.volume,\n",
    "    frequency=frequency,\n",
    "    material=IsotropicElectromagneticMaterial(),\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    ")\n",
    "walls = {\n",
    "    \"copper\": lambda m, part: SurfaceImpedanceBoundary(\n",
    "        physics=m, boundary=part.boundaries.walls, conductivity=copper\n",
    "    ),\n",
    "    \"perfect\": lambda m, part: PerfectElectricConductor(\n",
    "        physics=m, boundary=part.boundaries.walls\n",
    "    ),\n",
    "}\n",
    "solve = lambda part, mesh, m, wall=\"copper\": Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"Metal cavity\",\n",
    "        geometry=part,\n",
    "        physics=(m,),\n",
    "        boundary_conditions=(walls[wall](m, part),),\n",
    "    ),\n",
    "    mesh=mesh,\n",
    "    numerics=numerics,\n",
    ").solve_stationary()\n",
    "models = {name: model(cavities[name], 0.95 * exact[name]) for name in names}\n",
    "modes = {\n",
    "    name: electromagnetic_modes(\n",
    "        solve(cavities[name], meshes[name], models[name]),\n",
    "        models[name],\n",
    "        mode_count=3 if name == \"spherical\" else 1,\n",
    "    )\n",
    "    for name in names\n",
    "}\n",
    "perfect = {\n",
    "    name: electromagnetic_modes(\n",
    "        solve(cavities[name], meshes[name], models[name], \"perfect\"),\n",
    "        models[name],\n",
    "        mode_count=3 if name == \"spherical\" else 1,\n",
    "    )\n",
    "    for name in names\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The lowest mode of each cavity against the closed-form frequency $f_0(1-1/(2Q_c))$ and the\n",
    "conductor $Q$ from the surface resistance. The wall reactance lowers the resonance by\n",
    "$f_0/(2Q_c)$, a few hundred kHz: on the same mesh the copper cavity resonates exactly that much\n",
    "below the perfectly conducting one, whose frequency carries the (larger) discretization error."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "lossy = {name: exact[name] * (1 - 1 / (2 * quality[name])) for name in names}\n",
    "print(\n",
    "    f\"{'cavity':12s} {'mode':6s} {'f computed [GHz]':>17s} {'f exact [GHz]':>14s} {'deviation':>10s} {'Q computed':>11s} {'Q exact':>9s} {'deviation':>10s}\"\n",
    ")\n",
    "for name, mode in zip(names, (\"TE101\", \"TM010\", \"TM101\")):\n",
    "    for f, q in zip(modes[name].resonance_frequencies, modes[name].quality_factors):\n",
    "        print(\n",
    "            f\"{name:12s} {mode:6s} {f / 1e9:17.6f} {lossy[name] / 1e9:14.6f} {f / lossy[name] - 1:10.1e} {q:11.0f} {quality[name]:9.0f} {q / quality[name] - 1:10.1e}\"\n",
    "        )\n",
    "for name in names:\n",
    "    shift = modes[name].resonance_frequencies - perfect[name].resonance_frequencies\n",
    "    print(\n",
    "        f\"{name:12s} perfect walls {perfect[name].resonance_frequencies[0] / 1e9:.6f} GHz (deviation {perfect[name].resonance_frequencies[0] / exact[name] - 1:.1e}); \"\n",
    "        f\"shift by copper {np.mean(shift) / 1e3:7.1f} kHz, closed form -f0/(2Q) = {-exact[name] / (2 * quality[name]) / 1e3:7.1f} kHz\"\n",
    "    )\n",
    "print(\n",
    "    \"fixed-point iterations per mode:\",\n",
    "    {name: list(modes[name].iterations) for name in names},\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Mesh study\n",
    "\n",
    "The rectangular cavity on four meshes. The frequency of the perfectly conducting cavity converges\n",
    "from above with about the fourth power of the element size (second-order elements, the square\n",
    "of the field error); each unstructured mesh scatters the error about this trend. $Q$, a ratio of\n",
    "a wall integral to a volume integral of the field, converges at a similar rate."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "grids = {\n",
    "    h: TetrahedralMesher(target_size=h).generate(cavities[\"rectangular\"])\n",
    "    for h in (15e-3, 10e-3, 7.5e-3, 5e-3)\n",
    "}\n",
    "study = {\n",
    "    (h, wall): electromagnetic_modes(\n",
    "        solve(cavities[\"rectangular\"], grids[h], models[\"rectangular\"], wall),\n",
    "        models[\"rectangular\"],\n",
    "        mode_count=1,\n",
    "    )\n",
    "    for h in grids\n",
    "    for wall in walls\n",
    "}\n",
    "steps = np.array(sorted(grids))\n",
    "frequency_error = np.array(\n",
    "    [\n",
    "        abs(study[h, \"perfect\"].resonance_frequencies[0] / exact[\"rectangular\"] - 1)\n",
    "        for h in steps\n",
    "    ]\n",
    ")\n",
    "quality_error = np.array(\n",
    "    [\n",
    "        abs(study[h, \"copper\"].quality_factors[0] / quality[\"rectangular\"] - 1)\n",
    "        for h in steps\n",
    "    ]\n",
    ")\n",
    "for h, ef, eq in zip(steps, frequency_error, quality_error):\n",
    "    print(f\"h = {1e3 * h:4.1f} mm: frequency error {ef:.2e}, Q error {eq:.2e}\")\n",
    "print(\n",
    "    f\"observed orders: frequency {np.polyfit(np.log(steps), np.log(frequency_error), 1)[0]:.2f}, \"\n",
    "    f\"Q {np.polyfit(np.log(steps), np.log(quality_error), 1)[0]:.2f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Top: the magnitude of the electric field of each mode on a plane through the cavity (normalized\n",
    "to a stored energy of 1 J): the half sines of TE$_{101}$ across the broad wall, the Bessel profile\n",
    "of TM$_{010}$ across the cylinder and one of the three TM$_{101}$ modes of the sphere; any\n",
    "combination of the three is a mode, so its axis takes an arbitrary direction. Bottom: the mesh\n",
    "study, the field profiles against the closed forms, and the relative deviations of all results."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "planes = {\n",
    "    \"rectangular\": Plane(origin=(a / 2, b / 2, d / 2), normal=(0, 1, 0)),\n",
    "    \"cylindrical\": Plane(origin=(0, 0, length / 2), normal=(0, 1, 0)),\n",
    "    \"spherical\": Plane(origin=(0, 0, 0), normal=(0, 1, 0)),\n",
    "}\n",
    "labels = (\"TE101\", \"TM010\", \"TM101\")\n",
    "across = np.linspace(0, 1, 61)\n",
    "profiles = {\n",
    "    \"TE101 |E_y| along x\": (\n",
    "        across,\n",
    "        np.abs(\n",
    "            modes[\"rectangular\"]\n",
    "            .mode(0)\n",
    "            .field(models[\"rectangular\"].electric_field)\n",
    "            .evaluate(\n",
    "                np.column_stack(\n",
    "                    (\n",
    "                        across * a,\n",
    "                        np.full_like(across, b / 2),\n",
    "                        np.full_like(across, d / 2),\n",
    "                    )\n",
    "                )\n",
    "            )[:, 1]\n",
    "        ),\n",
    "    ),\n",
    "    \"TM010 |E_z| along r\": (\n",
    "        across,\n",
    "        np.abs(\n",
    "            modes[\"cylindrical\"]\n",
    "            .mode(0)\n",
    "            .field(models[\"cylindrical\"].electric_field)\n",
    "            .evaluate(\n",
    "                np.column_stack(\n",
    "                    (\n",
    "                        across * radius * 0.999,\n",
    "                        0 * across,\n",
    "                        np.full_like(across, length / 2),\n",
    "                    )\n",
    "                )\n",
    "            )[:, 2]\n",
    "        ),\n",
    "    ),\n",
    "}\n",
    "fig = plots.figure(2, 3, size=(18, 11))\n",
    "for column, (name, mode) in enumerate(zip(names, labels)):\n",
    "    plots.section(\n",
    "        modes[name].mode(0).field(models[name].electric_field),\n",
    "        plane=planes[name],\n",
    "        component=lambda E, p: np.sqrt(np.sum(np.abs(E) ** 2, axis=1)),\n",
    "        subdivisions=3,\n",
    "        label=\"|E| [V/m]\",\n",
    "        length_unit=\"mm\",\n",
    "        title=f\"{mode}, {modes[name].resonance_frequencies[0] / 1e9:.3f} GHz\",\n",
    "        ax=fig[column],\n",
    "    )\n",
    "plots.convergence(\n",
    "    steps * 1e3,\n",
    "    {\"frequency, perfect walls\": frequency_error, \"Q, copper walls\": quality_error},\n",
    "    order=(4, 2),\n",
    "    xlabel=\"element size h [mm]\",\n",
    "    ylabel=\"relative error\",\n",
    "    title=\"Rectangular cavity, TE101\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        label: (x, values / values.max()) for label, (x, values) in profiles.items()\n",
    "    },\n",
    "    reference={\n",
    "        \"sin(pi x / a)\": (across, np.sin(np.pi * across)),\n",
    "        \"J0(j01 r / R)\": (across, j0(j01 * across)),\n",
    "    },\n",
    "    xlabel=\"x / a or r / R\",\n",
    "    ylabel=\"normalized field\",\n",
    "    title=\"Field profiles at mid-height\",\n",
    "    legend=\"lower center\",\n",
    "    ax=fig[4],\n",
    ")\n",
    "plots.bars(\n",
    "    [f\"{name}\\n{mode}\" for name, mode in zip(names, labels)],\n",
    "    {\n",
    "        \"resonance frequency\": [\n",
    "            abs(modes[name].resonance_frequencies[0] / lossy[name] - 1)\n",
    "            for name in names\n",
    "        ],\n",
    "        \"quality factor\": [\n",
    "            abs(modes[name].quality_factors[0] / quality[name] - 1) for name in names\n",
    "        ],\n",
    "    },\n",
    "    scale=\"log\",\n",
    "    ylabel=\"relative deviation from the closed form\",\n",
    "    title=\"Accuracy of the copper cavities\",\n",
    "    ax=fig[5],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Fill a cavity with a lossy dielectric (`IsotropicElectromagneticMaterial(relative_permittivity=2.1 * (1 + 4e-4j))`):\n",
    "its $Q$ follows $1/Q=1/Q_c+\\tan\\delta$. A larger `mode_count` returns the higher modes with their\n",
    "own quality factors, and `frequency_range=(f1, f2)` every mode in a band."
   ]
  }
 ]
}
