{
 "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": [
    "# Half-wave dipole antenna\n",
    "\n",
    "The half-wave dipole is the reference antenna of radio engineering: two thin conductors, together\n",
    "about half a wavelength long, fed in the middle. Here the wire has a radius of 1 mm and a length of\n",
    "144 mm (0.48 wavelengths at 1 GHz) with a feed gap of 2 mm. A `LumpedPort` across the gap stands\n",
    "for the transmission line: a sheet of uniform current around the gap whose voltage and current give\n",
    "the input impedance directly, and the S-parameter against its reference impedance.\n",
    "\n",
    "The antenna and its field are symmetric about the wire: the electric field has only $E_r$ and\n",
    "$E_z$, the magnetic field only $H_\\varphi$. `FrequencyDomainMaxwell` with the polarization `Erphiz`\n",
    "and azimuthal mode $m=0$ 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",
    "on the meridian plane ($r$, $z$) with second-order Nédélec elements. A spherical absorbing layer\n",
    "(`spherical_pml`) between radii 250 and 350 mm takes up the outgoing wave.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| `gap` | lumped port, 73 Ω, 1 W |\n",
    "| `wire` | perfect electric conductor |\n",
    "| `outer` | perfect electric conductor behind the absorbing layer |\n",
    "| `axis` | regular: $E_r=0$ |\n",
    "\n",
    "**Reference** (C. A. Balanis, *Antenna Theory*, 4th ed., Wiley 2016, §4.5 and §8.5). With the\n",
    "sinusoidal current $I(z)=I_m\\sin k(\\ell/2-|z|)$ a centre-fed dipole of length $\\ell$ radiates\n",
    "\n",
    "$$F(\\theta)\\propto\\frac{\\cos(\\tfrac{k\\ell}{2}\\cos\\theta)-\\cos\\tfrac{k\\ell}{2}}{\\sin\\theta},$$\n",
    "\n",
    "and the induced EMF method gives its input impedance $Z=R+\\mathrm jX$ in terms of the sine and\n",
    "cosine integrals (Balanis eq. 8-60, with the wire radius $a$ in the reactance). The half-wave\n",
    "dipole radiates with directivity 1.64 (2.15 dBi) and a resistance of 73 Ω; its reactance vanishes\n",
    "slightly below half a wavelength. The sinusoidal current is an assumption: a wire of finite radius\n",
    "fed across a gap of finite size carries a somewhat different current, so that its impedance departs\n",
    "from the induced EMF values by up to some ten percent near resonance, while the pattern, which only\n",
    "needs the current to be roughly sinusoidal, and the resonant length agree closely."
   ]
  },
  {
   "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 (\n",
    "    IsotropicElectromagneticMaterial,\n",
    "    spherical_pml,\n",
    ")\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Nedelec, RevolvedH1SpaceFactory\n",
    "from onesim.numerics.linear import ComplexSparseDirect\n",
    "from onesim.physics.electromagnetics import (\n",
    "    FrequencyDomainMaxwell,\n",
    "    LumpedPort,\n",
    "    PerfectElectricConductor,\n",
    "    far_field,\n",
    "    input_impedance,\n",
    "    scattering_parameters,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.special import sici\n",
    "\n",
    "theme.set()\n",
    "\n",
    "light, eta0 = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY), np.sqrt(\n",
    "    VACUUM_PERMEABILITY / VACUUM_PERMITTIVITY\n",
    ")\n",
    "length, radius = 0.144, 0.001"
   ],
   "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 plane\n",
    "with the face names. Quadratic triangles of 20 mm (a fifteenth of the wavelength at 1 GHz) fill the\n",
    "air, refined to 2 mm along the wire and 0.7 mm across the gap."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "air = load(\"half_wave_dipole_antenna.step\")\n",
    "plane = air.section((0, 1, 0))\n",
    "sides = plane.boundaries\n",
    "mesh = TriangularMesher(\n",
    "    target_size=0.02, local_sizes={\"wire\": 0.002, \"gap\": 0.0007}, grading=0.25\n",
    ").generate(plane)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    air,\n",
    "    selection={\n",
    "        \"feed gap\": air.boundaries.gap,\n",
    "        \"wire\": air.boundaries.wire,\n",
    "        \"outer sphere\": air.boundaries.outer,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=20, azimuth=-120),\n",
    "    length_unit=\"mm\",\n",
    "    title=\"Air around the dipole, half (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    length_unit=\"mm\",\n",
    "    title=f\"Meridian plane: {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",
    "`simulate` solves the antenna at one frequency, fed with 1 W through a 73 Ω port. The sweep runs\n",
    "from 0.8 to 1.2 GHz."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Nedelec(order=2), provider=RevolvedH1SpaceFactory()),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "simulate = lambda f: (\n",
    "    lambda m: (\n",
    "        Simulation(\n",
    "            problem=Problem(\n",
    "                name=\"Dipole antenna\",\n",
    "                geometry=plane,\n",
    "                physics=(m,),\n",
    "                boundary_conditions=(\n",
    "                    LumpedPort(\n",
    "                        physics=m,\n",
    "                        boundary=sides.gap,\n",
    "                        impedance=73.0,\n",
    "                        incident_power=1.0,\n",
    "                    ),\n",
    "                    PerfectElectricConductor(\n",
    "                        physics=m, boundary=sides.wire | sides.outer\n",
    "                    ),\n",
    "                ),\n",
    "            ),\n",
    "            mesh=mesh,\n",
    "            numerics=numerics,\n",
    "        ).solve_stationary(),\n",
    "        m,\n",
    "    )\n",
    ")(\n",
    "    FrequencyDomainMaxwell(\n",
    "        domain=plane.domain(),\n",
    "        frequency=f,\n",
    "        polarization=\"Erphiz\",\n",
    "        azimuthal_mode=0,\n",
    "        phasor_convention=\"exp(-i*omega*t)\",\n",
    "        amplitude_convention=\"peak\",\n",
    "        material=spherical_pml(\n",
    "            IsotropicElectromagneticMaterial(), inner_radius=0.25, outer_radius=0.35\n",
    "        ),\n",
    "    )\n",
    ")\n",
    "frequencies = np.round(np.linspace(0.8e9, 1.2e9, 21), -6)\n",
    "runs = {f: simulate(f) for f in frequencies}\n",
    "\n",
    "\n",
    "def induced_emf(kl, ka):\n",
    "    si, ci, euler = (lambda x: sici(x)[0]), (lambda x: sici(x)[1]), 0.5772156649\n",
    "    resistance = (\n",
    "        eta0\n",
    "        / (2 * np.pi)\n",
    "        * (\n",
    "            euler\n",
    "            + np.log(kl)\n",
    "            - ci(kl)\n",
    "            + 0.5 * np.sin(kl) * (si(2 * kl) - 2 * si(kl))\n",
    "            + 0.5 * np.cos(kl) * (euler + np.log(kl / 2) + ci(2 * kl) - 2 * ci(kl))\n",
    "        )\n",
    "    )\n",
    "    reactance = (\n",
    "        eta0\n",
    "        / (4 * np.pi)\n",
    "        * (\n",
    "            2 * si(kl)\n",
    "            + np.cos(kl) * (2 * si(kl) - si(2 * kl))\n",
    "            - np.sin(kl) * (2 * ci(kl) - ci(2 * kl) - ci(2 * ka**2 / kl))\n",
    "        )\n",
    "    )\n",
    "    return (resistance + 1j * reactance) / np.sin(kl / 2) ** 2"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The input impedance over the band (engineering convention $R+\\mathrm jX$; the model uses\n",
    "$e^{-i\\omega t}$, hence the conjugate) against the induced EMF method, the resonance where the\n",
    "reactance vanishes, and the reflection against 73 Ω."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "wave = lambda f: 2 * np.pi * f / light\n",
    "impedance = {f: np.conj(input_impedance(*run)) for f, run in runs.items()}\n",
    "theory = {f: induced_emf(wave(f) * length, wave(f) * radius) for f in frequencies}\n",
    "print(\"f [GHz]  l/lambda   Z computed [ohm]      Z induced EMF [ohm]   |S11| [dB]\")\n",
    "for f in frequencies:\n",
    "    print(\n",
    "        f\"{f / 1e9:6.2f} {length * f / light:9.3f}   {impedance[f].real:7.2f} {impedance[f].imag:+8.2f}j   {theory[f].real:7.2f} {theory[f].imag:+8.2f}j \"\n",
    "        f\"{20 * np.log10(abs(scattering_parameters(*runs[f])[(0, 0)])):10.1f}\"\n",
    "    )\n",
    "reactance = np.array([impedance[f].imag for f in frequencies])\n",
    "emf_reactance = np.array([theory[f].imag for f in frequencies])\n",
    "resonance = np.interp(0.0, reactance, frequencies)\n",
    "emf_resonance = np.interp(0.0, emf_reactance, frequencies)\n",
    "print(\n",
    "    f\"resonance (X = 0): computed {resonance / 1e9:.4f} GHz (l = {length * resonance / light:.4f} wavelengths), induced EMF \"\n",
    "    f\"{emf_resonance / 1e9:.4f} GHz (l = {length * emf_resonance / light:.4f}), difference {resonance / emf_resonance - 1:+.1%}\"\n",
    ")\n",
    "print(\n",
    "    f\"resistance at resonance: computed {np.interp(resonance, frequencies, [impedance[f].real for f in frequencies]):.1f} ohm, induced EMF \"\n",
    "    f\"{np.interp(emf_resonance, frequencies, [theory[f].real for f in frequencies]):.1f} ohm\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Radiation pattern and directivity\n",
    "\n",
    "At the frequency of the sweep closest to resonance, `far_field` returns the far field\n",
    "$\\mathbf F(\\theta)$ ($\\mathbf E\\sim e^{\\mathrm ikR}/R\\,\\mathbf F$) from the field on a sphere of\n",
    "200 mm inside the absorbing layer. The directivity follows from the pattern,\n",
    "$D=4\\pi|F|^2_{\\max}/\\int|F|^2\\,\\mathrm d\\Omega$, and the radiated power\n",
    "$\\frac{1}{2\\eta_0}\\int|F|^2\\,\\mathrm d\\Omega$ must equal the power accepted at the port."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "near = min(frequencies, key=lambda f: abs(f - resonance))\n",
    "result, m = runs[near]\n",
    "theta = np.linspace(1e-3, np.pi - 1e-3, 721)\n",
    "pattern = np.linalg.norm(far_field(result, m, theta, radius=0.2), axis=1)\n",
    "half = wave(near) * length / 2\n",
    "sinusoidal = np.abs((np.cos(half * np.cos(theta)) - np.cos(half)) / np.sin(theta))\n",
    "total = 2 * np.pi * np.trapezoid(pattern**2 * np.sin(theta), theta)\n",
    "directivity = 4 * np.pi * pattern.max() ** 2 / total\n",
    "sinusoidal_directivity = (\n",
    "    4\n",
    "    * np.pi\n",
    "    * sinusoidal.max() ** 2\n",
    "    / (2 * np.pi * np.trapezoid(sinusoidal**2 * np.sin(theta), theta))\n",
    ")\n",
    "accepted = 1.0 - abs(scattering_parameters(result, m)[(0, 0)]) ** 2\n",
    "print(\n",
    "    f\"at {near / 1e9:.2f} GHz: pattern against the sinusoidal current, both normalized to their maximum: largest difference \"\n",
    "    f\"{np.max(np.abs(pattern / pattern.max() - sinusoidal / sinusoidal.max())):.1e}\"\n",
    ")\n",
    "print(\n",
    "    f\"directivity {directivity:.3f} ({10 * np.log10(directivity):.2f} dBi), sinusoidal current {sinusoidal_directivity:.3f} \"\n",
    "    f\"({10 * np.log10(sinusoidal_directivity):.2f} dBi)\"\n",
    ")\n",
    "print(\n",
    "    f\"radiated power {total / (2 * eta0):.4f} W, accepted at the port 1 - |S11|^2 = {accepted:.4f} W\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left: input resistance and reactance over the band against the induced EMF method. Middle: the\n",
    "normalized radiation pattern against the sinusoidal current. Right: the instantaneous field $E_z$\n",
    "on the meridian plane near resonance (colour limits at three times the far field of 1 W at 200 mm):\n",
    "the wave fronts leave the antenna and die out in the absorbing layer beyond 250 mm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "r, z = np.asarray(mesh.coordinates).T\n",
    "corners = (lambda nodes: nodes[np.hypot(r[nodes], z[nodes]) < 0.349])(\n",
    "    np.unique(np.asarray(mesh.cells)[:, :3])\n",
    ")\n",
    "vertical = np.zeros(len(r))\n",
    "vertical[corners] = np.real(\n",
    "    result.field(m.electric_field).evaluate(\n",
    "        np.column_stack((r[corners], z[corners])), tolerance=1e-3\n",
    "    )[:, 2]\n",
    ")\n",
    "fig = plots.figure(1, 3, size=(24, 6.5))\n",
    "plots.line(\n",
    "    points={\n",
    "        \"R computed\": (frequencies / 1e9, [impedance[f].real for f in frequencies]),\n",
    "        \"X computed\": (frequencies / 1e9, reactance),\n",
    "    },\n",
    "    reference={\n",
    "        \"R induced EMF\": (frequencies / 1e9, [theory[f].real for f in frequencies]),\n",
    "        \"X induced EMF\": (frequencies / 1e9, emf_reactance),\n",
    "    },\n",
    "    hlines={\"0\": 0.0},\n",
    "    xlabel=\"frequency [GHz]\",\n",
    "    ylabel=\"impedance [ohm]\",\n",
    "    title=\"Input impedance of the dipole\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"computed\": (np.degrees(theta[::20]), pattern[::20] / pattern.max())},\n",
    "    reference={\n",
    "        \"sinusoidal current\": (np.degrees(theta), sinusoidal / sinusoidal.max())\n",
    "    },\n",
    "    xlabel=\"polar angle [deg]\",\n",
    "    ylabel=\"|F| / max |F|\",\n",
    "    title=f\"Radiation pattern, {near / 1e9:.2f} GHz\",\n",
    "    legend=\"lower center\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.heatmap(\n",
    "    1e3 * r,\n",
    "    1e3 * z,\n",
    "    vertical,\n",
    "    triangles=np.asarray(mesh.cells)[:, :3],\n",
    "    colormap=\"diverging\",\n",
    "    limits=(-150.0, 150.0),\n",
    "    label=\"Re E_z [V/m]\",\n",
    "    xlabel=\"r [mm]\",\n",
    "    ylabel=\"z [mm]\",\n",
    "    title=f\"Electric field, {near / 1e9:.2f} 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 thicker in `half_wave_dipole_antenna_geometry.py`: the resonance moves to a shorter\n",
    "electrical length and the band widens. A conducting plane through the feed (half the antenna,\n",
    "`PerfectElectricConductor` on the plane z = 0) gives the quarter-wave monopole with half the\n",
    "impedance."
   ]
  }
 ]
}
