{
 "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": [
    "# Plane-wave scattering at any angle on a 2D-axisymmetric model\n",
    "\n",
    "A body of revolution can be solved on its meridian plane even when the wave hitting it is not\n",
    "symmetric: every field is a sum of azimuthal modes $e^{\\mathrm im\\varphi}$, and each mode is a 2D\n",
    "problem on the meridian. A plane wave along the axis contains only $m=\\pm1$; a wave at an angle\n",
    "$\\alpha$ to the axis contains all orders, of which about $kR+4$ on each side matter. OneSimulation\n",
    "takes the incident wave as a 3D background field, projects it onto every mode, solves the\n",
    "scattered field mode by mode (`polarization=\"Erphiz\"`, `azimuthal_mode=m`) and sums the modes\n",
    "back to 3D fields and far fields.\n",
    "\n",
    "Here a sphere of radius $R=0.3$ m and $\\varepsilon_r=4$ is hit by a wave of wavelength\n",
    "$\\lambda=1$ m ($kR=1.885$) polarized perpendicular to the plane of incidence, at $\\alpha=0°$,\n",
    "$45°$ and $90°$. A sphere scatters the same at every angle of incidence: a strict test of the\n",
    "modal sum.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| axis, $r=0$ | regular (handled by the meridian formulation) |\n",
    "| outer walls | perfect conductor behind a spherical PML between 0.9 and 1.2 m |\n",
    "| sphere surface | continuity (material interface) |\n",
    "\n",
    "The meridian plate comes from `sphere_scattering_azimuthal_modes.step`, the half sphere from\n",
    "`sphere_scattering_azimuthal_modes_sphere.step`; the script\n",
    "`sphere_scattering_azimuthal_modes_geometry.py` builds both with the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference.** The Mie series (Bohren and Huffman, *Absorption and Scattering of Light by Small\n",
    "Particles*, 1983, ch. 4): with the Riccati-Bessel functions $\\psi_n(x)=xj_n(x)$,\n",
    "$\\xi_n(x)=xh_n^{(1)}(x)$, the size parameter $x=kR$ and the relative index $n_r$,\n",
    "\n",
    "$$a_n=\\frac{n_r\\psi_n(n_rx)\\psi_n'(x)-\\psi_n(x)\\psi_n'(n_rx)}{n_r\\psi_n(n_rx)\\xi_n'(x)-\\xi_n(x)\\psi_n'(n_rx)},\\qquad\n",
    "  b_n=\\frac{\\psi_n(n_rx)\\psi_n'(x)-n_r\\psi_n(x)\\psi_n'(n_rx)}{\\psi_n(n_rx)\\xi_n'(x)-n_r\\xi_n(x)\\psi_n'(n_rx)},$$\n",
    "\n",
    "$$\\sigma_\\mathrm{sca}=\\frac{2\\pi}{k^2}\\sum_n(2n+1)\\big(|a_n|^2+|b_n|^2\\big) .$$\n",
    "\n",
    "The computed cross section is obtained twice: by integrating $|\\mathbf F|^2$ of the far field over\n",
    "all directions, and from the optical theorem $\\sigma_\\mathrm{ext}=\\frac{4\\pi}k\\,\\mathrm{Im}\\,\n",
    "\\hat{\\mathbf e}^*\\cdot\\mathbf F(\\hat{\\mathbf k})$, equal for a lossless sphere."
   ]
  },
  {
   "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",
    "    RegionwiseElectromagneticMaterial,\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",
    "    PerfectElectricConductor,\n",
    "    axisymmetric_far_field,\n",
    "    azimuthal_sum,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.special import spherical_jn, spherical_yn\n",
    "\n",
    "theme.set()\n",
    "\n",
    "light = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`section` with the plane $y=0$ gives the meridian plane ($x=r$) and the half disc of the sphere.\n",
    "Quadratic triangles of 40 mm in the sphere (about twelve per wavelength in it) and 70 mm outside."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plate, half = load(\"sphere_scattering_azimuthal_modes.step\"), load(\n",
    "    \"sphere_scattering_azimuthal_modes_sphere.step\"\n",
    ")\n",
    "meridian = plate.section((0, 1, 0))\n",
    "sphere = half.section((0, 1, 0)).named(\"sphere\")\n",
    "walls = (\n",
    "    meridian.boundaries.x_max | meridian.boundaries.z_min | meridian.boundaries.z_max\n",
    ")\n",
    "radius = sphere.size[0]\n",
    "mesh = TriangularMesher(\n",
    "    target_size=0.07, embedded_regions=(sphere,), region_sizes={\"sphere\": 0.04}\n",
    ").generate(meridian)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 6.5))\n",
    "plots.geometry(\n",
    "    [plate.named(\"meridian plane\"), half.named(\"half sphere\")],\n",
    "    camera=plots.Camera(elevation=15, azimuth=-80),\n",
    "    title=\"Meridian plate and half sphere (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\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",
    "One scattered-field model per azimuthal mode: the incident wave is the background field, the\n",
    "spherical PML absorbs the outgoing wave, the outer walls carry the scattered field."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "frequency, permittivity = light, 4.0\n",
    "k = 2 * np.pi * frequency / light\n",
    "medium = RegionwiseElectromagneticMaterial(\n",
    "    {\"sphere\": IsotropicElectromagneticMaterial(relative_permittivity=permittivity)},\n",
    "    default=IsotropicElectromagneticMaterial(),\n",
    ")\n",
    "incident = lambda alpha: (\n",
    "    lambda x, y, z: np.column_stack(\n",
    "        (0 * x, np.exp(1j * k * (x * np.sin(alpha) + z * np.cos(alpha))), 0 * x)\n",
    "    ).astype(complex)\n",
    ")\n",
    "model = lambda alpha, m: FrequencyDomainMaxwell(\n",
    "    domain=meridian.domain(),\n",
    "    frequency=frequency,\n",
    "    material=spherical_pml(medium, 0.9, 1.2),\n",
    "    polarization=\"Erphiz\",\n",
    "    azimuthal_mode=m,\n",
    "    background_field=incident(alpha),\n",
    "    background_material=spherical_pml(IsotropicElectromagneticMaterial(), 0.9, 1.2),\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Nedelec(order=2), provider=RevolvedH1SpaceFactory()),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "solve = lambda m: Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"Sphere, one azimuthal mode\",\n",
    "        geometry=meridian,\n",
    "        physics=(m,),\n",
    "        boundary_conditions=(PerfectElectricConductor(physics=m, boundary=walls),),\n",
    "    ),\n",
    "    mesh=mesh,\n",
    "    numerics=numerics,\n",
    ").solve_stationary()\n",
    "orders = int(k * radius + 4)\n",
    "angles = {\"0°\": 0.0, \"45°\": np.pi / 4, \"90°\": np.pi / 2}\n",
    "solved = {\n",
    "    name: [\n",
    "        (solve(m := model(alpha, order)), m)\n",
    "        for order in ((-1, 1) if alpha == 0 else range(-orders, orders + 1))\n",
    "    ]\n",
    "    for name, alpha in angles.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cross sections\n",
    "\n",
    "The far field on a grid of 37 polar and 24 azimuthal angles, integrated over the sphere of\n",
    "directions, and the forward amplitude for the optical theorem, against the Mie series."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "psi = lambda n, x, d=False: spherical_jn(n, x, derivative=d) * x + (\n",
    "    spherical_jn(n, x) if d else 0\n",
    ")\n",
    "xi = lambda n, x, d=False: psi(n, x, d) + 1j * (\n",
    "    (spherical_yn(n, x, derivative=True) * x + spherical_yn(n, x))\n",
    "    if d\n",
    "    else x * spherical_yn(n, x)\n",
    ")\n",
    "n, x, nr = np.arange(1, 21), k * radius, np.sqrt(permittivity)\n",
    "an = (nr * psi(n, nr * x) * psi(n, x, True) - psi(n, x) * psi(n, nr * x, True)) / (\n",
    "    nr * psi(n, nr * x) * xi(n, x, True) - xi(n, x) * psi(n, nr * x, True)\n",
    ")\n",
    "bn = (psi(n, nr * x) * psi(n, x, True) - nr * psi(n, x) * psi(n, nr * x, True)) / (\n",
    "    psi(n, nr * x) * xi(n, x, True) - nr * xi(n, x) * psi(n, nr * x, True)\n",
    ")\n",
    "mie = 2 * np.pi / k**2 * np.sum((2 * n + 1) * (np.abs(an) ** 2 + np.abs(bn) ** 2))\n",
    "theta, phi = np.linspace(0, np.pi, 37), np.linspace(0, 2 * np.pi, 25)[:-1]\n",
    "pattern = {\n",
    "    name: np.array(\n",
    "        [\n",
    "            axisymmetric_far_field(\n",
    "                [r for r, _ in runs], [m for _, m in runs], theta, p, radius=0.8\n",
    "            )\n",
    "            for p in phi\n",
    "        ]\n",
    "    )\n",
    "    for name, runs in solved.items()\n",
    "}\n",
    "print(\n",
    "    f\"Mie series: sigma_sca = {mie:.5f} m^2 = {mie / (np.pi * radius**2):.5f} pi R^2 (x = kR = {x:.3f})\"\n",
    ")\n",
    "print(\n",
    "    \"incidence   modes   sigma_sca from |F|^2 [m^2]   deviation    sigma_ext, optical theorem [m^2]   deviation\"\n",
    ")\n",
    "for name, alpha in angles.items():\n",
    "    weights = np.sin(theta)[None, :] * (np.pi / 36) * (2 * np.pi / 24)\n",
    "    integrated = np.sum(np.sum(np.abs(pattern[name]) ** 2, axis=2) * weights)\n",
    "    forward = axisymmetric_far_field(\n",
    "        [r for r, _ in solved[name]],\n",
    "        [m for _, m in solved[name]],\n",
    "        np.array([alpha]),\n",
    "        0.0,\n",
    "        radius=0.8,\n",
    "    )[0]\n",
    "    extinction = 4 * np.pi / k * forward[1].imag\n",
    "    print(\n",
    "        f\"{name:9s} {len(solved[name]):7d} {integrated:24.5f} {integrated / mie - 1:+12.2%} {extinction:30.5f} {extinction / mie - 1:+14.2%}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left: the differential cross section $|\\mathbf F|^2$ in the plane of incidence against the angle\n",
    "between the scattered and the incident direction: for a sphere the three curves must coincide.\n",
    "Right: the total field $|E_y|$ of the wave at 45° in the plane $y=0$, summed from all azimuthal modes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "scattering = lambda alpha: np.degrees(\n",
    "    np.arccos(\n",
    "        np.clip(np.sin(theta) * np.sin(alpha) + np.cos(theta) * np.cos(alpha), -1, 1)\n",
    "    )\n",
    ")\n",
    "in_plane = {name: np.sum(np.abs(pattern[name][0]) ** 2, axis=1) for name in angles}\n",
    "grid = np.stack(\n",
    "    np.meshgrid(\n",
    "        np.linspace(-0.85, 0.85, 69), np.linspace(-0.85, 0.85, 69), indexing=\"ij\"\n",
    "    ),\n",
    "    axis=-1,\n",
    ").reshape(-1, 2)\n",
    "points = np.column_stack((grid[:, 0], np.zeros(len(grid)), grid[:, 1]))\n",
    "total = np.abs(\n",
    "    azimuthal_sum([r for r, _ in solved[\"45°\"]], [m for _, m in solved[\"45°\"]], points)[\n",
    "        :, 1\n",
    "    ]\n",
    "    + incident(np.pi / 4)(*points.T)[:, 1]\n",
    ")\n",
    "fig = plots.figure(1, 2, size=(16, 6.5))\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"incidence {name}\": (scattering(alpha), in_plane[name])\n",
    "        for name, alpha in angles.items()\n",
    "    },\n",
    "    xlabel=\"scattering angle [°]\",\n",
    "    ylabel=\"|F|^2 [m^2]\",\n",
    "    title=\"Differential cross section, plane of incidence\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.heatmap(\n",
    "    np.unique(grid[:, 0]),\n",
    "    np.unique(grid[:, 1]),\n",
    "    total.reshape(69, 69).T,\n",
    "    limits=(0, np.percentile(total, 99.5)),\n",
    "    label=\"|E_y| [V/m]\",\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    title=\"Total field, incidence at 45°\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Replace the sphere in `sphere_scattering_azimuthal_modes_geometry.py` by a cone or a finite\n",
    "cylinder: the cross section then depends on the angle of incidence, and the meridian model gives\n",
    "it at a small fraction of the cost of a 3D model."
   ]
  }
 ]
}
