{
 "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": [
    "# Cascaded rectangular cavity filter\n",
    "\n",
    "A section of rectangular waveguide between two metal walls is a cavity resonator; a slot in each\n",
    "wall lets the TE$_{10}$ wave in and out. A single cavity passes a narrow peak. Three cavities in a\n",
    "row, each coupled to its neighbours, pass a flat band and reject the frequencies outside it much\n",
    "more strongly: a cascaded cavity filter.\n",
    "\n",
    "**Design from coupled resonators.** A three-pole Chebyshev filter with 0.1 dB ripple has the\n",
    "low-pass prototype values $g_0=g_4=1$, $g_1=g_3=1.0316$, $g_2=1.1474$. For the pass band 9.8 to\n",
    "10.2 GHz in a WR-90 guide ($a=22.86$ mm, $b=10.16$ mm) the relative bandwidth, measured in guide\n",
    "wavelength as dispersive waveguide filters require, is\n",
    "$w_\\lambda=(\\lambda_g(f_1)-\\lambda_g(f_2))/\\lambda_g(f_0)$, and the resonators need (Hong and\n",
    "Lancaster, *Microstrip Filters for RF/Microwave Applications*, §3.3; Matthaei, Young and Jones,\n",
    "*Microwave Filters, Impedance-Matching Networks, and Coupling Structures*, §8.06)\n",
    "\n",
    "$$k_{12}=k_{23}=\\frac{w_\\lambda}{\\sqrt{g_1g_2}},\\qquad Q_e=\\frac{g_0g_1}{w_\\lambda}.$$\n",
    "\n",
    "Impedance inverters turn these into slot widths and cavity lengths. The slot edges are rounded with\n",
    "a radius of 0.5 mm, as a milling cutter leaves them; this also removes the field singularity of a\n",
    "sharp metal edge, so that coarse meshes already give converged results. Refined on the H-plane\n",
    "section for the 2 mm walls and the rounded edges, the filter has:\n",
    "\n",
    "| | outer walls | inner walls | outer cavities | middle cavity |\n",
    "|---|---|---|---|---|\n",
    "| slot width [mm] | 11.31 | 7.80 | | |\n",
    "| wall centre to wall centre [mm] | | | 18.04 | 19.60 |\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` (guide and walls) | 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 files `cascaded_cavity_filter.step` (the filter) and\n",
    "`cascaded_cavity_filter_cavity.step` (the middle cavity, closed) are written by\n",
    "`cascaded_cavity_filter_geometry.py` with the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference.** (i) The prototype response $|S_{21}|^2=1/(1+\\varepsilon^2T_3^2(\\Omega))$ with\n",
    "$\\varepsilon^2=10^{0.01}-1$ and $\\Omega=\\frac{2}{w_\\lambda}\\frac{\\lambda_{g0}-\\lambda_g}{\\lambda_{g0}}$; in\n",
    "the pass band the reflection stays below $-16.4$ dB. (ii) The slots span the full height, so the\n",
    "TE$_{10}$ field does not vary across it and the 3D problem reduces exactly to the scalar Helmholtz\n",
    "equation on the H-plane section: an independent cross-check. (iii) The closed middle cavity of\n",
    "length $d$ resonates at $f_{101}=\\frac c2\\sqrt{a^{-2}+d^{-2}}$ (Pozar, *Microwave Engineering*,\n",
    "4th ed., §6.3). (iv) A lossless filter conserves power and is reciprocal, $S_{21}=S_{12}$."
   ]
  },
  {
   "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, with_order\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",
    "    electromagnetic_modes,\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": [
    "## Design values\n",
    "\n",
    "The coupling coefficient and the external quality factor the resonators must have."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "low, high, ripple = 9.8e9, 10.2e9, 10**0.01 - 1\n",
    "g = np.array((1.0, 1.0316, 1.1474, 1.0316, 1.0))\n",
    "guide_wavelength = lambda f: 1 / np.sqrt((f / light) ** 2 - (1 / (2 * 0.02286)) ** 2)\n",
    "centre = np.sqrt(low * high)\n",
    "spread = (guide_wavelength(low) - guide_wavelength(high)) / guide_wavelength(centre)\n",
    "print(\n",
    "    f\"centre {centre / 1e9:.4f} GHz, relative bandwidth in guide wavelength {spread:.4f}; \"\n",
    "    f\"coupling coefficient k12 = k23 = {spread / np.sqrt(g[1] * g[2]):.4f}, external quality factor Qe = {g[0] * g[1] / spread:.2f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the filter and the closed cavity; `section` at half height gives the H-plane\n",
    "section, whose sides keep the face names. The 3D mesh has tetrahedra of at most 5 mm that follow\n",
    "the rounded slot edges; `with_order` places their middle nodes on the curved faces. The section has\n",
    "triangles of 1.5 mm, 0.4 mm on the walls, and a second section mesh with 0.2 mm checks its\n",
    "convergence."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "guide, closed = load(\"cascaded_cavity_filter.step\"), load(\n",
    "    \"cascaded_cavity_filter_cavity.step\"\n",
    ")\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",
    "mesh = with_order(\n",
    "    TetrahedralMesher(target_size=0.005, curvature_angle=1.5, grading=0.8).generate(\n",
    "        guide\n",
    "    ),\n",
    "    2,\n",
    ")\n",
    "section_meshes = {\n",
    "    size: TriangularMesher(target_size=0.0015, local_sizes={\"walls\": size}).generate(\n",
    "        section\n",
    "    )\n",
    "    for size in (0.0004, 0.0002)\n",
    "}\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 cavity filter (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{mesh.cell_count} curved quadratic tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Closed cavity\n",
    "\n",
    "`electromagnetic_modes` returns the lowest resonance of the closed middle cavity."
   ]
  },
  {
   "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",
    "numerics = lambda element: Numerics(\n",
    "    spatial=FiniteElement(element=element), linear_solver=ComplexSparseDirect()\n",
    ")\n",
    "cavity_model = model(10e9, closed.volume, {})\n",
    "modes = electromagnetic_modes(\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Closed cavity\",\n",
    "            geometry=closed,\n",
    "            physics=(cavity_model,),\n",
    "            boundary_conditions=(\n",
    "                PerfectElectricConductor(\n",
    "                    physics=cavity_model, boundary=closed.boundaries.metal\n",
    "                ),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=TetrahedralMesher(target_size=0.004).generate(closed),\n",
    "        numerics=numerics(Nedelec(order=2)),\n",
    "    ).solve_stationary(),\n",
    "    cavity_model,\n",
    "    mode_count=1,\n",
    "    target_frequency=10e9,\n",
    ")\n",
    "f101 = light / 2 * np.hypot(1 / closed.size[1], 1 / closed.size[0])\n",
    "print(\n",
    "    f\"closed middle cavity, TE101: computed {modes.frequencies.real[0] / 1e9:.5f} GHz, exact {f101 / 1e9:.5f} GHz, \"\n",
    "    f\"relative difference {abs(modes.frequencies.real[0] / f101 - 1):.1e}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Filter\n",
    "\n",
    "`solve` adds the two ports (fed at `fed`) and the metal and returns the result with its model.\n",
    "The 3D filter is solved at six frequencies across the pass band and its flanks and fed from the\n",
    "other side at 10 GHz for the reciprocity check; the section is swept from 9.5 to 10.5 GHz in steps\n",
    "of 20 MHz, and solved on the finer mesh on the lower flank."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "solve = lambda m, part, mesh, element, fed: (\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Cavity filter\",\n",
    "            geometry=part,\n",
    "            physics=(m,),\n",
    "            boundary_conditions=(\n",
    "                SectionWaveguidePort(\n",
    "                    physics=m,\n",
    "                    boundary=part.boundaries[fed],\n",
    "                    modes=2,\n",
    "                    incident_power=1.0,\n",
    "                ),\n",
    "                SectionWaveguidePort(\n",
    "                    physics=m,\n",
    "                    boundary=part.boundaries[\n",
    "                        \"port_out\" if fed == \"port_in\" else \"port_in\"\n",
    "                    ],\n",
    "                    modes=2,\n",
    "                ),\n",
    "                PerfectElectricConductor(physics=m, boundary=part.boundaries.metal),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=mesh,\n",
    "        numerics=numerics(element),\n",
    "    ).solve_stationary(),\n",
    "    m,\n",
    ")\n",
    "in_3d = lambda frequency, fed=\"port_in\": solve(\n",
    "    model(frequency, guide.volume, {}), guide, mesh, Nedelec(order=2), fed\n",
    ")\n",
    "on_section = lambda frequency, size=0.0004: scattering_parameters(\n",
    "    *solve(\n",
    "        model(frequency, section.domain(), {\"polarization\": \"Ez\"}),\n",
    "        section,\n",
    "        section_meshes[size],\n",
    "        Lagrange(order=2),\n",
    "        \"port_in\",\n",
    "    )\n",
    ")\n",
    "\n",
    "coarse = np.array((9.7e9, 9.8e9, 9.9e9, 10.0e9, 10.2e9, 10.3e9))\n",
    "fine = np.arange(9.5e9, 10.501e9, 0.02e9)\n",
    "runs = {f: in_3d(f) for f in coarse}\n",
    "sweep = {\n",
    "    \"3D\": {f: scattering_parameters(*run) for f, run in runs.items()},\n",
    "    \"section\": {f: on_section(f) for f in fine},\n",
    "}\n",
    "reverse = {10.0e9: scattering_parameters(*in_3d(10.0e9, \"port_out\"))}\n",
    "study = {size: on_section(9.75e9, size) for size in section_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 prototype; the return loss in\n",
    "the ripple band; the half-power edges; power balance, reciprocity, the section mesh study and the\n",
    "agreement of 3D and section."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "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   prototype\")\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):11.5f}\"\n",
    "    )\n",
    "band = {\"3D\": np.abs(omega(coarse)) <= 1, \"section\": np.abs(omega(fine)) <= 1}\n",
    "print(\n",
    "    f\"ripple band of the prototype (|Omega| <= 1): {fine[band['section']].min() / 1e9:.2f} to {fine[band['section']].max() / 1e9:.2f} GHz\"\n",
    ")\n",
    "for name in sweep:\n",
    "    print(\n",
    "        f\"{name:8s}: return loss in the ripple band at least {-10 * np.log10(reflected[name][band[name]].max()):.1f} dB \"\n",
    "        f\"(prototype 16.4 dB), |S21|^2 at least {through[name][band[name]].min():.4f}\"\n",
    "    )\n",
    "edge = lambda f, t, side: (\n",
    "    np.interp(0.5, t[f <= centre], f[f <= centre])\n",
    "    if side == \"lower\"\n",
    "    else np.interp(0.5, t[f >= centre][::-1], f[f >= centre][::-1])\n",
    ")\n",
    "for side in (\"lower\", \"upper\"):\n",
    "    print(\n",
    "        f\"{side} half-power edge: section {edge(fine, through['section'], side) / 1e9:.4f} GHz, prototype {edge(fine, chebyshev(fine), side) / 1e9:.4f} GHz\"\n",
    "    )\n",
    "print(\n",
    "    f\"largest deviation of the section from the prototype: {np.max(np.abs(through['section'] - chebyshev(fine))):.3f} in |S21|^2\"\n",
    ")\n",
    "print(\n",
    "    f\"power balance |S11|^2 + |S21|^2 - 1: largest {max(abs(reflected[n] + through[n] - 1).max() for n in sweep):.1e}\"\n",
    ")\n",
    "print(\n",
    "    f\"reciprocity at 10 GHz: |S21 - S12| = {abs(sweep['3D'][10.0e9][(1, 0)] - reverse[10.0e9][(1, 0)]):.1e}\"\n",
    ")\n",
    "print(\n",
    "    \"section mesh study on the lower flank, 9.75 GHz: \"\n",
    "    + \", \".join(\n",
    "        f\"walls {1e3 * size:.1f} mm, {section_meshes[size].cell_count} triangles: \"\n",
    "        f\"|S21|^2 = {abs(s[(1, 0)]) ** 2:.5f}\"\n",
    "        for size, s in study.items()\n",
    "    )\n",
    ")\n",
    "print(\n",
    "    f\"3D against section at the six frequencies: largest difference in |S21|^2 {np.max(np.abs(through['3D'] - np.interp(coarse, fine, through['section']))):.1e}, \"\n",
    "    f\"in |S11| {np.max(np.abs(np.sqrt(reflected['3D']) - np.sqrt(np.interp(coarse, fine, reflected['section'])))):.1e}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Top: transmission and reflection in decibels, 3D (markers), section (lines) and prototype\n",
    "(dashed). Bottom: the magnitude of the electric field on the mid-plane at 10 GHz: the wave\n",
    "stands in the three cavities and passes through the slots."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "dB = lambda values: 10 * np.log10(np.maximum(values, 1e-12))\n",
    "field = runs[10.0e9][0].field(runs[10.0e9][1].electric_field)\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 prototype\": (fine / 1e9, dB(chebyshev(fine)))},\n",
    "    vlines={\"design band\": low / 1e9, \"\": high / 1e9},\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 fourth cavity in `cascaded_cavity_filter_geometry.py` (with the prototype values of a\n",
    "four-pole filter) for steeper flanks, or narrow all slots together: the couplings drop, the band\n",
    "narrows and the out-of-band rejection grows."
   ]
  }
 ]
}
