{
 "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": [
    "# TE11 cutoff of a circular waveguide\n",
    "\n",
    "An air-filled circular waveguide of radius $a$ is fed through a **waveguide\n",
    "port** on its bottom disk ($z=0$) and terminated by a perfectly conducting\n",
    "short at $z=\\ell$; the cylindrical wall is a perfect electric conductor. The\n",
    "port mode is not prescribed analytically: OneSimulation solves the transverse\n",
    "eigenvalue problem on the meshed port cross-section and uses its first TE\n",
    "eigenmode (the fundamental TE11 mode) as the excitation.\n",
    "\n",
    "The air volume comes from the CAD file `circular_waveguide_te11_cutoff.step` with the face\n",
    "groups `port`, `short` and `walls`; the script `circular_waveguide_te11_cutoff_geometry.py`\n",
    "builds it with the CAD objects of OneSimulation. The frequency-domain Maxwell equations are\n",
    "solved with Nédélec (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.** The cutoff wavenumbers of a circular guide are zeros of Bessel\n",
    "functions, $k_c=p'_{nm}/a$ for TE$_{nm}$ (zeros of $J_n'$) and $k_c=p_{nm}/a$\n",
    "for TM$_{nm}$ (zeros of $J_n$):\n",
    "\n",
    "$$f_c=\\frac{c\\,k_c}{2\\pi},\\qquad p'_{11}=1.8412,\\quad p_{01}=2.4048 .$$\n",
    "\n",
    "TE11 is the fundamental mode, TM01 the first higher mode, and the guide is\n",
    "single-moded between the two cutoffs. The TE11 electric field through the\n",
    "centre of the guide follows $2J_1(k_c r)/(k_c r)$ along the polarisation\n",
    "direction and $2J_1'(k_c r)$ perpendicular to it. With\n",
    "$\\beta=\\sqrt{k_0^2-k_c^2}$ the shorted guide carries the standing wave\n",
    "$|\\mathbf{E}_t(z)|\\propto|\\sin\\beta(\\ell-z)|$ on its axis."
   ]
  },
  {
   "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",
    "from scipy.special import jv, jvp\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "With a radius of 20 mm the TE11 mode cuts off at about 4.39 GHz and TM01 at 5.74 GHz."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "guide = load(\"circular_waveguide_te11_cutoff.step\")\n",
    "faces = guide.boundaries\n",
    "a, length = guide.size[0] / 2, guide.size[2]\n",
    "mesh = TetrahedralMesher(target_size=0.004).generate(guide)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 5.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",
    "The guide is driven at 5.4 GHz, inside the single-mode band, with the first TE port mode. A\n",
    "second solve at 6.5 GHz, above the TM01 cutoff, binds the first TM port mode."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def solve(frequency, mode):\n",
    "    \"\"\"Driven field of the shorted guide and the port eigenmode that feeds it.\"\"\"\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=\"Circular waveguide with a short\",\n",
    "        geometry=guide,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            WaveguidePort(\n",
    "                boundary=faces.port, physics=model, mode=mode, 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)),\n",
    "        linear_solver=ComplexSparseDirect(),\n",
    "    )\n",
    "    result = Simulation(\n",
    "        problem=problem, mesh=mesh, numerics=numerics\n",
    "    ).solve_stationary()\n",
    "    return (\n",
    "        result.field(model.electric_field),\n",
    "        result.field(model.absorbed_power_density),\n",
    "        result.operators[model.model_id].ports[0][1],\n",
    "    )\n",
    "\n",
    "\n",
    "frequency = 5.4e9\n",
    "electric_field, absorbed_power, te11 = solve(frequency, NumericalWaveguideMode(\"TE\"))\n",
    "tm01 = solve(6.5e9, NumericalWaveguideMode(\"TM\"))[2]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the Bessel-function solution\n",
    "\n",
    "Each bound port mode exposes its cutoff frequency and its transverse electric field. TE11 is\n",
    "linearly polarised at the centre; the mesh picks the polarisation direction of the degenerate\n",
    "pair, so it is read off the computed mode. The driven field is sampled along the guide axis."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "c0 = 1.0 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)\n",
    "kc = 1.841183781 / a\n",
    "cutoff_te11, cutoff_tm01 = c0 * kc / (2 * np.pi), c0 * 2.404825558 / (2 * np.pi * a)\n",
    "beta = np.sqrt((2 * np.pi * frequency / c0) ** 2 - kc**2)\n",
    "\n",
    "centre = te11.electric_field(np.zeros((1, 3)))[0]\n",
    "polarisation = centre / np.linalg.norm(centre)\n",
    "perpendicular = np.array([-polarisation[1], polarisation[0], 0.0])\n",
    "r = np.linspace(-0.9 * a, 0.9 * a, 25)\n",
    "along = te11.electric_field(np.outer(r, polarisation)) @ polarisation\n",
    "across = te11.electric_field(np.outer(r, perpendicular)) @ polarisation\n",
    "along, across = (along / along[len(r) // 2]).real, (across / across[len(r) // 2]).real\n",
    "fine_r = np.linspace(-a, a, 300)\n",
    "x, fine_x = (np.where(np.abs(kc * s) > 1e-12, kc * s, 1e-12) for s in (r, fine_r))\n",
    "\n",
    "z = np.linspace(0.02 * length, 0.98 * length, 25)\n",
    "axis_field = electric_field.evaluate(\n",
    "    np.column_stack((np.zeros_like(z), np.zeros_like(z), z))\n",
    ")\n",
    "transverse = np.hypot(np.abs(axis_field[:, 0]), np.abs(axis_field[:, 1]))\n",
    "standing_wave = np.abs(np.sin(beta * (length - z)))\n",
    "absorbed = absorbed_power.integrate()\n",
    "\n",
    "print(\n",
    "    f\"TE11 cutoff: computed {te11.cutoff_frequency / 1e9:.4f} GHz, reference {cutoff_te11 / 1e9:.4f} GHz, \"\n",
    "    f\"deviation {100 * abs(te11.cutoff_frequency / cutoff_te11 - 1):.2f} %\"\n",
    ")\n",
    "print(\n",
    "    f\"TM01 cutoff: computed {tm01.cutoff_frequency / 1e9:.4f} GHz, reference {cutoff_tm01 / 1e9:.4f} GHz, \"\n",
    "    f\"deviation {100 * abs(tm01.cutoff_frequency / cutoff_tm01 - 1):.2f} %\"\n",
    ")\n",
    "print(\n",
    "    f\"TE11 mode profile against 2 J1(x)/x and 2 J1'(x): largest deviation \"\n",
    "    f\"{max(np.max(np.abs(along - 2 * jv(1, x) / x)), np.max(np.abs(across - 2 * jvp(1, x)))):.3f} of the centre value\"\n",
    ")\n",
    "print(\n",
    "    f\"standing wave against |sin(beta (l - z))|: largest deviation \"\n",
    "    f\"{np.max(np.abs(transverse / transverse.max() - standing_wave / standing_wave.max())):.3f} of the peak, \"\n",
    "    f\"|E_z|/|E_t| = {np.max(np.abs(axis_field[:, 2])) / transverse.max():.3f}\"\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_z = np.linspace(0, length, 300)\n",
    "fig = plots.figure(1, 2, size=(12, 4.8))\n",
    "plots.line(\n",
    "    points={\n",
    "        \"along E: 2 J1(k_c r) / (k_c r)\": (1e3 * r, along),\n",
    "        \"across E: 2 J1'(k_c r)\": (1e3 * r, across),\n",
    "    },\n",
    "    reference={\n",
    "        \"along E: 2 J1(k_c r) / (k_c r)\": (1e3 * fine_r, 2 * jv(1, fine_x) / fine_x),\n",
    "        \"across E: 2 J1'(k_c r)\": (1e3 * fine_r, 2 * jvp(1, fine_x)),\n",
    "    },\n",
    "    xlabel=\"position through the centre [mm]\",\n",
    "    ylabel=\"E / E(centre)\",\n",
    "    title=\"TE11 profile at the port\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"|E_t| on the axis\": (1e3 * z, transverse / transverse.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_t| / 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 radius in `circular_waveguide_te11_cutoff_geometry.py` and write the STEP file again:\n",
    "both cutoffs scale with $1/a$. Ask for `NumericalWaveguideMode(\"TE\", order=3)` above 7.3 GHz to\n",
    "bind the TE21 mode and compare it with $p'_{21}=3.0542$, or refine `target_size` to tighten the\n",
    "cutoff comparisons, which converge quadratically with the port mesh size."
   ]
  }
 ]
}
