{
 "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": [
    "# Eigenmodes in a muffler chamber\n",
    "\n",
    "Automotive mufflers are often oval. A wave $p=\\psi(x,y)\\,e^{i(\\omega t-k_zz)}$ in a duct of\n",
    "constant cross-section has $k_z^2=(\\omega/c)^2-k_c^2$, where $\\psi$ and $k_c$ solve the\n",
    "two-dimensional eigenproblem of the cross-section,\n",
    "\n",
    "$$\\nabla_\\perp^2\\psi+k_c^2\\psi=0\\quad\\text{in the section},\\qquad\\partial_n\\psi=0\\quad\\text{on the wall}.$$\n",
    "\n",
    "A mode propagates only above its cut-off frequency $f_c=ck_c/(2\\pi)$; below the first one only the\n",
    "plane wave ($k_c=0$) travels. The chamber here has an elliptic cross-section with semi-axes\n",
    "$a=100$ mm and $b=60$ mm and holds air at 20 °C.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| wall of the cross-section | rigid, $\\partial\\psi/\\partial n=0$ |\n",
    "\n",
    "**Reference.** In elliptic coordinates $(\\xi,\\eta)$ with focal half-distance $h=\\sqrt{a^2-b^2}$\n",
    "the cross modes separate into Mathieu functions (P. M. Morse and H. Feshbach, *Methods of\n",
    "Theoretical Physics*, §11.2; N. W. McLachlan, *Theory and Application of Mathieu Functions*,\n",
    "1947). A rigid wall at $\\xi_0=\\operatorname{artanh}(b/a)$ requires\n",
    "$\\mathrm{Mc}_m'(\\xi_0,q)=0$ for the even and $\\mathrm{Ms}_m'(\\xi_0,q)=0$ for the odd modes,\n",
    "and each root gives $f_c=c\\sqrt q/(\\pi h)$."
   ]
  },
  {
   "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\n",
    "from onesim.numerics.linear import SparseSymmetricEigenSolver\n",
    "from onesim.physics.acoustics import (\n",
    "    AcousticPressureSpectrum,\n",
    "    ComplexPressurePencil,\n",
    "    ConstantPressureForms,\n",
    "    SampledPressureVolumeForms,\n",
    "    pressure_space_volume_samples,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.optimize import brentq\n",
    "from scipy.special import mathieu_modcem1, mathieu_modsem1\n",
    "\n",
    "theme.set()\n",
    "\n",
    "c0, rho0 = 343.0, 1.204\n",
    "a, b, top_frequency = 0.10, 0.06, 4500.0"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reference\n",
    "\n",
    "Cut-off frequencies from the roots of the radial Mathieu derivatives, found by scanning $q$\n",
    "and refining every sign change."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "h, rim = np.sqrt(a**2 - b**2), np.arctanh(b / a)\n",
    "scan = np.linspace(0.01, 40.0, 1600)\n",
    "cutoffs = sorted(\n",
    "    [\n",
    "        (\n",
    "            c0\n",
    "            * np.sqrt(brentq(lambda q: radial(m, q, rim)[1], scan[i], scan[i + 1]))\n",
    "            / (np.pi * h),\n",
    "            f\"{kind}{m}\",\n",
    "        )\n",
    "        for kind, radial, orders in (\n",
    "            (\"even \", mathieu_modcem1, range(0, 8)),\n",
    "            (\"odd \", mathieu_modsem1, range(1, 8)),\n",
    "        )\n",
    "        for m in orders\n",
    "        for i in np.flatnonzero(np.diff(np.sign([radial(m, q, rim)[1] for q in scan])))\n",
    "    ]\n",
    ")\n",
    "cutoffs = [(0.0, \"plane\")] + [item for item in cutoffs if item[0] < top_frequency]\n",
    "reference = np.array([fc for fc, _ in cutoffs])\n",
    "print(\n",
    "    f\"{len(cutoffs) - 1} cross modes cut on below {top_frequency:.0f} Hz:\",\n",
    "    \", \".join(f\"{name} {fc:.1f} Hz\" for fc, name in cutoffs[1:]),\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` returns the chamber, an elliptic cylinder written by `muffler_chamber_modes_geometry.py`;\n",
    "`section` cuts it across. Quadratic triangles of 10 mm (a seventh of the wavelength at 4.5 kHz)\n",
    "and, for the mesh study, 5 mm and 2.5 mm cover the section."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "chamber = load(\"muffler_chamber_modes.step\")\n",
    "section = chamber.section((0, 0, 1), origin=(0, 0, 0.2))\n",
    "sizes = (0.010, 0.005, 0.0025)\n",
    "meshes = {s: TriangularMesher(target_size=s).generate(section) for s in sizes}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.geometry(\n",
    "    chamber,\n",
    "    selection={\"mantle\": chamber.boundaries.mantle, \"ends\": chamber.boundaries.ends},\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=25, azimuth=-60),\n",
    "    title=\"Oval muffler chamber (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0.005],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Cross-section: {meshes[0.005].cell_count} quadratic triangles\",\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 stiffness and\n",
    "compressibility mass on the section, and `AcousticPressureSpectrum` returns the lowest modes from\n",
    "a shift-and-invert Lanczos solver. The rigid wall is natural and needs no term; the constant mode\n",
    "at 0 Hz is the plane wave."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "solver = SparseSymmetricEigenSolver()\n",
    "\n",
    "\n",
    "def solve_section(size):\n",
    "    \"\"\"Cut-off modes of the cross-section on one mesh.\"\"\"\n",
    "    mesh = meshes[size]\n",
    "    space = FiniteElement(element=Lagrange(order=2)).bind_space(mesh)\n",
    "    stiffness, mass = 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 / (rho0 * c0**2),\n",
    "    )(0.0)\n",
    "    eigenpairs = lambda operator: (\n",
    "        lambda values, vectors: (np.sqrt(np.abs(values)), vectors)\n",
    "    )(*solver(mass, operator(0.0).real, mode_count=len(cutoffs), target=-1.0))\n",
    "    modes = AcousticPressureSpectrum(\n",
    "        operator=ComplexPressurePencil(ConstantPressureForms(stiffness, mass)),\n",
    "        eigensolver=eigenpairs,\n",
    "    ).run()\n",
    "    order = np.argsort(modes.eigenfrequencies)\n",
    "    return dict(\n",
    "        space=space,\n",
    "        mesh=mesh,\n",
    "        dofs=space.dof_count,\n",
    "        f=modes.eigenfrequencies[order],\n",
    "        shapes=modes.pressure_modes[:, order],\n",
    "    )\n",
    "\n",
    "\n",
    "runs = {s: solve_section(s) for s in sizes}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The cut-off frequencies in order against the Mathieu solution, and their convergence. A residual\n",
    "of a few $10^{-4}$ remains on all meshes alike: it is not the discretisation of the field but the\n",
    "representation of the elliptic outline (and the accuracy of the Mathieu root search)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = runs[sizes[-1]]\n",
    "for s, run in runs.items():\n",
    "    print(\n",
    "        f\"mesh {1e3 * s:.1f} mm, {run['dofs']} unknowns: plane wave at {run['f'][0]:.1e} Hz, largest relative error of the \"\n",
    "        f\"{len(cutoffs) - 1} cut-off frequencies {np.max(np.abs(run['f'][1:] / reference[1:] - 1)):.1e}\"\n",
    "    )\n",
    "print(\"\\n  #   cross mode   exact [Hz]   computed [Hz]   rel. dev.\")\n",
    "for k, (f, name) in enumerate(cutoffs):\n",
    "    if k:\n",
    "        print(\n",
    "            f\"{k:3d}   {name:9s}   {f:10.2f}   {fine['f'][k]:13.3f}   {fine['f'][k] / f - 1:+.1e}\"\n",
    "        )\n",
    "print(\n",
    "    f\"first cut-off: {fine['f'][1]:.1f} Hz - below it only plane waves travel in the chamber\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The first nine propagating cross modes (teal and copper are opposite signs) and the error of each\n",
    "cut-off frequency on the three meshes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x, y = np.asarray(fine[\"mesh\"].coordinates).T\n",
    "fig = plots.figure(\n",
    "    layout=[\n",
    "        [\"m0\", \"m1\", \"m2\", \"conv\"],\n",
    "        [\"m3\", \"m4\", \"m5\", \"conv\"],\n",
    "        [\"m6\", \"m7\", \"m8\", \"conv\"],\n",
    "    ],\n",
    "    size=(22, 13),\n",
    ")\n",
    "for k in range(1, 10):\n",
    "    shape = np.asarray(fine[\"shapes\"][: len(x), k])\n",
    "    plots.heatmap(\n",
    "        x,\n",
    "        y,\n",
    "        shape / np.max(np.abs(shape)),\n",
    "        triangles=np.asarray(fine[\"mesh\"].cells),\n",
    "        colormap=\"diverging\",\n",
    "        limits=(-1, 1),\n",
    "        label=\"p / max|p|\",\n",
    "        title=f\"{cutoffs[k][1]}: {fine['f'][k]:.0f} Hz\",\n",
    "        ax=fig[f\"m{k - 1}\"],\n",
    "    )\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"mesh {1e3 * s:.1f} mm\": (\n",
    "            np.arange(1, len(cutoffs)),\n",
    "            np.abs(run[\"f\"][1:] / reference[1:] - 1),\n",
    "        )\n",
    "        for s, run in runs.items()\n",
    "    },\n",
    "    scale=\"logy\",\n",
    "    ylimits=(1e-5, 1e-2),\n",
    "    xlabel=\"cross mode (in order of frequency)\",\n",
    "    ylabel=\"relative error of the cut-off frequency\",\n",
    "    title=\"Error per cut-off frequency\",\n",
    "    ax=fig[\"conv\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the section rounder or flatter in `muffler_chamber_modes_geometry.py` and write the STEP file\n",
    "again: the first cut-off frequency, the upper limit of plane-wave muffler design, moves with the\n",
    "major axis. The cut-off modes found here are the shapes that the three-dimensional muffler\n",
    "(`expansion_chamber_muffler`) starts to carry above its cut-off."
   ]
  }
 ]
}
