{
 "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": [
    "# Sound scattered by a rigid ellipsoid\n",
    "\n",
    "A plane wave $p_i=p_0e^{-ik\\,\\hat{\\mathbf d}\\cdot\\mathbf x}$ with direction\n",
    "$\\hat{\\mathbf d}=(1,1,1)/\\sqrt3$ falls on a rigid ellipsoid with semi-axes $a_1=100$ mm,\n",
    "$a_2=60$ mm and $a_3=40$ mm. The scattered wave $p_s$ solves the Helmholtz equation outside the\n",
    "body, with the condition that the total normal velocity on the body vanishes. It is computed out to\n",
    "an outer sphere of radius $R$ with $kR=8$ for each frequency.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| ellipsoid | rigid: $\\partial_np_s=-\\partial_np_i$ |\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 reflects the dipole\n",
    "part by about $1/(kR)^2\\approx1.5$ %; a frequency-domain perfectly matched layer would remove that\n",
    "but is not used here.\n",
    "\n",
    "**Reference.** For a body small compared with the wavelength the scattered wave is a monopole,\n",
    "because the body displaces fluid, plus a dipole, because the fluid has to flow around it\n",
    "(Lord Rayleigh, *Phil. Mag.* 44, 28, 1897; G. Dassios and R. Kleinman, *Low Frequency Scattering*,\n",
    "Oxford 2000, ch. 3):\n",
    "\n",
    "$$p_s(\\mathbf x)\\simeq p_0k^2\\,\\frac{e^{-ikr}}{4\\pi r}\\Big[-V+\\Big(1-\\frac{i}{kr}\\Big)\\,\n",
    "  \\hat{\\mathbf r}\\cdot(V\\mathbf I+\\mathbf A)\\cdot\\hat{\\mathbf d}\\Big],$$\n",
    "\n",
    "with the volume $V$ and the added-mass tensor $\\mathbf A$ of the body (per unit fluid density).\n",
    "For an ellipsoid $\\mathbf A$ is diagonal in the axes with $A_j=V\\alpha_j/(2-\\alpha_j)$ and\n",
    "$\\alpha_j=a_1a_2a_3\\int_0^\\infty\\mathrm d\\lambda/\\big((a_j^2+\\lambda)\\sqrt{(a_1^2+\\lambda)(a_2^2+\\lambda)(a_3^2+\\lambda)}\\big)$\n",
    "(H. Lamb, *Hydrodynamics*, 6th ed., §114). The law is the first term of an expansion in $ka$; the\n",
    "simulation must approach it as the frequency falls, with a deviation that shrinks like $(ka)^2$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import LocalRefinement, TetrahedralMesher, with_order\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.integrate import quad\n",
    "from scipy.sparse.linalg import spsolve\n",
    "\n",
    "theme.set()\n",
    "\n",
    "c0, rho0, amplitude = 343.0, 1.204, 1.0\n",
    "impedance = rho0 * c0\n",
    "axes = np.array([0.10, 0.06, 0.04])\n",
    "direction = np.ones(3) / np.sqrt(3)\n",
    "cases = {\n",
    "    0.25: \"ellipsoid_scattering_ka025.step\",\n",
    "    0.5: \"ellipsoid_scattering_ka050.step\",\n",
    "    1.0: \"ellipsoid_scattering.step\",\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and meshes\n",
    "\n",
    "Each STEP file holds the air between the ellipsoid and an outer sphere of radius $8/k$. The\n",
    "tetrahedra are a sixth of the wavelength far away and 12 mm on the ellipsoid; `with_order` lifts\n",
    "them to quadratic cells whose edge nodes lie on the curved faces."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "parts = {ka: load(name) for ka, name in cases.items()}\n",
    "meshes = {\n",
    "    ka: with_order(\n",
    "        TetrahedralMesher(\n",
    "            target_size=2 * np.pi * axes[0] / ka / 6,\n",
    "            refinements=(\n",
    "                LocalRefinement(region=part.boundaries.body, target_size=0.012),\n",
    "            ),\n",
    "        ).generate(part),\n",
    "        2,\n",
    "    )\n",
    "    for ka, part in parts.items()\n",
    "}\n",
    "\n",
    "part = parts[1.0]\n",
    "view = plots.Camera(elevation=25, azimuth=-50)\n",
    "fig = plots.figure(1, 2, size=(15, 7))\n",
    "plots.geometry(\n",
    "    part,\n",
    "    selection={\"ellipsoid\": part.boundaries.body, \"outer sphere\": part.boundaries.air},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Air around the ellipsoid, ka = 1 (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[1.0],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"ka = 1: {meshes[1.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",
    "traces of ellipsoid and outer sphere come from the space's `trace_data`. The outer sphere carries\n",
    "the admittance, the ellipsoid the load $-\\int\\rho_0^{-1}\\partial_np_i\\,\\phi_i\\,\\mathrm dS$ with\n",
    "the normal of the ellipsoid. `AcousticHarmonicPressure` solves each frequency on its own mesh."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "incident = lambda k, points: amplitude * np.exp(-1j * k * points @ direction)\n",
    "body_normal = (\n",
    "    lambda points: points / axes**2 / np.linalg.norm(points / axes**2, axis=1)[:, None]\n",
    ")\n",
    "incident_flux = (\n",
    "    lambda k, points: (body_normal(points) @ direction) * 1j * k * incident(k, points)\n",
    ")\n",
    "\n",
    "\n",
    "def solve_ellipsoid(ka):\n",
    "    \"\"\"Scattered pressure at one frequency on its mesh.\"\"\"\n",
    "    mesh, faces, k = meshes[ka], parts[ka].boundaries, ka / axes[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 (\"body\", \"air\")\n",
    "    }\n",
    "    outer = parts[ka].size[0] / 2\n",
    "    pressure = (\n",
    "        AcousticHarmonicPressure(\n",
    "            operator=ComplexPressurePencil(\n",
    "                volume,\n",
    "                boundary=PressureAdmittanceBoundary(\n",
    "                    lambda omega: (1 + 1 / (1j * k * outer)) / impedance * traces[\"air\"]\n",
    "                ),\n",
    "            ),\n",
    "            angular_frequencies=[c0 * k],\n",
    "            load=lambda omega: -traces[\"body\"]\n",
    "            @ incident_flux(k, space.dof_coordinates)\n",
    "            / rho0,\n",
    "            linear_solver=spsolve,\n",
    "        )\n",
    "        .run()\n",
    "        .pressure[0]\n",
    "    )\n",
    "    return dict(\n",
    "        space=space, mesh=mesh, pressure=pressure, dofs=space.dof_count, outer=outer\n",
    "    )\n",
    "\n",
    "\n",
    "runs = {ka: solve_ellipsoid(ka) for ka in cases}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reference\n",
    "\n",
    "Volume, Lamb's coefficients and the low-frequency law."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "volume = 4 * np.pi / 3 * np.prod(axes)\n",
    "alpha = np.array(\n",
    "    [\n",
    "        np.prod(axes)\n",
    "        * quad(lambda s: 1 / ((a**2 + s) * np.sqrt(np.prod(axes**2 + s))), 0, np.inf)[0]\n",
    "        for a in axes\n",
    "    ]\n",
    ")\n",
    "added = volume * alpha / (2 - alpha)\n",
    "rayleigh = (\n",
    "    lambda k, points: amplitude\n",
    "    * k**2\n",
    "    * np.exp(-1j * k * np.linalg.norm(points, axis=1))\n",
    "    / (4 * np.pi * np.linalg.norm(points, axis=1))\n",
    "    * (\n",
    "        -volume\n",
    "        + (1 - 1j / (k * np.linalg.norm(points, axis=1)))\n",
    "        * (\n",
    "            (points / np.linalg.norm(points, axis=1)[:, None])\n",
    "            @ ((volume + added) * direction)\n",
    "        )\n",
    "    )\n",
    ")\n",
    "print(\n",
    "    f\"V = {1e6 * volume:.1f} cm3; Lamb coefficients alpha = {np.round(alpha, 4)} (sum {alpha.sum():.4f}); \"\n",
    "    f\"added mass / V = {np.round(added / volume, 4)}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The scattered pressure on 400 points spread over a sphere of radius $R/2$ around the body, against\n",
    "the low-frequency law."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "golden = np.pi * (3 - np.sqrt(5)) * np.arange(400)\n",
    "heights = 1 - (np.arange(400) + 0.5) / 200\n",
    "directions = np.column_stack(\n",
    "    (\n",
    "        np.sqrt(1 - heights**2) * np.cos(golden),\n",
    "        np.sqrt(1 - heights**2) * np.sin(golden),\n",
    "        heights,\n",
    "    )\n",
    ")\n",
    "deviation = {}\n",
    "for ka, run in runs.items():\n",
    "    k = ka / axes[0]\n",
    "    points = run[\"outer\"] / 2 * directions\n",
    "    computed, law = np.asarray(\n",
    "        run[\"space\"].evaluate(run[\"pressure\"], points)\n",
    "    ), rayleigh(k, points)\n",
    "    deviation[ka] = np.max(np.abs(computed - law)) / np.max(np.abs(law))\n",
    "    print(\n",
    "        f\"ka = {ka:.2f} ({run['dofs']} unknowns, R = {run['outer']:.1f} m): largest deviation from the low-frequency law \"\n",
    "        f\"{deviation[ka]:.3f} of its maximum; RMS |p_s| {np.sqrt(np.mean(np.abs(computed) ** 2)):.3e} Pa \"\n",
    "        f\"(law {np.sqrt(np.mean(np.abs(law) ** 2)):.3e} Pa)\"\n",
    "    )\n",
    "orders = [\n",
    "    np.log(deviation[b] / deviation[a]) / np.log(b / a)\n",
    "    for a, b in ((0.25, 0.5), (0.5, 1.0))\n",
    "]\n",
    "print(\n",
    "    f\"observed order of the deviation in ka: {orders[0]:.2f}, {orders[1]:.2f} (about 2 expected; the reflection of the outer condition adds a floor)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left: the total pressure on the ellipsoid at $ka=1$ - largest where the wave arrives, smallest in\n",
    "the shadow. Middle: the scattered amplitude at the 400 receivers at $ka=0.25$, simulation against\n",
    "law; on the diagonal they agree. Right: the deviation against $ka$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = runs[1.0]\n",
    "surface = np.asarray(fine[\"mesh\"].facets(parts[1.0].boundaries.body))\n",
    "nodes = np.unique(surface)\n",
    "points = np.asarray(fine[\"mesh\"].coordinates)[nodes]\n",
    "total = np.abs(\n",
    "    np.asarray(fine[\"space\"].evaluate(fine[\"pressure\"], points))\n",
    "    + incident(1.0 / axes[0], points)\n",
    ")\n",
    "low = runs[0.25]\n",
    "receivers = low[\"outer\"] / 2 * directions\n",
    "simulated, law = np.abs(\n",
    "    np.asarray(low[\"space\"].evaluate(low[\"pressure\"], receivers))\n",
    "), np.abs(rayleigh(0.25 / axes[0], receivers))\n",
    "fig = plots.figure(1, 3, size=(22, 6.5))\n",
    "plots.trisurface(\n",
    "    points,\n",
    "    np.searchsorted(nodes, surface),\n",
    "    total,\n",
    "    camera=view,\n",
    "    label=\"|p| / p0\",\n",
    "    title=\"Total pressure on the ellipsoid, ka = 1\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"receivers on r = R/2\": (1e3 * law, 1e3 * simulated)},\n",
    "    reference={\"equality\": ([0, 1e3 * law.max()], [0, 1e3 * law.max()])},\n",
    "    xlabel=\"|p_s|, low-frequency law [mPa]\",\n",
    "    ylabel=\"|p_s|, simulation [mPa]\",\n",
    "    title=\"Scattered amplitude, ka = 0.25\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    np.array(list(deviation)),\n",
    "    {\"largest deviation\": np.array(list(deviation.values()))},\n",
    "    markers=True,\n",
    "    slope=2.0,\n",
    "    scale=\"loglog\",\n",
    "    xlabel=\"ka\",\n",
    "    ylabel=\"deviation from the low-frequency law\",\n",
    "    title=\"Approach to the low-frequency law\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise $ka$ beyond 1 in `ellipsoid_scattering_geometry.py` (outer sphere $8/k$) to enter the\n",
    "region where the ellipsoid casts a real shadow and the low-frequency law no longer holds; or turn\n",
    "the incidence onto a principal axis, where the field becomes axisymmetric for a spheroid."
   ]
  }
 ]
}
