{
 "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": [
    "# Microstrip coupled-line bandpass filter\n",
    "\n",
    "Cascaded coupled lines, each pair a quarter wavelength long at the centre frequency, form a\n",
    "bandpass filter: the upper line of one section and the lower line of the next make a half-wave\n",
    "resonator, and the coupling across each gap sets the bandwidth. Here a third-order filter with\n",
    "0.5 dB equal ripple and 10 % bandwidth at 5 GHz is etched on a 0.813 mm substrate of relative\n",
    "permittivity 3.55. The even- and odd-mode impedances of the sections follow from the prototype;\n",
    "their widths and gaps come from the coupled microstrip formulas of Garg and Bahl, and each quarter\n",
    "wave is shortened by the open-end extension of the microstrip (Hammerstad), the fringing field\n",
    "beyond the open end of every resonator.\n",
    "\n",
    "OneSimulation solves the time-harmonic Maxwell equation\n",
    "\n",
    "$$\\nabla\\times\\big(\\mu_r^{-1}\\nabla\\times\\mathbf E\\big)-k_0^2\\,\\varepsilon_r\\,\\mathbf E=0$$\n",
    "\n",
    "with second-order Nédélec elements. Each piece of copper is a sheet without thickness: the face\n",
    "between the substrate and a thin layer of air shaped like the piece (`region_interface`). The feed\n",
    "lines end in `TEMPort`s that compute their quasi-TEM mode from the electrostatic potential of the\n",
    "cross-section; `scattering_matrix` gives the S-parameters in 50 Ω from one factorization per\n",
    "frequency.\n",
    "\n",
    "| faces | condition |\n",
    "|---|---|\n",
    "| `port_1`, `port_2` | TEM port, signal conductor: the copper |\n",
    "| `ground`, copper | perfect electric conductor |\n",
    "| `open` (lid and long sides) | impedance boundary $Y_0=\\sqrt{\\varepsilon_0/\\mu_0}$ |\n",
    "\n",
    "**Reference** (D. M. Pozar, *Microwave Engineering*, 4th ed., Wiley 2012, §8.8; M. K. Krishna Garg,\n",
    "I. J. Bahl, IEEE Trans. MTT 27 (1979) 700). With the prototype values $g_1=g_3=1.5963$, $g_2=1.0967$\n",
    "and the fractional bandwidth $\\Delta$, the inverters are $Z_0J_1=\\sqrt{\\pi\\Delta/2g_1}$,\n",
    "$Z_0J_n=\\pi\\Delta/(2\\sqrt{g_{n-1}g_n})$, $Z_0J_4=\\sqrt{\\pi\\Delta/2g_3}$ and the section\n",
    "impedances $Z_{0e,o}=Z_0(1\\pm JZ_0+(JZ_0)^2)$. A coupled-line section with two open ends has\n",
    "$Z_{11}=-\\tfrac{\\mathrm j}{2}(Z_{0e}+Z_{0o})\\cot\\theta$ and\n",
    "$Z_{21}=-\\tfrac{\\mathrm j}{2}(Z_{0e}-Z_{0o})\\csc\\theta$, $\\theta=\\tfrac\\pi2 f/f_0$; the cascade of\n",
    "the four sections is the ideal filter: passband 4.75-5.25 GHz with 0.5 dB ripple."
   ]
  },
  {
   "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 (\n",
    "    IsotropicElectromagneticMaterial,\n",
    "    RegionwiseElectromagneticMaterial,\n",
    ")\n",
    "from onesim.meshing import LocalRefinement, TetrahedralMesher, region_interface\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",
    "    ImpedanceBoundary,\n",
    "    PerfectElectricConductor,\n",
    "    TEMPort,\n",
    "    port_values,\n",
    "    scattering_matrix,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()\n",
    "\n",
    "eta0 = np.sqrt(VACUUM_PERMEABILITY / VACUUM_PERMITTIVITY)\n",
    "f0, bandwidth, height, prototype = 5e9, 0.10, 0.813e-3, (1.5963, 1.0967, 1.5963, 1.0)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the box of air, the substrate and the five pieces of copper (input line with the first\n",
    "quarter wave, three resonators, output line with the last quarter wave); each becomes a region of\n",
    "one mesh. Second-order tetrahedra of 0.6 mm follow the copper, 1.4 mm the substrate and 5 mm the air."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "box = load(\"coupled_line_bandpass_filter.step\")\n",
    "substrate = load(\"coupled_line_bandpass_filter_substrate.step\").named(\"substrate\")\n",
    "pieces = [\n",
    "    load(f\"coupled_line_bandpass_filter_copper_{k}.step\").named(f\"copper_{k}\")\n",
    "    for k in range(5)\n",
    "]\n",
    "faces = box.boundaries\n",
    "mesh = TetrahedralMesher(\n",
    "    target_size=5e-3,\n",
    "    embedded_regions=(substrate, *pieces),\n",
    "    refinements=(\n",
    "        *(LocalRefinement(region=piece, target_size=0.6e-3) for piece in pieces),\n",
    "        LocalRefinement(region=substrate, target_size=1.4e-3),\n",
    "    ),\n",
    ").generate(box)\n",
    "copper = region_interface(mesh, pieces[0], substrate)\n",
    "for piece in pieces[1:]:\n",
    "    copper = copper | region_interface(mesh, piece, substrate)\n",
    "\n",
    "view = plots.Camera(elevation=50, azimuth=-70)\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    [substrate, *pieces],\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    length_unit=\"mm\",\n",
    "    title=\"Substrate and copper (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    length_unit=\"mm\",\n",
    "    title=f\"{mesh.cell_count} quadratic tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`simulation` builds the filter at one frequency; the sweep runs from 4.4 to 5.6 GHz."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "material = RegionwiseElectromagneticMaterial(\n",
    "    {\"substrate\": IsotropicElectromagneticMaterial(relative_permittivity=3.55)},\n",
    "    default=IsotropicElectromagneticMaterial(),\n",
    ")\n",
    "simulation = lambda f, fed=False: (\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Coupled-line bandpass filter\",\n",
    "            geometry=box,\n",
    "            physics=(\n",
    "                m := FrequencyDomainMaxwell(\n",
    "                    domain=box.volume,\n",
    "                    frequency=f,\n",
    "                    material=material,\n",
    "                    phasor_convention=\"exp(-i*omega*t)\",\n",
    "                    amplitude_convention=\"peak\",\n",
    "                ),\n",
    "            ),\n",
    "            boundary_conditions=(\n",
    "                TEMPort(\n",
    "                    physics=m,\n",
    "                    boundary=faces.port_1,\n",
    "                    signal=copper,\n",
    "                    incident_power=float(fed),\n",
    "                ),\n",
    "                TEMPort(physics=m, boundary=faces.port_2, signal=copper),\n",
    "                PerfectElectricConductor(physics=m, boundary=faces.ground | copper),\n",
    "                ImpedanceBoundary(physics=m, boundary=faces.open, admittance=1 / eta0),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=mesh,\n",
    "        numerics=Numerics(\n",
    "            spatial=FiniteElement(element=Nedelec(order=2)),\n",
    "            linear_solver=ComplexSparseDirect(),\n",
    "        ),\n",
    "    ),\n",
    "    m,\n",
    ")\n",
    "frequencies = np.round(np.linspace(4.4e9, 5.6e9, 7), -6)\n",
    "sweep = {\n",
    "    f: scattering_matrix(*simulation(f), reference_impedance=50.0) for f in frequencies\n",
    "}\n",
    "\n",
    "\n",
    "def ideal(f):\n",
    "    inverters = (\n",
    "        [np.sqrt(np.pi * bandwidth / (2 * prototype[0]))]\n",
    "        + [\n",
    "            np.pi * bandwidth / (2 * np.sqrt(prototype[n - 1] * prototype[n]))\n",
    "            for n in (1, 2)\n",
    "        ]\n",
    "        + [np.sqrt(np.pi * bandwidth / (2 * prototype[2] * prototype[3]))]\n",
    "    )\n",
    "    theta, chain = np.pi / 2 * f / f0, np.eye(2, dtype=complex)\n",
    "    for j in inverters:\n",
    "        even, odd = 50 * (1 + j + j**2), 50 * (1 - j + j**2)\n",
    "        z11, z21 = -0.5j * (even + odd) / np.tan(theta), -0.5j * (even - odd) / np.sin(\n",
    "            theta\n",
    "        )\n",
    "        chain = chain @ np.array(\n",
    "            [[z11 / z21, (z11**2 - z21**2) / z21], [1 / z21, z11 / z21]]\n",
    "        )\n",
    "    (a, b), (c, d) = chain\n",
    "    return abs((a + b / 50 - c * 50 - d) / (a + b / 50 + c * 50 + d)), abs(\n",
    "        2 / (a + b / 50 + c * 50 + d)\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The characteristic impedance of the feed lines, the S-parameters over the band against the ideal\n",
    "coupled-line filter, the centre and the bandwidth of the computed passband, and reciprocity."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "result, m = (lambda run: (run[0].solve_stationary(), run[1]))(simulation(f0, fed=True))\n",
    "dB = lambda x: 20 * np.log10(max(abs(x), 1e-6))\n",
    "print(\n",
    "    \"feed lines (TEM ports): Z0 = \"\n",
    "    + \", \".join(\n",
    "        f\"{v['characteristic_impedance'].real:.2f}\" for v in port_values(result, m)\n",
    "    )\n",
    "    + \" ohm\"\n",
    ")\n",
    "print(\"f [GHz]   |S21| [dB]   |S11| [dB]    ideal |S21| [dB]   ideal |S11| [dB]\")\n",
    "for f, S in sweep.items():\n",
    "    print(\n",
    "        f\"{f / 1e9:6.2f} {dB(S[1, 0]):12.2f} {dB(S[0, 0]):12.2f} {dB(ideal(f)[1]):18.2f} {dB(ideal(f)[0]):18.2f}\"\n",
    "    )\n",
    "passing = [f for f, S in sweep.items() if dB(S[1, 0]) > -3.0]\n",
    "print(\n",
    "    f\"computed -3 dB passband of the sweep: {min(passing) / 1e9:.2f} to {max(passing) / 1e9:.2f} GHz (ideal filter -3 dB: \"\n",
    "    f\"{min(f for f in np.linspace(4.4e9, 5.6e9, 1201) if dB(ideal(f)[1]) > -3) / 1e9:.3f} to \"\n",
    "    f\"{max(f for f in np.linspace(4.4e9, 5.6e9, 1201) if dB(ideal(f)[1]) > -3) / 1e9:.3f} GHz)\"\n",
    ")\n",
    "print(\n",
    "    f\"largest transmission {max(dB(S[1, 0]) for S in sweep.values()):.2f} dB; reciprocity max |S12 - S21| \"\n",
    "    f\"{max(abs(S[0, 1] - S[1, 0]) for S in sweep.values()):.1e}; power lost by radiation at {f0 / 1e9:.1f} GHz \"\n",
    "    f\"{1 - abs(sweep[f0][0, 0]) ** 2 - abs(sweep[f0][1, 0]) ** 2:.3f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The computed passband lies a few percent below the design band and is somewhat narrower: the\n",
    "coupled microstrip formulas used for the design are accurate to a few percent in the even- and\n",
    "odd-mode impedances, and the open ends and the steps between the sections are only approximated\n",
    "by the open-end extension. Part of the power leaves through the open top of the box (the filter\n",
    "radiates at its open ends), which the ideal circuit does not know.\n",
    "\n",
    "## Figure\n",
    "\n",
    "Left: transmission and reflection over the band against the ideal filter. Right: the electric field\n",
    "in the substrate at 5 GHz with port 1 fed: the resonators carry standing waves and pass the signal\n",
    "from gap to gap."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = np.linspace(4.4e9, 5.6e9, 241)\n",
    "fig = plots.figure(1, 2, size=(18, 6.5))\n",
    "plots.line(\n",
    "    points={\n",
    "        \"|S21|\": (frequencies / 1e9, [dB(S[1, 0]) for S in sweep.values()]),\n",
    "        \"|S11|\": (frequencies / 1e9, [dB(S[0, 0]) for S in sweep.values()]),\n",
    "    },\n",
    "    reference={\n",
    "        \"ideal |S21|\": (fine / 1e9, [dB(ideal(f)[1]) for f in fine]),\n",
    "        \"ideal |S11|\": (fine / 1e9, [dB(ideal(f)[0]) for f in fine]),\n",
    "    },\n",
    "    xlabel=\"frequency [GHz]\",\n",
    "    ylabel=\"[dB]\",\n",
    "    ylimits=(-50, 2),\n",
    "    title=\"S-parameters of the filter\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.section(\n",
    "    result.field(m.electric_field),\n",
    "    plane=Plane(origin=(0.0, 0.0, 0.6 * height), normal=(0.0, 0.0, 1.0)),\n",
    "    component=lambda E, p: np.linalg.norm(np.abs(E), axis=1),\n",
    "    limits=\"robust\",\n",
    "    subdivisions=1,\n",
    "    length_unit=\"mm\",\n",
    "    label=\"|E| [V/m]\",\n",
    "    title=\"Electric field in the substrate, 5 GHz, port 1 fed\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the bandwidth or the order in `coupled_line_bandpass_filter_geometry.py` (prototype values of\n",
    "Pozar, Table 8.4); narrower gaps give stronger coupling and a wider band."
   ]
  }
 ]
}
