{
 "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": [
    "# Coaxial probe to waveguide transition\n",
    "\n",
    "The most common way into a rectangular waveguide is a coaxial connector on its broad wall: the\n",
    "inner conductor continues into the guide as a straight probe, parallel to the electric field of the\n",
    "TE$_{10}$ wave, and a short circuit behind the probe sends the wave that starts backwards forward\n",
    "again. The probe length sets the resistance the coaxial line sees; the distance to the short sets\n",
    "the reactance. With the short a quarter guide wavelength behind it, a probe of this size is\n",
    "strongly capacitive; moving the short closer adds the inductance of a short-circuited guide and\n",
    "matches the transition.\n",
    "\n",
    "Here an air-filled 50 Ω line (inner radius 0.65 mm) enters a WR-90 guide ($a=22.86$ mm,\n",
    "$b=10.16$ mm); the probe is $d=6.1$ mm long and the short $s=5.5$ mm behind it, found by a short\n",
    "parameter study of probe length and short for a match at 10 GHz. The transition is symmetric about\n",
    "the plane through the probe and the guide axis; only one half is modelled, with a magnetic wall on\n",
    "the plane of symmetry. 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 second-order Nédélec elements. The coaxial end is a `TEMPort`: it computes the TEM mode of its\n",
    "cross-section from the electrostatic potential between the probe and the outer conductor, with its\n",
    "characteristic impedance. The guide end is a `SectionWaveguidePort` with the computed TE$_{10}$ mode\n",
    "of the half guide. `scattering_matrix` feeds each port in turn, returns all S-parameters from one\n",
    "factorization and moves the reference plane of the coaxial port to the wall of the guide.\n",
    "\n",
    "| faces | condition |\n",
    "|---|---|\n",
    "| `coax_port` | TEM port, signal conductor `probe` |\n",
    "| `guide_port` | waveguide port, TE$_{10}$ |\n",
    "| `probe`, `metal` | perfect electric conductor |\n",
    "| `symmetry` | perfect magnetic conductor |\n",
    "\n",
    "**Reference** (R. E. Collin, *Field Theory of Guided Waves*, 2nd ed., IEEE Press 1991, §7.1;\n",
    "D. M. Pozar, *Microwave Engineering*, 4th ed., §4.7). A current $I(z)$ along the probe on the\n",
    "centre line of the guide excites the TE$_{10}$ wave with the amplitude\n",
    "$A=-\\frac{Z_{TE}}{ab}\\int_0^d I\\,\\mathrm dz$, $Z_{TE}=\\eta_0k_0/\\beta$. Only this wave carries\n",
    "power, and with the short at $s$ behind the probe it goes forward only: the input resistance referred\n",
    "to the current $I_0$ at the base is\n",
    "\n",
    "$$R_{in}=\\frac{2Z_{TE}}{ab}\\,\\sin^2(\\beta s)\\,\\Big|\\frac{1}{I_0}\\int_0^d I\\,\\mathrm dz\\Big|^2 ,$$\n",
    "\n",
    "for any current on the probe; the classical estimate takes the current of an open line,\n",
    "$\\int I\\,\\mathrm dz=I_0\\tan(k_0d/2)/k_0$. The reactance comes from the waves that do not\n",
    "propagate and has no such simple form. The study of the short below compares the computed\n",
    "resistance with this formula, evaluated with the computed probe current (Ampère's law around the\n",
    "probe). A lossless reciprocal two-port further has $S_{12}=S_{21}$ and $|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 LocalRefinement, 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",
    "    PerfectElectricConductor,\n",
    "    PerfectMagneticConductor,\n",
    "    SectionWaveguidePort,\n",
    "    TEMPort,\n",
    "    scattering_matrix,\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, eta0 = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY), np.sqrt(\n",
    "    VACUUM_PERMEABILITY / VACUUM_PERMITTIVITY\n",
    ")\n",
    "a, b, d, s, pin, coax = 0.02286, 0.01016, 0.0061, 0.0055, 0.00065, 0.008"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the matched half transition with its named faces, and the same transition with the\n",
    "short at 4.5, 6.5, 8.0 and 9.9 mm (a quarter guide wavelength at 10 GHz). Second-order tetrahedra of\n",
    "2.5 mm fill the guide (twelve per wavelength at 10 GHz), refined to 0.35 mm on the probe."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "part = load(\"coaxial_probe_waveguide_transition.step\")\n",
    "faces = part.boundaries\n",
    "shorts = {5.5: part} | {\n",
    "    mm: load(\n",
    "        f\"coaxial_probe_waveguide_transition_short_{mm:.1f}\".replace(\".\", \"p\") + \".step\"\n",
    "    )\n",
    "    for mm in (4.5, 6.5, 8.0, 9.9)\n",
    "}\n",
    "mesher = lambda body: TetrahedralMesher(\n",
    "    target_size=2.5e-3,\n",
    "    refinements=(LocalRefinement(region=body.boundaries.probe, target_size=0.35e-3),),\n",
    ").generate(body)\n",
    "mesh = mesher(part)\n",
    "\n",
    "view = plots.Camera(elevation=20, azimuth=-70)\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    part,\n",
    "    selection={\n",
    "        \"coaxial port\": faces.coax_port,\n",
    "        \"waveguide port\": faces.guide_port,\n",
    "        \"probe\": faces.probe,\n",
    "        \"plane of symmetry\": faces.symmetry,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    length_unit=\"mm\",\n",
    "    title=\"Half of the transition (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    length_unit=\"mm\",\n",
    "    title=f\"{mesh.cell_count} quadratic tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`simulation` builds the model of a transition at one frequency with its two ports. The sweep of the\n",
    "matched transition covers the single-mode band of the guide, 8.4 to 12.4 GHz. The half model\n",
    "carries half the current at the same voltage, so the impedances of the full transition are half\n",
    "those of the half model (the characteristic impedance of the port included). Impedances are given\n",
    "as $R+\\mathrm jX$ in the engineering convention ($X>0$ inductive); the model itself uses\n",
    "$e^{-i\\omega t}$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "simulation = lambda f, body=part, grid=mesh, power=0.0: (\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Coaxial probe transition\",\n",
    "            geometry=body,\n",
    "            physics=(\n",
    "                m := FrequencyDomainMaxwell(\n",
    "                    domain=body.volume,\n",
    "                    frequency=f,\n",
    "                    material=IsotropicElectromagneticMaterial(),\n",
    "                    phasor_convention=\"exp(-i*omega*t)\",\n",
    "                    amplitude_convention=\"peak\",\n",
    "                ),\n",
    "            ),\n",
    "            boundary_conditions=(\n",
    "                TEMPort(\n",
    "                    physics=m,\n",
    "                    boundary=body.boundaries.coax_port,\n",
    "                    signal=body.boundaries.probe,\n",
    "                    incident_power=power,\n",
    "                ),\n",
    "                SectionWaveguidePort(\n",
    "                    physics=m, boundary=body.boundaries.guide_port, modes=1\n",
    "                ),\n",
    "                PerfectElectricConductor(\n",
    "                    physics=m, boundary=body.boundaries.metal | body.boundaries.probe\n",
    "                ),\n",
    "                PerfectMagneticConductor(physics=m, boundary=body.boundaries.symmetry),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=grid,\n",
    "        numerics=Numerics(\n",
    "            spatial=FiniteElement(element=Nedelec(order=2)),\n",
    "            linear_solver=ComplexSparseDirect(),\n",
    "        ),\n",
    "    ),\n",
    "    m,\n",
    ")\n",
    "frequencies = np.round(np.arange(8.4e9, 12.41e9, 0.4e9), -6)\n",
    "sweep = {\n",
    "    f: scattering_matrix(*simulation(f), reference_planes=(coax, 0.0))\n",
    "    for f in frequencies\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The characteristic impedance of the coaxial port, the S-parameters, reciprocity and power balance\n",
    "over the band, and the input impedance of the full transition at the wall,\n",
    "$Z_{in}=Z_0(1+S_{11})/(1-S_{11})$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "beta = lambda f: np.sqrt((2 * np.pi * f / light) ** 2 - (np.pi / a) ** 2)\n",
    "z_te = lambda f: eta0 * (2 * np.pi * f / light) / beta(f)\n",
    "z0 = sweep[frequencies[0]].impedances[0].real / 2\n",
    "impedance = {f: np.conj(z0 * (1 + S[0, 0]) / (1 - S[0, 0])) for f, S in sweep.items()}\n",
    "dB = lambda x: 20 * np.log10(abs(x))\n",
    "print(\n",
    "    f\"coaxial port: characteristic impedance {z0:.2f} ohm, closed form eta0 ln(b/a)/(2 pi) = {eta0 * 50 / 60 / (2 * np.pi):.2f} ohm\"\n",
    ")\n",
    "print(\"f [GHz]  |S11| [dB]   |S21|    |S11|^2+|S21|^2-1   |S12-S21|   Z_in [ohm]\")\n",
    "for f, S in sweep.items():\n",
    "    print(\n",
    "        f\"{f / 1e9:6.2f} {dB(S[0, 0]):10.1f} {abs(S[1, 0]):9.4f} {abs(S[0, 0]) ** 2 + abs(S[1, 0]) ** 2 - 1:16.1e} {abs(S[0, 1] - S[1, 0]):12.1e}\"\n",
    "        f\"   {impedance[f].real:7.2f} {impedance[f].imag:+7.2f}j\"\n",
    "    )\n",
    "band = [f for f in frequencies if dB(sweep[f][0, 0]) < -15]\n",
    "print(\n",
    "    f\"at 10 GHz |S11| = {dB(sweep[10e9][0, 0]):.1f} dB; |S11| below -15 dB from {min(band) / 1e9:.1f} to {max(band) / 1e9:.1f} GHz \"\n",
    "    f\"of the sweep ({(max(band) - min(band)) / 1e8:.0f} % of 10 GHz)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The short and the modal theory\n",
    "\n",
    "At 10 GHz each of the five transitions is fed with 1 W (0.5 W in the half model). Ampère's law on a\n",
    "circle of 1.5 probe radii, $I(z)=2\\rho\\int_0^\\pi H_\\varphi\\,\\mathrm d\\varphi$ on the half\n",
    "circle, gives the current along the probe, the modal formula with it the input resistance; the port\n",
    "reports it independently, from the reflection moved to the wall,\n",
    "$\\Gamma=S_{11}e^{-2\\mathrm ik_0\\ell}$ over the $\\ell=8$ mm of coaxial line. A finer mesh\n",
    "(1.8 mm, 0.35 → 0.25 mm on the probe) checks the matched transition."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "heights, ring = np.linspace(0.0, d, 60), np.linspace(0.0, np.pi, 25)\n",
    "circle = np.array(\n",
    "    [[1.5 * pin * np.cos(p), 1.5 * pin * np.sin(p), z] for z in heights for p in ring]\n",
    ")\n",
    "ampere = (\n",
    "    lambda r, m: 3\n",
    "    * pin\n",
    "    * np.trapezoid(\n",
    "        np.einsum(\n",
    "            \"hpd,pd->hp\",\n",
    "            r.field(m.magnetic_flux_density).evaluate(circle).reshape(60, 25, 3),\n",
    "            np.column_stack((-np.sin(ring), np.cos(ring), 0 * ring)),\n",
    "        ),\n",
    "        ring,\n",
    "        axis=1,\n",
    "    )\n",
    "    / VACUUM_PERMEABILITY\n",
    ")\n",
    "runs = {\n",
    "    mm: (lambda run: (run[0].solve_stationary(), run[1]))(\n",
    "        simulation(10e9, body, mesh if mm == 5.5 else mesher(body), power=0.5)\n",
    "    )\n",
    "    for mm, body in sorted(shorts.items())\n",
    "}\n",
    "study = {}\n",
    "for mm, (r, m) in runs.items():\n",
    "    gamma = scattering_parameters(r, m)[(0, 0)] * np.exp(\n",
    "        -2j * 2 * np.pi * 10e9 / light * coax\n",
    "    )\n",
    "    current = ampere(r, m)\n",
    "    mean = abs(np.trapezoid(current, heights) / current[0]) / d\n",
    "    study[mm] = (\n",
    "        np.conj(z0 * (1 + gamma) / (1 - gamma)),\n",
    "        2\n",
    "        * z_te(10e9)\n",
    "        / (a * b)\n",
    "        * np.sin(beta(10e9) * mm * 1e-3) ** 2\n",
    "        * (mean * d) ** 2,\n",
    "        mean,\n",
    "    )\n",
    "print(\n",
    "    \"short [mm]   beta s [deg]   Z_in [ohm]          |S11| [dB]   R modal, computed current [ohm]   mean I / I0\"\n",
    ")\n",
    "for mm, (z, modal, mean) in study.items():\n",
    "    print(\n",
    "        f\"{mm:8.1f} {np.degrees(beta(10e9) * mm * 1e-3):12.1f}   {z.real:7.2f} {z.imag:+7.2f}j {dB((z - 50) / (z + 50)):12.1f} {modal:20.2f} ({modal / z.real - 1:+.1%})\"\n",
    "        f\" {mean:14.3f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"sinusoidal current: mean I / I0 = {np.tan(np.pi * 10e9 * d / light) / (2 * np.pi * 10e9 / light) / d:.3f}\"\n",
    ")\n",
    "fine = TetrahedralMesher(\n",
    "    target_size=1.8e-3,\n",
    "    refinements=(LocalRefinement(region=faces.probe, target_size=0.25e-3),),\n",
    ").generate(part)\n",
    "refined = scattering_matrix(*simulation(10e9, part, fine), reference_planes=(coax, 0.0))\n",
    "refined = np.conj(\n",
    "    refined.impedances[0].real / 2 * (1 + refined[0, 0]) / (1 - refined[0, 0])\n",
    ")\n",
    "print(\n",
    "    f\"mesh study at 10 GHz: Z_in = {impedance[10e9].real:.2f} {impedance[10e9].imag:+.2f}j ohm ({mesh.cell_count} tetrahedra), \"\n",
    "    f\"{refined.real:.2f} {refined.imag:+.2f}j ohm ({fine.cell_count} tetrahedra)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The short changes the current on the probe (its mean falls from 0.73 to 0.57 of the base current\n",
    "as the short moves from 4.5 mm to a quarter wavelength), and the resistance follows: the modal\n",
    "formula with the computed current stays 3 to 10 % below what the port reports, at every position of\n",
    "the short. The formula counts only the current on the probe; the fields in the opening of the\n",
    "coaxial line and the step from the line into the guide add to what the port measures. The\n",
    "reactance swings from capacitive at a quarter wavelength to inductive close to the short; at\n",
    "5.5 mm it nearly vanishes, which is the match.\n",
    "\n",
    "## Figure\n",
    "\n",
    "Left: reflection of the matched transition over the band. Middle: the input impedance against the\n",
    "position of the short at 10 GHz, with the modal resistance. Right: the electric field on the plane\n",
    "of symmetry of the matched transition at 10 GHz: the TEM wave of the coaxial line turns into the\n",
    "TE$_{10}$ wave that travels towards the port."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "result, m = runs[5.5]\n",
    "positions = np.array(sorted(study))\n",
    "fig = plots.figure(1, 3, size=(24, 6.5))\n",
    "plots.line(\n",
    "    frequencies / 1e9,\n",
    "    {\"|S11|\": [dB(S[0, 0]) for S in sweep.values()]},\n",
    "    markers=True,\n",
    "    hlines={\"-15 dB\": -15.0},\n",
    "    xlabel=\"frequency [GHz]\",\n",
    "    ylabel=\"|S11| [dB]\",\n",
    "    title=\"Reflection of the matched transition\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"R (port)\": (positions, [study[mm][0].real for mm in positions]),\n",
    "        \"X (port)\": (positions, [study[mm][0].imag for mm in positions]),\n",
    "    },\n",
    "    reference={\n",
    "        \"R, modal formula with the computed current\": (\n",
    "            positions,\n",
    "            [study[mm][1] for mm in positions],\n",
    "        )\n",
    "    },\n",
    "    hlines={\"50 ohm\": 50.0},\n",
    "    xlabel=\"short behind the probe [mm]\",\n",
    "    ylabel=\"impedance [ohm]\",\n",
    "    title=\"Input impedance at 10 GHz\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.section(\n",
    "    result.field(m.electric_field),\n",
    "    plane=Plane(origin=(0.0, 5e-5, 0.0), normal=(0.0, 1.0, 0.0)),\n",
    "    component=lambda E, p: np.linalg.norm(np.abs(E), axis=1),\n",
    "    limits=\"robust\",\n",
    "    subdivisions=2,\n",
    "    length_unit=\"mm\",\n",
    "    label=\"|E| [V/m]\",\n",
    "    title=\"Electric field on the plane of symmetry, 10 GHz\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the probe length `probe` in `coaxial_probe_waveguide_transition_geometry.py`: a longer probe\n",
    "raises the resistance and needs the short closer to cancel its capacitance. A disc on the probe tip\n",
    "(a top hat) or a thicker probe widens the band of good match."
   ]
  }
 ]
}
