{
 "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": [
    "# Waveguide with several propagating modes\n",
    "\n",
    "Between two metal walls $W=50$ mm apart (the H-plane section of a rectangular waveguide), a wave\n",
    "with the electric field $E_z$ out of the plane travels in the modes\n",
    "\n",
    "$$E_z=\\sin\\frac{m\\pi y}{W}\\,e^{\\mathrm i\\beta_mx},\\qquad \\beta_m=\\sqrt{k^2-(m\\pi/W)^2},\\qquad\n",
    "  f_{c,m}=\\frac{mc}{2W}=3,\\ 6,\\ 9,\\ 12\\ \\text{GHz}.$$\n",
    "\n",
    "At 10 GHz three modes propagate. A port must then absorb all of them, not only the fundamental\n",
    "one: `SectionWaveguidePort` computes the modes of its port line and imposes the exact radiation\n",
    "condition for each of them (four here, the fourth evanescent), and feeds the mode `incident_mode`\n",
    "with 1 W per metre of depth.\n",
    "\n",
    "A dielectric insert ($\\varepsilon_r=2.25$, length $d=40$ mm) sits in the middle of the 200 mm\n",
    "long guide.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| `x_min` | waveguide port 1, four modes, one of them fed |\n",
    "| `x_max` | waveguide port 2, four modes, matched |\n",
    "| `y_min`, `y_max` | perfect electric conductor |\n",
    "\n",
    "**Reference.** An insert that fills the whole width does not couple the modes; each one meets\n",
    "a slab with the wavenumbers $\\beta_m$ outside and $\\beta'_m=\\sqrt{\\varepsilon_rk^2-(m\\pi/W)^2}$\n",
    "inside, and reflects the power fraction (D. M. Pozar, *Microwave Engineering*, 4th ed., §2.7\n",
    "and §3.3)\n",
    "\n",
    "$$|S_{11}|^2=\\frac{4\\rho^2\\sin^2\\beta'_md}{(1-\\rho^2)^2+4\\rho^2\\sin^2\\beta'_md},\\qquad\n",
    "  \\rho=\\frac{\\beta_m-\\beta'_m}{\\beta_m+\\beta'_m},\\qquad |S_{21}|^2=1-|S_{11}|^2 .$$\n",
    "\n",
    "An insert across half the width converts modes. Its S-matrix has no closed form, but it must be\n",
    "reciprocal ($S_{1n,1m}=S_{1m,1n}$ for the reflection from mode $m$ into mode $n$) and, being\n",
    "lossless, conserve the power of every incident mode."
   ]
  },
  {
   "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 (\n",
    "    IsotropicElectromagneticMaterial,\n",
    "    RegionwiseElectromagneticMaterial,\n",
    ")\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import ComplexSparseDirect\n",
    "from onesim.physics.electromagnetics import (\n",
    "    FrequencyDomainMaxwell,\n",
    "    PerfectElectricConductor,\n",
    "    SectionWaveguidePort,\n",
    "    scattering_parameters,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()\n",
    "\n",
    "permittivity = 2.25\n",
    "light = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the guide and the two inserts; `section` cuts them at half thickness. Each insert\n",
    "gets its own mesh that follows its outline, with quadratic triangles of 3 mm (between five\n",
    "and six per wavelength in the dielectric at 12 GHz)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "section = lambda name: load(f\"multimode_waveguide_scattering{name}.step\").section(\n",
    "    (0, 0, 1), origin=(0, 0, 0.0025)\n",
    ")\n",
    "guide = section(\"\")\n",
    "inserts = {\n",
    "    \"full width\": section(\"_full\").named(\"insert\"),\n",
    "    \"half width\": section(\"_half\").named(\"insert\"),\n",
    "}\n",
    "sides = guide.boundaries\n",
    "width = guide.size[1]\n",
    "meshes = {\n",
    "    name: TriangularMesher(target_size=3e-3, embedded_regions=(insert,)).generate(guide)\n",
    "    for name, insert in inserts.items()\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(16, 4.5))\n",
    "plots.geometry(\n",
    "    guide,\n",
    "    selection={\n",
    "        \"port 1\": sides.x_min,\n",
    "        \"port 2\": sides.x_max,\n",
    "        \"metal walls\": sides.y_min | sides.y_max,\n",
    "    },\n",
    "    labels=False,\n",
    "    title=\"Waveguide section (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"half width\"],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Half-width insert: {meshes['half width'].cell_count} quadratic triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "One `FrequencyDomainMaxwell` model per frequency solves $E_z$. `scattering_parameters` returns\n",
    "$S$ for every port and mode, `(port, mode)` counted from zero, normalized to the power each mode\n",
    "carries. The full-width insert is swept from 3.25 to 11.65 GHz in steps of 0.4 GHz with each propagating mode fed in\n",
    "turn."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "material = RegionwiseElectromagneticMaterial(\n",
    "    {\"insert\": IsotropicElectromagneticMaterial(relative_permittivity=permittivity)},\n",
    "    default=IsotropicElectromagneticMaterial(),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "model = lambda frequency: FrequencyDomainMaxwell(\n",
    "    domain=guide.domain(),\n",
    "    frequency=frequency,\n",
    "    material=material,\n",
    "    polarization=\"Ez\",\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    ")\n",
    "simulate = lambda model, insert, mode: Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"Multimode waveguide\",\n",
    "        geometry=guide,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            SectionWaveguidePort(\n",
    "                physics=model,\n",
    "                boundary=sides.x_min,\n",
    "                modes=4,\n",
    "                incident_mode=mode,\n",
    "                incident_power=1.0,\n",
    "            ),\n",
    "            SectionWaveguidePort(physics=model, boundary=sides.x_max, modes=4),\n",
    "            PerfectElectricConductor(physics=model, boundary=sides.y_min | sides.y_max),\n",
    "        ),\n",
    "    ),\n",
    "    mesh=meshes[insert],\n",
    "    numerics=numerics,\n",
    ").solve_stationary()\n",
    "scattering = lambda frequency, insert, mode: scattering_parameters(\n",
    "    simulate(m := model(frequency), insert, mode), m\n",
    ")\n",
    "\n",
    "frequencies = np.arange(3.25e9, 11.9e9, 0.4e9)\n",
    "cutoff = lambda mode: (mode + 1) * light / (2 * width)\n",
    "sweep = {\n",
    "    mode: {\n",
    "        f: scattering(f, \"full width\", mode)\n",
    "        for f in frequencies\n",
    "        if f > 1.01 * cutoff(mode)\n",
    "    }\n",
    "    for mode in range(3)\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Full-width insert: the reflected and transmitted power of each mode against the slab formula,\n",
    "and the largest power found in any other mode (it must vanish without coupling)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def slab(mode, frequency):\n",
    "    k = 2 * np.pi * frequency / light\n",
    "    outside, inside = np.sqrt(k**2 - ((mode + 1) * np.pi / width) ** 2), np.sqrt(\n",
    "        permittivity * k**2 - ((mode + 1) * np.pi / width) ** 2\n",
    "    )\n",
    "    rho, phase = (outside - inside) / (outside + inside), np.sin(\n",
    "        inside * inserts[\"full width\"].size[0]\n",
    "    ) ** 2\n",
    "    return 4 * rho**2 * phase / ((1 - rho**2) ** 2 + 4 * rho**2 * phase)\n",
    "\n",
    "\n",
    "reflected = {\n",
    "    mode: np.array([abs(s[(0, mode)]) ** 2 for s in runs.values()])\n",
    "    for mode, runs in sweep.items()\n",
    "}\n",
    "transmitted = {\n",
    "    mode: np.array([abs(s[(1, mode)]) ** 2 for s in runs.values()])\n",
    "    for mode, runs in sweep.items()\n",
    "}\n",
    "exact = {mode: slab(mode, np.array(list(runs))) for mode, runs in sweep.items()}\n",
    "print(\n",
    "    \"fed mode   frequencies   max ||S11|^2 - slab|   max ||S21|^2 - (1 - slab)|   largest power in another mode\"\n",
    ")\n",
    "for mode, runs in sweep.items():\n",
    "    leak = max(\n",
    "        abs(value) ** 2\n",
    "        for s in runs.values()\n",
    "        for (port, other), value in s.items()\n",
    "        if other != mode\n",
    "    )\n",
    "    print(\n",
    "        f\"TE{mode + 1:d}        {len(runs):11d}   {np.abs(reflected[mode] - exact[mode]).max():20.2e}   \"\n",
    "        f\"{np.abs(transmitted[mode] - (1 - exact[mode])).max():26.2e}   {leak:29.1e}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Half-width insert at 10 GHz: the S-matrix of the three propagating modes for each fed mode, its\n",
    "reciprocity and the power balance."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "half = {mode: scattering(10e9, \"half width\", mode) for mode in range(3)}\n",
    "print(\n",
    "    \"\\nhalf-width insert, 10 GHz: |S| from the fed mode (rows) into port 1 / port 2 modes (columns)\"\n",
    ")\n",
    "print(\"fed     port 1: TE1    TE2    TE3     port 2: TE1    TE2    TE3     total power\")\n",
    "for mode, s in half.items():\n",
    "    print(\n",
    "        f\"TE{mode + 1}           \"\n",
    "        + \"  \".join(f\"{abs(s[(0, n)]):.3f}\" for n in range(3))\n",
    "        + \"            \"\n",
    "        + \"  \".join(f\"{abs(s[(1, n)]):.3f}\" for n in range(3))\n",
    "        + f\"     {sum(abs(v) ** 2 for v in s.values()):.10f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"reciprocity: largest |S(1 n <- 1 m) - S(1 m <- 1 n)| = {max(abs(half[m][(0, n)] - half[n][(0, m)]) for m in range(3) for n in range(3)):.1e}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left: reflected power of each mode at the full-width insert against the slab formula (dashed):\n",
    "every mode has its own Fabry-Perot fringes, starting at its cutoff. Right: the field of the\n",
    "half-width insert fed with the fundamental mode, which leaves the insert as a mixture of modes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "field = simulate(m := model(10e9), \"half width\", 0).field(m.electric_field)\n",
    "fine = np.linspace(3.0e9, 11.9e9, 900)\n",
    "x, y = np.asarray(meshes[\"half width\"].coordinates).T\n",
    "fig = plots.figure(1, 2, size=(17, 5))\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"TE{mode + 1}\": (np.array(list(runs)) / 1e9, reflected[mode])\n",
    "        for mode, runs in sweep.items()\n",
    "    },\n",
    "    reference={\n",
    "        f\"TE{mode + 1}\": (\n",
    "            fine[fine > 1.001 * cutoff(mode)] / 1e9,\n",
    "            slab(mode, fine[fine > 1.001 * cutoff(mode)]),\n",
    "        )\n",
    "        for mode in range(3)\n",
    "    },\n",
    "    xlabel=\"frequency [GHz]\",\n",
    "    ylabel=\"|S11|^2 of the fed mode\",\n",
    "    title=\"Full-width insert (dashed: slab formula)\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.heatmap(\n",
    "    1e3 * x,\n",
    "    1e3 * y,\n",
    "    field.evaluate(np.column_stack((x, y)))[:, 2].real,\n",
    "    triangles=np.asarray(meshes[\"half width\"].cells),\n",
    "    colormap=\"diverging\",\n",
    "    centre=0.0,\n",
    "    label=\"Re E_z [V/m]\",\n",
    "    xlabel=\"x [mm]\",\n",
    "    ylabel=\"y [mm]\",\n",
    "    title=\"Half-width insert, TE1 fed at 10 GHz\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Feed port 2 instead of port 1 and check $S_{21}=S_{12}$ mode by mode, or replace the insert by a\n",
    "metal post (a hole in the section with a `PerfectElectricConductor`) to see the strong mode\n",
    "conversion of an inductive obstacle."
   ]
  }
 ]
}
