{
 "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 iris bandpass filter\n",
    "\n",
    "A metal plate across a rectangular waveguide that leaves a centred aperture of width $d$ over the\n",
    "full height, an *inductive iris*, acts on the TE$_{10}$ wave like a shunt inductance. Two irises\n",
    "half a guide wavelength apart enclose a resonator; a row of irises couples several resonators and\n",
    "gives a bandpass filter whose pass band and ripple are set by the aperture widths and the\n",
    "spacings.\n",
    "\n",
    "This filter in a WR-90 guide ($a=22.86$ mm, $b=10.16$ mm) has four irises 1 mm thick and three\n",
    "resonators. Its dimensions come from the classical coupled-resonator design of a Chebyshev filter\n",
    "with 0.1 dB ripple and the pass band 9.7 to 10.3 GHz (impedance inverters from the low-pass\n",
    "prototype, Matthaei, Young and Jones, *Microwave Filters, Impedance-Matching Networks, and\n",
    "Coupling Structures*, 1980, §8.06; iris reactance after Marcuvitz, *Waveguide Handbook*, §5.21),\n",
    "refined on the H-plane section for the finite iris thickness:\n",
    "\n",
    "| | irises 1 and 4 | irises 2 and 3 |\n",
    "|---|---|---|\n",
    "| aperture $d$, thin-iris design [mm] | 10.76 | 6.99 |\n",
    "| aperture $d$, built [mm] | 11.60 | 8.18 |\n",
    "\n",
    "The iris spacings are 16.91 mm (outer resonators) and 18.41 mm (middle resonator); the design\n",
    "gave 16.50 and 17.95 mm.\n",
    "\n",
    "| faces | condition |\n",
    "|---|---|\n",
    "| `port_in` | waveguide port, TE$_{10}$ fed with 1 W, TE$_{20}$ absorbed |\n",
    "| `port_out` | waveguide port, TE$_{10}$ and TE$_{20}$ absorbed |\n",
    "| `metal` (walls and irises) | perfect electric conductor |\n",
    "\n",
    "OneSimulation solves $\\nabla\\times(\\mu_r^{-1}\\nabla\\times\\mathbf E)-k_0^2\\varepsilon_r\\mathbf E=0$\n",
    "with second-order Nédélec elements. The air comes from `waveguide_iris_bandpass_filter.step`,\n",
    "written by `waveguide_iris_bandpass_filter_geometry.py` with the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference.** (i) The design target: a three-pole Chebyshev response with the ripple\n",
    "$\\varepsilon^2=10^{0.01}-1$,\n",
    "\n",
    "$$|S_{21}|^2=\\frac{1}{1+\\varepsilon^2T_3^2(\\Omega)},\\qquad \\Omega=\\frac{2}{w_\\lambda}\\,\\frac{\\lambda_{g0}-\\lambda_g}{\\lambda_{g0}},\\qquad\n",
    "  w_\\lambda=\\frac{\\lambda_g(f_1)-\\lambda_g(f_2)}{\\lambda_{g0}},$$\n",
    "\n",
    "with the guide wavelength $\\lambda_g=1/\\sqrt{(f/c)^2-(2a)^{-2}}$ and $\\lambda_{g0}$ at the centre\n",
    "$f_0=\\sqrt{f_1f_2}$. (ii) The irises span the full height, so the TE$_{10}$ field does not vary\n",
    "across it: the 3D problem reduces exactly to the scalar Helmholtz equation for $E_z$ on the\n",
    "H-plane section. That 2D computation is the independent cross-check of the 3D filter. (iii) A\n",
    "lossless filter conserves power, $|S_{11}|^2+|S_{21}|^2=1$."
   ]
  },
  {
   "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, 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",
    "    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",
    "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 air of the filter; `section` at half height gives the H-plane section, whose\n",
    "sides keep the face names. The 3D meshes have tetrahedra of at most 4, 3 and 2.5 mm (refined at the\n",
    "iris edges by the mesher), the section triangles of 0.8 mm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "guide = load(\"waveguide_iris_bandpass_filter.step\")\n",
    "faces = guide.boundaries\n",
    "width, height = guide.size[1], guide.size[2]\n",
    "section = guide.section((0, 0, 1), origin=(0, 0, height / 2))\n",
    "meshes = {\n",
    "    h: TetrahedralMesher(target_size=h).generate(guide) for h in (0.004, 0.003, 0.0025)\n",
    "}\n",
    "section_mesh = TriangularMesher(target_size=0.0008).generate(section)\n",
    "\n",
    "view = plots.Camera(elevation=35, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.geometry(\n",
    "    guide,\n",
    "    selection={\n",
    "        \"input port\": faces.port_in,\n",
    "        \"output port\": faces.port_out,\n",
    "        \"metal\": faces.metal,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Air of the iris filter (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0.004],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{meshes[0.004].cell_count} quadratic tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`model` builds the Maxwell model in 3D or on the section (polarization across the guide height,\n",
    "$E_z$, which is normal to the section); `solve` adds the ports and the metal. The 3D filter is swept\n",
    "from 9.3 to 10.7 GHz in steps of 100 MHz (50 MHz on the flanks), the section in steps of 20 MHz."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "model = lambda frequency, domain, options: FrequencyDomainMaxwell(\n",
    "    domain=domain,\n",
    "    frequency=frequency,\n",
    "    material=IsotropicElectromagneticMaterial(),\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    "    **options,\n",
    ")\n",
    "solve = lambda m, part, mesh, element: Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"Iris filter\",\n",
    "        geometry=part,\n",
    "        physics=(m,),\n",
    "        boundary_conditions=(\n",
    "            SectionWaveguidePort(\n",
    "                physics=m, boundary=part.boundaries.port_in, modes=2, incident_power=1.0\n",
    "            ),\n",
    "            SectionWaveguidePort(physics=m, boundary=part.boundaries.port_out, modes=2),\n",
    "            PerfectElectricConductor(physics=m, boundary=part.boundaries.metal),\n",
    "        ),\n",
    "    ),\n",
    "    mesh=mesh,\n",
    "    numerics=Numerics(\n",
    "        spatial=FiniteElement(element=element), linear_solver=ComplexSparseDirect()\n",
    "    ),\n",
    ").solve_stationary()\n",
    "in_3d = lambda frequency, h: scattering_parameters(\n",
    "    solve(m := model(frequency, guide.volume, {}), guide, meshes[h], Nedelec(order=2)),\n",
    "    m,\n",
    ")\n",
    "on_section = lambda frequency: scattering_parameters(\n",
    "    solve(\n",
    "        m := model(frequency, section.domain(), {\"polarization\": \"Ez\"}),\n",
    "        section,\n",
    "        section_mesh,\n",
    "        Lagrange(order=2),\n",
    "    ),\n",
    "    m,\n",
    ")\n",
    "\n",
    "coarse, fine = np.sort(\n",
    "    np.r_[np.arange(9.3e9, 10.71e9, 0.1e9), 9.55e9, 9.65e9, 10.35e9, 10.45e9]\n",
    "), np.arange(9.3e9, 10.701e9, 0.02e9)\n",
    "sweep = {\n",
    "    \"3D\": {f: in_3d(f, 0.004) for f in coarse},\n",
    "    \"section\": {f: on_section(f) for f in fine},\n",
    "}\n",
    "study = {h: in_3d(9.65e9, h) for h in meshes}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The transmitted power of the 3D filter, of the section and of the Chebyshev design target, the\n",
    "pass band of the section, the half-power edges, the power balance and the mesh study on the lower\n",
    "flank, where the transmission is most sensitive."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "guide_wavelength = lambda f: 1 / np.sqrt((f / light) ** 2 - (1 / (2 * width)) ** 2)\n",
    "low, high, ripple = 9.7e9, 10.3e9, 10**0.01 - 1\n",
    "centre = np.sqrt(low * high)\n",
    "spread = (guide_wavelength(low) - guide_wavelength(high)) / guide_wavelength(centre)\n",
    "omega = (\n",
    "    lambda f: 2\n",
    "    / spread\n",
    "    * (guide_wavelength(centre) - guide_wavelength(f))\n",
    "    / guide_wavelength(centre)\n",
    ")\n",
    "chebyshev = lambda f: 1 / (\n",
    "    1\n",
    "    + ripple\n",
    "    * np.where(\n",
    "        np.abs(omega(f)) <= 1,\n",
    "        np.cos(3 * np.arccos(np.clip(omega(f), -1, 1))),\n",
    "        np.cosh(3 * np.arccosh(np.maximum(np.abs(omega(f)), 1))),\n",
    "    )\n",
    "    ** 2\n",
    ")\n",
    "through = {\n",
    "    name: np.array([abs(runs[f][(1, 0)]) ** 2 for f in runs])\n",
    "    for name, runs in sweep.items()\n",
    "}\n",
    "reflected = {\n",
    "    name: np.array([abs(runs[f][(0, 0)]) ** 2 for f in runs])\n",
    "    for name, runs in sweep.items()\n",
    "}\n",
    "print(\"f [GHz]   |S21|^2 3D   |S21|^2 section   Chebyshev target\")\n",
    "for f, value in zip(coarse, through[\"3D\"]):\n",
    "    print(\n",
    "        f\"{f / 1e9:7.2f} {value:12.5f} {np.interp(f, fine, through['section']):17.5f} {chebyshev(f):18.5f}\"\n",
    "    )\n",
    "passing = fine[through[\"section\"] >= 0.999 / (1 + ripple)]\n",
    "edge = lambda f, t, side: (\n",
    "    np.interp(0.5, t[f <= 9.7e9], f[f <= 9.7e9])\n",
    "    if side == \"lower\"\n",
    "    else np.interp(0.5, t[f >= 10.3e9][::-1], f[f >= 10.3e9][::-1])\n",
    ")\n",
    "for side in (\"lower\", \"upper\"):\n",
    "    e3, e2 = edge(coarse, through[\"3D\"], side), edge(\n",
    "        coarse, np.interp(coarse, fine, through[\"section\"]), side\n",
    "    )\n",
    "    print(\n",
    "        f\"{side} half-power edge: 3D {e3 / 1e9:.4f} GHz, section {e2 / 1e9:.4f} GHz, difference {(e3 - e2) / 1e6:+.0f} MHz ({100 * (e3 / e2 - 1):+.2f} %)\"\n",
    "    )\n",
    "inside = (coarse >= 9.8e9) & (coarse <= 10.3e9)\n",
    "print(\n",
    "    f\"in the pass band 9.8-10.3 GHz: |S21|^2 of 3D and section differ by at most {np.max(np.abs(through['3D'] - np.interp(coarse, fine, through['section']))[inside]):.1e}\"\n",
    ")\n",
    "print(\n",
    "    f\"pass band of the section (|S21|^2 within the 0.1 dB ripple): {passing.min() / 1e9:.2f} to {passing.max() / 1e9:.2f} GHz, design 9.70 to 10.30 GHz; \"\n",
    "    f\"largest deviation from the Chebyshev response over 9.3-10.7 GHz {np.max(np.abs(through['section'] - chebyshev(fine))):.3f}\"\n",
    ")\n",
    "print(\n",
    "    f\"power balance |S11|^2 + |S21|^2 - 1: largest {max(abs(abs(s[(0, 0)]) ** 2 + abs(s[(1, 0)]) ** 2 - 1) for runs in sweep.values() for s in runs.values()):.1e}\"\n",
    ")\n",
    "print(\n",
    "    \"mesh study at 9.65 GHz:  cell size [mm]   tetrahedra   |S21|^2     arg S21 [°]   (section: |S21|^2 \"\n",
    "    + f\"{np.interp(9.65e9, fine, through['section']):.5f})\"\n",
    ")\n",
    "for h, s in study.items():\n",
    "    print(\n",
    "        f\"{1e3 * h:36.1f} {meshes[h].cell_count:12d} {abs(s[(1, 0)]) ** 2:10.5f} {np.degrees(np.angle(s[(1, 0)])):13.2f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Top: the transmission and the reflection in decibels, 3D (markers), section (line) and\n",
    "Chebyshev target (dashed). Bottom: the magnitude of the electric field on the mid-plane of the\n",
    "guide at 10 GHz: the wave builds up in the three resonators and leaves at the output."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "dB = lambda values: 10 * np.log10(np.maximum(values, 1e-12))\n",
    "field = (\n",
    "    lambda m: solve(m, guide, meshes[0.003], Nedelec(order=2)).field(m.electric_field)\n",
    ")(model(10e9, guide.volume, {}))\n",
    "fig = plots.figure(layout=[[\"spectrum\"], [\"field\"]], size=(15, 12))\n",
    "plots.line(\n",
    "    y={\n",
    "        \"|S21|, section\": (fine / 1e9, dB(through[\"section\"])),\n",
    "        \"|S11|, section\": (fine / 1e9, dB(reflected[\"section\"])),\n",
    "    },\n",
    "    points={\n",
    "        \"|S21|, 3D\": (coarse / 1e9, dB(through[\"3D\"])),\n",
    "        \"|S11|, 3D\": (coarse / 1e9, dB(reflected[\"3D\"])),\n",
    "    },\n",
    "    reference={\"Chebyshev target\": (fine / 1e9, dB(chebyshev(fine)))},\n",
    "    vlines={\"design band\": 9.7, \"\": 10.3},\n",
    "    ylimits=(-45, 2),\n",
    "    xlabel=\"frequency [GHz]\",\n",
    "    ylabel=\"[dB]\",\n",
    "    title=\"Transmission and reflection\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[\"spectrum\"],\n",
    ")\n",
    "plots.section(\n",
    "    field,\n",
    "    plane=Plane(origin=(0, 0, height / 2), normal=(0, 0, 1)),\n",
    "    component=lambda E, p: np.linalg.norm(np.abs(E), axis=1),\n",
    "    limits=\"robust\",\n",
    "    subdivisions=2,\n",
    "    label=\"|E| [V/m]\",\n",
    "    title=\"|E| on the mid-plane, 10 GHz\",\n",
    "    ax=fig[\"field\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add a fifth iris and a fourth resonator in `waveguide_iris_bandpass_filter_geometry.py` for steeper\n",
    "flanks, or make the irises thicker: the coupling drops, the band narrows and moves up, which is\n",
    "why the thin-iris design had to be refined in the first place."
   ]
  }
 ]
}
