{
 "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": [
    "# Circular waveguide iris filter\n",
    "\n",
    "A circular waveguide of radius $a=20$ mm carries, among others, the circularly symmetric modes\n",
    "TE$_{0n}$ (only $E_\\varphi$, the low-loss mode of long-distance waveguides) and TM$_{0n}$ (only\n",
    "$H_\\varphi$). Two metal rings, 2 mm thick with a hole of radius 10 mm, block most of the\n",
    "cross-section 25 mm apart. Between them a cavity forms; waves at its resonance tunnel through the\n",
    "holes and pass the filter, all others are reflected.\n",
    "\n",
    "Everything is symmetric about the axis, so the field of these modes is computed on the meridian\n",
    "plane ($r$, $z$): `FrequencyDomainMaxwell` with the polarization `Ephi` solves the TE$_{0n}$\n",
    "family and with `Hphi` the TM$_{0n}$ family. `SectionWaveguidePort` computes the modes of the\n",
    "port line (Bessel functions) and absorbs each of them exactly.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| `input`, $z=0$ | waveguide port, two modes, the first fed with 1 W |\n",
    "| `output`, $z=89$ mm | waveguide port, two modes |\n",
    "| `metal` (wall and irises) | perfect electric conductor |\n",
    "| `axis`, $r=0$ | regular: $E_\\varphi=H_\\varphi=0$ |\n",
    "\n",
    "**Reference** (D. M. Pozar, *Microwave Engineering*, 4th ed., §3.4 and §6.7; N. Marcuvitz,\n",
    "*Waveguide Handbook*, §2.3). The modes are cut off below $f_c=c\\,x/(2\\pi a)$ with the Bessel zeros\n",
    "$x=j'_{01}=3.8317$ (TE$_{01}$, 9.14 GHz), $j'_{02}=7.0156$ (TE$_{02}$, 16.75 GHz), $j_{01}=2.4048$\n",
    "(TM$_{01}$, 5.74 GHz) and $j_{02}=5.5201$ (TM$_{02}$, 13.18 GHz). A closed cylindrical cavity of\n",
    "length $L$ resonates at\n",
    "\n",
    "$$f_{0np}=\\frac{c}{2\\pi}\\sqrt{\\Big(\\frac{x}{a}\\Big)^2+\\Big(\\frac{p\\pi}{L}\\Big)^2}:\\qquad\n",
    "  \\text{TE}_{011}\\ 10.94\\ \\text{GHz},\\qquad \\text{TM}_{010}\\ 5.74\\ \\text{GHz},\\qquad\n",
    "  \\text{TM}_{011}\\ 8.30\\ \\text{GHz}\\quad(L=25\\ \\text{mm}).$$\n",
    "\n",
    "The pass band of the filter opens near the closed-cavity resonance, shifted by the holes; a\n",
    "symmetric lossless filter passes the full power at its peak."
   ]
  },
  {
   "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, RevolvedH1SpaceFactory\n",
    "from onesim.numerics.linear import ComplexSparseDirect\n",
    "from onesim.physics.electromagnetics import (\n",
    "    FrequencyDomainMaxwell,\n",
    "    PerfectElectricConductor,\n",
    "    SectionWaveguidePort,\n",
    "    harmonic_resonances,\n",
    "    scattering_parameters,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.optimize import minimize_scalar\n",
    "from scipy.special import jn_zeros, jnp_zeros\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",
    "`load` reads the half solids of revolution; `section` with the plane $y=0$ returns their meridian\n",
    "planes, whose sides keep the face names. Quadratic triangles of 1.6 mm in the filter (a\n",
    "thirteenth of the wavelength at 14 GHz) and 1 mm in the cavity."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "parts = {\n",
    "    name: load(f\"circular_waveguide_iris_filter{name}.step\") for name in (\"\", \"_cavity\")\n",
    "}\n",
    "filter_plane, cavity_plane = parts[\"\"].section((0, 1, 0)), parts[\"_cavity\"].section(\n",
    "    (0, 1, 0)\n",
    ")\n",
    "sides = filter_plane.boundaries\n",
    "radius, cavity = cavity_plane.size[0], cavity_plane.size[1]\n",
    "mesh = TriangularMesher(target_size=1.6e-3).generate(filter_plane)\n",
    "cavity_mesh = TriangularMesher(target_size=1e-3).generate(cavity_plane)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    parts[\"\"],\n",
    "    selection={\n",
    "        \"input port\": parts[\"\"].boundaries.input,\n",
    "        \"output port\": parts[\"\"].boundaries.output,\n",
    "        \"metal\": parts[\"\"].boundaries.metal,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=20, azimuth=-150),\n",
    "    title=\"Air in the filter, half (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Meridian plane: {mesh.cell_count} quadratic triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Closed cavity\n",
    "\n",
    "The cavity between the irises with metal on all sides: `harmonic_resonances` returns its lowest\n",
    "resonances in both families."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2), provider=RevolvedH1SpaceFactory()),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "model = lambda plane, polarization, frequency: FrequencyDomainMaxwell(\n",
    "    domain=plane.domain(),\n",
    "    frequency=frequency,\n",
    "    material=IsotropicElectromagneticMaterial(),\n",
    "    polarization=polarization,\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    ")\n",
    "closed = {\n",
    "    polarization: harmonic_resonances(\n",
    "        Simulation(\n",
    "            problem=Problem(\n",
    "                name=\"Closed cavity\",\n",
    "                geometry=cavity_plane,\n",
    "                physics=(m,),\n",
    "                boundary_conditions=(\n",
    "                    PerfectElectricConductor(\n",
    "                        physics=m, boundary=cavity_plane.boundaries.metal\n",
    "                    ),\n",
    "                ),\n",
    "            ),\n",
    "            mesh=cavity_mesh,\n",
    "            numerics=numerics,\n",
    "        ).solve_stationary(),\n",
    "        m,\n",
    "        count=3,\n",
    "        near=5e9,\n",
    "    ).real\n",
    "    for polarization in (\"Ephi\", \"Hphi\")\n",
    "    for m in [model(cavity_plane, polarization, 10e9)]\n",
    "}\n",
    "resonance = lambda x, p: light / (2 * np.pi) * np.hypot(x / radius, p * np.pi / cavity)\n",
    "exact = {\n",
    "    \"TE011\": resonance(jnp_zeros(0, 1)[0], 1),\n",
    "    \"TM010\": resonance(jn_zeros(0, 1)[0], 0),\n",
    "    \"TM011\": resonance(jn_zeros(0, 1)[0], 1),\n",
    "}\n",
    "computed = {\n",
    "    \"TE011\": closed[\"Ephi\"][0],\n",
    "    \"TM010\": closed[\"Hphi\"][0],\n",
    "    \"TM011\": closed[\"Hphi\"][1],\n",
    "}\n",
    "for name in exact:\n",
    "    print(\n",
    "        f\"closed cavity {name}: computed {computed[name] / 1e9:.5f} GHz, Bessel formula {exact[name] / 1e9:.5f} GHz, \"\n",
    "        f\"relative difference {abs(computed[name] / exact[name] - 1):.1e}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Filter\n",
    "\n",
    "The filter is swept over the band in which only the first mode of each family propagates:\n",
    "TE$_{01}$ from 9.4 to 14 GHz, TM$_{01}$ from 6 to 13 GHz. The TE$_{01}$ peak is located by\n",
    "maximizing $|S_{21}|^2$ near the highest transmission of the sweep and then swept finely over\n",
    "$\\pm15$ MHz. `scattering_parameters` returns\n",
    "$S$ for `(port, mode)`; the second mode of each port is evanescent here and carries no power."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "problem = lambda m: Problem(\n",
    "    name=\"Iris filter\",\n",
    "    geometry=filter_plane,\n",
    "    physics=(m,),\n",
    "    boundary_conditions=(\n",
    "        SectionWaveguidePort(\n",
    "            physics=m, boundary=sides.input, modes=2, incident_power=1.0\n",
    "        ),\n",
    "        SectionWaveguidePort(physics=m, boundary=sides.output, modes=2),\n",
    "        PerfectElectricConductor(physics=m, boundary=sides.metal),\n",
    "    ),\n",
    ")\n",
    "solve = lambda m: Simulation(\n",
    "    problem=problem(m), mesh=mesh, numerics=numerics\n",
    ").solve_stationary()\n",
    "simulate = lambda polarization, frequency: scattering_parameters(\n",
    "    solve(m := model(filter_plane, polarization, frequency)), m\n",
    ")\n",
    "coarse = {\n",
    "    \"Ephi\": np.arange(9.4e9, 14.001e9, 0.2e9),\n",
    "    \"Hphi\": np.arange(6.0e9, 13.001e9, 0.25e9),\n",
    "}\n",
    "scan = {\n",
    "    polarization: {f: simulate(polarization, f) for f in frequencies}\n",
    "    for polarization, frequencies in coarse.items()\n",
    "}\n",
    "best = max(scan[\"Ephi\"], key=lambda f: abs(scan[\"Ephi\"][f][(1, 0)]))\n",
    "peak = minimize_scalar(\n",
    "    lambda f: -abs(simulate(\"Ephi\", f)[(1, 0)]) ** 2,\n",
    "    bounds=(best - 0.2e9, best + 0.2e9),\n",
    "    method=\"bounded\",\n",
    "    options={\"xatol\": 1e5},\n",
    ")\n",
    "scan[\"Ephi\"] |= {f: simulate(\"Ephi\", f) for f in peak.x + np.linspace(-15e6, 15e6, 31)}\n",
    "bands = {polarization: np.array(sorted(runs)) for polarization, runs in scan.items()}\n",
    "through = {\n",
    "    polarization: np.array(\n",
    "        [abs(scan[polarization][f][(1, 0)]) ** 2 for f in bands[polarization]]\n",
    "    )\n",
    "    for polarization in scan\n",
    "}\n",
    "balance = max(\n",
    "    abs(sum(abs(v) ** 2 for v in s.values()) - 1)\n",
    "    for runs in scan.values()\n",
    "    for s in runs.values()\n",
    ")\n",
    "print(\n",
    "    f\"TE01 pass band: peak at {peak.x / 1e9:.4f} GHz with |S21|^2 = {-peak.fun:.6f}; closed cavity TE011 at {exact['TE011'] / 1e9:.4f} GHz \"\n",
    "    f\"(shift by the holes {(peak.x - exact['TE011']) / 1e6:+.0f} MHz); |S21|^2 > 0.5 over {np.ptp(bands['Ephi'][through['Ephi'] > 0.5]) / 1e6:.1f} MHz, \"\n",
    "    f\"loaded Q about {peak.x / max(np.ptp(bands['Ephi'][through['Ephi'] > 0.5]), 1.0):.0f}\"\n",
    ")\n",
    "print(\n",
    "    f\"TM01: transmitted power between {through['Hphi'].min():.3f} and {through['Hphi'].max():.3f} over 6 - 13 GHz, \"\n",
    "    f\"smallest at {bands['Hphi'][np.argmin(through['Hphi'])] / 1e9:.2f} GHz\"\n",
    ")\n",
    "print(f\"power balance |S11|^2 + |S21|^2 - 1 over both sweeps: largest {balance:.1e}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left: the transmitted power of both families over the band, with the closed-cavity resonances\n",
    "and the TE$_{01}$ cutoff marked. Middle: the narrow TE$_{01}$ pass band. Right: the electric field\n",
    "$|E_\\varphi|$ in the meridian plane at the TE$_{01}$ peak: the wave builds up in the cavity and\n",
    "leaves through the second hole."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "field = solve(m := model(filter_plane, \"Ephi\", peak.x)).field(m.electric_field)\n",
    "r, z = np.asarray(mesh.coordinates).T\n",
    "fig = plots.figure(1, 3, size=(24, 6))\n",
    "near = np.abs(bands[\"Ephi\"] - peak.x) <= 15.1e6\n",
    "plots.line(\n",
    "    y={\n",
    "        \"TE01 (E_phi)\": (bands[\"Ephi\"] / 1e9, through[\"Ephi\"]),\n",
    "        \"TM01 (H_phi)\": (bands[\"Hphi\"] / 1e9, through[\"Hphi\"]),\n",
    "    },\n",
    "    vlines={\n",
    "        \"closed TE011\": exact[\"TE011\"] / 1e9,\n",
    "        \"closed TM011\": exact[\"TM011\"] / 1e9,\n",
    "        \"TE01 cutoff\": light * jnp_zeros(0, 1)[0] / (2 * np.pi * radius) / 1e9,\n",
    "    },\n",
    "    xlabel=\"frequency [GHz]\",\n",
    "    ylabel=\"|S21|^2\",\n",
    "    title=\"Transmitted power of the iris filter\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    (bands[\"Ephi\"][near] - peak.x) / 1e6,\n",
    "    {\"TE01 (E_phi)\": through[\"Ephi\"][near]},\n",
    "    markers=True,\n",
    "    xlabel=f\"frequency - {peak.x / 1e9:.4f} GHz [MHz]\",\n",
    "    ylabel=\"|S21|^2\",\n",
    "    title=\"TE01 pass band\",\n",
    "    legend=False,\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.heatmap(\n",
    "    1e3 * z,\n",
    "    1e3 * r,\n",
    "    np.abs(field.evaluate(np.column_stack((r, z)))[:, 1]),\n",
    "    triangles=np.asarray(mesh.cells),\n",
    "    limits=\"robust\",\n",
    "    label=\"|E_phi| [V/m]\",\n",
    "    xlabel=\"z [mm]\",\n",
    "    ylabel=\"r [mm]\",\n",
    "    title=f\"TE01 at the peak, {peak.x / 1e9:.3f} GHz\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add a third iris in `circular_waveguide_iris_filter_geometry.py` to couple two cavities: the\n",
    "pass band widens into a two-pole response with steeper flanks. Smaller holes make the band\n",
    "narrower and move the peak towards the closed-cavity resonance."
   ]
  }
 ]
}
