{
 "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": [
    "# Helmholtz resonator in a wall\n",
    "\n",
    "A plane sound wave of amplitude $p_0$ falls perpendicularly on a rigid wall. Without the\n",
    "resonator the wall reflects it, and the pressure on the wall is the blocked pressure $2p_0$. Set\n",
    "into the wall is a Helmholtz resonator: a neck of radius $a=20$ mm and length $L=40$ mm in front\n",
    "of a cylindrical cavity of radius 60 mm and depth 60 mm (volume $V$). Near its resonance the air\n",
    "in the neck swings like a mass on the spring of the compressed cavity air, and the cavity pressure\n",
    "rises far above the blocked pressure.\n",
    "\n",
    "The field is axisymmetric and is solved in the meridian plane $(r,z)$ as the sum of the known\n",
    "incident-plus-reflected wave $p_b=2p_0\\cos kz$ and the wave $p-p_b$ that the resonator sends out.\n",
    "The computed region is the resonator and a hemisphere of radius 0.4 m in front of the wall.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| wall, neck and cavity walls | rigid, $\\partial p/\\partial n=0$ |\n",
    "| hemisphere of radius $R=0.4$ m | $p-p_b$ is an outgoing spherical wave, $v_n=(p-p_b)\\,(1+1/(ikR))/(\\rho_0c)$ |\n",
    "| axis $r=0$ | regular |\n",
    "\n",
    "**Reference.** The lumped model (L. E. Kinsler et al., *Fundamentals of Acoustics*, 4th ed.,\n",
    "§10.8) gives the resonance and the quality factor from the neck area $S=\\pi a^2$, the cavity\n",
    "volume and the effective neck length $L'$,\n",
    "\n",
    "$$\\omega_0=c\\sqrt{\\frac{S}{L'V}},\\qquad Q=2\\pi\\sqrt{V\\Big(\\frac{L'}{S}\\Big)^3},\\qquad\n",
    "  \\frac{|p_\\mathrm{cavity}|}{2p_0}\\Big|_{\\omega_0}=Q ,$$\n",
    "\n",
    "where $Q$ comes from the radiation resistance of the flanged opening alone (no viscous losses).\n",
    "The effective length adds the end corrections of both ends: $0.8216\\,a$ outside, for an opening\n",
    "in a wall (A. N. Norris and I. C. Sheng, *J. Sound Vib.* 135, 1989), and\n",
    "$0.48\\sqrt S\\,(1-1.25\\,a/R_\\mathrm{cavity})$ inside the cavity (U. Ingard, *J. Acoust. Soc. Am.*\n",
    "25, 1037, 1953). These corrections and the lumped picture itself are accurate to a few per cent.\n",
    "The cavity here is $kH\\approx0.3$ deep at resonance, so its air is not quite a lumped spring; the\n",
    "refinement that treats it as a closed tube of depth $H$ and area $S_c$ (Kinsler et al., §10.8)\n",
    "moves the resonance to the root of\n",
    "\n",
    "$$\\frac{kL'}{S}=\\frac{\\cot kH}{S_c}.$$"
   ]
  },
  {
   "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.numerics.linear import BeynContourEigenSolver, elliptic_contour_quadrature\n",
    "from onesim.physics.acoustics import (\n",
    "    AcousticHarmonicPressure,\n",
    "    AcousticPressureSpectrum,\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.optimize import brentq\n",
    "from scipy.sparse.linalg import spsolve\n",
    "\n",
    "theme.set()\n",
    "\n",
    "c0, rho0, incident = 343.0, 1.204, 1.0\n",
    "impedance = rho0 * c0\n",
    "neck_radius, neck_length, cavity_radius, cavity_depth = 0.02, 0.04, 0.06, 0.06"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "The STEP file holds half of the air - resonator and hemisphere - as a solid of revolution;\n",
    "`section` with the plane $y=0$ returns the meridian half-plane. The triangles are 1 mm at the two\n",
    "rims of the neck and grow to 25 mm (a fifth of the shortest wavelength) far away; a second mesh\n",
    "halves all sizes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "air = load(\"helmholtz_resonator_baffle.step\")\n",
    "plane = air.section((0, 1, 0))\n",
    "outer = plane.size[1] - neck_length - cavity_depth\n",
    "rims = np.array([[neck_radius, 0.0], [neck_radius, -neck_length]])\n",
    "levels = (1.0, 0.5)\n",
    "meshes = {\n",
    "    s: TriangularMesher(\n",
    "        target_size=0.025 * s,\n",
    "        size_field=lambda p, s=s: np.minimum(\n",
    "            0.025 * s,\n",
    "            s\n",
    "            * (\n",
    "                0.001\n",
    "                + 0.15 * np.min(np.linalg.norm(p[:, None, :2] - rims, axis=2), axis=1)\n",
    "            ),\n",
    "        ),\n",
    "    ).generate(plane)\n",
    "    for s in levels\n",
    "}\n",
    "\n",
    "view = plots.Camera(elevation=18, azimuth=-150)\n",
    "fig = plots.figure(1, 2, size=(15, 6.5))\n",
    "plots.geometry(\n",
    "    air,\n",
    "    selection={\n",
    "        \"cavity\": air.boundaries.cavity,\n",
    "        \"neck\": air.boundaries.neck,\n",
    "        \"wall\": air.boundaries.wall,\n",
    "        \"outer hemisphere\": air.boundaries.outer,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Half of the air: resonator and hemisphere (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[1.0],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Meridian plane: {meshes[1.0].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 axisymmetric (weights $2\\pi r$).\n",
    "`SampledPressureVolumeForms` integrates the volume forms; the hemisphere carries the\n",
    "spherical-wave admittance $Y(\\omega)$ and the load\n",
    "$\\int\\big(\\rho_0^{-1}\\partial_n p_b+i\\omega Y p_b\\big)\\phi_i\\,\\mathrm dS$ from the incident wave.\n",
    "The admittance is an analytic function of the complex frequency, so the same\n",
    "`ComplexPressurePencil` serves two solvers:\n",
    "\n",
    "- `AcousticHarmonicPressure` sweeps real frequencies from 150 to 450 Hz with a sparse direct\n",
    "  solver;\n",
    "- `AcousticPressureSpectrum` with `BeynContourEigenSolver` finds the complex frequencies inside an\n",
    "  ellipse around the resonance where the pencil becomes singular: the real part is the resonance,\n",
    "  the imaginary part its radiation damping, $Q=\\mathrm{Re}\\,\\omega/(2\\,\\mathrm{Im}\\,\\omega)$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "admittance = lambda omega: (1 + c0 / (1j * omega * outer)) / impedance\n",
    "background = lambda omega, points: 2 * incident * np.cos(omega / c0 * points[:, 1])\n",
    "background_flux = (\n",
    "    lambda omega, points: -2\n",
    "    * incident\n",
    "    * omega\n",
    "    / c0\n",
    "    * np.sin(omega / c0 * points[:, 1])\n",
    "    * points[:, 1]\n",
    "    / outer\n",
    ")\n",
    "frequencies = np.arange(150.0, 450.5, 1.0)\n",
    "contour = elliptic_contour_quadrature(\n",
    "    2 * np.pi * 290.0, (2 * np.pi * 120.0, 2 * np.pi * 30.0), 48\n",
    ")\n",
    "\n",
    "\n",
    "def solve_resonator(level):\n",
    "    \"\"\"Frequency sweep and complex resonance of the resonator on one mesh.\"\"\"\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",
    "    surface = [\n",
    "        PressureTraceSamples(space.cell_dofs[owner], points, weights, basis)\n",
    "        for owner, points, weights, _, basis, _ in map(\n",
    "            space.trace_data, mesh.facets(plane.boundaries.outer)\n",
    "        )\n",
    "    ]\n",
    "    trace = SampledPressureAdmittanceForms(\n",
    "        size=space.dof_count,\n",
    "        samples=lambda: iter(surface),\n",
    "        admittance=lambda omega, sample: 1.0,\n",
    "    )(0.0)\n",
    "    pencil = ComplexPressurePencil(\n",
    "        volume,\n",
    "        boundary=PressureAdmittanceBoundary(lambda omega: admittance(omega) * trace),\n",
    "    )\n",
    "    nodes = space.dof_coordinates\n",
    "    sweep = AcousticHarmonicPressure(\n",
    "        operator=pencil,\n",
    "        angular_frequencies=2 * np.pi * frequencies,\n",
    "        linear_solver=spsolve,\n",
    "        load=lambda omega: trace\n",
    "        @ (\n",
    "            background_flux(omega, nodes) / rho0\n",
    "            + 1j * omega * admittance(omega) * background(omega, nodes)\n",
    "        ),\n",
    "    ).run()\n",
    "    probe = np.random.default_rng(7).standard_normal((space.dof_count, 4))\n",
    "    modes = AcousticPressureSpectrum(\n",
    "        operator=pencil,\n",
    "        eigensolver=BeynContourEigenSolver(contour=contour, probe=probe),\n",
    "    ).run()\n",
    "    bottom = [[0.0, -neck_length - cavity_depth]]\n",
    "    return dict(\n",
    "        space=space,\n",
    "        mesh=mesh,\n",
    "        pressure=sweep.pressure,\n",
    "        dofs=space.dof_count,\n",
    "        omega=modes.angular_frequencies,\n",
    "        cavity=np.asarray(space.evaluate(sweep.pressure.T, bottom))[0],\n",
    "    )\n",
    "\n",
    "\n",
    "runs = {level: solve_resonator(level) for level in levels}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The complex resonance from the contour solver, the peak of the swept cavity pressure, and the\n",
    "lumped model with the two end corrections."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "S, V = np.pi * neck_radius**2, np.pi * cavity_radius**2 * cavity_depth\n",
    "effective = (\n",
    "    neck_length\n",
    "    + 0.8216 * neck_radius\n",
    "    + 0.48 * np.sqrt(S) * (1 - 1.25 * neck_radius / cavity_radius)\n",
    ")\n",
    "f_lumped, Q_lumped = c0 * np.sqrt(S / (effective * V)) / (\n",
    "    2 * np.pi\n",
    "), 2 * np.pi * np.sqrt(V * (effective / S) ** 3)\n",
    "f_tube = brentq(\n",
    "    lambda f: 2 * np.pi * f / c0 * effective / S\n",
    "    - 1 / (np.tan(2 * np.pi * f / c0 * cavity_depth) * np.pi * cavity_radius**2),\n",
    "    150,\n",
    "    450,\n",
    ")\n",
    "print(\n",
    "    f\"lumped model: effective neck length {1e3 * effective:.1f} mm, f0 = {f_lumped:.1f} Hz, Q = {Q_lumped:.1f}; \"\n",
    "    f\"cavity as a closed tube: f0 = {f_tube:.1f} Hz\"\n",
    ")\n",
    "for level, run in runs.items():\n",
    "    omega = run[\"omega\"][np.argmin(np.abs(run[\"omega\"] - 2 * np.pi * f_lumped))]\n",
    "    gain = np.abs(run[\"cavity\"]) / (2 * incident)\n",
    "    peak = np.argmax(gain)\n",
    "    run[\"f0\"], run[\"Q\"], run[\"peak\"] = (\n",
    "        omega.real / (2 * np.pi),\n",
    "        omega.real / (2 * omega.imag),\n",
    "        peak,\n",
    "    )\n",
    "    print(\n",
    "        f\"mesh {level}: {run['dofs']} unknowns; contour solver: {len(run['omega'])} resonance(s) in the ellipse, \"\n",
    "        f\"f0 = {run['f0']:.2f} Hz ({100 * (run['f0'] / f_lumped - 1):+.1f} % from lumped, {100 * (run['f0'] / f_tube - 1):+.1f} % from tube), Q = {run['Q']:.1f} \"\n",
    "        f\"({100 * (run['Q'] / Q_lumped - 1):+.1f} %); sweep: peak at {frequencies[peak]:.0f} Hz, \"\n",
    "        f\"cavity pressure / blocked pressure {gain[peak]:.1f}\"\n",
    "    )\n",
    "fine = runs[levels[-1]]\n",
    "print(\n",
    "    f\"change of f0 between the meshes {abs(fine['f0'] / runs[1.0]['f0'] - 1):.1e}, of Q {abs(fine['Q'] / runs[1.0]['Q'] - 1):.1e}\"\n",
    ")\n",
    "single_mode = lambda f: fine[\"Q\"] / np.abs(\n",
    "    fine[\"Q\"] * (1 - (f / fine[\"f0\"]) ** 2) + 1j * f / fine[\"f0\"]\n",
    ")\n",
    "print(\n",
    "    f\"sweep against the single resonance built from the contour solver's f0 and Q: largest deviation of the gain within \"\n",
    "    f\"f0 +- 10 Hz {np.max(np.abs(np.abs(fine['cavity']) / 2 - single_mode(frequencies))[np.abs(frequencies - fine['f0']) < 10] / fine['Q']):.1e} Q\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The sound pressure level near the resonator at resonance (incident wave 1 Pa, i.e. 91 dB), and the\n",
    "cavity pressure over frequency from the sweep, against the single resonance with the contour\n",
    "solver's $f_0$ and $Q$ and against the lumped model."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "i = fine[\"peak\"]\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",
    "fig = plots.figure(1, 2, size=(16, 6.5))\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",
    "    xlimits=(0, 0.25),\n",
    "    ylimits=(-0.11, 0.2),\n",
    "    title=f\"Sound pressure level at {frequencies[i]:.0f} Hz\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    frequencies,\n",
    "    {\"frequency sweep\": np.abs(fine[\"cavity\"]) / (2 * incident)},\n",
    "    reference={\n",
    "        \"single resonance, contour solver f0 and Q\": single_mode(frequencies),\n",
    "        \"lumped model\": Q_lumped\n",
    "        / np.abs(\n",
    "            Q_lumped * (1 - (frequencies / f_lumped) ** 2) + 1j * frequencies / f_lumped\n",
    "        ),\n",
    "    },\n",
    "    scale=\"logy\",\n",
    "    xlabel=\"frequency [Hz]\",\n",
    "    ylabel=\"cavity pressure / blocked pressure\",\n",
    "    title=\"Pressure gain in the cavity\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change neck and cavity in `helmholtz_resonator_baffle_geometry.py` and write the STEP file again:\n",
    "a longer, narrower neck lowers the resonance and sharpens it. Viscous and thermal losses in the\n",
    "neck, which a real resonator has, enter as a complex density in the neck\n",
    "(`inverse_density` per quadrature point) and lower the gain well below the radiation-limited Q."
   ]
  }
 ]
}
