{
 "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": [
    "# Eigenmodes of a rectangular metallic cavity\n",
    "\n",
    "A long metallic tube of rectangular cross-section, $a=200$ mm by $b=100$ mm, supports standing\n",
    "waves whose fields do not vary along the tube: the resonances of its 2D cross-section. Two families\n",
    "exist. TM modes have only $E_z$ (out of the plane) and vanish on the walls; TE modes have only\n",
    "$H_z$, equivalently an electric field in the plane that is tangentially zero on the walls.\n",
    "\n",
    "OneSimulation finds them with `electromagnetic_modes` in three formulations of the same equation\n",
    "$\\nabla\\times\\nabla\\times\\mathbf E=k_0^2\\mathbf E$:\n",
    "\n",
    "| formulation | unknown | elements | wall condition |\n",
    "|---|---|---|---|\n",
    "| `Ez` | $E_z$ | quadratic Lagrange | $E_z=0$ (perfect conductor) |\n",
    "| `Hz` | $H_z$ | quadratic Lagrange | natural ($\\partial H_z/\\partial n=0$) |\n",
    "| `Exy` | $E_x, E_y$ | second-order Nédélec | $\\mathbf n\\times\\mathbf E=0$ |\n",
    "\n",
    "The in-plane formulation also has the static (curl-free) fields as solutions at zero frequency;\n",
    "the eigensolver removes them, so no spurious mode appears among the resonances.\n",
    "\n",
    "The cross-section comes from the plate `rectangular_cavity_eigenmodes.step`, written by\n",
    "`rectangular_cavity_eigenmodes_geometry.py` with the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference** (Pozar, *Microwave Engineering*, 4th ed., §3.3; Jackson, *Classical\n",
    "Electrodynamics*, 3rd ed., §8.7). The cut-off frequencies of the rectangular guide are the\n",
    "resonances of the cross-section,\n",
    "\n",
    "$$f_{mn}=\\frac c2\\sqrt{\\Big(\\frac ma\\Big)^2+\\Big(\\frac nb\\Big)^2},\\qquad\n",
    "  \\text{TM: } m,n\\ge1,\\qquad \\text{TE: } m,n\\ge0,\\ m+n\\ge1 .$$"
   ]
  },
  {
   "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, Lagrange, Nedelec\n",
    "from onesim.numerics.linear import ComplexSparseDirect\n",
    "from onesim.physics.electromagnetics import (\n",
    "    FrequencyDomainMaxwell,\n",
    "    PerfectElectricConductor,\n",
    "    electromagnetic_modes,\n",
    ")\n",
    "from onesim.results.comparisons import convergence\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()\n",
    "\n",
    "light = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`section` cuts the plate at mid-thickness. Quadratic triangles of 10 mm carry the three\n",
    "formulations; 20, 14, 10 and 7 mm form the mesh study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plate = load(\"rectangular_cavity_eigenmodes.step\")\n",
    "cavity = plate.section((0, 0, 1), origin=(0, 0, plate.size[2] / 2))\n",
    "a, b = cavity.size[0], cavity.size[1]\n",
    "sizes = (0.02, 0.014, 0.01, 0.007)\n",
    "meshes = {h: TriangularMesher(target_size=h).generate(cavity) for h in sizes}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 4.5))\n",
    "plots.geometry(\n",
    "    plate,\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=55, azimuth=-70),\n",
    "    title=\"Cavity cross-section as a plate (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0.01],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"{meshes[0.01].cell_count} quadratic triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Eigenmodes\n",
    "\n",
    "`modes` returns the six lowest resonances of one formulation on one mesh; the walls are perfect\n",
    "conductors, which for `Hz` is the natural condition."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "elements = {\"Ez\": Lagrange(order=2), \"Hz\": Lagrange(order=2), \"Exy\": Nedelec(order=2)}\n",
    "modes = lambda polarization, h: (\n",
    "    lambda m: (\n",
    "        electromagnetic_modes(\n",
    "            Simulation(\n",
    "                problem=Problem(\n",
    "                    name=\"Cavity\",\n",
    "                    geometry=cavity,\n",
    "                    physics=(m,),\n",
    "                    boundary_conditions=(\n",
    "                        PerfectElectricConductor(\n",
    "                            physics=m, boundary=cavity.boundaries.all\n",
    "                        ),\n",
    "                    ),\n",
    "                ),\n",
    "                mesh=meshes[h],\n",
    "                numerics=Numerics(\n",
    "                    spatial=FiniteElement(element=elements[polarization]),\n",
    "                    linear_solver=ComplexSparseDirect(),\n",
    "                ),\n",
    "            ).solve_stationary(),\n",
    "            m,\n",
    "            mode_count=6,\n",
    "            target_frequency=0.5e9,\n",
    "        ),\n",
    "        m,\n",
    "    )\n",
    ")(\n",
    "    FrequencyDomainMaxwell(\n",
    "        domain=cavity.domain(),\n",
    "        frequency=1e9,\n",
    "        material=IsotropicElectromagneticMaterial(),\n",
    "        polarization=polarization,\n",
    "        phasor_convention=\"exp(-i*omega*t)\",\n",
    "        amplitude_convention=\"peak\",\n",
    "    )\n",
    ")\n",
    "solved = {polarization: modes(polarization, 0.01) for polarization in elements}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the exact frequencies\n",
    "\n",
    "The exact TM frequencies belong to `Ez`, the exact TE frequencies to `Hz` and `Exy`."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "exact = {\n",
    "    \"TM\": sorted(\n",
    "        (light / 2 * np.hypot(m / a, n / b), f\"TM{m}{n}\")\n",
    "        for m in range(1, 6)\n",
    "        for n in range(1, 4)\n",
    "    )[:6],\n",
    "    \"TE\": sorted(\n",
    "        (light / 2 * np.hypot(m / a, n / b), f\"TE{m}{n}\")\n",
    "        for m in range(0, 7)\n",
    "        for n in range(0, 4)\n",
    "        if m + n > 0\n",
    "    )[:6],\n",
    "}\n",
    "family = {\"Ez\": \"TM\", \"Hz\": \"TE\", \"Exy\": \"TE\"}\n",
    "print(\"formulation   mode     computed [MHz]    exact [MHz]   relative difference\")\n",
    "for polarization, (found, _) in solved.items():\n",
    "    for f, (value, name) in zip(\n",
    "        np.sort(found.frequencies.real), exact[family[polarization]]\n",
    "    ):\n",
    "        print(\n",
    "            f\"{polarization:12s} {name:6s} {f / 1e6:15.4f} {value / 1e6:15.4f} {abs(f / value - 1):18.1e}\"\n",
    "        )\n",
    "study = {h: np.sort(modes(\"Exy\", h)[0].frequencies.real) for h in sizes}\n",
    "error = [abs(study[h][2] / exact[\"TE\"][2][0] - 1) for h in sizes]\n",
    "print(\n",
    "    f\"mesh study, {exact['TE'][2][1]} with Nedelec elements: \"\n",
    "    + \", \".join(f\"{1e3 * h:.0f} mm: {e:.1e}\" for h, e in zip(sizes, error))\n",
    "    + f\"; observed order {np.polyfit(np.log(sizes), np.log(error), 1)[0]:.2f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The six lowest TM modes ($|E_z|$) and TE modes (the magnitude of the in-plane electric field from\n",
    "the Nédélec formulation), each normalized to its maximum."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x, y = np.asarray(meshes[0.01].coordinates).T\n",
    "triangles = np.asarray(meshes[0.01].cells)\n",
    "shape = lambda polarization, i: (lambda values: values / values.max())(\n",
    "    np.linalg.norm(\n",
    "        np.abs(\n",
    "            solved[polarization][0]\n",
    "            .mode(i)\n",
    "            .field(solved[polarization][1].electric_field)\n",
    "            .evaluate(np.column_stack((x, y)))\n",
    "        ),\n",
    "        axis=1,\n",
    "    )\n",
    ")\n",
    "fig = plots.figure(4, 3, size=(18, 14))\n",
    "for row, polarization in enumerate((\"Ez\", \"Exy\")):\n",
    "    order = np.argsort(solved[polarization][0].frequencies.real)\n",
    "    for column, i in enumerate(order):\n",
    "        plots.heatmap(\n",
    "            1e3 * x,\n",
    "            1e3 * y,\n",
    "            shape(polarization, i),\n",
    "            triangles=triangles,\n",
    "            limits=(0, 1),\n",
    "            label=\"|E| / max\",\n",
    "            title=f\"{exact[family[polarization]][column][1]}, {solved[polarization][0].frequencies.real[i] / 1e6:.0f} MHz\",\n",
    "            xlabel=\"x [mm]\",\n",
    "            ylabel=\"y [mm]\",\n",
    "            ax=fig[6 * row + column],\n",
    "        )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Fill part of the cavity with a dielectric through `RegionwiseElectromagneticMaterial` to lower and\n",
    "split the resonances, or give the walls a finite conductivity with `SurfaceImpedanceBoundary`: the\n",
    "eigensolver then returns complex frequencies whose ratio is the quality factor of each mode."
   ]
  }
 ]
}
