{
 "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": [
    "# Remeshing per octave band\n",
    "\n",
    "The element size a frequency-domain acoustic model needs scales with the wavelength: about six\n",
    "quadratic elements per wavelength keep the error small. A sweep over several octaves therefore\n",
    "needs a mesh 32 times finer at the top than at the bottom; using that mesh everywhere costs far\n",
    "more unknowns than needed. Remeshing per band follows the wavelength instead: band $b$ with upper\n",
    "edge $f_b$ gets elements of size $h_b=c/(6f_b)$, limited by what the geometry itself requires.\n",
    "\n",
    "The test object is a concentric expansion chamber (radius 60 mm, length 250 mm) between pipes of\n",
    "radius 20 mm. A quarter of the air is computed, cut in the two symmetry planes.\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 and symmetry planes | rigid, $\\partial p/\\partial n=0$ |\n",
    "\n",
    "**References.** Concentric pipes excite only axisymmetric modes, and the first of them cuts on at\n",
    "$3.8317\\,c/(2\\pi R)=3486$ Hz, above the sweep. At low frequency the plane-wave formula holds\n",
    "(L. E. Kinsler et al., *Fundamentals of Acoustics*, 4th ed., §10.10; M. L. Munjal, *Acoustics of\n",
    "Ducts and Mufflers*, 2nd ed., §3.5):\n",
    "\n",
    "$$TL=10\\log_{10}\\Big[1+\\tfrac14\\big(m-\\tfrac1m\\big)^2\\sin^2kL\\Big],\\qquad m=(R/r)^2 .$$\n",
    "\n",
    "With rising frequency the evanescent higher modes at the two area steps lengthen the chamber\n",
    "acoustically and shift the domes of the transmission loss (A. Selamet and P. M. Radavich,\n",
    "*J. Sound Vib.* 201, 407, 1997), so the formula is the check of the low bands. The accuracy of the\n",
    "band meshes in every band is measured against one fine mesh, half the size of the top band's.\n",
    "\n",
    "The octave bands follow IEC 61260: centre frequencies 125 Hz to 4 kHz halved, here 125 Hz to\n",
    "2 kHz, band edges at $f_c/\\sqrt2$ and $\\sqrt2 f_c$."
   ]
  },
  {
   "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.06, 0.25, 0.02\n",
    "centres = 125.0 * 2.0 ** np.arange(5)\n",
    "bands = {fc: np.geomspace(fc / np.sqrt(2), fc * np.sqrt(2), 13) for fc in centres}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and meshes\n",
    "\n",
    "`load` returns the quarter muffler with its named faces. Each band gets a mesh of curved quadratic\n",
    "tetrahedra with $h_b=c/(6f_b)$, at most 100 mm; a curved element may turn by 60° on the round walls.\n",
    "The fine reference mesh uses half the size of the top band throughout."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "muffler = load(\"octave_band_remeshing.step\")\n",
    "faces = muffler.boundaries\n",
    "size = {fc: min(0.100, c0 / (6 * np.sqrt(2) * fc)) for fc in centres}\n",
    "fine = size[centres[-1]] / 2\n",
    "meshes = {\n",
    "    h: TetrahedralMesher(\n",
    "        target_size=h, geometry_order=2, curvature_angle=np.pi / 3\n",
    "    ).generate(muffler)\n",
    "    for h in sorted(set(size.values()) | {fine})\n",
    "}\n",
    "\n",
    "view = plots.Camera(elevation=25, azimuth=-60)\n",
    "fig = plots.figure(1, 3, size=(21, 7))\n",
    "plots.geometry(\n",
    "    muffler,\n",
    "    selection={\n",
    "        \"inlet\": faces.inlet,\n",
    "        \"outlet\": faces.outlet,\n",
    "        \"walls\": faces.walls,\n",
    "        \"symmetry planes\": faces.symmetry,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Quarter of the muffler (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "for panel, fc in zip((fig[1], fig[2]), (centres[0], centres[-1])):\n",
    "    plots.mesh(\n",
    "        meshes[size[fc]],\n",
    "        groups=(\"all\",),\n",
    "        legend=False,\n",
    "        camera=view,\n",
    "        title=f\"Mesh of the {fc:.0f} Hz band: {meshes[size[fc]].cell_count} tetrahedra\",\n",
    "        ax=panel,\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",
    "port traces come from the space's `trace_data`. One function sets up the model on a mesh and\n",
    "sweeps the given frequencies with `AcousticHarmonicPressure`; it is called once per band with the\n",
    "band's mesh, and once per band with the fine mesh."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def solve_band(h, frequencies):\n",
    "    \"\"\"Transmission loss at the frequencies on the mesh of size h, and the number of unknowns.\"\"\"\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",
    "    drive = ports[\"inlet\"] @ np.ones(space.dof_count)\n",
    "    pressure = (\n",
    "        AcousticHarmonicPressure(\n",
    "            operator=ComplexPressurePencil(\n",
    "                volume,\n",
    "                boundary=PressureAdmittanceBoundary(\n",
    "                    lambda omega: (ports[\"inlet\"] + ports[\"outlet\"]) / impedance\n",
    "                ),\n",
    "            ),\n",
    "            angular_frequencies=2 * np.pi * frequencies,\n",
    "            load=lambda omega: 2j * omega * incident / impedance * drive,\n",
    "            linear_solver=spsolve,\n",
    "        )\n",
    "        .run()\n",
    "        .pressure\n",
    "    )\n",
    "    transmitted = np.real(\n",
    "        np.sum(pressure.conj() * (ports[\"outlet\"] @ pressure.T).T, axis=1)\n",
    "    )\n",
    "    return dict(\n",
    "        tl=10 * np.log10(incident**2 * drive.sum() / transmitted), dofs=space.dof_count\n",
    "    )\n",
    "\n",
    "\n",
    "remeshed = {fc: solve_band(size[fc], bands[fc]) for fc in centres}\n",
    "reference = {fc: solve_band(fine, bands[fc]) for fc in centres}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Per band: element size and unknowns of the band mesh, its deviation from the fine mesh and from\n",
    "the plane-wave formula, and the work in unknowns times frequencies."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "m = (chamber_radius / pipe_radius) ** 2\n",
    "formula = lambda f: 10 * np.log10(\n",
    "    1 + 0.25 * (m - 1 / m) ** 2 * np.sin(2 * np.pi * f / c0 * chamber_length) ** 2\n",
    ")\n",
    "print(f\"fine mesh: h = {1e3 * fine:.1f} mm, {reference[centres[0]]['dofs']} unknowns\")\n",
    "print(\n",
    "    \" band [Hz]   h [mm]   unknowns   max |TL - TL fine| [dB]   max |TL - formula| [dB]   fine mesh: max |TL - formula| [dB]\"\n",
    ")\n",
    "for fc in centres:\n",
    "    print(\n",
    "        f\"{fc:8.0f}   {1e3 * size[fc]:6.1f}   {remeshed[fc]['dofs']:8d}   {np.max(np.abs(remeshed[fc]['tl'] - reference[fc]['tl'])):23.3f}\"\n",
    "        f\"   {np.max(np.abs(remeshed[fc]['tl'] - formula(bands[fc]))):23.3f}   {np.max(np.abs(reference[fc]['tl'] - formula(bands[fc]))):34.3f}\"\n",
    "    )\n",
    "work = sum(remeshed[fc][\"dofs\"] * len(bands[fc]) for fc in centres), sum(\n",
    "    reference[fc][\"dofs\"] * len(bands[fc]) for fc in centres\n",
    ")\n",
    "print(\n",
    "    f\"work (unknowns x frequencies): remeshed {work[0]}, one fine mesh {work[1]}, ratio {work[1] / work[0]:.1f}\"\n",
    ")\n",
    "print(\n",
    "    f\"largest difference between remeshed and fine sweep: \"\n",
    "    f\"{max(np.max(np.abs(remeshed[fc]['tl'] - reference[fc]['tl'])) for fc in centres):.3f} dB\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left: the transmission loss over the whole sweep, band by band, with the fine-mesh sweep and the\n",
    "formula. Right: the unknowns used in each band."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(17, 6.5))\n",
    "plots.line(\n",
    "    y={f\"{fc:.0f} Hz band mesh\": (bands[fc], remeshed[fc][\"tl\"]) for fc in centres},\n",
    "    points={\n",
    "        \"one fine mesh\": (\n",
    "            np.concatenate([bands[fc][::3] for fc in centres]),\n",
    "            np.concatenate([reference[fc][\"tl\"][::3] for fc in centres]),\n",
    "        )\n",
    "    },\n",
    "    reference={\n",
    "        \"plane-wave formula\": (\n",
    "            np.geomspace(80, 2900, 600),\n",
    "            formula(np.geomspace(80, 2900, 600)),\n",
    "        )\n",
    "    },\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"frequency [Hz]\",\n",
    "    ylabel=\"transmission loss [dB]\",\n",
    "    title=\"Transmission loss, remeshed per octave band\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.bars(\n",
    "    [f\"{fc:.0f} Hz\" for fc in centres],\n",
    "    [remeshed[fc][\"dofs\"] for fc in centres],\n",
    "    scale=\"log\",\n",
    "    ylabel=\"pressure unknowns\",\n",
    "    title=f\"Unknowns per band (fine mesh: {reference[centres[0]]['dofs']})\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Switch to third-octave bands (`2.0 ** (np.arange(16) / 3)`) for a finer staircase of meshes, or\n",
    "lower the elements per wavelength to see where the band meshes start to lose accuracy at their\n",
    "upper edges. The same pattern applies to any geometry in a STEP file, for example a room or a\n",
    "car cabin."
   ]
  }
 ]
}
