{
 "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": [
    "# TE10 mode of a rectangular waveguide\n",
    "\n",
    "An air-filled rectangular waveguide of cross-section $a\\times b$ is fed\n",
    "through a **waveguide port** at $z=0$ and terminated by a perfectly conducting\n",
    "short at $z=\\ell$. All other walls are perfect electric conductors. The port\n",
    "mode is not prescribed analytically: OneSimulation solves the transverse\n",
    "eigenvalue problem on the port cross-section numerically and uses the first\n",
    "TE eigenmode as the excitation.\n",
    "\n",
    "The air volume comes from the CAD file `rectangular_waveguide_te10.step` with the face groups\n",
    "`port`, `short` and `walls`; the script `rectangular_waveguide_te10_geometry.py` builds it with the CAD\n",
    "objects of OneSimulation. The frequency-domain Maxwell equations are solved with Nédélec\n",
    "(H(curl)) elements of order 2 on a tetrahedral mesh:\n",
    "\n",
    "$$\\nabla\\times\\big(\\mu_r^{-1}\\nabla\\times\\mathbf{E}\\big)-k_0^2\\,\\varepsilon_r\\,\\mathbf{E}=0,\n",
    "  \\qquad k_0=\\omega/c.$$\n",
    "\n",
    "**Reference.** For the TE$_{mn}$ modes of a rectangular guide\n",
    "\n",
    "$$f_{c,mn}=\\frac{c}{2}\\sqrt{\\Big(\\frac{m}{a}\\Big)^2+\\Big(\\frac{n}{b}\\Big)^2},\\qquad\n",
    "  f_{c,10}=\\frac{c}{2a},\\qquad\n",
    "  E_y\\propto\\sin\\!\\Big(\\frac{\\pi x}{a}\\Big),$$\n",
    "\n",
    "and, with $\\beta=\\sqrt{k_0^2-(\\pi/a)^2}$, the shorted guide carries the\n",
    "standing wave $|E_y(z)|\\propto|\\sin\\beta(\\ell-z)|$ without absorbing power."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\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\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",
    "    NumericalWaveguideMode,\n",
    "    PerfectElectricConductor,\n",
    "    WaveguidePort,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "The guide is 100 mm wide and 50 mm high, so TE10 cuts off at about 1.5 GHz and the next modes\n",
    "(TE20, TE01) at 3.0 GHz."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "guide = load(\"rectangular_waveguide_te10.step\")\n",
    "faces = guide.boundaries\n",
    "a, b, length = guide.size\n",
    "mesh = TetrahedralMesher(target_size=0.010).generate(guide)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 5))\n",
    "plots.geometry(\n",
    "    guide,\n",
    "    selection={\"port\": faces.port, \"short\": faces.short},\n",
    "    labels=False,\n",
    "    title=\"Air volume of the guide with port and short\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"{mesh.cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "At 2.5 GHz only TE10 propagates. The port carries the first numerical TE eigenmode with 1 W."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "frequency = 2.5e9\n",
    "model = FrequencyDomainMaxwell(\n",
    "    domain=guide.volume,\n",
    "    frequency=frequency,\n",
    "    material=IsotropicElectromagneticMaterial(),\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"TE10 mode of a rectangular waveguide\",\n",
    "    geometry=guide,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        WaveguidePort(\n",
    "            boundary=faces.port,\n",
    "            physics=model,\n",
    "            mode=NumericalWaveguideMode(\"TE\"),\n",
    "            incident_power=1.0,\n",
    "        ),\n",
    "        PerfectElectricConductor(boundary=faces.walls | faces.short, physics=model),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Nedelec(order=2)), linear_solver=ComplexSparseDirect()\n",
    ")\n",
    "result = Simulation(problem=problem, mesh=mesh, numerics=numerics).solve_stationary()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the closed-form TE10 solution\n",
    "\n",
    "The bound port mode exposes its cutoff frequency and its transverse electric field; the driven\n",
    "3D solution is sampled along the guide axis."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "c0 = 1.0 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)\n",
    "cutoff, beta = c0 / (2 * a), np.sqrt(\n",
    "    (2 * np.pi * frequency / c0) ** 2 - (np.pi / a) ** 2\n",
    ")\n",
    "port_mode = result.operators[model.model_id].ports[0][1]\n",
    "x = np.linspace(0.05 * a, 0.95 * a, 19)\n",
    "port_field = port_mode.electric_field(\n",
    "    np.column_stack((x, np.full_like(x, b / 2), np.zeros_like(x)))\n",
    ")\n",
    "mode_shape = port_field[:, 1] / port_field[np.argmax(np.abs(port_field[:, 1])), 1]\n",
    "z = np.linspace(0.02 * length, 0.98 * length, 25)\n",
    "amplitude = np.abs(\n",
    "    result.field(model.electric_field).evaluate(\n",
    "        np.column_stack((np.full_like(z, a / 2), np.full_like(z, b / 2), z))\n",
    "    )[:, 1]\n",
    ")\n",
    "standing_wave = np.abs(np.sin(beta * (length - z)))\n",
    "absorbed = result.field(model.absorbed_power_density).integrate()\n",
    "\n",
    "print(\n",
    "    f\"TE10 cutoff: computed {port_mode.cutoff_frequency / 1e9:.4f} GHz, reference {cutoff / 1e9:.4f} GHz, \"\n",
    "    f\"deviation {100 * abs(port_mode.cutoff_frequency / cutoff - 1):.2f} %\"\n",
    ")\n",
    "print(\n",
    "    f\"port mode shape against sin(pi x / a): largest deviation {np.max(np.abs(mode_shape - np.sin(np.pi * x / a))):.3f} of the peak, \"\n",
    "    f\"|E_x|/|E_y| = {np.max(np.abs(port_field[:, 0])) / np.max(np.abs(port_field[:, 1])):.3f}\"\n",
    ")\n",
    "print(\n",
    "    f\"standing wave against |sin(beta (l - z))|: largest deviation \"\n",
    "    f\"{np.max(np.abs(amplitude / amplitude.max() - standing_wave / standing_wave.max())):.3f} of the peak\"\n",
    ")\n",
    "print(\n",
    "    f\"absorbed power in the lossless guide: {absorbed.value:.3e} {absorbed.unit} (incident 1 W)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine_x, fine_z = np.linspace(0, a, 200), np.linspace(0, length, 300)\n",
    "fig = plots.figure(1, 2, size=(12, 4.8))\n",
    "plots.line(\n",
    "    points={\"port eigenmode\": (1e3 * x, mode_shape.real)},\n",
    "    reference={\"sin(pi x / a)\": (1e3 * fine_x, np.sin(np.pi * fine_x / a))},\n",
    "    xlabel=\"position x across the broad wall [mm]\",\n",
    "    ylabel=\"E_y / E_y,max\",\n",
    "    title=\"TE10 mode shape at the port\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"|E_y| on the axis\": (1e3 * z, amplitude / amplitude.max())},\n",
    "    reference={\n",
    "        \"|sin(beta (l - z))|\": (1e3 * fine_z, np.abs(np.sin(beta * (length - fine_z))))\n",
    "    },\n",
    "    xlabel=\"position z along the guide [mm]\",\n",
    "    ylabel=\"|E_y| / max\",\n",
    "    title=f\"Standing wave in the shorted guide at {frequency / 1e9:.1f} GHz\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the cross-section in `rectangular_waveguide_te10_geometry.py` and write the STEP file\n",
    "again: the cutoff follows $c/(2a)$. Ask for `NumericalWaveguideMode(\"TE\", order=2)` to excite the\n",
    "next mode (raise the drive frequency above its cutoff first), or give the material a finite\n",
    "conductivity to turn the absorbed power on."
   ]
  }
 ]
}
