{
 "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": [
    "# Acoustic modes of a rigid rectangular box\n",
    "\n",
    "A closed room or enclosure filled with air only \"rings\" at discrete frequencies: its\n",
    "acoustic eigenmodes. For small-amplitude sound the pressure $p(\\mathbf x)\\,e^{i\\omega t}$\n",
    "obeys the Helmholtz equation\n",
    "\n",
    "$$\\nabla\\cdot\\Big(\\frac{1}{\\rho_0}\\nabla p\\Big)+\\frac{\\omega^2}{\\rho_0 c^2}\\,p=0\n",
    "  \\quad\\text{in the box},\\qquad \\frac{\\partial p}{\\partial n}=0\\quad\\text{on all six walls},$$\n",
    "\n",
    "where the wall condition says that a rigid (sound-hard) wall does not move: the normal\n",
    "particle velocity $v_n=-\\partial_n p/(i\\omega\\rho_0)$ vanishes. The box measures\n",
    "$L_x\\times L_y\\times L_z=1.0\\times0.7\\times0.5$ m and holds air at 20 °C\n",
    "($c=343$ m/s, $\\rho_0=1.204$ kg/m³).\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| walls $x=0$ and $x=L_x$ | rigid, $\\partial p/\\partial n=0$ |\n",
    "| walls $y=0$ and $y=L_y$ | rigid, $\\partial p/\\partial n=0$ |\n",
    "| walls $z=0$ and $z=L_z$ | rigid, $\\partial p/\\partial n=0$ |\n",
    "\n",
    "**Reference (exact solution of the 3D problem).** The eigenmodes separate into\n",
    "products of cosines (Lord Rayleigh, *The Theory of Sound*, Vol. II, §267, 1896;\n",
    "P. M. Morse and K. U. Ingard, *Theoretical Acoustics*, McGraw-Hill 1968, §9.4),\n",
    "\n",
    "$$p_{lmn}=\\cos\\frac{l\\pi x}{L_x}\\,\\cos\\frac{m\\pi y}{L_y}\\,\\cos\\frac{n\\pi z}{L_z},\\qquad\n",
    "  f_{lmn}=\\frac{c}{2}\\sqrt{\\Big(\\frac{l}{L_x}\\Big)^2+\\Big(\\frac{m}{L_y}\\Big)^2+\\Big(\\frac{n}{L_z}\\Big)^2}.$$\n",
    "\n",
    "Modes with one non-zero index are *axial*, with two *tangential* and with three\n",
    "*oblique*. Because $L_x=2L_z$, the modes $(2,0,0)$ and $(0,0,1)$ have exactly the same\n",
    "frequency (343 Hz), and so do $(2,1,0)$/$(0,1,1)$ and $(2,2,0)$/$(0,2,1)$: there the\n",
    "eigenvalue is double and every combination of the two shapes is an eigenmode too. The\n",
    "first twenty non-zero modes reach up to 665 Hz; the twenty-first lies at 686 Hz.\n",
    "\n",
    "**Numerical method.**\n",
    "- Spatial: continuous Galerkin finite elements. Primary: tensor-product Lagrange\n",
    "  elements $Q_p$ of degree $p=1,2,3,4$ on hexahedra; cross-check: Lagrange $P_p$\n",
    "  ($p=1,2,3$) on an unstructured tetrahedral mesh from OneSimulation's CAD mesher.\n",
    "  The element stiffness $\\int\\rho_0^{-1}\\nabla\\phi_i\\cdot\\nabla\\phi_j$ and the\n",
    "  compressibility mass $\\int(\\rho_0c^2)^{-1}\\phi_i\\phi_j$ come from OneSimulation's\n",
    "  acoustic Helmholtz element kernel on the quadrature of each finite-element space.\n",
    "- The rigid walls are the natural boundary condition of this weak form: no wall\n",
    "  term enters the matrices, and the computed modes are checked for\n",
    "  $\\partial p/\\partial n\\approx 0$ afterwards.\n",
    "- Eigenproblem: the generalized symmetric eigenvalue problem $K\\mathbf p=\\omega^2M\\mathbf p$\n",
    "  is solved with shift-and-invert Lanczos iterations (OneSimulation's sparse symmetric\n",
    "  eigensolver, sparse LU of $K-\\sigma M$ with a small negative shift $\\sigma$). The\n",
    "  constant pressure mode at $\\omega=0$ is the expected null mode of a closed box.\n",
    "- Time integration: none (eigenvalue problem).\n",
    "\n",
    "**Discretisation error.** For a conforming Galerkin method the computed eigenvalues\n",
    "lie above the exact ones and their error falls like $h^{2p}$ (I. Babuška and\n",
    "J. Osborn, \"Eigenvalue problems\", *Handbook of Numerical Analysis* II, 1991). In wave\n",
    "terms this is the *dispersion error*: on a given mesh the error grows quickly with\n",
    "frequency, i.e. with fewer elements per wavelength, and high-order elements push it\n",
    "down by orders of magnitude at the same number of unknowns."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import time\n",
    "\n",
    "import numpy as np\n",
    "import scipy.sparse as sp\n",
    "from onesim.cad.d3 import Box\n",
    "from onesim.meshing import StructuredHexahedralMesher, TetrahedralMesher\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseSymmetricEigenSolver\n",
    "from onesim.physics.acoustics import pressure_eigenmodes, pressure_helmholtz_element\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.sparse.linalg import LinearOperator, splu\n",
    "\n",
    "theme.set()\n",
    "start_time = time.perf_counter()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Parameters"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "Lx, Ly, Lz = 1.0, 0.7, 0.5\n",
    "c0 = 343.0\n",
    "rho0 = 1.204\n",
    "compressibility = 1.0 / (rho0 * c0**2)\n",
    "mode_count = 20\n",
    "\n",
    "hex_levels = {1: (1, 2, 3, 4), 2: (1, 2, 3), 3: (1, 2), 4: (1,)}\n",
    "tet_size = 0.1\n",
    "tet_degrees = (1, 2, 3)\n",
    "\n",
    "exact = sorted(\n",
    "    (c0 / 2 * np.sqrt((l / Lx) ** 2 + (m / Ly) ** 2 + (n / Lz) ** 2), (l, m, n))\n",
    "    for l in range(8)\n",
    "    for m in range(8)\n",
    "    for n in range(8)\n",
    "    if l + m + n\n",
    ")\n",
    "f_exact = np.array([f for f, _ in exact[:mode_count]])\n",
    "indices = [lmn for _, lmn in exact[:mode_count]]\n",
    "kind = {1: \"axial\", 2: \"tangential\", 3: \"oblique\"}\n",
    "group_of = [\n",
    "    int(np.flatnonzero(np.isclose(f_exact, f, rtol=1e-12, atol=0))[0]) for f in f_exact\n",
    "]\n",
    "print(\n",
    "    f\"first {mode_count} exact modes: {f_exact[0]:.2f} ... {f_exact[-1]:.2f} Hz; \"\n",
    "    f\"next mode {exact[mode_count][0]:.2f} Hz {exact[mode_count][1]}\"\n",
    ")\n",
    "print(\n",
    "    \"degenerate pairs:\",\n",
    "    [(indices[i], indices[j]) for j, i in enumerate(group_of) if i != j],\n",
    ")\n",
    "\n",
    "\n",
    "def exact_shape(lmn, points):\n",
    "    l, m, n = lmn\n",
    "    x, y, z = np.asarray(points).T\n",
    "    return (\n",
    "        np.cos(l * np.pi * x / Lx)\n",
    "        * np.cos(m * np.pi * y / Ly)\n",
    "        * np.cos(n * np.pi * z / Lz)\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "The air volume is a `Box`. The hexahedral meshes are uniform with cubic cells of side\n",
    "$h=0.1\\,\\mathrm m/k$ (10 x 7 x 5 cells at $k=1$, 40 x 28 x 20 at $k=4$); the element\n",
    "degree $p$ adds $p-1$ nodes per cell edge. The tetrahedral mesh is generated by\n",
    "OneSimulation's CAD mesher with target size 0.1 m. It is genuinely unstructured, so its\n",
    "discrete operator is not a tensor product of one-dimensional ones: it tests the 3D\n",
    "discretisation without any help from the box's separable shape."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "geometry = Box(length=Lx, width=Ly, height=Lz)\n",
    "\n",
    "\n",
    "def hex_mesh(level):\n",
    "    return StructuredHexahedralMesher(\n",
    "        cells=(10 * level, 7 * level, 5 * level)\n",
    "    ).generate(geometry)\n",
    "\n",
    "\n",
    "tet_mesh = TetrahedralMesher(target_size=tet_size).generate(geometry)\n",
    "print(f\"unstructured tetrahedral mesh: {tet_mesh.cell_count} cells\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Global stiffness $K$ and compressibility mass $M$ are assembled cell by cell from the\n",
    "Lagrange space bound to the mesh; `pressure_helmholtz_element` evaluates\n",
    "$\\int\\rho_0^{-1}\\nabla\\phi_i\\cdot\\nabla\\phi_j\\,\\mathrm dV$ and\n",
    "$\\int(\\rho_0c^2)^{-1}\\phi_i\\phi_j\\,\\mathrm dV$ on the space's own quadrature rule. The\n",
    "rigid walls need no boundary term (natural condition, see the parameters table above)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def acoustic_matrices(mesh, degree):\n",
    "    space = FiniteElement(element=Lagrange(order=degree)).bind_space(mesh)\n",
    "    n, local = space.dof_count, space.cell_dofs.shape[1]\n",
    "    rows, cols, k_values, m_values = [], [], [], []\n",
    "    for cell, dofs in enumerate(space.cell_dofs):\n",
    "        _, weights, (basis, gradients, _) = space.element_data(cell)\n",
    "        k_cell, m_cell = pressure_helmholtz_element(\n",
    "            basis, gradients, weights, density=rho0, compressibility=compressibility\n",
    "        )\n",
    "        rows.append(np.repeat(dofs, local))\n",
    "        cols.append(np.tile(dofs, local))\n",
    "        k_values.append(np.asarray(k_cell).ravel())\n",
    "        m_values.append(np.asarray(m_cell).ravel())\n",
    "    rows, cols = np.concatenate(rows), np.concatenate(cols)\n",
    "    K = sp.csr_matrix((np.concatenate(k_values), (rows, cols)), shape=(n, n))\n",
    "    M = sp.csr_matrix((np.concatenate(m_values), (rows, cols)), shape=(n, n))\n",
    "    return space, K, M\n",
    "\n",
    "\n",
    "def shift_invert(stiffness, mass, shift):\n",
    "    factor = splu((stiffness - shift * mass).tocsc())\n",
    "    return LinearOperator(stiffness.shape, matvec=factor.solve)\n",
    "\n",
    "\n",
    "eigensolver = SparseSymmetricEigenSolver(shift_inverse=shift_invert)\n",
    "\n",
    "\n",
    "def acoustic_modes(mesh, degree):\n",
    "    started = time.perf_counter()\n",
    "    space, K, M = acoustic_matrices(mesh, degree)\n",
    "    frequencies, vectors = pressure_eigenmodes(\n",
    "        K,\n",
    "        M,\n",
    "        zero_tolerance=1e-3,\n",
    "        eigensolver=lambda mass, stiffness: eigensolver(\n",
    "            mass, stiffness, mode_count=mode_count + 1, target=-1.0\n",
    "        ),\n",
    "    )\n",
    "    return dict(\n",
    "        space=space,\n",
    "        M=M,\n",
    "        f=frequencies[1:],\n",
    "        null=frequencies[0],\n",
    "        modes=vectors[:, 1:],\n",
    "        dofs=space.dof_count,\n",
    "        seconds=time.perf_counter() - started,\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Solve"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "hex_runs = {}\n",
    "for degree, levels in hex_levels.items():\n",
    "    for level in levels:\n",
    "        run = acoustic_modes(hex_mesh(level), degree)\n",
    "        hex_runs[degree, level] = run\n",
    "        print(\n",
    "            f\"Q{degree}, h = {10 / level:5.2f} cm: {run['dofs']:6d} unknowns, null mode {run['null']:.1e} Hz, \"\n",
    "            f\"max error {np.max(np.abs(run['f'] / f_exact - 1)):.2e}, {run['seconds']:.1f} s\"\n",
    "        )\n",
    "tet_runs = {}\n",
    "for degree in tet_degrees:\n",
    "    run = acoustic_modes(tet_mesh, degree)\n",
    "    tet_runs[degree] = run\n",
    "    print(\n",
    "        f\"P{degree} tetrahedra: {run['dofs']:6d} unknowns, null mode {run['null']:.1e} Hz, \"\n",
    "        f\"max error {np.max(np.abs(run['f'] / f_exact - 1)):.2e}, {run['seconds']:.1f} s\"\n",
    "    )\n",
    "final = hex_runs[3, 2]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "**Mode shapes (MAC).** The modal assurance criterion compares a computed mode\n",
    "$\\mathbf p_h$ with the exact shape $\\mathbf q$ sampled at the nodes, in the mass inner\n",
    "product: $\\mathrm{MAC}=(\\mathbf p_h^\\top M\\mathbf q)^2/\n",
    "\\big((\\mathbf p_h^\\top M\\mathbf p_h)(\\mathbf q^\\top M\\mathbf q)\\big)$, 1 for identical\n",
    "shapes. For a degenerate pair the solver may return any rotation of the two shapes, so\n",
    "the criterion measures the fraction of $\\mathbf p_h$ that lies in the span of both exact\n",
    "shapes (subspace MAC)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def subspace_mac(run):\n",
    "    space, M, V = run[\"space\"], run[\"M\"], run[\"modes\"]\n",
    "    exact_nodal = np.column_stack(\n",
    "        [exact_shape(lmn, space.dof_coordinates) for lmn in indices]\n",
    "    )\n",
    "    mac = np.empty(mode_count)\n",
    "    for j in range(mode_count):\n",
    "        members = [i for i in range(mode_count) if group_of[i] == group_of[j]]\n",
    "        Q = exact_nodal[:, members]\n",
    "        gram = Q.T @ (M @ Q)\n",
    "        projection = Q.T @ (M @ V[:, j])\n",
    "        mac[j] = (\n",
    "            projection @ np.linalg.solve(gram, projection) / (V[:, j] @ (M @ V[:, j]))\n",
    "        )\n",
    "    return mac\n",
    "\n",
    "\n",
    "mac_final, mac_tet = subspace_mac(final), subspace_mac(tet_runs[3])"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Three discretisations with exactly the same number of unknowns (24,969): Q1 with\n",
    "h = 2.5 cm, Q2 with h = 5 cm and Q4 with h = 10 cm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "same = {1: hex_runs[1, 4], 2: hex_runs[2, 2], 4: hex_runs[4, 1]}\n",
    "print(\n",
    "    f\"\\nFinal mesh: Q3 hexahedra, h = 5 cm, {final['dofs']} unknowns; P3 tetrahedra: {tet_runs[3]['dofs']} unknowns;\"\n",
    "    f\" equal-cost comparison Q1/Q2/Q4 with {same[1]['dofs']} unknowns each\"\n",
    ")\n",
    "print(\n",
    "    \" #   (l,m,n)   type         exact [Hz]   Q3 [Hz]       rel. dev.  | Q1        Q2        Q4       \"\n",
    "    \"| P3-tet    | 1-MAC Q3  1-MAC P3-tet\"\n",
    ")\n",
    "for j in range(mode_count):\n",
    "    lmn = indices[j]\n",
    "    print(\n",
    "        f\"{j + 1:2d}   {str(lmn):9s} {kind[np.count_nonzero(lmn)]:11s} {f_exact[j]:10.4f}   {final['f'][j]:11.6f}\"\n",
    "        f\"   {final['f'][j] / f_exact[j] - 1:+.2e} | \"\n",
    "        + \"  \".join(f\"{same[p]['f'][j] / f_exact[j] - 1:+.1e}\" for p in (1, 2, 4))\n",
    "        + f\" | {tet_runs[3]['f'][j] / f_exact[j] - 1:+.1e} | {1 - mac_final[j]:.1e}   {1 - mac_tet[j]:.1e}\"\n",
    "    )\n",
    "print(\n",
    "    f\"smallest MAC: Q3 hexahedra {mac_final.min():.10f}, P3 tetrahedra {mac_tet.min():.10f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Splitting of the degenerate pairs.** On the tensor-product hexahedral mesh the two\n",
    "members of a pair remain exactly degenerate; on the unstructured tetrahedra the\n",
    "discrete symmetry is broken and the pair splits slightly - by much less than the\n",
    "discretisation error itself."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "for j, i in enumerate(group_of):\n",
    "    if i != j:\n",
    "        print(\n",
    "            f\"pair {indices[i]}/{indices[j]} at {f_exact[j]:.3f} Hz: splitting Q3-hex \"\n",
    "            f\"{abs(final['f'][j] - final['f'][i]):.1e} Hz, P1/P2/P3-tet \"\n",
    "            + \", \".join(\n",
    "                f\"{abs(tet_runs[p]['f'][j] - tet_runs[p]['f'][i]):.1e}\"\n",
    "                for p in tet_degrees\n",
    "            )\n",
    "            + \" Hz\"\n",
    "        )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Mesh convergence and observed order.** Error measure: the largest relative\n",
    "frequency error over the twenty modes. With $h$ halved the error should fall by\n",
    "$2^{2p}$, i.e. the observed order of the eigenvalue error is $2p$ (frequency error\n",
    "$\\propto h^{2p}$ as well, since $f\\propto\\sqrt{\\lambda}$)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "print(\"\\nConvergence of the largest relative frequency error over the 20 modes\")\n",
    "for degree, levels in hex_levels.items():\n",
    "    errors = [np.max(np.abs(hex_runs[degree, k][\"f\"] / f_exact - 1)) for k in levels]\n",
    "    text = \"  \".join(f\"h = {10 / k:.2f} cm: {e:.3e}\" for k, e in zip(levels, errors))\n",
    "    print(f\"Q{degree}: {text}\")\n",
    "    if len(levels) > 1:\n",
    "        orders = [\n",
    "            np.log(errors[i] / errors[i + 1]) / np.log(levels[i + 1] / levels[i])\n",
    "            for i in range(len(levels) - 1)\n",
    "        ]\n",
    "        last, prev = (\n",
    "            hex_runs[degree, levels[-1]][\"f\"],\n",
    "            hex_runs[degree, levels[-2]][\"f\"],\n",
    "        )\n",
    "        print(\n",
    "            f\"     observed order(s) {', '.join(f'{o:.2f}' for o in orders)} (theory {2 * degree});\"\n",
    "            f\" largest change between the last two meshes {np.max(np.abs(last / prev - 1)):.2e}\"\n",
    "        )\n",
    "f_rich = final[\"f\"] + (final[\"f\"] - hex_runs[3, 1][\"f\"]) / (2**6 - 1)\n",
    "print(\n",
    "    f\"Q3 Richardson estimate (order 6): largest deviation from exact {np.max(np.abs(f_rich / f_exact - 1)):.1e}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Wall condition.** The rigid-wall condition is not imposed but follows from the weak\n",
    "form. The normal pressure gradient on the six walls, relative to the RMS pressure\n",
    "gradient in the volume, shows how well the computed modes satisfy it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "space = final[\"space\"]\n",
    "grid = np.linspace(0.02, 0.98, 25)\n",
    "U, W = np.meshgrid(grid, grid)\n",
    "u, w = U.ravel(), W.ravel()\n",
    "eps = 1e-9\n",
    "walls = {\n",
    "    \"x = 0\": (np.column_stack((np.full_like(u, eps), u * Ly, w * Lz)), 0),\n",
    "    \"x = Lx\": (np.column_stack((np.full_like(u, Lx - eps), u * Ly, w * Lz)), 0),\n",
    "    \"y = 0\": (np.column_stack((u * Lx, np.full_like(u, eps), w * Lz)), 1),\n",
    "    \"y = Ly\": (np.column_stack((u * Lx, np.full_like(u, Ly - eps), w * Lz)), 1),\n",
    "    \"z = 0\": (np.column_stack((u * Lx, w * Ly, np.full_like(u, eps))), 2),\n",
    "    \"z = Lz\": (np.column_stack((u * Lx, w * Ly, np.full_like(u, Lz - eps))), 2),\n",
    "}\n",
    "interior = np.column_stack(\n",
    "    [\n",
    "        g.ravel()\n",
    "        for g in np.meshgrid(\n",
    "            np.linspace(0.05, 0.95, 9) * Lx,\n",
    "            np.linspace(0.05, 0.95, 9) * Ly,\n",
    "            np.linspace(0.05, 0.95, 9) * Lz,\n",
    "        )\n",
    "    ]\n",
    ")\n",
    "worst = 0.0\n",
    "for j in range(mode_count):\n",
    "    values = final[\"modes\"][:, j]\n",
    "    scale = np.sqrt(\n",
    "        np.mean(np.sum(np.asarray(space.gradient(values, interior)) ** 2, axis=-1))\n",
    "    )\n",
    "    for points, axis in walls.values():\n",
    "        normal = np.asarray(space.gradient(values, points))[:, axis]\n",
    "        worst = max(worst, np.sqrt(np.mean(normal**2)) / scale)\n",
    "print(\n",
    "    f\"\\nRMS normal pressure gradient on the walls / RMS gradient in the volume, worst of 20 modes x 6 walls: {worst:.1e}\"\n",
    ")\n",
    "print(f\"Total run time: {time.perf_counter() - start_time:.0f} s\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Top and bottom left: computed pressure modes on the final Q3 mesh, shown on the three\n",
    "visible walls of the box ($x=L_x$, $y=0$, $z=L_z$); teal and copper are opposite signs. For the degenerate pair at 343 Hz the\n",
    "computed two-dimensional eigenspace is rotated onto the exact shapes $(2,0,0)$ and\n",
    "$(0,0,1)$. Right: convergence of the largest frequency error with the number of\n",
    "unknowns, and the dispersion error over the twenty modes on the coarsest mesh."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def rotated_pair(run, members):\n",
    "    \"\"\"Rotate the computed degenerate eigenspace onto the exact shapes of the pair.\"\"\"\n",
    "    space, M, V = run[\"space\"], run[\"M\"], run[\"modes\"][:, members]\n",
    "    return [\n",
    "        V\n",
    "        @ np.linalg.solve(\n",
    "            V.T @ (M @ V), V.T @ (M @ exact_shape(indices[i], space.dof_coordinates))\n",
    "        )\n",
    "        for i in members\n",
    "    ]\n",
    "\n",
    "\n",
    "shown = [\n",
    "    indices.index(lmn)\n",
    "    for lmn in ((1, 1, 0), (1, 1, 1), (2, 0, 0), (0, 0, 1), (2, 1, 1), (3, 1, 1))\n",
    "]\n",
    "pair = [indices.index((0, 0, 1)), indices.index((2, 0, 0))]\n",
    "pair_vectors = dict(zip(pair, rotated_pair(final, pair)))\n",
    "n = 41\n",
    "s, t = (\n",
    "    grid.ravel()\n",
    "    for grid in np.meshgrid(\n",
    "        np.linspace(1e-6, 1 - 1e-6, n), np.linspace(1e-6, 1 - 1e-6, n), indexing=\"ij\"\n",
    "    )\n",
    ")\n",
    "walls = np.vstack(\n",
    "    (\n",
    "        np.column_stack((np.full_like(s, Lx * (1 - 1e-9)), s * Ly, t * Lz)),\n",
    "        np.column_stack((s * Lx, np.full_like(s, 1e-9 * Ly), t * Lz)),\n",
    "        np.column_stack((s * Lx, t * Ly, np.full_like(s, Lz * (1 - 1e-9)))),\n",
    "    )\n",
    ")\n",
    "wall_triangles = (\n",
    "    np.array(\n",
    "        [\n",
    "            (i * n + j + a, i * n + j + b, i * n + j + c)\n",
    "            for i in range(n - 1)\n",
    "            for j in range(n - 1)\n",
    "            for a, b, c in ((0, n, n + 1), (0, n + 1, 1))\n",
    "        ]\n",
    "    )[None]\n",
    "    + (np.arange(3) * n * n)[:, None, None]\n",
    ").reshape(-1, 3)\n",
    "convergence, guides = {}, {}\n",
    "for degree, levels in hex_levels.items():\n",
    "    dofs = np.array([hex_runs[degree, k][\"dofs\"] for k in levels])\n",
    "    errors = np.array(\n",
    "        [np.max(np.abs(hex_runs[degree, k][\"f\"] / f_exact - 1)) for k in levels]\n",
    "    )\n",
    "    convergence[f\"Q{degree} hexahedra\"] = (dofs, errors)\n",
    "    if len(levels) > 1:\n",
    "        guides[f\"Q{degree} hexahedra\"] = (\n",
    "            dofs,\n",
    "            errors[0] * (dofs / dofs[0]) ** (-2 * degree / 3),\n",
    "        )\n",
    "fig = plots.figure(\n",
    "    layout=[[\"m0\", \"m1\", \"m2\", \"convergence\"], [\"m3\", \"m4\", \"m5\", \"dispersion\"]],\n",
    "    size=(23, 10),\n",
    ")\n",
    "for k, j in enumerate(shown):\n",
    "    pressure = np.asarray(\n",
    "        final[\"space\"].evaluate(pair_vectors.get(j, final[\"modes\"][:, j]), walls)\n",
    "    )\n",
    "    label = kind[np.count_nonzero(indices[j])]\n",
    "    plots.trisurface(\n",
    "        walls,\n",
    "        wall_triangles,\n",
    "        pressure / np.max(np.abs(pressure)) * np.sign(pressure[n * n - 1]),\n",
    "        colormap=\"diverging\",\n",
    "        limits=(-1.0, 1.0),\n",
    "        camera=plots.Camera(elevation=24, azimuth=-58),\n",
    "        label=\"pressure p / max|p|\",\n",
    "        ax=fig[f\"m{k}\"],\n",
    "        title=f\"Mode {indices[j]}, {label}: {final['f'][j]:.1f} Hz\",\n",
    "    )\n",
    "plots.line(\n",
    "    y=convergence,\n",
    "    reference=guides,\n",
    "    points={\n",
    "        f\"P{degree} tetrahedra (unstructured)\": (\n",
    "            [tet_runs[degree][\"dofs\"]],\n",
    "            [np.max(np.abs(tet_runs[degree][\"f\"] / f_exact - 1))],\n",
    "        )\n",
    "        for degree in tet_degrees\n",
    "    },\n",
    "    markers=True,\n",
    "    scale=\"loglog\",\n",
    "    xlabel=\"number of pressure unknowns\",\n",
    "    ylabel=\"largest relative frequency error\",\n",
    "    title=\"Convergence (dashed: h^(2p))\",\n",
    "    ax=fig[\"convergence\"],\n",
    ")\n",
    "plots.line(\n",
    "    f_exact,\n",
    "    {\n",
    "        **{\n",
    "            f\"Q{degree}, h = 10 cm ({hex_runs[degree, 1]['dofs']} unknowns)\": np.abs(\n",
    "                hex_runs[degree, 1][\"f\"] / f_exact - 1\n",
    "            )\n",
    "            for degree in (1, 2, 3, 4)\n",
    "        },\n",
    "        f\"Q3, h = 5 cm ({final['dofs']} unknowns)\": np.abs(final[\"f\"] / f_exact - 1),\n",
    "    },\n",
    "    markers=True,\n",
    "    scale=\"logy\",\n",
    "    xlabel=\"exact frequency [Hz]\",\n",
    "    ylabel=\"relative frequency error\",\n",
    "    title=\"Dispersion error over the first 20 modes\",\n",
    "    ax=fig[\"dispersion\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make one wall absorbing: a locally reacting impedance $Z$ adds the boundary matrix\n",
    "$i\\omega\\int Z^{-1}\\phi_i\\phi_j\\,\\mathrm dS$ and turns the problem into a quadratic\n",
    "eigenproblem with complex frequencies whose imaginary parts give the reverberation\n",
    "decay. Or replace the box by a room with a non-rectangular floor plan from the CAD\n",
    "kernel: the unstructured tetrahedral route above carries over unchanged, while the\n",
    "exact cosine modes no longer exist and the mesh study becomes the reference."
   ]
  }
 ]
}
