{
 "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": [
    "# H-plane bend of a rectangular waveguide\n",
    "\n",
    "A hollow rectangular waveguide of width $a=22.86$ mm and height $b=10.16$ mm (WR-90) carries\n",
    "microwaves of the X band, 8.2 to 12.4 GHz. In this band only the TE$_{10}$ wave propagates: its\n",
    "electric field has a single component, across the narrow side, with a half sine over the width\n",
    "and zeros at the side walls. To route the guide, it is bent by 90° in the plane of the broad walls\n",
    "(an *H-plane bend*: the magnetic field lines lie in the plane of the bend). A smooth bend with an\n",
    "inner wall radius of 10 mm reflects only a small part of the wave.\n",
    "\n",
    "OneSimulation solves the time-harmonic Maxwell equation for the electric field in the air of the\n",
    "guide,\n",
    "\n",
    "$$\\nabla\\times\\big(\\mu_r^{-1}\\nabla\\times\\mathbf E\\big)-k_0^2\\,\\varepsilon_r\\,\\mathbf E=0,\\qquad k_0=\\omega/c,$$\n",
    "\n",
    "with second-order Nédélec elements on curved tetrahedra. Each waveguide port computes the modes of\n",
    "its cross-section, feeds or absorbs them exactly and returns the S-parameters.\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` (all walls) | perfect electric conductor |\n",
    "\n",
    "The air comes from the CAD file `waveguide_h_bend.step`, written by `waveguide_h_bend_geometry.py`\n",
    "with the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference** (D. M. Pozar, *Microwave Engineering*, 4th ed., Wiley 2012, §3.3; N. Marcuvitz,\n",
    "*Waveguide Handbook*, §5.31). The TE$_{10}$ wave has the propagation constant\n",
    "\n",
    "$$\\beta=\\sqrt{k_0^2-(\\pi/a)^2},\\qquad f_c=\\frac{c}{2a}=6.557\\ \\text{GHz},$$\n",
    "\n",
    "and TE$_{20}$ starts to propagate only at $c/a=13.11$ GHz. The bend has no closed form, but in an\n",
    "H-plane structure the TE$_{n0}$ fields do not vary across the height: the 3D problem reduces\n",
    "exactly to the scalar Helmholtz equation for $E_z$ on the H-plane section, with the side walls as\n",
    "$E_z=0$. That 2D computation, with a different element and its own ports, is the independent\n",
    "cross-check of the 3D bend. A lossless bend also 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",
    "    port_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": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the air of the bend with its named faces; `section` at half height gives the H-plane\n",
    "section for the cross-check, whose sides keep the face names. The 3D meshes have quadratic\n",
    "(curved) tetrahedra of 4, 3 and 2.2 mm, about six to eleven per wavelength at 12.4 GHz; the 4 mm\n",
    "mesh carries the frequency sweep. The section gets triangles of 0.8 mm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "guide = load(\"waveguide_h_bend.step\")\n",
    "faces = guide.boundaries\n",
    "width, height = 0.02286, guide.size[2]\n",
    "section = guide.section((0, 0, 1), origin=(0, 0, height / 2))\n",
    "sizes = (0.004, 0.003, 0.0022)\n",
    "meshes = {\n",
    "    h: TetrahedralMesher(target_size=h, geometry_order=2).generate(guide) for h in sizes\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=(14, 6))\n",
    "plots.geometry(\n",
    "    guide,\n",
    "    selection={\n",
    "        \"input port\": faces.port_in,\n",
    "        \"output port\": faces.port_out,\n",
    "        \"metal walls\": faces.metal,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Air of the H-plane bend (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[sizes[0]],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{meshes[sizes[0]].cell_count} curved 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 for a frequency, in 3D or on the section (polarization $E_z$);\n",
    "`solve` adds the two ports and the metal walls. The sweep runs from 8.2 to 12.4 GHz in steps of\n",
    "0.3 GHz, in 3D and on the section."
   ]
  },
  {
   "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=\"H-plane bend\",\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: (\n",
    "    r := solve(\n",
    "        m := model(frequency, guide.volume, {}), guide, meshes[h], Nedelec(order=2)\n",
    "    ),\n",
    "    m,\n",
    ")\n",
    "on_section = lambda frequency: (\n",
    "    r := solve(\n",
    "        m := model(frequency, section.domain(), {\"polarization\": \"Ez\"}),\n",
    "        section,\n",
    "        section_mesh,\n",
    "        Lagrange(order=2),\n",
    "    ),\n",
    "    m,\n",
    ")\n",
    "\n",
    "frequencies = np.arange(8.2e9, 12.41e9, 0.3e9)\n",
    "runs = {f: in_3d(f, sizes[0]) for f in frequencies}\n",
    "sweep = {\n",
    "    \"3D\": {f: scattering_parameters(*run) for f, run in runs.items()},\n",
    "    \"section\": {f: scattering_parameters(*on_section(f)) for f in frequencies},\n",
    "}\n",
    "study = {h: scattering_parameters(*in_3d(10e9, h)) for h in sizes}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The propagation constant of the computed port mode against the closed form, the reflection and\n",
    "transmission of the bend in 3D and on the section, the power balance, and the mesh study at\n",
    "10 GHz."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "exact_beta = lambda f: np.sqrt((2 * np.pi * f / light) ** 2 - (np.pi / width) ** 2)\n",
    "beta = {f: port_modes(*run)[0][\"propagation_constant\"] for f, run in runs.items()}\n",
    "print(\n",
    "    \"port mode TE10: largest relative deviation of beta from sqrt(k0^2 - (pi/a)^2) over the band \"\n",
    "    f\"{max(abs(b[0].real / exact_beta(f) - 1) for f, b in beta.items()):.1e}; second port mode evanescent at every frequency: \"\n",
    "    f\"{all(abs(b[1].real) < 1e-6 * abs(b[1]) for b in beta.values())}\"\n",
    ")\n",
    "print(\n",
    "    \"f [GHz]   |S11| 3D   |S11| section   |S21| 3D   arg S21 3D [°]   arg S21 section [°]   |S11|^2 + |S21|^2 - 1 (3D)\"\n",
    ")\n",
    "for f in frequencies:\n",
    "    s, t = sweep[\"3D\"][f], sweep[\"section\"][f]\n",
    "    print(\n",
    "        f\"{f / 1e9:7.1f} {abs(s[(0, 0)]):10.5f} {abs(t[(0, 0)]):15.5f} {abs(s[(1, 0)]):10.6f} {np.degrees(np.angle(s[(1, 0)])):16.2f} \"\n",
    "        f\"{np.degrees(np.angle(t[(1, 0)])):21.2f} {abs(s[(0, 0)]) ** 2 + abs(s[(1, 0)]) ** 2 - 1:28.1e}\"\n",
    "    )\n",
    "print(\n",
    "    f\"largest difference 3D - section over the band: |S11| {max(abs(abs(sweep['3D'][f][(0, 0)]) - abs(sweep['section'][f][(0, 0)])) for f in frequencies):.1e}, \"\n",
    "    f\"S21 {max(abs(sweep['3D'][f][(1, 0)] - sweep['section'][f][(1, 0)]) for f in frequencies):.1e}\"\n",
    ")\n",
    "print(\"mesh study at 10 GHz:  cell size [mm]   tetrahedra   |S11|      arg S21 [°]\")\n",
    "for h, s in study.items():\n",
    "    print(\n",
    "        f\"{1e3 * h:36.1f} {meshes[h].cell_count:12d} {abs(s[(0, 0)]):9.6f} {np.degrees(np.angle(s[(1, 0)])):12.3f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left: the reflection of the bend in decibels over the band, 3D against the section. Right: the\n",
    "instantaneous field $E_z$ on the mid-plane of the guide at 10 GHz (3 mm tetrahedra), with colour\n",
    "limits just above the TE$_{10}$ peak field of 1 W, $E_0=\\sqrt{4Z_{TE}P/(ab)}$ with\n",
    "$Z_{TE}=\\eta_0k_0/\\beta$: the wave turns around the bend with a half sine across the width."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "picture = solve(\n",
    "    m := model(10e9, guide.volume, {}),\n",
    "    guide,\n",
    "    TetrahedralMesher(target_size=0.003).generate(guide),\n",
    "    Nedelec(order=2),\n",
    ")\n",
    "field = picture.field(m.electric_field)\n",
    "peak = np.sqrt(\n",
    "    4\n",
    "    * np.sqrt(VACUUM_PERMEABILITY / VACUUM_PERMITTIVITY)\n",
    "    * (2 * np.pi * 10e9 / light)\n",
    "    / exact_beta(10e9)\n",
    "    / (width * height)\n",
    ")\n",
    "dB = lambda runs: np.array([20 * np.log10(abs(runs[f][(0, 0)])) for f in frequencies])\n",
    "fig = plots.figure(1, 2, size=(16, 6.5))\n",
    "plots.line(\n",
    "    points={\"3D, Nedelec elements\": (frequencies / 1e9, dB(sweep[\"3D\"]))},\n",
    "    reference={\"H-plane section, 2D\": (frequencies / 1e9, dB(sweep[\"section\"]))},\n",
    "    xlabel=\"frequency [GHz]\",\n",
    "    ylabel=\"|S11| [dB]\",\n",
    "    title=\"Reflection of the H-plane bend\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.section(\n",
    "    field,\n",
    "    plane=Plane(origin=(0, 0, height / 2), normal=(0, 0, 1)),\n",
    "    component=lambda E, p: np.real(E[:, 2]),\n",
    "    colormap=\"diverging\",\n",
    "    limits=(-500 * np.ceil(peak / 450), 500 * np.ceil(peak / 450)),\n",
    "    subdivisions=2,\n",
    "    label=\"Re E_z [V/m]\",\n",
    "    title=\"Electric field on the mid-plane, 10 GHz\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Set the inner radius in `waveguide_h_bend_geometry.py` to zero for a sharp corner, which reflects\n",
    "far more, or swap $a$ and $b$ in the profile and the extrusion to bend the guide in the plane of\n",
    "its narrow walls (an E-plane bend): that bend has no 2D reduction and needs the 3D model."
   ]
  }
 ]
}
