{
 "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": [
    "# Radiation impedance of a flanged pipe\n",
    "\n",
    "A rigid piston at the closed end of a pipe (radius $a=20$ mm, length $L=250$ mm) oscillates with\n",
    "velocity $U e^{i\\omega t}$. The pipe opens through an infinite rigid flange into air. For small\n",
    "amplitudes the pressure obeys the Helmholtz equation, and since nothing depends on the angle\n",
    "around the pipe axis it is solved in the meridian plane $(r,z)$:\n",
    "\n",
    "$$\\frac{1}{r}\\frac{\\partial}{\\partial r}\\Big(\\frac{r}{\\rho_0}\\frac{\\partial p}{\\partial r}\\Big)\n",
    "  +\\frac{\\partial}{\\partial z}\\Big(\\frac{1}{\\rho_0}\\frac{\\partial p}{\\partial z}\\Big)\n",
    "  +\\frac{\\omega^2}{\\rho_0c^2}\\,p=0 .$$\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| piston, $z=0$ | normal velocity $U$ into the air, $\\partial_n p=i\\omega\\rho_0U$ |\n",
    "| pipe wall and flange | rigid, $\\partial_n p=0$ |\n",
    "| hemisphere of radius 0.3 m | outgoing spherical wave, $v_n=p\\,(1+1/(ikr))/(\\rho_0c)$ |\n",
    "| axis $r=0$ | regular (natural in the axisymmetric form) |\n",
    "\n",
    "The open end acts on the pipe like a load impedance $Z_L=p/v$. At low frequency it is a small\n",
    "resistance plus the inertia of an extra slug of air of length $\\delta$, the **end correction**:\n",
    "$Z_L/\\rho_0c\\approx\\tfrac12(ka)^2+ik\\delta$.\n",
    "\n",
    "**Reference.** Lord Rayleigh (*The Theory of Sound*, Vol. II, §302) gives the impedance of a\n",
    "flat piston of radius $a$ in an infinite baffle,\n",
    "\n",
    "$$\\frac{Z_P}{\\rho_0c}=1-\\frac{2J_1(2ka)}{2ka}+i\\,\\frac{2\\mathbf H_1(2ka)}{2ka},\\qquad\n",
    "  \\delta_P=\\frac{8a}{3\\pi}=0.849\\,a ,$$\n",
    "\n",
    "with the Struve function $\\mathbf H_1$ (also L. E. Kinsler et al., *Fundamentals of Acoustics*,\n",
    "4th ed., §7.5). The open end of a pipe is not a flat piston: its velocity peaks at the edge, and\n",
    "A. N. Norris and I. C. Sheng (*J. Sound Vib.* 135, 85-93, 1989) found $\\delta=0.8216\\,a$ for\n",
    "the flanged pipe at low frequency. The pipe itself is a plane-wave transmission line,\n",
    "\n",
    "$$Z_\\mathrm{in}=\\rho_0c\\,\\frac{Z_L+i\\rho_0c\\tan kL}{\\rho_0c+iZ_L\\tan kL},$$\n",
    "\n",
    "which turns the computed input impedance at the piston into the load impedance of the open end."
   ]
  },
  {
   "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.results.comparisons import convergence\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\n",
    "frequencies = np.linspace(40.0, 2000.0, 197)\n",
    "omegas = 2 * np.pi * frequencies"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "The two STEP files hold half solids of revolution: the pipe with the hemisphere of outside air,\n",
    "and the pipe alone. `section` with the plane $y=0$ returns their meridian half-planes $r\\ge0$.\n",
    "The triangles are smallest at the rim of the open end, where the velocity is singular, and grow\n",
    "towards the hemisphere. Three meshes are made, from 2.5 mm at the rim and 25 mm (a seventh of the\n",
    "shortest wavelength) far away down to a quarter of those sizes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "parts = {\n",
    "    \"pipe and outside air\": load(\"flanged_pipe_radiation_impedance.step\"),\n",
    "    \"pipe alone\": load(\"flanged_pipe_radiation_impedance_pipe.step\"),\n",
    "}\n",
    "planes = {name: part.section((0, 1, 0)) for name, part in parts.items()}\n",
    "radius, length = planes[\"pipe alone\"].size[:2]\n",
    "rim = np.array([radius, length])\n",
    "levels = (1.0, 0.5, 0.25)\n",
    "meshes = {\n",
    "    (name, s): TriangularMesher(\n",
    "        target_size=0.025 * s,\n",
    "        size_field=lambda p, s=s: np.minimum(\n",
    "            0.025 * s, 0.0025 * s + 0.2 * np.linalg.norm(p[:, :2] - rim, axis=1)\n",
    "        ),\n",
    "    ).generate(plane)\n",
    "    for name, plane in planes.items()\n",
    "    for s in levels\n",
    "}\n",
    "finest = levels[-1]\n",
    "\n",
    "full = parts[\"pipe and outside air\"]\n",
    "view = plots.Camera(elevation=18, azimuth=-150)\n",
    "fig = plots.figure(1, 2, size=(15, 6.5))\n",
    "plots.geometry(\n",
    "    full,\n",
    "    selection={\n",
    "        \"piston\": full.boundaries.piston,\n",
    "        \"pipe wall\": full.boundaries.wall,\n",
    "        \"flange\": full.boundaries.flange,\n",
    "        \"outer hemisphere\": full.boundaries.outer,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Half of the air volume (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"pipe and outside air\", 0.5],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Meridian plane, middle mesh: {meshes['pipe and outside air', 0.5].cell_count} triangles \"\n",
    "    f\"(pipe alone: {meshes['pipe alone', 0.5].cell_count})\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`RevolvedH1SpaceFactory` turns the quadratic Lagrange space of the meridian plane into an\n",
    "axisymmetric one: every volume and boundary weight carries the factor $2\\pi r$. The volume forms\n",
    "come from `SampledPressureVolumeForms`, the boundary traces of a face from the space's\n",
    "`trace_data`. The outer hemisphere gets the spherical-wave admittance, and the piston load is\n",
    "$i\\omega U\\int\\phi_i\\,\\mathrm dS$; `AcousticHarmonicPressure` solves the sweep.\n",
    "\n",
    "The second model is the pipe alone. Its opening carries a uniform admittance $1/Z_L$; the\n",
    "impedance is either the one measured in the first model or Rayleigh's piston."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def solve_pipe(name, level, end_face, open_end):\n",
    "    \"\"\"Input impedance at the piston over the sweep; open_end(omega, points) is the admittance of end_face.\"\"\"\n",
    "    plane, mesh = planes[name], meshes[name, 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\", end_face)\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[end_face]),\n",
    "        admittance=lambda omega, sample: open_end(omega, sample.points),\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_in=result.pressure @ piston / (np.pi * radius**2) / velocity,\n",
    "    )\n",
    "\n",
    "\n",
    "spherical_wave = (\n",
    "    lambda omega, points: (\n",
    "        1 + c0 / (1j * omega.real * np.linalg.norm(points - [0.0, length], axis=1))\n",
    "    )\n",
    "    / impedance\n",
    ")\n",
    "study = {\n",
    "    s: solve_pipe(\"pipe and outside air\", s, \"outer\", spherical_wave) for s in levels\n",
    "}\n",
    "outside = study[finest]\n",
    "k = omegas / c0\n",
    "line_load = (\n",
    "    lambda z_in: impedance\n",
    "    * (z_in - 1j * impedance * np.tan(k * length))\n",
    "    / (impedance - 1j * z_in * np.tan(k * length))\n",
    ")\n",
    "load_impedance = line_load(outside[\"z_in\"])\n",
    "rayleigh = impedance * (\n",
    "    1\n",
    "    - j1(2 * k * radius) / (k * radius)\n",
    "    + 1j * struve(1, 2 * k * radius) / (k * radius)\n",
    ")\n",
    "lumped = {\n",
    "    \"measured impedance\": solve_pipe(\n",
    "        \"pipe alone\",\n",
    "        finest,\n",
    "        \"opening\",\n",
    "        lambda omega, points: 1 / np.interp(omega.real, omegas, load_impedance),\n",
    "    ),\n",
    "    \"Rayleigh piston\": solve_pipe(\n",
    "        \"pipe alone\",\n",
    "        finest,\n",
    "        \"opening\",\n",
    "        lambda omega, points: 1 / np.interp(omega.real, omegas, rayleigh),\n",
    "    ),\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The load impedance of the open end, divided by $\\rho_0c$, against Rayleigh's piston; the end\n",
    "correction $\\delta=\\mathrm{Im}\\,Z_L/(\\rho_0ck)$ against both references, with the mesh study; and\n",
    "the input impedance of the two pipe-alone models against the full model. The measured impedance\n",
    "reproduces the full model; Rayleigh's flat piston has a 3 % longer end correction, which shifts\n",
    "the sharp resonance peaks of $|Z_\\mathrm{in}|$ by a few hertz and so changes the curve by tens of\n",
    "percent right at the peaks."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "delta = load_impedance.imag / (impedance * k) / radius\n",
    "print(\n",
    "    f\"unknowns: pipe and outside air {outside['dofs']}, pipe alone {lumped['Rayleigh piston']['dofs']}\"\n",
    ")\n",
    "print(\n",
    "    \"  f [Hz]    ka      Re Z_L/rho c   Rayleigh    Im Z_L/rho c   Rayleigh    delta/a   Rayleigh delta/a\"\n",
    ")\n",
    "for f in (100, 200, 400, 800, 1200, 1600, 2000):\n",
    "    i = np.argmin(np.abs(frequencies - f))\n",
    "    print(\n",
    "        f\"{frequencies[i]:7.0f}  {k[i] * radius:6.3f}   {load_impedance[i].real / impedance:11.5f}  {rayleigh[i].real / impedance:9.5f}\"\n",
    "        f\"   {load_impedance[i].imag / impedance:11.5f}  {rayleigh[i].imag / impedance:9.5f}   {delta[i]:7.4f}\"\n",
    "        f\"   {rayleigh[i].imag / (impedance * k[i] * radius):7.4f}\"\n",
    "    )\n",
    "low = frequencies <= 100\n",
    "corrections = [\n",
    "    np.mean(line_load(study[s][\"z_in\"]).imag[low] / (impedance * k[low] * radius))\n",
    "    for s in levels\n",
    "]\n",
    "trend = convergence(corrections, list(levels))\n",
    "print(\n",
    "    \"end correction below 100 Hz on the three meshes: \"\n",
    "    + \", \".join(\n",
    "        f\"{value:.4f} a ({study[s]['dofs']} unknowns)\"\n",
    "        for s, value in zip(levels, corrections)\n",
    "    )\n",
    ")\n",
    "print(\n",
    "    f\"finest mesh {corrections[-1]:.4f} a, extrapolated {trend.extrapolated:.4f} a (observed order {trend.order:.1f}); \"\n",
    "    f\"Norris and Sheng 0.8216 a: {100 * (corrections[-1] / 0.8216 - 1):+.2f} % (finest), \"\n",
    "    f\"{100 * (trend.extrapolated / 0.8216 - 1):+.2f} % (extrapolated); flat piston 8/(3 pi) = {8 / (3 * np.pi):.4f} a\"\n",
    ")\n",
    "for name, run in lumped.items():\n",
    "    print(\n",
    "        f\"pipe alone with the {name}: largest deviation of |Z_in| from the full model \"\n",
    "        f\"{np.max(np.abs(run['z_in'] - outside['z_in']) / np.abs(outside['z_in'])):.2e} (relative, over the sweep)\"\n",
    "    )\n",
    "peaks = [\n",
    "    frequencies[i]\n",
    "    for i in range(1, len(frequencies) - 1)\n",
    "    if abs(outside[\"z_in\"][i])\n",
    "    > max(abs(outside[\"z_in\"][i - 1]), abs(outside[\"z_in\"][i + 1]))\n",
    "]\n",
    "quarter_wave = [\n",
    "    (2 * n - 1) * c0 / (4 * (length + 0.8216 * radius))\n",
    "    for n in range(1, len(peaks) + 1)\n",
    "]\n",
    "print(\n",
    "    \"resonances of |Z_in| (sweep step 10 Hz) [Hz]:\",\n",
    "    \", \".join(f\"{p:.0f}\" for p in peaks),\n",
    "    \"| quarter-wave with delta = 0.8216 a:\",\n",
    "    \", \".join(f\"{q:.0f}\" for q in quarter_wave),\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Top: the sound pressure level in the meridian plane at the first resonance, and the load\n",
    "impedance of the open end. Bottom: the end correction over frequency and the input impedance at\n",
    "the piston for the full model and the two pipe-alone models."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "first = np.argmin(np.abs(frequencies - peaks[0]))\n",
    "x, y = np.asarray(outside[\"mesh\"].coordinates).T\n",
    "level = 20 * np.log10(\n",
    "    np.abs(\n",
    "        np.asarray(\n",
    "            outside[\"space\"].evaluate(\n",
    "                outside[\"pressure\"][first], outside[\"mesh\"].coordinates\n",
    "            )\n",
    "        )\n",
    "    )\n",
    "    / 2e-5\n",
    ")\n",
    "fig = plots.figure(2, 2, size=(16, 12))\n",
    "plots.heatmap(\n",
    "    x,\n",
    "    y,\n",
    "    level,\n",
    "    triangles=np.asarray(outside[\"mesh\"].cells),\n",
    "    limits=(level.max() - 50, level.max()),\n",
    "    contours=10,\n",
    "    label=\"sound pressure level [dB]\",\n",
    "    xlabel=\"r [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    title=f\"First resonance, {frequencies[first]:.0f} Hz, piston velocity 1 mm/s\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    k * radius,\n",
    "    {\n",
    "        \"Re Z_L / rho c, simulation\": load_impedance.real / impedance,\n",
    "        \"Im Z_L / rho c, simulation\": load_impedance.imag / impedance,\n",
    "    },\n",
    "    reference={\n",
    "        \"Re Z_L / rho c, simulation\": rayleigh.real / impedance,\n",
    "        \"Im Z_L / rho c, simulation\": rayleigh.imag / impedance,\n",
    "    },\n",
    "    xlabel=\"ka\",\n",
    "    ylabel=\"normalised impedance\",\n",
    "    title=\"Open end (dashed: Rayleigh's flat piston)\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    k * radius,\n",
    "    {\"simulation\": delta},\n",
    "    reference={\"flat piston (Rayleigh)\": rayleigh.imag / (impedance * k * radius)},\n",
    "    hlines={\"Norris and Sheng, 0.8216 a\": 0.8216},\n",
    "    xlabel=\"ka\",\n",
    "    ylabel=\"end correction delta / a\",\n",
    "    title=\"End correction of the flanged pipe\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    frequencies,\n",
    "    {\n",
    "        \"pipe and outside air\": np.abs(outside[\"z_in\"]) / impedance,\n",
    "        \"pipe alone, measured impedance\": np.abs(lumped[\"measured impedance\"][\"z_in\"])\n",
    "        / impedance,\n",
    "    },\n",
    "    reference={\n",
    "        \"pipe alone, Rayleigh piston\": np.abs(lumped[\"Rayleigh piston\"][\"z_in\"])\n",
    "        / impedance\n",
    "    },\n",
    "    scale=\"logy\",\n",
    "    xlabel=\"frequency [Hz]\",\n",
    "    ylabel=\"|Z_in| / rho c\",\n",
    "    title=\"Input impedance at the piston\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Remove the flange in `flanged_pipe_radiation_impedance_geometry.py` (a thin pipe wall standing\n",
    "in the air) and write the STEP file again: the end correction drops towards Levine and\n",
    "Schwinger's 0.6133 a. Or move the hemisphere closer to the opening to see where the\n",
    "spherical-wave admittance, exact only for the monopole part of the far field, starts to cost\n",
    "accuracy."
   ]
  }
 ]
}
