{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "language": "python",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Substrate integrated waveguide\n",
    "\n",
    "A substrate integrated waveguide (SIW) is a rectangular waveguide built into a printed circuit\n",
    "board: the top and bottom copper are its broad walls, two rows of plated vias its narrow walls.\n",
    "Like a hollow waveguide it is a high-pass filter: below the cutoff of its TE$_{10}$ mode nothing\n",
    "passes. Here the vias have a diameter of 1.0 mm and a pitch of 1.8 mm, the rows are 11.81 mm apart\n",
    "on a 0.787 mm substrate of relative permittivity 2.2; 50 Ω microstrip lines feed the guide through\n",
    "tapers that turn the microstrip field into the TE$_{10}$ field.\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 first-order Nédélec elements. The top copper is a sheet without thickness (`region_interface`\n",
    "of a thin layer of air shaped like it, lying over the via holes); the vias are holes in the\n",
    "substrate with perfectly conducting walls. The feed lines end in `TEMPort`s that compute their\n",
    "quasi-TEM mode from the electrostatic potential of the cross-section; port 1 is fed and\n",
    "`scattering_parameters` gives reflection and transmission in the impedance of the feed lines.\n",
    "\n",
    "| faces | condition |\n",
    "|---|---|\n",
    "| `port_1`, `port_2` | TEM port, signal conductor: the copper |\n",
    "| `ground`, `vias`, copper | perfect electric conductor |\n",
    "| `open` (lid and long sides) | impedance boundary $Y_0=\\sqrt{\\varepsilon_0/\\mu_0}$ |\n",
    "\n",
    "**Reference** (Y. Cassivi, L. Perregrini, P. Arcioni, M. Bressan, K. Wu, G. Conciauro, *Dispersion\n",
    "characteristics of substrate integrated rectangular waveguide*, IEEE MWCL 12 (2002) 333-335;\n",
    "D. Deslandes, K. Wu, IEEE MWCL 11 (2001) 68-70). For $p/d<2$ and $d/w<0.2$ the SIW behaves like a\n",
    "rectangular waveguide of width\n",
    "\n",
    "$$w_{\\rm eff}=w-\\frac{d^2}{0.95\\,p},\\qquad f_c=\\frac{c}{2\\,w_{\\rm eff}\\sqrt{\\varepsilon_r}},\n",
    "  \\qquad \\beta=\\sqrt{\\varepsilon_r k_0^2-(\\pi/w_{\\rm eff})^2},$$\n",
    "\n",
    "11.225 mm and 9.003 GHz here. Above the cutoff the TE$_{10}$ wave travels with the propagation\n",
    "constant $\\beta$ of that waveguide; below it the wave decays and the transmission collapses."
   ],
   "id": "markdown-01"
  },
  {
   "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, RegionwiseElectromagneticMaterial\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 (FrequencyDomainMaxwell, ImpedanceBoundary, PerfectElectricConductor, TEMPort,\n",
    "                                             scattering_parameters)\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()\n",
    "\n",
    "light, eta0 = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY), np.sqrt(VACUUM_PERMEABILITY / VACUUM_PERMITTIVITY)\n",
    "rows, diameter, pitch, permittivity, height = 11.81e-3, 1.0e-3, 1.8e-3, 2.2, 0.787e-3"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "code-02"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the air with the vias removed, the substrate and the thin layer shaped like the top\n",
    "copper; substrate and layer become regions of one mesh. Mesh targets are 0.7 mm at the copper, 0.8 mm in the substrate, 0.22 mm at the vias and 1.3 mm in air. This increases the mesh from 38,395 to 73,139 tetrahedra and from 8,062 to 15,318 vertices."
   ],
   "id": "markdown-03"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "air = load(\"substrate_integrated_waveguide.step\")\n",
    "substrate = load(\"substrate_integrated_waveguide_substrate.step\").named(\"substrate\")\n",
    "copper = load(\"substrate_integrated_waveguide_copper.step\").named(\"copper\")\n",
    "faces = air.boundaries\n",
    "mesh = TetrahedralMesher(target_size=1.3e-3, embedded_regions=(substrate, copper), refinements=(\n",
    "    LocalRefinement(region=copper, target_size=0.7e-3), LocalRefinement(region=substrate, target_size=0.8e-3),\n",
    "    LocalRefinement(region=faces.vias, target_size=0.22e-3))).generate(air)\n",
    "sheet = region_interface(mesh, copper, substrate)\n",
    "print(f\"Mesh: {mesh.cell_count:,} tetrahedra, {len(mesh.coordinates):,} vertices\")\n",
    "\n",
    "view = plots.Camera(elevation=40, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry([copper, load(\"substrate_integrated_waveguide_vias.step\")], labels=False, camera=view, length_unit=\"mm\",\n",
    "               title=\"Top copper and vias (STEP)\", ax=fig[0])\n",
    "plots.mesh(mesh, groups=(\"all\",), legend=False, camera=view, length_unit=\"mm\", title=f\"{mesh.cell_count} tetrahedra\", ax=fig[1])\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "code-04"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Port 1 supplies 1 W. One frequency is below the predicted cutoff and three are above it.\n",
    "The final solve also supplies the field for the phase measurement at 12 GHz."
   ],
   "id": "markdown-05"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "material = RegionwiseElectromagneticMaterial({\"substrate\": IsotropicElectromagneticMaterial(relative_permittivity=permittivity)},\n",
    "                                             default=IsotropicElectromagneticMaterial())\n",
    "frequencies = np.array([8.0e9, 9.3e9, 10.5e9, 12.0e9])\n",
    "numerics = Numerics(spatial=FiniteElement(element=Nedelec(order=1)), linear_solver=ComplexSparseDirect())\n",
    "sweep = {}\n",
    "for frequency in frequencies:\n",
    "    m = FrequencyDomainMaxwell(domain=air.volume, frequency=frequency, material=material,\n",
    "                               phasor_convention=\"exp(-i*omega*t)\", amplitude_convention=\"peak\")\n",
    "    boundaries = (TEMPort(physics=m, boundary=faces.port_1, signal=sheet, incident_power=1.0),\n",
    "                  TEMPort(physics=m, boundary=faces.port_2, signal=sheet),\n",
    "                  PerfectElectricConductor(physics=m, boundary=faces.ground | faces.vias | sheet),\n",
    "                  ImpedanceBoundary(physics=m, boundary=faces.open, admittance=1 / eta0))\n",
    "    problem = Problem(name=\"Via-fenced waveguide\", geometry=air, physics=(m,), boundary_conditions=boundaries)\n",
    "    result = Simulation(problem=problem, mesh=mesh, numerics=numerics).solve_stationary()\n",
    "    sweep[frequency] = scattering_parameters(result, m)"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "code-06"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Transmission and reflection over the band against the cutoff of the equivalent waveguide; the\n",
    "power that is neither reflected nor transmitted leaves through the open top of the box, radiated by\n",
    "the feed lines and tapers. At 12 GHz the reflected wave is weak, so the field in the\n",
    "middle of the guide is one travelling wave: the slope of its phase along the guide is the\n",
    "propagation constant, compared with the equivalent waveguide and with a guide as wide as the via\n",
    "rows."
   ],
   "id": "markdown-07"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "dB = lambda x: 20 * np.log10(max(abs(x), 1e-6))\n",
    "effective = rows - diameter**2 / (0.95 * pitch)\n",
    "cutoff = light / (2 * effective * np.sqrt(permittivity))\n",
    "print(f\"equivalent width {effective * 1e3:.3f} mm, TE10 cutoff {cutoff / 1e9:.3f} GHz\")\n",
    "print(\"f [GHz]   |S21| [dB]   |S11| [dB]   |S11|^2 + |S21|^2\")\n",
    "for f, S in sweep.items():\n",
    "    print(f\"{f / 1e9:6.2f} {dB(S[(1, 0)]):12.2f} {dB(S[(0, 0)]):12.2f} {abs(S[(0, 0)]) ** 2 + abs(S[(1, 0)]) ** 2:18.4f}\")\n",
    "print(f\"below the cutoff ({frequencies[0] / 1e9:.1f} GHz) |S21| = {dB(sweep[frequencies[0]][(1, 0)]):.1f} dB; \"\n",
    "      f\"above it ({frequencies[-2] / 1e9:.1f} and {frequencies[-1] / 1e9:.1f} GHz) {dB(sweep[frequencies[-2]][(1, 0)]):.2f} and {dB(sweep[frequencies[-1]][(1, 0)]):.2f} dB\")\n",
    "x = np.linspace(-8e-3, 8e-3, 81)\n",
    "along = result.field(m.electric_field).evaluate(np.column_stack((x, 0 * x, 0 * x + height / 2)))[:, 2]\n",
    "phase = np.unwrap(np.angle(along))\n",
    "k0 = 2 * np.pi * 12e9 / light\n",
    "beta = {\"equivalent width\": np.sqrt(permittivity * k0**2 - (np.pi / effective) ** 2), \"width of the via rows\": np.sqrt(permittivity * k0**2 - (np.pi / rows) ** 2)}\n",
    "measured = abs(np.polyfit(x, phase, 1)[0])\n",
    "print(f\"propagation constant at 12 GHz from the phase along the guide: {measured:.1f} rad/m; equivalent waveguide {beta['equivalent width']:.1f} rad/m \"\n",
    "      f\"({measured / beta['equivalent width'] - 1:+.1%}), guide as wide as the via rows {beta['width of the via rows']:.1f} rad/m ({measured / beta['width of the via rows'] - 1:+.1%})\")"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "code-08"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left: transmission and reflection over the band, with the cutoff of the equivalent waveguide.\n",
    "Middle: the phase of the vertical field along the middle of the guide at 12 GHz against the two\n",
    "waveguide widths. Right: the electric field in the middle of the substrate at 12 GHz with port 1\n",
    "fed: the microstrip field spreads in the taper into the half sine of the TE$_{10}$ mode between the\n",
    "via rows."
   ],
   "id": "markdown-09"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(24, 6.5))\n",
    "plots.line(frequencies / 1e9, {\"|S21|\": [dB(S[(1, 0)]) for S in sweep.values()], \"|S11|\": [dB(S[(0, 0)]) for S in sweep.values()]}, markers=True,\n",
    "           vlines={\"TE10 cutoff, equivalent width\": cutoff / 1e9}, xlabel=\"frequency [GHz]\", ylabel=\"[dB]\", ylimits=(-60, 2),\n",
    "           title=\"S-parameters of the SIW\", legend=\"lower right\", ax=fig[0])\n",
    "plots.line(points={\"computed\": (x * 1e3, phase - phase[0])}, reference={f\"{name}\": (x * 1e3, np.sign(phase[-1] - phase[0]) * value * (x - x[0])) for name, value in beta.items()},\n",
    "           xlabel=\"x [mm]\", ylabel=\"phase of E_z [rad]\", title=\"Phase along the guide, 12 GHz\", legend=\"upper left\", ax=fig[1])\n",
    "plots.section(result.field(m.electric_field), plane=Plane(origin=(0.0, 0.0, 0.5 * height), normal=(0.0, 0.0, 1.0)),\n",
    "              component=lambda E, p: np.linalg.norm(np.abs(E), axis=1), limits=\"robust\", subdivisions=1, length_unit=\"mm\",\n",
    "              label=\"|E| [V/m]\", title=\"Electric field in the substrate, 12 GHz\", ax=fig[2])\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "code-10"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the via pitch or the row spacing in `substrate_integrated_waveguide_geometry.py`: the cutoff\n",
    "follows the equivalent width. With a pitch above twice the diameter the via walls start to leak."
   ],
   "id": "markdown-11"
  }
 ]
}
