{
 "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": [
    "# Baffled piston radiation\n",
    "\n",
    "A rigid circular piston of radius $a=50$ mm, set flush in an infinite rigid wall (the baffle),\n",
    "vibrates with normal velocity $U e^{i\\omega t}$ and radiates into the air in front of it. The\n",
    "pressure obeys the Helmholtz equation, which by symmetry is solved in the meridian plane $(r,z)$\n",
    "of the half-space $z>0$. The computed region is a hemisphere of radius 0.6 m; on its surface an\n",
    "outgoing spherical wave is assumed.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| piston, $z=0$, $r<a$ | normal velocity $U$ |\n",
    "| baffle, $z=0$, $r>a$ | rigid, $\\partial p/\\partial z=0$ |\n",
    "| hemisphere $\\rho=0.6$ m | outgoing spherical wave, $v_n=p\\,(1+1/(ik\\rho))/(\\rho_0c)$ |\n",
    "| axis $r=0$ | regular (natural in the axisymmetric form) |\n",
    "\n",
    "**Reference.** Lord Rayleigh (*The Theory of Sound*, Vol. II, §278 and §302) wrote the field of a\n",
    "baffled piston as the integral over its surface,\n",
    "\n",
    "$$p(\\mathbf x)=\\frac{i\\omega\\rho_0U}{2\\pi}\\int_\\mathrm{piston}\\frac{e^{-ik|\\mathbf x-\\mathbf y|}}{|\\mathbf x-\\mathbf y|}\\,\\mathrm dS_y ,$$\n",
    "\n",
    "which is exact at every point in front of the baffle. Far away it becomes\n",
    "$p\\propto D(\\theta)\\,e^{-ikr}/r$ with the directivity $D(\\theta)=2J_1(ka\\sin\\theta)/(ka\\sin\\theta)$,\n",
    "and the mean pressure on the piston gives the radiation impedance\n",
    "$Z/\\rho_0c=1-2J_1(2ka)/(2ka)+i\\,2\\mathbf H_1(2ka)/(2ka)$ (also L. E. Kinsler et al.,\n",
    "*Fundamentals of Acoustics*, 4th ed., §7.4-7.5).\n",
    "\n",
    "The spherical-wave condition on the hemisphere is exact for the monopole part of the far field\n",
    "only; for a directive source it leaves a small reflection of order $1/(k\\rho)^2$. A\n",
    "frequency-domain perfectly matched layer would remove it but is not used here."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange, RevolvedH1SpaceFactory\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 j1, struve\n",
    "\n",
    "theme.set()\n",
    "\n",
    "c0, rho0, velocity = 343.0, 1.204, 1e-3\n",
    "impedance = rho0 * c0"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "The STEP file holds half of the hemisphere of air as a solid of revolution; `section` with the\n",
    "plane $y=0$ returns its meridian quarter disc. The shortest wavelength of the sweep is 63 mm; the\n",
    "triangles are a sixth of it far away (coarse mesh) or a twelfth (fine mesh) and shrink towards\n",
    "the rim of the piston, where the velocity jumps."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "air = load(\"baffled_piston_radiation.step\")\n",
    "plane = air.section((0, 1, 0))\n",
    "outer = plane.size[1]\n",
    "piston_radius = 0.05\n",
    "ka = np.round(np.arange(0.1, 5.05, 0.1), 2)\n",
    "omegas = c0 * ka / piston_radius\n",
    "shortest = 2 * np.pi * c0 / omegas.max()\n",
    "levels = {\"coarse\": shortest / 6, \"fine\": shortest / 12}\n",
    "meshes = {\n",
    "    level: TriangularMesher(\n",
    "        target_size=h,\n",
    "        size_field=lambda p, h=h: np.minimum(\n",
    "            h, h / 8 + 0.2 * np.linalg.norm(p[:, :2] - [piston_radius, 0.0], axis=1)\n",
    "        ),\n",
    "    ).generate(plane)\n",
    "    for level, h in levels.items()\n",
    "}\n",
    "\n",
    "view = plots.Camera(elevation=25, azimuth=-150)\n",
    "fig = plots.figure(1, 2, size=(15, 6.5))\n",
    "plots.geometry(\n",
    "    air,\n",
    "    selection={\n",
    "        \"piston\": air.boundaries.piston,\n",
    "        \"baffle\": air.boundaries.baffle,\n",
    "        \"outer hemisphere\": air.boundaries.outer,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Half of the air in front of the baffle (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"coarse\"],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Meridian plane, coarse mesh: {meshes['coarse'].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`RevolvedH1SpaceFactory` makes the quadratic Lagrange space of the meridian plane axisymmetric\n",
    "(weights $2\\pi r$). The volume forms come from `SampledPressureVolumeForms`, the boundary traces\n",
    "of a face from the space's `trace_data`; the hemisphere carries the spherical-wave admittance and\n",
    "the piston the load $i\\omega U\\int\\phi_i\\,\\mathrm dS$. `AcousticHarmonicPressure` solves the 50\n",
    "frequencies from $ka=0.1$ to 5."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def solve_piston(level):\n",
    "    \"\"\"Pressure field over the sweep on one mesh, and the radiation impedance of the piston.\"\"\"\n",
    "    mesh = meshes[level]\n",
    "    space = FiniteElement(\n",
    "        element=Lagrange(order=2), provider=RevolvedH1SpaceFactory()\n",
    "    ).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: [\n",
    "            PressureTraceSamples(space.cell_dofs[owner], points, weights, basis)\n",
    "            for owner, points, weights, _, basis, _ in map(\n",
    "                space.trace_data, mesh.facets(getattr(plane.boundaries, face))\n",
    "            )\n",
    "        ]\n",
    "        for face in (\"piston\", \"outer\")\n",
    "    }\n",
    "    piston = SampledPressureAdmittanceForms(\n",
    "        size=space.dof_count,\n",
    "        samples=lambda: iter(traces[\"piston\"]),\n",
    "        admittance=lambda omega, sample: 1.0,\n",
    "    )(0.0) @ np.ones(space.dof_count)\n",
    "    radiation = SampledPressureAdmittanceForms(\n",
    "        size=space.dof_count,\n",
    "        samples=lambda: iter(traces[\"outer\"]),\n",
    "        admittance=lambda omega, sample: (1 + c0 / (1j * omega.real * outer))\n",
    "        / impedance,\n",
    "    )\n",
    "    result = AcousticHarmonicPressure(\n",
    "        operator=ComplexPressurePencil(\n",
    "            volume, boundary=PressureAdmittanceBoundary(radiation)\n",
    "        ),\n",
    "        load=lambda omega: 1j * omega * velocity * piston,\n",
    "        angular_frequencies=omegas,\n",
    "        linear_solver=spsolve,\n",
    "    ).run()\n",
    "    return dict(\n",
    "        space=space,\n",
    "        mesh=mesh,\n",
    "        pressure=result.pressure,\n",
    "        dofs=space.dof_count,\n",
    "        z=result.pressure @ piston / (np.pi * piston_radius**2) / velocity,\n",
    "    )\n",
    "\n",
    "\n",
    "runs = {level: solve_piston(level) for level in levels}\n",
    "fine = runs[\"fine\"]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reference\n",
    "\n",
    "Rayleigh's impedance, and his surface integral evaluated with 48 Gauss points across the radius\n",
    "and 96 points around the piston."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "k = omegas / c0\n",
    "rayleigh_impedance = impedance * (\n",
    "    1\n",
    "    - j1(2 * k * piston_radius) / (k * piston_radius)\n",
    "    + 1j * struve(1, 2 * k * piston_radius) / (k * piston_radius)\n",
    ")\n",
    "nodes, weights = np.polynomial.legendre.leggauss(48)\n",
    "s, phi = np.meshgrid(piston_radius * (nodes + 1) / 2, np.arange(96) * 2 * np.pi / 96)\n",
    "y, dS = (\n",
    "    np.column_stack((s.ravel() * np.cos(phi.ravel()), s.ravel() * np.sin(phi.ravel()))),\n",
    "    np.tile(weights * piston_radius / 2, 96) * s.ravel() * 2 * np.pi / 96,\n",
    ")\n",
    "distance = lambda points: np.sqrt(\n",
    "    (points[:, :1] - y[:, 0]) ** 2 + y[:, 1] ** 2 + points[:, 1:] ** 2\n",
    ")\n",
    "rayleigh_field = (\n",
    "    lambda omega, points: 1j\n",
    "    * omega\n",
    "    * rho0\n",
    "    * velocity\n",
    "    / (2 * np.pi)\n",
    "    * (np.exp(-1j * omega / c0 * distance(points)) / distance(points))\n",
    "    @ dS\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Radiation impedance over the sweep; the pressure on the axis from 20 mm to 0.55 m, through the\n",
    "near-field maxima and minima; and the directivity on a half circle of radius 0.5 m at\n",
    "$ka=1$, 3 and 5."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "for level, run in runs.items():\n",
    "    print(\n",
    "        f\"{level} mesh, {run['dofs']} unknowns: largest deviation of Z from Rayleigh over ka = 0.1 ... 5: \"\n",
    "        f\"{np.max(np.abs(run['z'] - rayleigh_impedance)) / impedance:.1e} rho c\"\n",
    "    )\n",
    "print(\"   ka     Re Z/rho c  Rayleigh   Im Z/rho c  Rayleigh\")\n",
    "for value in (0.5, 1.0, 2.0, 3.0, 4.0, 5.0):\n",
    "    i = np.argmin(np.abs(ka - value))\n",
    "    print(\n",
    "        f\"{ka[i]:5.1f}   {fine['z'][i].real / impedance:10.5f}  {rayleigh_impedance[i].real / impedance:8.5f}\"\n",
    "        f\"   {fine['z'][i].imag / impedance:10.5f}  {rayleigh_impedance[i].imag / impedance:8.5f}\"\n",
    "    )\n",
    "axis = np.column_stack((np.zeros(200), np.linspace(0.02, 0.55, 200)))\n",
    "theta = np.radians(np.linspace(0.0, 90.0, 181))\n",
    "arc = 0.5 * np.column_stack((np.sin(theta), np.cos(theta)))\n",
    "shown = {value: int(np.argmin(np.abs(ka - value))) for value in (1.0, 3.0, 5.0)}\n",
    "on_axis, directivity = {}, {}\n",
    "for value, i in shown.items():\n",
    "    for level, run in runs.items():\n",
    "        on_axis[level, value] = np.asarray(\n",
    "            run[\"space\"].evaluate(run[\"pressure\"][i], axis)\n",
    "        )\n",
    "        directivity[level, value] = np.asarray(\n",
    "            run[\"space\"].evaluate(run[\"pressure\"][i], arc)\n",
    "        )\n",
    "    exact_axis, exact_arc = rayleigh_field(omegas[i], axis), rayleigh_field(\n",
    "        omegas[i], arc\n",
    "    )\n",
    "    print(\n",
    "        f\"ka = {value:.0f}: on-axis pressure, largest deviation / peak: coarse \"\n",
    "        f\"{np.max(np.abs(on_axis['coarse', value] - exact_axis)) / np.max(np.abs(exact_axis)):.1e}, fine \"\n",
    "        f\"{np.max(np.abs(on_axis['fine', value] - exact_axis)) / np.max(np.abs(exact_axis)):.1e}; \"\n",
    "        f\"level on the half circle, largest deviation: coarse \"\n",
    "        f\"{np.max(np.abs(20 * np.log10(np.abs(directivity['coarse', value] / exact_arc)))):.2f} dB, fine \"\n",
    "        f\"{np.max(np.abs(20 * np.log10(np.abs(directivity['fine', value] / exact_arc)))):.2f} dB\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Top: the sound pressure level in the meridian plane at $ka=5$ with its side lobe, and the\n",
    "radiation impedance. Bottom: the pressure amplitude along the axis and the directivity at 0.5 m,\n",
    "each against Rayleigh's integral; the far-field directivity $|D(\\theta)|$ is drawn dotted."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "i = shown[5.0]\n",
    "x, z = np.asarray(fine[\"mesh\"].coordinates).T\n",
    "level = 20 * np.log10(\n",
    "    np.abs(\n",
    "        np.asarray(\n",
    "            fine[\"space\"].evaluate(fine[\"pressure\"][i], fine[\"mesh\"].coordinates)\n",
    "        )\n",
    "    )\n",
    "    / 2e-5\n",
    ")\n",
    "far_field = lambda value: np.abs(\n",
    "    2 * j1(value * np.sin(theta) + 1e-12) / (value * np.sin(theta) + 1e-12)\n",
    ")\n",
    "fig = plots.figure(2, 2, size=(16, 12))\n",
    "plots.heatmap(\n",
    "    x,\n",
    "    z,\n",
    "    level,\n",
    "    triangles=np.asarray(fine[\"mesh\"].cells),\n",
    "    limits=(level.max() - 40, level.max()),\n",
    "    contours=8,\n",
    "    label=\"sound pressure level [dB]\",\n",
    "    xlabel=\"r [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    title=f\"ka = 5 ({omegas[i] / (2 * np.pi):.0f} Hz), piston velocity 1 mm/s\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    ka,\n",
    "    {\n",
    "        \"Re Z / rho c\": fine[\"z\"].real / impedance,\n",
    "        \"Im Z / rho c\": fine[\"z\"].imag / impedance,\n",
    "    },\n",
    "    reference={\n",
    "        \"Re Z / rho c\": rayleigh_impedance.real / impedance,\n",
    "        \"Im Z / rho c\": rayleigh_impedance.imag / impedance,\n",
    "    },\n",
    "    xlabel=\"ka\",\n",
    "    ylabel=\"normalised radiation impedance\",\n",
    "    title=\"Radiation impedance (dashed: Rayleigh)\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    axis[:, 1],\n",
    "    {f\"ka = {value:.0f}\": np.abs(on_axis[\"fine\", value]) for value in shown},\n",
    "    reference={\n",
    "        f\"ka = {value:.0f}\": np.abs(rayleigh_field(omegas[i], axis))\n",
    "        for value, i in shown.items()\n",
    "    },\n",
    "    xlabel=\"distance from the piston z [m]\",\n",
    "    ylabel=\"|p| [Pa]\",\n",
    "    title=\"Pressure on the axis (dashed: Rayleigh integral)\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    np.degrees(theta),\n",
    "    {\n",
    "        f\"ka = {value:.0f}\": np.abs(\n",
    "            directivity[\"fine\", value] / directivity[\"fine\", value][0]\n",
    "        )\n",
    "        for value in shown\n",
    "    },\n",
    "    reference={\n",
    "        f\"ka = {value:.0f}\": np.abs(\n",
    "            rayleigh_field(omegas[i], arc) / rayleigh_field(omegas[i], arc[:1])\n",
    "        )\n",
    "        for value, i in shown.items()\n",
    "    },\n",
    "    points={\n",
    "        f\"ka = {value:.0f}\": (np.degrees(theta[::6]), far_field(value)[::6])\n",
    "        for value in shown\n",
    "    },\n",
    "    scale=\"logy\",\n",
    "    ylimits=(1e-3, 1.5),\n",
    "    xlabel=\"angle from the axis [deg]\",\n",
    "    ylabel=\"|p(theta)| / |p(0)| at 0.5 m\",\n",
    "    title=\"Directivity (dashed: Rayleigh integral, dots: far field)\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the baffle finite in `baffled_piston_radiation_geometry.py` (a disc with air behind it) and\n",
    "write the STEP file again to see diffraction at its edge fill the nulls; or replace the uniform\n",
    "piston velocity by a flexible cone with a velocity profile over the radius."
   ]
  }
 ]
}
