{
 "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 of a room\n",
    "\n",
    "At low frequencies a room sounds through its standing waves: some bass notes boom, others are\n",
    "weak, depending on where the eigenfrequencies fall. For rigid walls the modes solve\n",
    "\n",
    "$$\\nabla\\cdot\\Big(\\frac1{\\rho_0}\\nabla p\\Big)+\\frac{\\omega^2}{\\rho_0c^2}\\,p=0\\quad\\text{in the room},\n",
    "  \\qquad\\frac{\\partial p}{\\partial n}=0\\quad\\text{on floor, walls and ceiling}.$$\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| floor, walls, sloped ceiling | rigid, $\\partial p/\\partial n=0$ |\n",
    "\n",
    "The living room is 5 m long and 4 m wide; its ceiling rises from 2.4 m to 3.4 m along the length\n",
    "($V=58$ m³). A sloped ceiling has no closed-form modes.\n",
    "\n",
    "**References.** A box room of $L_x\\times L_y\\times L_z$ has the modes\n",
    "$f_{lmn}=\\tfrac c2\\sqrt{(l/L_x)^2+(m/L_y)^2+(n/L_z)^2}$ (Lord Rayleigh, *The Theory of Sound*, §267),\n",
    "used here to check the solver. For any room shape the number of modes below $f$ follows the\n",
    "Weyl-Bolt formula (H. Kuttruff, *Room Acoustics*, 5th ed., §3.3; R. H. Bolt, *J. Acoust. Soc. Am.*\n",
    "10, 1939),\n",
    "\n",
    "$$N(f)\\approx\\frac{4\\pi V}{3c^3}f^3+\\frac{\\pi S}{4c^2}f^2+\\frac{L}{8c}f ,$$\n",
    "\n",
    "with the wall area $S$ and the total edge length $L$. Above the Schroeder frequency\n",
    "$f_S\\approx2000\\sqrt{T/V}$ (M. R. Schroeder, 1962; $T$ the reverberation time in s) the modes overlap\n",
    "and the room is described statistically."
   ]
  },
  {
   "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.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",
    "\n",
    "theme.set()\n",
    "\n",
    "c0, rho0 = 343.0, 1.204\n",
    "top_frequency, mode_count = 250.0, 150"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` returns the two rooms. Curved quadratic tetrahedra of 0.25 m (a fifth of the wavelength at\n",
    "250 Hz) and, for the mesh study, 0.18 m fill them."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "rooms = {\n",
    "    \"sloped room\": load(\"room_eigenmodes.step\"),\n",
    "    \"box room\": load(\"room_eigenmodes_box.step\"),\n",
    "}\n",
    "cases = ((\"sloped room\", 0.25), (\"sloped room\", 0.18), (\"box room\", 0.25))\n",
    "meshes = {\n",
    "    (name, h): TetrahedralMesher(target_size=h, geometry_order=2).generate(rooms[name])\n",
    "    for name, h in cases\n",
    "}\n",
    "\n",
    "room = rooms[\"sloped room\"]\n",
    "view = plots.Camera(elevation=28, azimuth=-55)\n",
    "fig = plots.figure(1, 2, size=(15, 7))\n",
    "plots.geometry(\n",
    "    room,\n",
    "    selection={\n",
    "        \"floor\": room.boundaries.floor,\n",
    "        \"sloped ceiling\": room.boundaries.ceiling,\n",
    "        \"walls\": room.boundaries.wall | room.boundaries.top | room.boundaries.bottom,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Living room with a sloped ceiling (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"sloped room\", 0.25],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{meshes['sloped room', 0.25].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 stiffness and the\n",
    "compressibility mass, and `AcousticPressureSpectrum` returns the lowest 150 modes from a\n",
    "shift-and-invert Lanczos solver. The rigid walls are the natural boundary condition and need no\n",
    "term; the constant pressure at 0 Hz is the expected null mode of a closed room."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "solver = SparseSymmetricEigenSolver()\n",
    "\n",
    "\n",
    "def solve_room(name, h):\n",
    "    \"\"\"Lowest modes of one room on one mesh.\"\"\"\n",
    "    mesh = meshes[name, h]\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=mode_count + 1, 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 = {case: solve_room(*case) for case in cases}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "First the box room against its exact modes, then the sloped room: its lowest modes, the mesh\n",
    "study, and the mode count against Weyl-Bolt."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "box = runs[\"box room\", 0.25]\n",
    "dimensions = (5.0, 4.0, 2.8)\n",
    "exact = np.sort(\n",
    "    [\n",
    "        c0\n",
    "        / 2\n",
    "        * np.sqrt(\n",
    "            (l / dimensions[0]) ** 2\n",
    "            + (m / dimensions[1]) ** 2\n",
    "            + (n / dimensions[2]) ** 2\n",
    "        )\n",
    "        for l in range(12)\n",
    "        for m in range(10)\n",
    "        for n in range(8)\n",
    "    ]\n",
    ")[: mode_count + 1]\n",
    "below = exact < top_frequency\n",
    "print(\n",
    "    f\"box room ({box['dofs']} unknowns): null mode {box['f'][0]:.1e} Hz; {np.count_nonzero(below) - 1} modes below \"\n",
    "    f\"{top_frequency:.0f} Hz, largest relative frequency error {np.max(np.abs(box['f'][1:][below[1:]] / exact[1:][below[1:]] - 1)):.1e}\"\n",
    ")\n",
    "coarse, fine = runs[\"sloped room\", 0.25], runs[\"sloped room\", 0.18]\n",
    "print(\n",
    "    f\"sloped room: {coarse['dofs']} and {fine['dofs']} unknowns; largest change of the modes below {top_frequency:.0f} Hz \"\n",
    "    f\"between the meshes {np.max(np.abs(coarse['f'][1:] / fine['f'][1:] - 1)[fine['f'][1:] < top_frequency]):.1e}\"\n",
    ")\n",
    "print(\n",
    "    \"lowest modes of the sloped room [Hz]:\",\n",
    "    \", \".join(f\"{f:.2f}\" for f in fine[\"f\"][1:13]),\n",
    ")\n",
    "print(\n",
    "    \"the same in the box room [Hz]:       \",\n",
    "    \", \".join(f\"{f:.2f}\" for f in box[\"f\"][1:13]),\n",
    ")\n",
    "volume, area = (\n",
    "    5.0 * 4.0 * 2.9,\n",
    "    2 * 5.0 * 2.9 + 2.4 * 4.0 + 3.4 * 4.0 + 5.0 * 4.0 + np.hypot(5.0, 1.0) * 4.0,\n",
    ")\n",
    "edges = 2 * (5.0 + np.hypot(5.0, 1.0) + 2.4 + 3.4) + 4 * 4.0\n",
    "weyl = (\n",
    "    lambda f: 4 * np.pi * volume * f**3 / (3 * c0**3)\n",
    "    + np.pi * area * f**2 / (4 * c0**2)\n",
    "    + edges * f / (8 * c0)\n",
    ")\n",
    "print(f\"\\nV = {volume:.1f} m3, S = {area:.1f} m2, L = {edges:.1f} m\")\n",
    "print(\"  f [Hz]   modes below f, sloped room   Weyl-Bolt   deviation\")\n",
    "for f in (100, 150, 200, 250):\n",
    "    count = np.count_nonzero(fine[\"f\"][1:] < f)\n",
    "    print(\n",
    "        f\"{f:7d}   {count:26d}   {weyl(f):9.1f}   {100 * (count / weyl(f) - 1):+.0f} %\"\n",
    "    )\n",
    "print(\n",
    "    f\"Schroeder frequency for a reverberation time of 0.5 s: {2000 * np.sqrt(0.5 / volume):.0f} Hz\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Four modes of the sloped room on its walls, floor and ceiling (teal and copper are opposite\n",
    "signs), and the mode count against the Weyl-Bolt formula."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "points = np.asarray(fine[\"mesh\"].coordinates)\n",
    "surface = np.asarray(fine[\"mesh\"].facets(room.boundaries.all))\n",
    "shown = (1, 2, 4, 12)\n",
    "fig = plots.figure(layout=[[\"m0\", \"m1\", \"count\"], [\"m2\", \"m3\", \"count\"]], size=(20, 11))\n",
    "for panel, k in zip((\"m0\", \"m1\", \"m2\", \"m3\"), shown):\n",
    "    shape = np.asarray(fine[\"space\"].evaluate(fine[\"shapes\"][:, k], points))\n",
    "    plots.trisurface(\n",
    "        points,\n",
    "        surface,\n",
    "        shape / np.max(np.abs(shape)),\n",
    "        colormap=\"diverging\",\n",
    "        limits=(-1, 1),\n",
    "        camera=view,\n",
    "        label=\"p / max|p|\",\n",
    "        title=f\"Mode {k}: {fine['f'][k]:.1f} Hz\",\n",
    "        ax=fig[panel],\n",
    "    )\n",
    "grid = np.linspace(1.0, top_frequency, 500)\n",
    "plots.line(\n",
    "    grid,\n",
    "    {\n",
    "        \"sloped room, finite elements\": np.array(\n",
    "            [np.count_nonzero(fine[\"f\"][1:] < f) for f in grid]\n",
    "        ),\n",
    "        \"box room, finite elements\": np.array(\n",
    "            [np.count_nonzero(box[\"f\"][1:] < f) for f in grid]\n",
    "        ),\n",
    "    },\n",
    "    reference={\"sloped room, finite elements\": weyl(grid)},\n",
    "    xlabel=\"frequency [Hz]\",\n",
    "    ylabel=\"number of modes below f\",\n",
    "    title=\"Mode count (dashed: Weyl-Bolt)\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[\"count\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Move a wall in `room_eigenmodes_geometry.py` and write the STEP file again to see how the bass\n",
    "modes shift; or put an absorbing carpet on the floor as an admittance boundary\n",
    "(`PressureAdmittanceBoundary`) and compute the complex modes with the contour eigensolver - their\n",
    "imaginary parts are the decay rates that set the reverberation time."
   ]
  }
 ]
}
