{
 "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": [
    "# Radar cross section of a ship\n",
    "\n",
    "A distant radar illuminates a boat with a plane wave. The boat scatters part of the wave in all\n",
    "directions; the radar cross section $\\sigma$ measures how strongly it does so in a direction, as\n",
    "the area that would intercept and isotropically re-radiate the observed power. In a\n",
    "two-dimensional section (a body long across the section) it is a length:\n",
    "\n",
    "$$\\sigma(\\varphi)=\\lim_{r\\to\\infty}2\\pi r\\frac{|E_s|^2}{|E_0|^2}=\\frac4k|F(\\varphi)|^2,\n",
    "  \\qquad E_s\\simeq\\sqrt{\\frac2{\\pi kr}}\\,e^{\\mathrm i(kr-\\pi/4)}F(\\varphi).$$\n",
    "\n",
    "The hull, the deck house and the mast are perfect conductors. The model solves the **scattered\n",
    "field** only: the incident wave $E_0$ is given analytically as `background_field`, and on the\n",
    "conductor the total tangential field vanishes, $E_s=-E_0$ - a `PerfectElectricConductor` on the\n",
    "inner boundary (the silhouette) carries the total field, the one behind the absorbing layer the\n",
    "scattered field. Both polarizations are solved: $E_z$ along the boat (TM, `Ez`) and $H_z$ along\n",
    "the boat (TE, `Hz`). `far_field` transforms the field on a circle around the boat into $F$.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| silhouette of the boat (inner boundary) | perfect conductor, total field $E=0$ tangentially |\n",
    "| outer box behind the 1.5 m absorbing layer | perfect conductor, scattered field |\n",
    "\n",
    "**Reference** (C. A. Balanis, *Advanced Engineering Electromagnetics*, 2nd ed., §11.5 and\n",
    "§11.8; J. A. Stratton, *Electromagnetic Theory*, §9.20). A conducting cylinder of radius $a$\n",
    "scatters the series $F=\\sum_n s_n e^{\\mathrm in\\varphi}$ with $s_n=-J_n(ka)/H^{(1)}_n(ka)$ (TM) and\n",
    "$s_n=-J_n'(ka)/H^{(1)\\prime}_n(ka)$ (TE). For any lossless scatterer the optical theorem ties the\n",
    "total scattered power to the forward amplitude:\n",
    "\n",
    "$$\\sigma_s=\\frac1{2\\pi}\\oint\\frac4k|F|^2\\,\\mathrm d\\varphi=\\sigma_{ext}=-\\frac4k\\,\\mathrm{Re}\\,F(\\varphi_{\\rm forward}).$$"
   ]
  },
  {
   "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",
    "    CartesianPML,\n",
    "    IsotropicElectromagneticMaterial,\n",
    ")\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import ComplexSparseDirect\n",
    "from onesim.physics.electromagnetics import (\n",
    "    FrequencyDomainMaxwell,\n",
    "    PerfectElectricConductor,\n",
    "    far_field,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.special import h1vp, hankel1, jv, jvp\n",
    "\n",
    "theme.set()\n",
    "\n",
    "frequency = 150e6\n",
    "light = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)\n",
    "wave, omega, admittance = (\n",
    "    2 * np.pi * frequency / light,\n",
    "    2 * np.pi * frequency,\n",
    "    np.sqrt(VACUUM_PERMITTIVITY / VACUUM_PERMEABILITY),\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the air around the boat and, for the validation, around the cylinder; `section`\n",
    "cuts them at half thickness. Quadratic triangles of 0.2 m, a tenth of the wavelength, and 5 cm\n",
    "along the conductors."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "bodies = {\n",
    "    name: load(f\"radar_cross_section_ship{suffix}.step\").section(\n",
    "        (0, 0, 1), origin=(0, 0, 0.1)\n",
    "    )\n",
    "    for name, suffix in ((\"ship\", \"\"), (\"cylinder\", \"_cylinder\"))\n",
    "}\n",
    "meshes = {\n",
    "    name: TriangularMesher(target_size=0.2, local_sizes={\"all\": 0.05}).generate(body)\n",
    "    for name, body in bodies.items()\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(16, 7))\n",
    "plots.geometry(\n",
    "    bodies[\"ship\"],\n",
    "    selection={\"conductor and outer wall\": bodies[\"ship\"].boundaries.all},\n",
    "    labels=False,\n",
    "    title=\"Air around the boat (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"ship\"],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"{meshes['ship'].cell_count} quadratic triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The absorbing layer is a `CartesianPML` whose damping grows quadratically over the outer 1.5 m;\n",
    "the background material is the same layer around air, so that the incident wave passes through\n",
    "it unchanged. The radar sits on the right, its wave arrives at the elevation angle $\\beta$ above\n",
    "the horizon: $\\hat k=(-\\cos\\beta,-\\sin\\beta)$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "damping = lambda x, y, z: np.column_stack(\n",
    "    (\n",
    "        3 * omega * np.clip((np.abs(x) - 9.5) / 1.5, 0, None) ** 2,\n",
    "        3 * omega * np.clip((np.abs(y) - 8.5) / 1.5, 0, None) ** 2,\n",
    "        0 * x,\n",
    "    )\n",
    ")\n",
    "medium = CartesianPML(material=IsotropicElectromagneticMaterial(), damping=damping)\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "incident = lambda polarization, direction: lambda x, y, z: (\n",
    "    np.exp(1j * wave * (direction[0] * x + direction[1] * y))[:, None]\n",
    "    * (\n",
    "        np.array([0.0, 0.0, 1.0])\n",
    "        if polarization == \"Ez\"\n",
    "        else np.array([-direction[1], direction[0], 0.0])\n",
    "    )\n",
    ")\n",
    "models = lambda name, polarization, direction: FrequencyDomainMaxwell(\n",
    "    domain=bodies[name].domain(),\n",
    "    frequency=frequency,\n",
    "    material=medium,\n",
    "    polarization=polarization,\n",
    "    background_field=incident(polarization, direction),\n",
    "    background_material=medium,\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    ")\n",
    "direction = lambda elevation: (\n",
    "    -np.cos(np.radians(elevation)),\n",
    "    -np.sin(np.radians(elevation)),\n",
    ")\n",
    "simulate = lambda name, physics: Simulation(\n",
    "    problem=Problem(\n",
    "        name=name,\n",
    "        geometry=bodies[name],\n",
    "        physics=(physics,),\n",
    "        boundary_conditions=(\n",
    "            PerfectElectricConductor(\n",
    "                physics=physics, boundary=bodies[name].boundaries.all\n",
    "            ),\n",
    "        ),\n",
    "    ),\n",
    "    mesh=meshes[name],\n",
    "    numerics=numerics,\n",
    ").solve_stationary()\n",
    "circles = {\n",
    "    \"ship\": {\"radius\": 6.8, \"center\": (0.0, 1.0)},\n",
    "    \"cylinder\": {\"radius\": 3.0, \"center\": (0.0, 0.0)},\n",
    "}\n",
    "\n",
    "angles = np.radians(np.arange(0.0, 360.0, 1.0))\n",
    "lit = {\"ship\": 10.0, \"cylinder\": 180.0}\n",
    "cases = {\n",
    "    (name, polarization): models(name, polarization, direction(lit[name]))\n",
    "    for name in (\"ship\", \"cylinder\")\n",
    "    for polarization in (\"Ez\", \"Hz\")\n",
    "}\n",
    "results = {key: simulate(key[0], physics) for key, physics in cases.items()}\n",
    "bistatic = {\n",
    "    key: far_field(results[key], physics, angles, **circles[key[0]])\n",
    "    / (1.0 if key[1] == \"Ez\" else admittance)\n",
    "    for key, physics in cases.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The cylinder, lit from the left ($\\hat k=+x$), against the Bessel series; then the optical theorem\n",
    "for both bodies: the scattered width from the integral of $|F|^2$ over all directions against the\n",
    "extinction width from the forward amplitude."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "orders, ka = np.arange(-30, 31), wave * 1.0\n",
    "series = {\n",
    "    \"Ez\": -jv(orders, ka) / hankel1(orders, ka),\n",
    "    \"Hz\": -jvp(orders, ka) / h1vp(orders, ka),\n",
    "}\n",
    "print(\n",
    "    \"cylinder ka = pi      max |sigma - sigma_series| / max sigma    sigma back [m]: computed  series\"\n",
    ")\n",
    "for polarization in (\"Ez\", \"Hz\"):\n",
    "    exact = (\n",
    "        4\n",
    "        / wave\n",
    "        * np.abs(np.exp(1j * np.outer(angles, orders)) @ series[polarization]) ** 2\n",
    "    )\n",
    "    computed = 4 / wave * np.abs(bistatic[(\"cylinder\", polarization)]) ** 2\n",
    "    print(\n",
    "        f\"{'TM (E_z)' if polarization == 'Ez' else 'TE (H_z)':20s}   {np.max(np.abs(computed - exact)) / exact.max():30.1e}\"\n",
    "        f\"                    {computed[180]:8.3f}  {exact[180]:8.3f}\"\n",
    "    )\n",
    "print(\n",
    "    \"\\nbody      polarization   scattered width [m]   extinction width [m]   difference\"\n",
    ")\n",
    "for (name, polarization), pattern in bistatic.items():\n",
    "    forward = int(\n",
    "        np.argmin(\n",
    "            np.abs(\n",
    "                np.angle(\n",
    "                    np.exp(1j * (angles - np.radians(190.0 if name == \"ship\" else 0.0)))\n",
    "                )\n",
    "            )\n",
    "        )\n",
    "    )\n",
    "    scattered = 4 / wave * np.mean(np.abs(pattern) ** 2)\n",
    "    extinction = -4 / wave * pattern[forward].real\n",
    "    print(\n",
    "        f\"{name:9s} {'TM (E_z)' if polarization == 'Ez' else 'TE (H_z)':12s}   {scattered:19.3f}   {extinction:20.3f}   {abs(scattered / extinction - 1):10.1e}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The monostatic cross section is what the radar itself receives: the boat is lit at elevations\n",
    "from 0 to 60 degrees and the backscattered amplitude is read in the direction of the radar."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "elevations = np.arange(0.0, 61.0, 5.0)\n",
    "monostatic = {\n",
    "    polarization: np.array(\n",
    "        [\n",
    "            4\n",
    "            / wave\n",
    "            * abs(\n",
    "                far_field(\n",
    "                    simulate(\"ship\", physics),\n",
    "                    physics,\n",
    "                    np.radians([b]),\n",
    "                    **circles[\"ship\"],\n",
    "                )[0]\n",
    "                / (1.0 if polarization == \"Ez\" else admittance)\n",
    "            )\n",
    "            ** 2\n",
    "            for b, physics in (\n",
    "                (b, models(\"ship\", polarization, direction(b))) for b in elevations\n",
    "            )\n",
    "        ]\n",
    "    )\n",
    "    for polarization in (\"Ez\", \"Hz\")\n",
    "}\n",
    "print(\"\\nelevation [deg]   monostatic sigma TM [m]   TE [m]\")\n",
    "for b, tm, te in zip(elevations, monostatic[\"Ez\"], monostatic[\"Hz\"]):\n",
    "    print(f\"{b:10.0f}        {tm:12.2f}          {te:8.2f}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The total field $|E_z|$ around the boat lit at 10 degrees, the bistatic cross section of the boat\n",
    "in dB above 1 m (the radar lies at 10 degrees), and the cylinder against its series."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "result, physics = results[(\"ship\", \"Ez\")], cases[(\"ship\", \"Ez\")]\n",
    "x, y = np.asarray(meshes[\"ship\"].coordinates).T\n",
    "total = np.abs(\n",
    "    result.field(physics.electric_field).evaluate(np.column_stack((x, y)))[:, 2]\n",
    ")\n",
    "fig = plots.figure(1, 3, size=(26, 7))\n",
    "plots.heatmap(\n",
    "    x,\n",
    "    y,\n",
    "    total,\n",
    "    triangles=np.asarray(meshes[\"ship\"].cells),\n",
    "    limits=(0, 2.2),\n",
    "    label=\"|E_z| / |E_0|\",\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    xlimits=(-9.5, 9.5),\n",
    "    ylimits=(-8.5, 8.5),\n",
    "    title=\"Total field, TM wave at 10 deg elevation\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    np.degrees(angles),\n",
    "    {\n",
    "        \"TM (E_z)\": 10 * np.log10(4 / wave * np.abs(bistatic[(\"ship\", \"Ez\")]) ** 2),\n",
    "        \"TE (H_z)\": 10 * np.log10(4 / wave * np.abs(bistatic[(\"ship\", \"Hz\")]) ** 2),\n",
    "    },\n",
    "    vlines={\"radar\": 10.0, \"forward\": 190.0},\n",
    "    xlimits=(0, 360),\n",
    "    xlabel=\"observation angle [deg]\",\n",
    "    ylabel=\"sigma [dB m]\",\n",
    "    title=\"Bistatic cross section of the boat\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    np.degrees(angles),\n",
    "    {\n",
    "        f\"{'TM' if p == 'Ez' else 'TE'} computed\": 4\n",
    "        / wave\n",
    "        * np.abs(bistatic[(\"cylinder\", p)]) ** 2\n",
    "        for p in (\"Ez\", \"Hz\")\n",
    "    },\n",
    "    reference={\n",
    "        f\"{'TM' if p == 'Ez' else 'TE'} computed\": 4\n",
    "        / wave\n",
    "        * np.abs(np.exp(1j * np.outer(angles, orders)) @ series[p]) ** 2\n",
    "        for p in (\"Ez\", \"Hz\")\n",
    "    },\n",
    "    xlimits=(0, 360),\n",
    "    xlabel=\"observation angle [deg]\",\n",
    "    ylabel=\"sigma [m]\",\n",
    "    title=\"Cylinder ka = pi (dashed: Bessel series)\",\n",
    "    legend=\"upper center\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()\n",
    "\n",
    "fig = plots.figure(1, 1, size=(9, 5.5))\n",
    "plots.line(\n",
    "    elevations,\n",
    "    {\n",
    "        \"TM (E_z)\": 10 * np.log10(monostatic[\"Ez\"]),\n",
    "        \"TE (H_z)\": 10 * np.log10(monostatic[\"Hz\"]),\n",
    "    },\n",
    "    markers=True,\n",
    "    xlabel=\"elevation of the radar [deg]\",\n",
    "    ylabel=\"monostatic sigma [dB m]\",\n",
    "    title=\"What the radar receives\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the silhouette in `radar_cross_section_ship_geometry.py`: tilting the flat walls of the deck\n",
    "house away from the radar removes their specular flashes from the monostatic cross section - the\n",
    "idea of stealth shaping. A lossy coating on the hull is a thin region with a complex permittivity."
   ]
  }
 ]
}
