{
 "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": [
    "# Monopole antenna fed by a magnetic frill\n",
    "\n",
    "Voltages are not defined in an electromagnetic wave model, so an antenna needs a feed that is a\n",
    "field. The classic one is the **magnetic frill**: the radial electric field\n",
    "$E_r=V/(r\\ln(b/a))$ in the annular aperture of a coaxial line between its inner radius $a$ and\n",
    "outer radius $b$, equivalent to a ring of magnetic current $M_\\varphi=-2E_r$ on the ground plane.\n",
    "Here the frill is not imposed by hand: 10 mm of the 50 ohm coaxial line are part of the model, and\n",
    "a `SectionWaveguidePort` at its end feeds the TEM mode and absorbs what is reflected. The field\n",
    "in the aperture then is the frill field of the actual antenna current.\n",
    "\n",
    "The monopole (height $h=70$ mm, radius $a=1.5$ mm) and its feed are bodies of revolution, and the\n",
    "field has only $H_\\varphi$, $E_r$ and $E_z$: `FrequencyDomainMaxwell` with polarization `Hphi` on\n",
    "the meridian plane ($r$, $z$). A first-order absorbing `ImpedanceBoundary` on the hemisphere of\n",
    "0.3 m (one wavelength at 1 GHz) lets the radiation leave.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| `feed` (end of the coaxial line) | waveguide port, TEM mode, 1 W |\n",
    "| `antenna`, `ground` | perfect electric conductor |\n",
    "| `outer` (hemisphere) | impedance boundary $Y_0=\\sqrt{\\varepsilon_0/\\mu_0}$ |\n",
    "| `axis` | regular: $H_\\varphi=0$ |\n",
    "\n",
    "The impedance is read inside the coaxial line, 5 mm below the ground plane, where the field is a\n",
    "pure TEM wave: $V=\\int_a^bE_r\\,\\mathrm dr$ and $I=2\\pi rH_\\varphi$ (Ampère) give $Z=V/I$, whose\n",
    "reflection $|Z-Z_c|/|Z+Z_c|$ ($Z_c=\\eta_0\\ln(b/a)/2\\pi$) must match the reflection of the port and\n",
    "$\\tfrac12\\mathrm{Re}(VI^*)$ the power accepted at the port. Moving the reflection coefficient\n",
    "$\\Gamma$ along the 5 mm of line, $\\Gamma_L=\\Gamma e^{-2\\mathrm ik\\ell}$, gives the input impedance at\n",
    "the ground plane, $Z_{in}=Z_c(1+\\Gamma_L)/(1-\\Gamma_L)$. `far_field` with `ground_plane=0`\n",
    "mirrors the hemisphere in the ground plane and returns the pattern of the full space.\n",
    "\n",
    "**Reference** (C. A. Balanis, *Antenna Theory*, 4th ed., §4.6 and §4.7.4; S. A. Schelkunoff and\n",
    "H. T. Friis, *Antennas: Theory and Practice*, 1952). With the sinusoidal current\n",
    "$I(z)=I_0\\sin k(h-z)$ the monopole radiates\n",
    "\n",
    "$$E_\\theta=\\frac{\\mathrm i\\eta_0I_0}{2\\pi}\\frac{e^{\\mathrm ikr}}{r}\n",
    "  \\frac{\\cos(kh\\cos\\theta)-\\cos kh}{\\sin\\theta},\\qquad\n",
    "  R_{in}=\\frac{\\eta_0}{2\\pi\\sin^2kh}\\int_0^{\\pi/2}\\frac{(\\cos(kh\\cos\\theta)-\\cos kh)^2}{\\sin\\theta}\\mathrm d\\theta,$$\n",
    "\n",
    "the input resistance referred to the base current (36.5 ohm for $h=\\lambda/4$). The thickness of\n",
    "a real wire shortens the resonance by a few percent but leaves the resistance there close to the\n",
    "thin-wire value."
   ]
  },
  {
   "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 TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange, RevolvedH1SpaceFactory\n",
    "from onesim.numerics.linear import ComplexSparseDirect\n",
    "from onesim.physics.electromagnetics import (\n",
    "    FrequencyDomainMaxwell,\n",
    "    ImpedanceBoundary,\n",
    "    PerfectElectricConductor,\n",
    "    SectionWaveguidePort,\n",
    "    far_field,\n",
    "    scattering_parameters,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()\n",
    "\n",
    "height, wire, shield = 0.07, 0.0015, 0.00345\n",
    "light = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)\n",
    "impedance = np.sqrt(VACUUM_PERMEABILITY / VACUUM_PERMITTIVITY)\n",
    "characteristic = impedance * np.log(shield / wire) / (2 * np.pi)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the half solid of revolution; `section` with the plane $y=0$ returns its meridian\n",
    "plane with the named sides. Quadratic triangles of 12 mm (a 25th of the wavelength), 0.7 mm along\n",
    "the antenna and 0.4 mm in the coaxial line."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plane = load(\"monopole_magnetic_frill_feed.step\").section((0, 1, 0))\n",
    "sides = plane.boundaries\n",
    "mesh = TriangularMesher(\n",
    "    target_size=0.012, local_sizes={\"antenna\": 7e-4, \"feed\": 4e-4}\n",
    ").generate(plane)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 7))\n",
    "plots.geometry(\n",
    "    plane,\n",
    "    selection={\n",
    "        \"feed (coaxial port)\": sides.feed,\n",
    "        \"antenna\": sides.antenna,\n",
    "        \"ground\": sides.ground,\n",
    "        \"outer\": sides.outer,\n",
    "    },\n",
    "    labels=False,\n",
    "    title=\"Meridian plane of monopole and feed (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"{mesh.cell_count} quadratic triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "One model per frequency from 0.8 to 1.3 GHz; the port feeds 1 W in the TEM mode of the coaxial\n",
    "line."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2), provider=RevolvedH1SpaceFactory()),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "model = lambda frequency: FrequencyDomainMaxwell(\n",
    "    domain=plane.domain(),\n",
    "    frequency=frequency,\n",
    "    material=IsotropicElectromagneticMaterial(),\n",
    "    polarization=\"Hphi\",\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    ")\n",
    "solve = lambda physics: Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"monopole\",\n",
    "        geometry=plane,\n",
    "        physics=(physics,),\n",
    "        boundary_conditions=(\n",
    "            SectionWaveguidePort(\n",
    "                physics=physics, boundary=sides.feed, modes=1, incident_power=1.0\n",
    "            ),\n",
    "            PerfectElectricConductor(\n",
    "                physics=physics, boundary=sides.antenna | sides.ground\n",
    "            ),\n",
    "            ImpedanceBoundary(\n",
    "                physics=physics, boundary=sides.outer, admittance=1 / impedance\n",
    "            ),\n",
    "        ),\n",
    "    ),\n",
    "    mesh=mesh,\n",
    "    numerics=numerics,\n",
    ").solve_stationary()\n",
    "\n",
    "frequencies = np.linspace(0.8e9, 1.3e9, 11)\n",
    "models = [model(frequency) for frequency in frequencies]\n",
    "results = [solve(physics) for physics in models]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Voltage and current in the coaxial line, the reflection and power they imply against those of the\n",
    "port, and the input impedance at the ground plane."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "across, below = np.linspace(wire, shield, 201), 0.005\n",
    "aperture = np.column_stack((across, -below + 0 * across))\n",
    "voltage = np.array(\n",
    "    [\n",
    "        np.trapezoid(\n",
    "            result.field(physics.electric_field).evaluate(aperture)[:, 0], across\n",
    "        )\n",
    "        for result, physics in zip(results, models)\n",
    "    ]\n",
    ")\n",
    "middle = np.array([[(wire + shield) / 2, -below]])\n",
    "current = np.array(\n",
    "    [\n",
    "        2\n",
    "        * np.pi\n",
    "        * middle[0, 0]\n",
    "        * result.field(physics.magnetic_flux_density).evaluate(middle)[0, 1]\n",
    "        / VACUUM_PERMEABILITY\n",
    "        for result, physics in zip(results, models)\n",
    "    ]\n",
    ")\n",
    "line_impedance = voltage / current\n",
    "reflection = np.array(\n",
    "    [\n",
    "        abs(scattering_parameters(result, physics)[(0, 0)])\n",
    "        for result, physics in zip(results, models)\n",
    "    ]\n",
    ")\n",
    "from_impedance = np.abs(\n",
    "    (line_impedance - characteristic) / (line_impedance + characteristic)\n",
    ")\n",
    "load_reflection = (\n",
    "    (line_impedance - characteristic)\n",
    "    / (line_impedance + characteristic)\n",
    "    * np.exp(-2j * 2 * np.pi * frequencies / light * below)\n",
    ")\n",
    "input_impedance = characteristic * (1 + load_reflection) / (1 - load_reflection)\n",
    "print(f\"coaxial line: Z_c = {characteristic:.2f} ohm\")\n",
    "print(\n",
    "    \"f [GHz]   Z_in at the ground [ohm]   |S11| port   |Z-Zc|/|Z+Zc|   accepted power [W]: 1-|S11|^2   Re(V I*)/2\"\n",
    ")\n",
    "for f, z, s, r, v, i in zip(\n",
    "    frequencies, input_impedance, reflection, from_impedance, voltage, current\n",
    "):\n",
    "    print(\n",
    "        f\"{f / 1e9:6.2f}   {z.real:7.2f} {z.imag:+8.2f}i      {s:.4f}       {r:.4f}            {1 - s**2:.4f}          {0.5 * (v * np.conj(i)).real:.4f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The resonance lies where the reactance changes sign; the induced EMF resistance of the\n",
    "sinusoidal current is evaluated at the same electrical height."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "resonance = np.interp(0.0, input_impedance.imag[::-1], frequencies[::-1])\n",
    "kh = 2 * np.pi * resonance / light * height\n",
    "theta = np.linspace(1e-4, np.pi / 2, 4001)\n",
    "emf = (\n",
    "    impedance\n",
    "    / (2 * np.pi * np.sin(kh) ** 2)\n",
    "    * np.trapezoid(\n",
    "        (np.cos(kh * np.cos(theta)) - np.cos(kh)) ** 2 / np.sin(theta), theta\n",
    "    )\n",
    ")\n",
    "print(\n",
    "    f\"\\nresonance at {resonance / 1e9:.3f} GHz (h = {height / (light / resonance):.3f} wavelengths); \"\n",
    "    f\"R_in there {np.interp(resonance, frequencies, input_impedance.real):.1f} ohm, induced EMF (thin wire) {emf:.1f} ohm\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The radiated power from the far field over the upper half space against the power accepted at\n",
    "the port, and the pattern against the sinusoidal-current pattern, at 1 GHz."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "at = int(np.argmin(np.abs(frequencies - 1.0e9)))\n",
    "angles = np.linspace(0.01, np.pi / 2 - 0.01, 90)\n",
    "pattern = far_field(\n",
    "    results[at], models[at], angles, radius=0.2, center=(0.0, 0.0), ground_plane=0.0\n",
    ")\n",
    "radiated = np.trapezoid(\n",
    "    np.sum(np.abs(pattern) ** 2, axis=1) / (2 * impedance) * 2 * np.pi * np.sin(angles),\n",
    "    angles,\n",
    ")\n",
    "kh = 2 * np.pi * frequencies[at] / light * height\n",
    "ideal = np.abs((np.cos(kh * np.cos(angles)) - np.cos(kh)) / np.sin(angles))\n",
    "shape = np.linalg.norm(pattern, axis=1)\n",
    "print(\n",
    "    f\"at {frequencies[at] / 1e9:.1f} GHz: radiated {radiated:.4f} W, accepted 1 - |S11|^2 = {1 - reflection[at]**2:.4f} W; \"\n",
    "    f\"pattern against the sinusoidal current (both normalized at the horizon): max deviation {np.max(np.abs(shape / shape[-1] - ideal / ideal[-1])):.1e}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Input impedance and reflection over frequency, the pattern in the vertical plane, and the\n",
    "magnitude of $H_\\varphi$ near the antenna at 1 GHz."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "r, z = np.asarray(mesh.coordinates).T\n",
    "field = (\n",
    "    np.abs(\n",
    "        results[at]\n",
    "        .field(models[at].magnetic_flux_density)\n",
    "        .evaluate(np.column_stack((r, z)))[:, 1]\n",
    "    )\n",
    "    / VACUUM_PERMEABILITY\n",
    ")\n",
    "fig = plots.figure(1, 3, size=(24, 6.5))\n",
    "plots.line(\n",
    "    frequencies / 1e9,\n",
    "    {\"R_in\": input_impedance.real, \"X_in\": input_impedance.imag},\n",
    "    hlines={\"Z_c\": characteristic, \"induced EMF R\": emf},\n",
    "    xlabel=\"frequency [GHz]\",\n",
    "    ylabel=\"impedance [ohm]\",\n",
    "    title=\"Input impedance at the ground plane\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    np.degrees(angles),\n",
    "    {\"computed |F|\": shape / shape[-1]},\n",
    "    reference={\"computed |F|\": ideal / ideal[-1]},\n",
    "    xlimits=(0, 90),\n",
    "    ylimits=(0, 1.05),\n",
    "    xlabel=\"angle from the zenith [deg]\",\n",
    "    ylabel=\"|E| / |E(horizon)|\",\n",
    "    title=\"Pattern at 1 GHz (dashed: sinusoidal current)\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.heatmap(\n",
    "    1e3 * r,\n",
    "    1e3 * z,\n",
    "    field,\n",
    "    triangles=np.asarray(mesh.cells),\n",
    "    limits=(0, np.percentile(field[z > 0.005], 95)),\n",
    "    label=\"|H_phi| [A/m]\",\n",
    "    xlabel=\"r [mm]\",\n",
    "    ylabel=\"z [mm]\",\n",
    "    xlimits=(0, 150),\n",
    "    ylimits=(-10, 150),\n",
    "    title=\"Field near the antenna at 1 GHz\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the wire thinner in `monopole_magnetic_frill_feed_geometry.py`: the resonance moves towards\n",
    "a quarter wavelength and the impedance curve towards the thin-wire values. A top hat (a disc on\n",
    "the antenna) or a dielectric sleeve shortens the antenna for the same resonance."
   ]
  }
 ]
}
