{
 "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": [
    "# Transmission loss of an expansion-chamber muffler\n",
    "\n",
    "The simplest reactive muffler is a sudden widening of the exhaust pipe: a chamber of length\n",
    "$L=0.3$ m and radius 80 mm between pipes of radius 25 mm. The two area jumps reflect part of the\n",
    "sound back towards the engine. Here inlet and outlet sit 40 mm off the axis on opposite sides,\n",
    "as they often do in vehicles. The field is symmetric about the plane through both pipe axes, so\n",
    "half of the muffler is computed:\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| inlet | incoming plane wave $p_\\mathrm{in}$, reflected wave absorbed: $v_n=(p-2p_\\mathrm{in})/(\\rho_0c)$ |\n",
    "| outlet | anechoic, $v_n=p/(\\rho_0c)$ |\n",
    "| walls | rigid, $\\partial p/\\partial n=0$ |\n",
    "| symmetry plane $y=0$ | $\\partial p/\\partial n=0$ |\n",
    "\n",
    "The **transmission loss** compares the incident power with the power that leaves through the\n",
    "outlet, $TL=10\\log_{10}(W_\\mathrm{in}/W_\\mathrm{out})$, with $W_\\mathrm{in}=|p_\\mathrm{in}|^2S/(2\\rho_0c)$\n",
    "and $W_\\mathrm{out}=\\int|p|^2\\,\\mathrm dS/(2\\rho_0c)$.\n",
    "\n",
    "**Reference.** For plane waves the chamber is a transmission-line section, and with the area\n",
    "ratio $m=(R/r)^2$ (L. E. Kinsler et al., *Fundamentals of Acoustics*, 4th ed., §10.10; M. L.\n",
    "Munjal, *Acoustics of Ducts and Mufflers*, 2nd ed., §3.5)\n",
    "\n",
    "$$TL=10\\log_{10}\\Big[1+\\tfrac14\\big(m-\\tfrac1m\\big)^2\\sin^2kL\\Big].$$\n",
    "\n",
    "The formula holds while only plane waves propagate in the chamber. The first cross mode, which\n",
    "the offset pipes excite, cuts on at $f_{11}=1.8412\\,c/(2\\pi R)=1256$ Hz; above it the\n",
    "three-dimensional field departs from the formula."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import 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",
    "\n",
    "theme.set()\n",
    "\n",
    "c0, rho0, incident = 343.0, 1.204, 1.0\n",
    "impedance = rho0 * c0\n",
    "chamber_radius, chamber_length, pipe_radius = 0.08, 0.30, 0.025\n",
    "frequencies = np.arange(20.0, 2001.0, 15.0)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` returns the half muffler with the named faces inlet, outlet, walls and symmetry. Curved\n",
    "quadratic tetrahedra of 20 mm (an eighth of the shortest wavelength) and, for the mesh study,\n",
    "14 mm fill it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "muffler = load(\"expansion_chamber_muffler.step\")\n",
    "faces = muffler.boundaries\n",
    "sizes = (0.020, 0.014)\n",
    "meshes = {\n",
    "    h: TetrahedralMesher(target_size=h, geometry_order=2).generate(muffler)\n",
    "    for h in sizes\n",
    "}\n",
    "\n",
    "view = plots.Camera(elevation=25, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(15, 7))\n",
    "plots.geometry(\n",
    "    muffler,\n",
    "    selection={\n",
    "        \"inlet\": faces.inlet,\n",
    "        \"outlet\": faces.outlet,\n",
    "        \"walls\": faces.walls,\n",
    "        \"symmetry plane\": faces.symmetry,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Half of the muffler (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0.020],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{meshes[0.020].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 inlet and outlet come from the space's `trace_data`. Both ports carry the admittance\n",
    "$1/\\rho_0c$, the inlet also the load $2i\\omega p_\\mathrm{in}/(\\rho_0c)\\int\\phi_i\\,\\mathrm dS$ of the\n",
    "incoming wave. `AcousticHarmonicPressure` sweeps 20 Hz to 2 kHz."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def solve_muffler(h):\n",
    "    \"\"\"Pressure over the sweep on one mesh, and the transmission loss.\"\"\"\n",
    "    mesh = meshes[h]\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",
    "    ports = {\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 (\"inlet\", \"outlet\")\n",
    "    }\n",
    "    boundary = PressureAdmittanceBoundary(\n",
    "        lambda omega: (ports[\"inlet\"] + ports[\"outlet\"]) / impedance\n",
    "    )\n",
    "    drive = ports[\"inlet\"] @ np.ones(space.dof_count)\n",
    "    result = AcousticHarmonicPressure(\n",
    "        operator=ComplexPressurePencil(volume, boundary=boundary),\n",
    "        angular_frequencies=2 * np.pi * frequencies,\n",
    "        load=lambda omega: 2j * omega * incident / impedance * drive,\n",
    "        linear_solver=spsolve,\n",
    "    ).run()\n",
    "    transmitted = np.real(\n",
    "        np.sum(result.pressure.conj() * (ports[\"outlet\"] @ result.pressure.T).T, axis=1)\n",
    "    ) / (2 * impedance)\n",
    "    supplied = incident**2 * drive.sum() / (2 * impedance)\n",
    "    return dict(\n",
    "        space=space,\n",
    "        mesh=mesh,\n",
    "        pressure=result.pressure,\n",
    "        dofs=space.dof_count,\n",
    "        tl=10 * np.log10(supplied / transmitted),\n",
    "    )\n",
    "\n",
    "\n",
    "runs = {h: solve_muffler(h) for h in sizes}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Transmission loss against the plane-wave formula, below and above the cut-on of the first cross\n",
    "mode."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "m = (chamber_radius / pipe_radius) ** 2\n",
    "k = 2 * np.pi * frequencies / c0\n",
    "plane_wave = 10 * np.log10(\n",
    "    1 + 0.25 * (m - 1 / m) ** 2 * np.sin(k * chamber_length) ** 2\n",
    ")\n",
    "cut_on = 1.8412 * c0 / (2 * np.pi * chamber_radius)\n",
    "below = frequencies < 1000\n",
    "fine = runs[sizes[-1]]\n",
    "for h, run in runs.items():\n",
    "    print(\n",
    "        f\"mesh {1e3 * h:.0f} mm, {run['dofs']} unknowns: largest |TL - plane-wave TL| below 1 kHz \"\n",
    "        f\"{np.max(np.abs(run['tl'] - plane_wave)[below]):.2f} dB\"\n",
    "    )\n",
    "print(\n",
    "    f\"largest change between the meshes over the whole sweep {np.max(np.abs(runs[sizes[0]]['tl'] - fine['tl'])):.2f} dB\"\n",
    ")\n",
    "for low, high in ((0, 572), (572, 1143)):\n",
    "    band = (frequencies > low) & (frequencies < high)\n",
    "    print(\n",
    "        f\"dome {low}-{high} Hz: peak TL simulation {fine['tl'][band].max():.2f} dB at {frequencies[band][np.argmax(fine['tl'][band])]:.0f} Hz, \"\n",
    "        f\"plane-wave formula {plane_wave[band].max():.2f} dB at {frequencies[band][np.argmax(plane_wave[band])]:.0f} Hz\"\n",
    "    )\n",
    "passes = [\n",
    "    f\n",
    "    for f, previous, current, following in zip(\n",
    "        frequencies[1:-1], fine[\"tl\"][:-2], fine[\"tl\"][1:-1], fine[\"tl\"][2:]\n",
    "    )\n",
    "    if current < min(previous, following) and f < cut_on\n",
    "]\n",
    "print(\n",
    "    \"pass bands (TL minima) below the cut-on [Hz]:\",\n",
    "    \", \".join(f\"{f:.0f}\" for f in passes),\n",
    "    \"| plane wave: n c / (2L) =\",\n",
    "    \", \".join(\n",
    "        f\"{n * c0 / (2 * chamber_length):.0f}\" for n in range(1, len(passes) + 1)\n",
    "    ),\n",
    ")\n",
    "print(\n",
    "    f\"first cross mode cuts on at {cut_on:.0f} Hz; above it the largest |TL - plane-wave TL| is \"\n",
    "    f\"{np.max(np.abs(fine['tl'] - plane_wave)[frequencies > cut_on]):.1f} dB\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left: the sound pressure level on the walls and the symmetry plane at 1.7 kHz, where the first\n",
    "cross mode fills the chamber. Right: the transmission loss over frequency."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "i = int(np.argmin(np.abs(frequencies - 1700)))\n",
    "points = np.asarray(fine[\"mesh\"].coordinates)\n",
    "level = 20 * np.log10(\n",
    "    np.abs(np.asarray(fine[\"space\"].evaluate(fine[\"pressure\"][i], points))) / 2e-5\n",
    ")\n",
    "fig = plots.figure(1, 2, size=(17, 7))\n",
    "plots.trisurface(\n",
    "    points,\n",
    "    np.asarray(fine[\"mesh\"].facets(faces.walls | faces.symmetry)),\n",
    "    level,\n",
    "    camera=view,\n",
    "    limits=(level.max() - 30, level.max()),\n",
    "    label=\"sound pressure level [dB]\",\n",
    "    title=f\"{frequencies[i]:.0f} Hz, incoming wave 1 Pa\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    frequencies,\n",
    "    {f\"simulation, {1e3 * h:.0f} mm mesh\": run[\"tl\"] for h, run in runs.items()},\n",
    "    reference={\"plane-wave formula\": plane_wave},\n",
    "    vlines={\"cut-on of the first cross mode\": cut_on},\n",
    "    xlabel=\"frequency [Hz]\",\n",
    "    ylabel=\"transmission loss [dB]\",\n",
    "    title=\"Transmission loss\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Put the pipes on the axis in `expansion_chamber_muffler_geometry.py` and write the STEP file\n",
    "again: the cross mode is no longer excited and the formula holds up to the first axisymmetric\n",
    "mode at 2.6 kHz. A perforated pipe through the chamber, or an absorbing lining as a complex\n",
    "density and compressibility, turns the reactive muffler into an absorptive one."
   ]
  }
 ]
}
