{
 "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": [
    "# Polarized ports of a circular waveguide\n",
    "\n",
    "The fundamental TE$_{11}$ mode of a circular waveguide is twofold degenerate: two patterns of the\n",
    "same cutoff frequency, rotated by 90° against each other, carry the two polarizations. A numerical\n",
    "mode solver on a meshed port returns *some* orthogonal pair of this degenerate eigenspace, turned\n",
    "by an angle that depends on the mesh. To excite a defined polarization, the pair must be aligned\n",
    "first; any polarization, linear at any angle or circular, is then a complex combination of the\n",
    "two modes:\n",
    "\n",
    "$$\\mathbf E_t=a_1\\,\\mathbf e_1+a_2\\,\\mathbf e_2 .$$\n",
    "\n",
    "The air-filled guide of radius $a$ comes from the CAD file\n",
    "`polarized_circular_waveguide_port.step` with the face groups `port`, `exit` and `wall`, written\n",
    "by `polarized_circular_waveguide_port_geometry.py` with the CAD objects of OneSimulation. The\n",
    "port carries a `WaveguideModeBasis` of the first two numerical TE eigenmodes with the amplitudes\n",
    "$a_1,a_2$; the wall is a perfect conductor; the exit is an impedance boundary with the TE$_{11}$\n",
    "wave admittance $Y=\\beta/(\\omega\\mu_0)$, which absorbs the travelling mode without reflection.\n",
    "Nédélec elements of order 2 solve\n",
    "\n",
    "$$\\nabla\\times\\big(\\mu_r^{-1}\\nabla\\times\\mathbf E\\big)-k_0^2\\,\\varepsilon_r\\,\\mathbf E=0 .$$\n",
    "\n",
    "**Reference** (D. M. Pozar, *Microwave Engineering*, 4th ed., Wiley 2012, §3.4; C. A. Balanis,\n",
    "*Advanced Engineering Electromagnetics*, 2nd ed., §9.4).\n",
    "\n",
    "$$f_c=\\frac{c\\,p'_{11}}{2\\pi a},\\quad p'_{11}=1.8412,\\qquad\n",
    "  \\beta=\\sqrt{k_0^2-(p'_{11}/a)^2},\\qquad\n",
    "  \\mathbf E_t(0,0,z)\\propto(\\hat{\\mathbf x}\\pm\\mathrm i\\,\\hat{\\mathbf y})\\,e^{\\mathrm i\\beta z}$$\n",
    "\n",
    "for a circularly polarized wave on the axis: equal components in quadrature (axial ratio 1),\n",
    "with $|\\mathbf E_t|$ constant along the matched guide and the phase growing as $\\beta z$."
   ]
  },
  {
   "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",
    "    ImpedanceBoundary,\n",
    "    NumericalWaveguideMode,\n",
    "    PerfectElectricConductor,\n",
    "    WaveguideModeBasis,\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",
    "With a radius of 20 mm, TE11 cuts off at 4.39 GHz and TM01 at 5.74 GHz; the guide is driven at\n",
    "5.4 GHz, where only the TE11 pair propagates."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "guide = load(\"polarized_circular_waveguide_port.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, \"matched exit\": faces.exit},\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=20, azimuth=-60),\n",
    "    title=\"Air volume of the circular guide\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=plots.Camera(elevation=20, azimuth=-60),\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",
    "`drive` solves the guide for a pair of modal amplitudes. A first solve with $(a_1,a_2)=(1,0)$\n",
    "binds the two mesh modes; their fields at the centre of the port form the matrix that converts a\n",
    "wanted polarization into amplitudes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "frequency = 5.4e9\n",
    "c0 = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)\n",
    "kc, k0 = 1.841183781 / a, 2 * np.pi * frequency / c0\n",
    "beta = np.sqrt(k0**2 - kc**2)\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",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Nedelec(order=2)), linear_solver=ComplexSparseDirect()\n",
    ")\n",
    "drive = lambda amplitudes: Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"Circular guide with a polarized port\",\n",
    "        geometry=guide,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            WaveguidePort(\n",
    "                boundary=faces.port,\n",
    "                physics=model,\n",
    "                incident_power=1.0,\n",
    "                mode=WaveguideModeBasis(\n",
    "                    modes=(\n",
    "                        NumericalWaveguideMode(\"TE\", order=1),\n",
    "                        NumericalWaveguideMode(\"TE\", order=2),\n",
    "                    ),\n",
    "                    amplitudes=amplitudes,\n",
    "                ),\n",
    "            ),\n",
    "            PerfectElectricConductor(boundary=faces.wall, physics=model),\n",
    "            ImpedanceBoundary(\n",
    "                boundary=faces.exit,\n",
    "                physics=model,\n",
    "                admittance=beta / (2 * np.pi * frequency * VACUUM_PERMEABILITY),\n",
    "            ),\n",
    "        ),\n",
    "    ),\n",
    "    mesh=mesh,\n",
    "    numerics=numerics,\n",
    ").solve_stationary()\n",
    "\n",
    "first = drive((1.0, 0.0))\n",
    "pair = [port.mode for _, port in first.operators[model.model_id].ports]\n",
    "centre = np.column_stack(\n",
    "    [mode.electric_field(np.zeros((1, 3)))[0, :2] for mode in pair]\n",
    ")\n",
    "print(\n",
    "    \"TE11 pair from the port mesh: cutoffs \"\n",
    "    + \", \".join(f\"{mode.cutoff_frequency / 1e9:.4f} GHz\" for mode in pair)\n",
    "    + f\" (Bessel zero: {c0 * kc / (2 * np.pi) / 1e9:.4f} GHz); polarization angles \"\n",
    "    + \", \".join(f\"{np.degrees(np.arctan2(e[1], e[0])):.1f}°\" for e in centre.T)\n",
    ")\n",
    "\n",
    "wanted = {\n",
    "    \"linear at 45°\": np.array([1.0, 1.0]) / np.sqrt(2),\n",
    "    \"circular\": np.array([1.0, 1.0j]) / np.sqrt(2),\n",
    "}\n",
    "amplitudes = {name: np.linalg.solve(centre, target) for name, target in wanted.items()}\n",
    "solutions = {\n",
    "    name: drive(tuple(values / np.linalg.norm(values)))\n",
    "    for name, values in amplitudes.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the closed forms\n",
    "\n",
    "On the axis the transverse field gives the polarization ellipse at every position: its tilt,\n",
    "its axial ratio (minor over major axis) and its sense of rotation; the amplitudes $(1,\\mathrm i)$\n",
    "turn the field from $x$ towards $y$ in time. The magnitude shows whether the exit reflects, the\n",
    "phase slope is the propagation constant."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "z = np.linspace(0.01 * length, 0.99 * length, 41)\n",
    "axis = {\n",
    "    name: result.field(model.electric_field).evaluate(\n",
    "        np.column_stack((np.zeros_like(z), np.zeros_like(z), z))\n",
    "    )[:, :2]\n",
    "    for name, result in solutions.items()\n",
    "}\n",
    "print(\n",
    "    \"drive            tilt [°]   axial ratio   rotation   |E_t| max/min on the axis   beta [rad/m]   closed form   deviation\"\n",
    ")\n",
    "for name, field in axis.items():\n",
    "    ex, ey = field[:, 0], field[:, 1]\n",
    "    tilt = 0.5 * np.degrees(\n",
    "        np.arctan2(\n",
    "            np.mean(2 * (ex * ey.conj()).real),\n",
    "            np.mean(np.abs(ex) ** 2 - np.abs(ey) ** 2),\n",
    "        )\n",
    "    )\n",
    "    ratio = np.mean(\n",
    "        np.abs(np.abs(ex + 1j * ey) - np.abs(ex - 1j * ey))\n",
    "        / (np.abs(ex + 1j * ey) + np.abs(ex - 1j * ey))\n",
    "    )\n",
    "    magnitude = np.linalg.norm(np.abs(field), axis=1)\n",
    "    slope = np.polyfit(z, np.unwrap(np.angle(ex + ey)), 1)[0]\n",
    "    turn = (\n",
    "        \"none\"\n",
    "        if ratio < 0.05\n",
    "        else (\"x -> y\" if np.mean((ex.conj() * ey).imag) > 0 else \"y -> x\")\n",
    "    )\n",
    "    tilt = f\"{tilt:9.2f}\" if ratio < 0.95 else f\"{'-':>9s}\"\n",
    "    print(\n",
    "        f\"{name:15s} {tilt} {ratio:13.4f}   {turn:6s} {magnitude.max() / magnitude.min():22.4f}\"\n",
    "        f\" {slope:16.3f} {beta:13.3f} {100 * (slope / beta - 1):+10.3f} %\"\n",
    "    )\n",
    "print(\n",
    "    \"closed form: linear drive -> tilt 45°, axial ratio 0; circular drive -> axial ratio 1, rotation x -> y; matched exit -> max/min 1\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The tip of the electric field vector on the axis over one period at three positions along the\n",
    "guide, and the field magnitude along the axis."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "phase = np.exp(-2j * np.pi * np.linspace(0, 1, 121))\n",
    "stations = {f\"z = {1e3 * z[index]:.0f} mm\": index for index in (4, 20, 36)}\n",
    "fig = plots.figure(1, 3, size=(17, 5.2))\n",
    "for panel, (name, field) in enumerate(axis.items()):\n",
    "    plots.line(\n",
    "        y={\n",
    "            label: ((field[index, 0] * phase).real, (field[index, 1] * phase).real)\n",
    "            for label, index in stations.items()\n",
    "        },\n",
    "        xlabel=\"E_x [V/m]\",\n",
    "        ylabel=\"E_y [V/m]\",\n",
    "        title=f\"Field vector over one period, {name}\",\n",
    "        legend=\"center\",\n",
    "        ax=fig[panel],\n",
    "    )\n",
    "plots.line(\n",
    "    1e3 * z,\n",
    "    {name: np.linalg.norm(np.abs(field), axis=1) for name, field in axis.items()},\n",
    "    ylimits=(0, None),\n",
    "    xlabel=\"position z along the guide [mm]\",\n",
    "    ylabel=\"|E_t| on the axis [V/m]\",\n",
    "    title=\"Travelling wave into the matched exit\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Choose `wanted = np.array([1, -1j]) / np.sqrt(2)` for the opposite sense of rotation, or replace\n",
    "the matched exit by a perfect conductor: the reflected circular wave returns with the opposite\n",
    "handedness, which is how a polarizer and a short separate transmit and receive channels in an\n",
    "antenna feed."
   ]
  }
 ]
}
