{
 "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": [
    "# Mode analysis of a rectangular waveguide cross-section\n",
    "\n",
    "A hollow metal waveguide carries transverse electric (TE) and transverse magnetic (TM) modes.\n",
    "Each mode has a pattern over the cross-section and a cutoff frequency below which it cannot\n",
    "propagate. Mode analysis is the 2D eigenvalue problem on the cross-section $S$: for TE modes the\n",
    "axial magnetic field $H_z$, for TM modes the axial electric field $E_z$, satisfies\n",
    "\n",
    "$$\\nabla_t^2\\psi+k_c^2\\,\\psi=0\\ \\text{in }S,\\qquad\n",
    "  \\partial_n H_z=0\\ \\text{(TE)},\\quad E_z=0\\ \\text{(TM) on the wall},\\qquad f_c=\\frac{c\\,k_c}{2\\pi},$$\n",
    "\n",
    "and the transverse electric field follows from the gradient of $\\psi$.\n",
    "\n",
    "OneSimulation solves this eigenproblem with linear triangles on the **port\n",
    "cross-section** of a waveguide model: `NumericalWaveguideMode(\"TE\", order=n)` binds the $n$-th TE\n",
    "eigenmode computed on the meshed port face. Here the face belongs to a 1.5 mm long piece of a WR-90\n",
    "guide (inner size $a\\times b=22.86\\times10.16$ mm, the standard X-band guide) read from the CAD\n",
    "file `waveguide_mode_analysis.step`, written by `waveguide_mode_analysis_geometry.py` with the CAD\n",
    "objects of OneSimulation. Each mode is bound in a driven solve at 25 GHz, above all cutoffs\n",
    "considered.\n",
    "\n",
    "**Reference** (D. M. Pozar, *Microwave Engineering*, 4th ed., Wiley 2012, §3.3; R. E. Collin,\n",
    "*Foundations for Microwave Engineering*, 2nd ed., §3.12). For the TE$_{mn}$ and TM$_{mn}$ modes\n",
    "\n",
    "$$f_{c,mn}=\\frac c2\\sqrt{\\Big(\\frac ma\\Big)^2+\\Big(\\frac nb\\Big)^2},\\qquad\n",
    "  H_z\\propto\\cos\\frac{m\\pi x}a\\cos\\frac{n\\pi y}b\\ \\text{(TE)},\\qquad\n",
    "  E_z\\propto\\sin\\frac{m\\pi x}a\\sin\\frac{n\\pi y}b\\ \\text{(TM)},$$\n",
    "\n",
    "with $m,n\\ge0$, not both zero, for TE and $m,n\\ge1$ for TM. In WR-90 the TE$_{10}$ mode propagates\n",
    "alone between 6.56 and 13.12 GHz."
   ]
  },
  {
   "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 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",
    "    NumericalWaveguideMode,\n",
    "    PerfectElectricConductor,\n",
    "    WaveguidePort,\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()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "The mode solve uses the triangles of the port face. Three meshes are built for the mesh study;\n",
    "the finest, 0.5 mm, resolves the eighth mode with about eleven triangles per half wavelength."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "guide = load(\"waveguide_mode_analysis.step\")\n",
    "faces = guide.boundaries\n",
    "a, b, length = guide.size\n",
    "sizes = (2.0e-3, 1.0e-3, 0.5e-3)\n",
    "meshes = {size: TetrahedralMesher(target_size=size).generate(guide) for size in sizes}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 5))\n",
    "plots.geometry(\n",
    "    guide,\n",
    "    selection={\"port cross-section\": faces.port, \"short\": faces.short},\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=-30, azimuth=-55),\n",
    "    title=\"Piece of the WR-90 guide\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[sizes[-1]],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=plots.Camera(elevation=-30, azimuth=-55),\n",
    "    title=f\"Finest mesh: {meshes[sizes[-1]].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "One driven solve per requested mode; only its port eigenmode is used here. The bound mode\n",
    "exposes its cutoff frequency and its transverse electric field on the cross-section."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "frequency = 25e9\n",
    "model = FrequencyDomainMaxwell(\n",
    "    domain=guide.volume,\n",
    "    frequency=frequency,\n",
    "    material=IsotropicElectromagneticMaterial(),\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Nedelec(order=1)), linear_solver=ComplexSparseDirect()\n",
    ")\n",
    "port_mode = (\n",
    "    lambda family, order, mesh: Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"WR-90 port\",\n",
    "            geometry=guide,\n",
    "            physics=(model,),\n",
    "            boundary_conditions=(\n",
    "                WaveguidePort(\n",
    "                    boundary=faces.port,\n",
    "                    physics=model,\n",
    "                    mode=NumericalWaveguideMode(family, order=order),\n",
    "                    incident_power=1.0,\n",
    "                ),\n",
    "                PerfectElectricConductor(\n",
    "                    boundary=faces.walls | faces.short, physics=model\n",
    "                ),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=mesh,\n",
    "        numerics=numerics,\n",
    "    )\n",
    "    .solve_stationary()\n",
    "    .operators[model.model_id]\n",
    "    .ports[0][1]\n",
    ")\n",
    "requested = {\n",
    "    \"TE10\": (\"TE\", 1),\n",
    "    \"TE20\": (\"TE\", 2),\n",
    "    \"TE01\": (\"TE\", 3),\n",
    "    \"TE11\": (\"TE\", 4),\n",
    "    \"TE30\": (\"TE\", 5),\n",
    "    \"TE21\": (\"TE\", 6),\n",
    "    \"TM11\": (\"TM\", 1),\n",
    "    \"TM21\": (\"TM\", 2),\n",
    "}\n",
    "modes = {\n",
    "    name: port_mode(family, order, meshes[sizes[-1]])\n",
    "    for name, (family, order) in requested.items()\n",
    "}\n",
    "fundamental = [\n",
    "    port_mode(\"TE\", 1, meshes[size]).cutoff_frequency for size in sizes[:-1]\n",
    "] + [modes[\"TE10\"].cutoff_frequency]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the closed forms"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "c0 = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)\n",
    "cutoff = lambda m, n: c0 / 2 * np.hypot(m / a, n / b)\n",
    "print(\"mode    computed [GHz]   closed form [GHz]   deviation\")\n",
    "for name, mode in modes.items():\n",
    "    exact = cutoff(int(name[2]), int(name[3]))\n",
    "    print(\n",
    "        f\"{name:6s} {mode.cutoff_frequency / 1e9:15.4f} {exact / 1e9:19.4f} {100 * (mode.cutoff_frequency / exact - 1):+10.3f} %\"\n",
    "    )\n",
    "errors = [abs(value / cutoff(1, 0) - 1) for value in fundamental]\n",
    "study = convergence(fundamental, sizes)\n",
    "print(\n",
    "    \"TE10 mesh study: \"\n",
    "    + \", \".join(\n",
    "        f\"h = {1e3 * h:.1f} mm: {100 * error:.4f} %\" for h, error in zip(sizes, errors)\n",
    "    )\n",
    "    + f\"; observed order {study.order:.2f}\"\n",
    ")\n",
    "\n",
    "x = np.linspace(0.02 * a, 0.98 * a, 25)\n",
    "profile = modes[\"TE10\"].electric_field(\n",
    "    np.column_stack((x, np.full_like(x, b / 2), np.zeros_like(x)))\n",
    ")\n",
    "shape = np.abs(profile[:, 1]) / np.abs(profile[:, 1]).max()\n",
    "print(\n",
    "    f\"TE10 pattern against sin(pi x / a): largest deviation {np.abs(shape - np.sin(np.pi * x / a)).max():.4f} of the peak\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The transverse electric field strength of the eight modes on the cross-section, each scaled to\n",
    "its maximum, and the mesh study of the fundamental cutoff."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "gx, gy = np.linspace(0.002 * a, 0.998 * a, 91), np.linspace(0.002 * b, 0.998 * b, 41)\n",
    "grid = np.column_stack(\n",
    "    [value.ravel() for value in np.meshgrid(gx, gy, indexing=\"ij\")]\n",
    "    + [np.zeros(gx.size * gy.size)]\n",
    ")\n",
    "strength = {\n",
    "    name: np.linalg.norm(mode.electric_field(grid), axis=1).reshape(gx.size, gy.size)\n",
    "    for name, mode in modes.items()\n",
    "}\n",
    "fig = plots.figure(3, 3, size=(16, 9.5))\n",
    "for index, (name, values) in enumerate(strength.items()):\n",
    "    plots.heatmap(\n",
    "        1e3 * gx,\n",
    "        1e3 * gy,\n",
    "        values / values.max(),\n",
    "        limits=(0, 1),\n",
    "        label=\"|E_t| / max\",\n",
    "        xlabel=\"x [mm]\",\n",
    "        ylabel=\"y [mm]\",\n",
    "        title=f\"{name}: {modes[name].cutoff_frequency / 1e9:.3f} GHz\",\n",
    "        ax=fig[index],\n",
    "    )\n",
    "plots.convergence(\n",
    "    list(sizes),\n",
    "    {\"TE10 cutoff\": errors},\n",
    "    order=2,\n",
    "    xlabel=\"mesh size h [m]\",\n",
    "    ylabel=\"relative deviation\",\n",
    "    title=\"Mesh study of the TE10 cutoff\",\n",
    "    ax=fig[8],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the cross-section in `waveguide_mode_analysis_geometry.py` (for example WR-75 with\n",
    "19.05 x 9.525 mm) and write the STEP file again, or replace the box by a ridged or elliptical\n",
    "profile, for which no closed form exists: the numerical port mode is computed the same way and\n",
    "feeds the 3D field of a longer guide directly."
   ]
  }
 ]
}
