{
 "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 scattered by a rigid sphere\n",
    "\n",
    "A plane wave $p_i=p_0e^{-ikz}$ travels along $z$ and meets a rigid sphere of radius $a=0.1$ m.\n",
    "The sphere throws back a scattered wave $p_s$; the total pressure is $p=p_i+p_s$. The scattered\n",
    "field solves the Helmholtz equation outside the sphere with the condition that the total normal\n",
    "velocity on the sphere vanishes. It is computed on a quarter of the air (the field is symmetric\n",
    "about the planes $x=0$ and $y=0$) out to an outer sphere of radius $R$:\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| scatterer, $r=a$ | rigid: $\\partial_n p_s=-\\partial_n p_i$ |\n",
    "| symmetry planes $x=0$ and $y=0$ | $\\partial_n p_s=0$ |\n",
    "| outer sphere, $r=R$ | outgoing spherical wave, $v_n=p_s\\,(1+1/(ikR))/(\\rho_0c)$ |\n",
    "\n",
    "The outer condition is exact for the monopole part of the scattered wave and leaves a reflection\n",
    "of order $1/(kR)^2$ for the higher multipoles. It is the limiting error here, so the outer sphere\n",
    "is taken at $R=0.4$ m and $R=0.7$ m ($kR=4$ and 7 at $ka=1$); a frequency-domain perfectly\n",
    "matched layer would remove it but is not used here.\n",
    "\n",
    "**Reference.** The exact scattered field is the partial-wave series (P. M. Morse and K. U.\n",
    "Ingard, *Theoretical Acoustics*, McGraw-Hill 1968, §8.2; J. J. Bowman, T. B. A. Senior and\n",
    "P. L. E. Uslenghi, *Electromagnetic and Acoustic Scattering by Simple Shapes*, ch. 10),\n",
    "\n",
    "$$p_s(r,\\theta)=-p_0\\sum_{n=0}^\\infty(-i)^n(2n+1)\\,\\frac{j_n'(ka)}{h_n^{(2)\\prime}(ka)}\\,\n",
    "  h_n^{(2)}(kr)\\,P_n(\\cos\\theta),$$\n",
    "\n",
    "with spherical Bessel and Hankel functions and $\\theta$ measured from the direction of incidence."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import LocalRefinement, TetrahedralMesher\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.physics.acoustics import (\n",
    "    AcousticHarmonicPressure,\n",
    "    ComplexPressurePencil,\n",
    "    ConstantPressureForms,\n",
    "    PressureAdmittanceBoundary,\n",
    "    PressureTraceSamples,\n",
    "    SampledPressureAdmittanceForms,\n",
    "    SampledPressureVolumeForms,\n",
    "    pressure_space_volume_samples,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.sparse.linalg import spsolve\n",
    "from scipy.special import eval_legendre, spherical_jn, spherical_yn\n",
    "\n",
    "theme.set()\n",
    "\n",
    "c0, rho0, amplitude = 343.0, 1.204, 1.0\n",
    "impedance = rho0 * c0\n",
    "radius = 0.1\n",
    "ka = np.array([1.0, 3.0])\n",
    "omegas = c0 * ka / radius"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "Each STEP file holds the quarter of a spherical shell of air as a solid of revolution. Curved\n",
    "quadratic tetrahedra follow the spheres; they are 10 mm on the scatterer and 35 mm (a sixth of\n",
    "the wavelength at $ka=3$) far away. On the small shell a second mesh shrinks both sizes by 0.7."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "airs = {\n",
    "    \"R = 0.4 m\": load(\"rigid_sphere_scattering.step\"),\n",
    "    \"R = 0.7 m\": load(\"rigid_sphere_scattering_large.step\"),\n",
    "}\n",
    "cases = ((\"R = 0.4 m\", 1.0), (\"R = 0.4 m\", 0.7), (\"R = 0.7 m\", 1.0))\n",
    "meshes = {\n",
    "    (name, s): TetrahedralMesher(\n",
    "        target_size=0.035 * s,\n",
    "        geometry_order=2,\n",
    "        refinements=(\n",
    "            LocalRefinement(\n",
    "                region=airs[name].boundaries.scatterer, target_size=0.010 * s\n",
    "            ),\n",
    "        ),\n",
    "    ).generate(airs[name])\n",
    "    for name, s in cases\n",
    "}\n",
    "air = airs[\"R = 0.4 m\"]\n",
    "faces = air.boundaries\n",
    "\n",
    "view = plots.Camera(elevation=25, azimuth=35)\n",
    "fig = plots.figure(1, 2, size=(15, 7))\n",
    "plots.geometry(\n",
    "    air,\n",
    "    selection={\n",
    "        \"scatterer\": faces.scatterer,\n",
    "        \"outer sphere\": faces.outer,\n",
    "        \"symmetry planes\": faces.symmetry_xz | faces.symmetry_yz,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Quarter of the air around the sphere (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[cases[0]],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{meshes[cases[0]].cell_count} curved quadratic tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Quadratic Lagrange elements; `SampledPressureVolumeForms` integrates the volume forms and the\n",
    "boundary traces of the two spheres come from the space's `trace_data`. The outer sphere carries\n",
    "the admittance; the scatterer the load $-\\int\\rho_0^{-1}\\partial_np_i\\,\\phi_i\\,\\mathrm dS$ of the\n",
    "incident wave. `AcousticHarmonicPressure` solves both frequencies."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "incident = lambda omega, points: amplitude * np.exp(-1j * omega / c0 * points[:, 2])\n",
    "incident_flux = (\n",
    "    lambda omega, points: 1j\n",
    "    * omega\n",
    "    / c0\n",
    "    * points[:, 2]\n",
    "    / radius\n",
    "    * incident(omega, points)\n",
    ")\n",
    "\n",
    "\n",
    "def solve_scattering(name, level):\n",
    "    \"\"\"Scattered pressure at the two frequencies for one outer sphere and mesh.\"\"\"\n",
    "    mesh, faces, outer = meshes[name, level], airs[name].boundaries, airs[name].size[0]\n",
    "    space = FiniteElement(element=Lagrange(order=2)).bind_space(mesh)\n",
    "    volume = ConstantPressureForms(\n",
    "        *SampledPressureVolumeForms(\n",
    "            size=space.dof_count,\n",
    "            samples=lambda: pressure_space_volume_samples(space),\n",
    "            inverse_density=lambda omega, sample: 1 / rho0,\n",
    "            compressibility=lambda omega, sample: 1 / impedance / c0,\n",
    "        )(0.0)\n",
    "    )\n",
    "    traces = {\n",
    "        face: SampledPressureAdmittanceForms(\n",
    "            size=space.dof_count,\n",
    "            admittance=lambda omega, sample: 1.0,\n",
    "            samples=lambda face=face: iter(\n",
    "                [\n",
    "                    PressureTraceSamples(space.cell_dofs[owner], points, weights, basis)\n",
    "                    for owner, points, weights, _, basis, _ in map(\n",
    "                        space.trace_data, mesh.facets(getattr(faces, face))\n",
    "                    )\n",
    "                ]\n",
    "            ),\n",
    "        )(0.0)\n",
    "        for face in (\"scatterer\", \"outer\")\n",
    "    }\n",
    "    radiation = PressureAdmittanceBoundary(\n",
    "        lambda omega: (1 + c0 / (1j * omega * outer)) / impedance * traces[\"outer\"]\n",
    "    )\n",
    "    nodes = space.dof_coordinates\n",
    "    result = AcousticHarmonicPressure(\n",
    "        operator=ComplexPressurePencil(volume, boundary=radiation),\n",
    "        angular_frequencies=omegas,\n",
    "        load=lambda omega: -traces[\"scatterer\"] @ incident_flux(omega, nodes) / rho0,\n",
    "        linear_solver=spsolve,\n",
    "    ).run()\n",
    "    return dict(space=space, mesh=mesh, scattered=result.pressure, dofs=space.dof_count)\n",
    "\n",
    "\n",
    "runs = {case: solve_scattering(*case) for case in cases}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reference\n",
    "\n",
    "The series, summed to $n=40$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "orders = np.arange(41)\n",
    "hankel = lambda n, x, derivative=False: spherical_jn(\n",
    "    n, x, derivative\n",
    ") - 1j * spherical_yn(n, x, derivative)\n",
    "series = lambda value, r, theta: -amplitude * np.sum(\n",
    "    (\n",
    "        (-1j) ** orders\n",
    "        * (2 * orders + 1)\n",
    "        * spherical_jn(orders, value, True)\n",
    "        / hankel(orders, value, True)\n",
    "    )[:, None]\n",
    "    * hankel(orders[:, None], value * r / radius)\n",
    "    * eval_legendre(orders[:, None], np.cos(theta)),\n",
    "    axis=0,\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The total pressure on the sphere (sampled 0.2 mm above it) and the scattered pressure on a circle\n",
    "of radius 0.3 m, both in the plane $y=0$ from $\\theta=0$ (back side, in the direction of travel) to $\\theta=180°$ (lit side),\n",
    "against the series."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "theta = np.linspace(0.0, np.pi, 181)\n",
    "on_sphere = (\n",
    "    1.002\n",
    "    * radius\n",
    "    * np.column_stack((np.sin(theta), np.zeros_like(theta), np.cos(theta)))\n",
    ")\n",
    "ring = 0.3 * np.column_stack((np.sin(theta), np.zeros_like(theta), np.cos(theta)))\n",
    "surface, around = {}, {}\n",
    "for level, run in runs.items():\n",
    "    sphere_values = np.asarray(run[\"space\"].evaluate(run[\"scattered\"].T, on_sphere))\n",
    "    ring_values = np.asarray(run[\"space\"].evaluate(run[\"scattered\"].T, ring))\n",
    "    for i, (value, omega) in enumerate(zip(ka, omegas)):\n",
    "        surface[level, value] = sphere_values[:, i] + incident(omega, on_sphere)\n",
    "        around[level, value] = ring_values[:, i]\n",
    "for value, omega in zip(ka, omegas):\n",
    "    exact_surface = series(value, 1.002 * radius, theta) + incident(omega, on_sphere)\n",
    "    exact_around = series(value, 0.3, theta)\n",
    "    for level, run in runs.items():\n",
    "        print(\n",
    "            f\"ka = {value:.0f}, {level[0]}, mesh {level[1]} ({run['dofs']} unknowns): pressure on the sphere, largest deviation \"\n",
    "            f\"{np.max(np.abs(surface[level, value] - exact_surface)) / np.max(np.abs(exact_surface)):.1e} of its maximum; \"\n",
    "            f\"scattered pressure at r = 0.3 m, largest deviation {np.max(np.abs(around[level, value] - exact_around)) / np.max(np.abs(exact_around)):.1e}\"\n",
    "        )\n",
    "    print(\n",
    "        f\"ka = {value:.0f}: |p| on the lit pole {np.abs(surface[cases[-1], value][-1]):.4f} (series {np.abs(exact_surface[-1]):.4f}), \"\n",
    "        f\"on the shadow pole {np.abs(surface[cases[-1], value][0]):.4f} (series {np.abs(exact_surface[0]):.4f})\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Top: the total sound pressure level on the surface of the quarter model at $ka=3$. Bottom: the\n",
    "pressure amplitude on the sphere and the scattered amplitude at 0.3 m against the series."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = runs[cases[-1]]\n",
    "total = lambda position: np.abs(\n",
    "    np.asarray(fine[\"space\"].evaluate(fine[\"scattered\"][1], position))\n",
    "    + incident(omegas[1], position)\n",
    ")\n",
    "fig = plots.figure(layout=[[\"field\", \"sphere\"], [\"field\", \"ring\"]], size=(17, 11))\n",
    "plots.trisurface(\n",
    "    *[\n",
    "        np.asarray(item)\n",
    "        for item in (\n",
    "            fine[\"mesh\"].coordinates,\n",
    "            fine[\"mesh\"].facets(\n",
    "                airs[cases[-1][0]].boundaries.symmetry_xz\n",
    "                | airs[cases[-1][0]].boundaries.symmetry_yz\n",
    "                | airs[cases[-1][0]].boundaries.scatterer\n",
    "            ),\n",
    "        )\n",
    "    ],\n",
    "    total(np.asarray(fine[\"mesh\"].coordinates)),\n",
    "    camera=plots.Camera(elevation=20, azimuth=40),\n",
    "    limits=(0, 2.0),\n",
    "    label=\"|p| / p0\",\n",
    "    title=\"Total pressure at ka = 3 on the symmetry planes and the sphere\",\n",
    "    ax=fig[\"field\"],\n",
    ")\n",
    "plots.line(\n",
    "    np.degrees(theta),\n",
    "    {f\"ka = {value:.0f}\": np.abs(surface[cases[-1], value]) for value in ka},\n",
    "    reference={\n",
    "        f\"ka = {value:.0f}\": np.abs(\n",
    "            series(value, 1.002 * radius, theta) + incident(omega, on_sphere)\n",
    "        )\n",
    "        for value, omega in zip(ka, omegas)\n",
    "    },\n",
    "    xlabel=\"angle from the direction of travel [deg]\",\n",
    "    ylabel=\"|p| / p0 on the sphere\",\n",
    "    title=\"Pressure on the sphere (dashed: series)\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[\"sphere\"],\n",
    ")\n",
    "plots.line(\n",
    "    np.degrees(theta),\n",
    "    {f\"ka = {value:.0f}\": np.abs(around[cases[-1], value]) for value in ka},\n",
    "    reference={f\"ka = {value:.0f}\": np.abs(series(value, 0.3, theta)) for value in ka},\n",
    "    xlabel=\"angle from the direction of travel [deg]\",\n",
    "    ylabel=\"|p_s| / p0 at r = 0.3 m\",\n",
    "    title=\"Scattered pressure (dashed: series)\",\n",
    "    legend=\"upper center\",\n",
    "    ax=fig[\"ring\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the sphere sound-soft (pressure release) by fixing $p_s=-p_i$ on it, or replace it by an\n",
    "ellipsoid or a cube in `rigid_sphere_scattering_geometry.py`: the finite-element route stays the\n",
    "same, only the series is gone."
   ]
  }
 ]
}
