{
 "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": [
    "# Isospectral drums: can one hear the shape of a drum?\n",
    "\n",
    "A stretched membrane with tension $T$ (N/m) and areal density $\\sigma$ (kg/m²), clamped along\n",
    "its rim, vibrates in modes $w(\\mathbf x)\\,e^{i\\omega t}$ that solve the Helmholtz eigenproblem\n",
    "\n",
    "$$-T\\,\\nabla^2 w=\\omega^2\\sigma\\,w\\quad\\text{on the drumhead},\\qquad w=0\\quad\\text{on the rim}.$$\n",
    "\n",
    "The eigenvalues $\\lambda=\\omega^2\\sigma/T$ are what the ear hears. In 1966 Mark Kac asked whether\n",
    "they determine the shape of the drum (*Amer. Math. Monthly* 73, 1966). The answer came in 1992:\n",
    "C. Gordon, D. Webb and S. Wolpert (*Invent. Math.* 110, 1992) found two different polygons with\n",
    "identical spectra. Each is made of seven copies of a right isosceles triangle, glued in two\n",
    "different ways.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| rim of each drum | clamped, $w=0$ |\n",
    "\n",
    "**Reference.** T. A. Driscoll, \"Eigenmodes of isospectral drums\", *SIAM Review* 39, 1-17 (1997),\n",
    "computed the first eigenvalues of this pair to twelve digits with a domain-decomposition method\n",
    "that resolves the corner singularities exactly. In the scale where the shortest horizontal and\n",
    "vertical sides have length 2, they are $\\lambda_1=2.53794399980$, $\\lambda_2=3.65550971352$, ...;\n",
    "the ninth is $5\\pi^2/4$ exactly. The drums here are drawn with that unit set to 0.1 m.\n",
    "\n",
    "The membrane equation is the same Helmholtz operator as linear acoustics, so OneSimulation's\n",
    "pressure forms solve it directly: the tension takes the place of the inverse density and the\n",
    "areal density the place of the compressibility."
   ]
  },
  {
   "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",
    "\n",
    "theme.set()\n",
    "\n",
    "tension, areal_density, unit = 1500.0, 0.26, 0.1\n",
    "driscoll = np.array(\n",
    "    [\n",
    "        2.53794399980,\n",
    "        3.65550971352,\n",
    "        5.17555935622,\n",
    "        6.53755744376,\n",
    "        7.24807786256,\n",
    "        9.20929499840,\n",
    "        10.5969856913,\n",
    "        11.5413953956,\n",
    "        12.3370055014,\n",
    "        13.0536540557,\n",
    "    ]\n",
    ")\n",
    "mode_count = len(driscoll)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the two drums, thin plates written by `isospectral_drums_geometry.py`; `section`\n",
    "cuts each at half thickness. Both have re-entrant corners of 270° at $(\\pm0.1, \\pm0.1)$ m, where\n",
    "the modes have a singular gradient. The `size_field` of the triangle mesher shrinks the elements\n",
    "towards these two points, from the target size down to a twentieth of it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "drums = {\n",
    "    \"drum A\": load(\"isospectral_drums.step\"),\n",
    "    \"drum B\": load(\"isospectral_drums_twin.step\"),\n",
    "}\n",
    "heads = {\n",
    "    name: drum.section((0, 0, 1), origin=(0, 0, 0.005)) for name, drum in drums.items()\n",
    "}\n",
    "corners = unit * np.array([[1.0, 1.0], [-1.0, -1.0]])\n",
    "mesh_of = lambda head, h: TriangularMesher(\n",
    "    target_size=h,\n",
    "    size_field=lambda p: np.minimum(\n",
    "        h,\n",
    "        h / 20 + 0.3 * np.min(np.linalg.norm(p[:, None, :2] - corners, axis=2), axis=1),\n",
    "    ),\n",
    ").generate(head)\n",
    "sizes = (0.04, 0.02, 0.01, 0.005)\n",
    "meshes = {(name, h): mesh_of(head, h) for name, head in heads.items() for h in sizes}\n",
    "\n",
    "view = plots.Camera(elevation=55, azimuth=-70)\n",
    "fig = plots.figure(2, 2, size=(13, 11))\n",
    "for row, (name, drum) in enumerate(drums.items()):\n",
    "    plots.geometry(\n",
    "        drum,\n",
    "        selection={\"rim\": drum.boundaries.rim},\n",
    "        labels=False,\n",
    "        camera=view,\n",
    "        title=f\"{name}: STEP part\",\n",
    "        ax=fig[2 * row],\n",
    "    )\n",
    "    plots.mesh(\n",
    "        meshes[name, 0.01],\n",
    "        groups=(\"all\",),\n",
    "        legend=False,\n",
    "        title=f\"{name}: {meshes[name, 0.01].cell_count} triangles\",\n",
    "        ax=fig[2 * row + 1],\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Quadratic Lagrange elements; `SampledPressureVolumeForms` integrates the stiffness\n",
    "$\\int T\\,\\nabla\\phi_i\\cdot\\nabla\\phi_j$ and the mass $\\int\\sigma\\,\\phi_i\\phi_j$. The clamped\n",
    "rim removes its nodes through the restriction of the `ComplexPressurePencil`, and\n",
    "`AcousticPressureSpectrum` returns the lowest ten modes from a shift-and-invert Lanczos solver."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "solver = SparseSymmetricEigenSolver()\n",
    "\n",
    "\n",
    "def solve_drum(name, h):\n",
    "    \"\"\"Lowest modes of one drum on the mesh of size h.\"\"\"\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: tension,\n",
    "        compressibility=lambda omega, sample: areal_density,\n",
    "    )(0.0)\n",
    "    free = np.setdiff1d(\n",
    "        np.arange(space.dof_count),\n",
    "        space.boundary_dofs(mesh.facets(heads[name].boundaries.all)),\n",
    "    )\n",
    "    pencil = ComplexPressurePencil(\n",
    "        ConstantPressureForms(stiffness, mass),\n",
    "        restrict=lambda matrix: matrix[free][:, free],\n",
    "    )\n",
    "    eigenpairs = lambda operator: (lambda values, vectors: (np.sqrt(values), vectors))(\n",
    "        *solver(\n",
    "            mass[free][:, free], operator(0.0).real, mode_count=mode_count, target=0.0\n",
    "        )\n",
    "    )\n",
    "    modes = AcousticPressureSpectrum(operator=pencil, eigensolver=eigenpairs).run()\n",
    "    shapes = np.zeros((space.dof_count, mode_count))\n",
    "    shapes[free] = modes.pressure_modes\n",
    "    return dict(\n",
    "        space=space,\n",
    "        mesh=mesh,\n",
    "        f=modes.eigenfrequencies,\n",
    "        shapes=shapes,\n",
    "        dofs=space.dof_count,\n",
    "        lam=modes.angular_frequencies**2 * areal_density / tension * unit**2,\n",
    "    )\n",
    "\n",
    "\n",
    "runs = {(name, h): solve_drum(name, h) for name in heads for h in sizes}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Eigenvalues in Driscoll's scale, $\\lambda=\\omega^2\\sigma\\,(0.1\\,\\mathrm m)^2/T$, on the finest\n",
    "mesh, the frequency of each mode for a drumhead of tension 1500 N/m and 0.26 kg/m², and the\n",
    "difference between the two drums."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "finest = sizes[-1]\n",
    "a, b = runs[\"drum A\", finest], runs[\"drum B\", finest]\n",
    "print(f\"finest meshes: drum A {a['dofs']} unknowns, drum B {b['dofs']} unknowns\")\n",
    "print(\n",
    "    \" mode   Driscoll        drum A          dev. A     drum B          dev. B     |A-B|/A    f [Hz]\"\n",
    ")\n",
    "for k in range(mode_count):\n",
    "    print(\n",
    "        f\"{k + 1:4d}   {driscoll[k]:.10f}  {a['lam'][k]:.10f}  {a['lam'][k] / driscoll[k] - 1:+.1e}  \"\n",
    "        f\"{b['lam'][k]:.10f}  {b['lam'][k] / driscoll[k] - 1:+.1e}  {abs(a['lam'][k] - b['lam'][k]) / a['lam'][k]:.1e}\"\n",
    "        f\"   {a['f'][k]:7.2f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"ninth eigenvalue against 5 pi^2/4 = {5 * np.pi**2 / 4:.10f}: drum A {a['lam'][8] / (5 * np.pi**2 / 4) - 1:+.1e}, \"\n",
    "    f\"drum B {b['lam'][8] / (5 * np.pi**2 / 4) - 1:+.1e}\"\n",
    ")\n",
    "print(\"\\nlargest relative deviation from Driscoll over the ten modes\")\n",
    "for h in sizes:\n",
    "    print(\n",
    "        f\"h = {100 * h:4.1f} cm: drum A {np.max(np.abs(runs['drum A', h]['lam'] / driscoll - 1)):.2e} \"\n",
    "        f\"({runs['drum A', h]['dofs']:6d} unknowns), drum B {np.max(np.abs(runs['drum B', h]['lam'] / driscoll - 1)):.2e} \"\n",
    "        f\"({runs['drum B', h]['dofs']:6d} unknowns)\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The first three modes of both drums: the shapes differ, the pitches agree. Teal and copper are\n",
    "opposite signs of the displacement. Last row: convergence of the largest eigenvalue error with the\n",
    "number of unknowns."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(\n",
    "    layout=[[\"A0\", \"A1\", \"A2\"], [\"B0\", \"B1\", \"B2\"], [\"conv\", \"conv\", \"dev\"]],\n",
    "    size=(18, 16),\n",
    ")\n",
    "for name, key in ((\"drum A\", \"A\"), (\"drum B\", \"B\")):\n",
    "    run = runs[name, 0.01]\n",
    "    x, y = np.asarray(run[\"mesh\"].coordinates).T\n",
    "    for k in range(3):\n",
    "        shape = np.asarray(\n",
    "            run[\"space\"].evaluate(run[\"shapes\"][:, k], run[\"mesh\"].coordinates)\n",
    "        )\n",
    "        shape = shape / shape[np.argmax(np.abs(shape))]\n",
    "        plots.heatmap(\n",
    "            x,\n",
    "            y,\n",
    "            shape,\n",
    "            triangles=np.asarray(run[\"mesh\"].cells),\n",
    "            colormap=\"diverging\",\n",
    "            limits=(-1, 1),\n",
    "            label=\"w / max|w|\",\n",
    "            title=f\"{name}, mode {k + 1}: {run['f'][k]:.1f} Hz\",\n",
    "            ax=fig[f\"{key}{k}\"],\n",
    "        )\n",
    "plots.line(\n",
    "    y={\n",
    "        name: (\n",
    "            np.array([runs[name, h][\"dofs\"] for h in sizes]),\n",
    "            np.array(\n",
    "                [np.max(np.abs(runs[name, h][\"lam\"] / driscoll - 1)) for h in sizes]\n",
    "            ),\n",
    "        )\n",
    "        for name in heads\n",
    "    },\n",
    "    markers=True,\n",
    "    scale=\"loglog\",\n",
    "    xlabel=\"number of unknowns\",\n",
    "    ylabel=\"largest relative eigenvalue error\",\n",
    "    title=\"Convergence against Driscoll's eigenvalues\",\n",
    "    ax=fig[\"conv\"],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        name: (\n",
    "            np.arange(1, mode_count + 1),\n",
    "            np.abs(runs[name, finest][\"lam\"] / driscoll - 1),\n",
    "        )\n",
    "        for name in heads\n",
    "    },\n",
    "    scale=\"logy\",\n",
    "    xlabel=\"mode number\",\n",
    "    ylabel=\"relative eigenvalue error\",\n",
    "    title=f\"Finest meshes, h = {100 * finest:.1f} cm\",\n",
    "    ax=fig[\"dev\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the outlines in `isospectral_drums_geometry.py` to another isospectral pair of Buser,\n",
    "Conway, Doyle and Semmler (*Int. Math. Res. Notices* 1994) and write the STEP files again. Or\n",
    "replace the clamped rim by a free one (drop the restriction): the Neumann spectra of the pair\n",
    "coincide as well."
   ]
  }
 ]
}
