{
 "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": [
    "# Ear canal acoustics\n",
    "\n",
    "The outer ear canal leads from the concha to the eardrum. It is about 25 mm long and 7.5 mm wide\n",
    "and bends on its way. Driven at the entrance, it resonates as a tube that is open at one end and\n",
    "nearly closed at the other, near $c/(4L)\\approx3.4$ kHz, and raises the sound pressure at the\n",
    "eardrum by 10-15 dB there (E. A. G. Shaw, *J. Acoust. Soc. Am.* 56, 1848, 1974).\n",
    "\n",
    "Here the canal is a circular tube of radius 3.75 mm swept along a centre line with a 60° bend.\n",
    "The eardrum closes it as a locally reacting surface with a mass-spring-damper impedance,\n",
    "$Z_d=\\rho_0c\\,[\\,r+i\\,x\\,(f/f_d-f_d/f)\\,]$ with $r=2$, $x=3$ and $f_d=1.5$ kHz - a simple\n",
    "representative model; measured eardrum impedances (H. Hudde, *J. Acoust. Soc. Am.* 73, 242, 1983)\n",
    "have the same stiffness-controlled behaviour at low frequencies.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| entrance | uniform normal velocity $U$ into the canal |\n",
    "| eardrum | impedance, $v_n=p/Z_d(\\omega)$ |\n",
    "| canal wall | rigid, $\\partial p/\\partial n=0$ |\n",
    "\n",
    "**Reference.** Below the first cross mode of the canal ($1.84\\,c/(2\\pi a)=27$ kHz) only plane waves\n",
    "propagate, and the canal is a transmission line of length $L$ along its centre line (Kinsler et\n",
    "al., *Fundamentals of Acoustics*, 4th ed., §10.3):\n",
    "\n",
    "$$Z_\\mathrm{in}=\\rho_0c\\,\\frac{Z_d+i\\rho_0c\\tan kL}{\\rho_0c+iZ_d\\tan kL},\\qquad\n",
    "  \\frac{p_\\mathrm{drum}}{p_\\mathrm{entrance}}=\\frac{Z_d}{Z_d\\cos kL+i\\rho_0c\\sin kL} .$$\n",
    "\n",
    "The bend (radius 10 mm, almost three canal radii) changes the plane wave only slightly."
   ]
  },
  {
   "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, velocity = 343.0, 1.204, 1e-3\n",
    "impedance = rho0 * c0\n",
    "length = (\n",
    "    0.0135 + 0.012575 - 2 * 0.010 * np.tan(np.radians(30.0)) + 0.010 * np.radians(60.0)\n",
    ")\n",
    "frequencies = np.geomspace(100.0, 10000.0, 121)\n",
    "eardrum = lambda f: impedance * (2.0 + 3.0j * (f / 1500.0 - 1500.0 / f))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` returns the canal with the named faces entrance, eardrum and wall. Curved quadratic\n",
    "tetrahedra of 1.5 mm (a 23rd of the wavelength at 10 kHz) and, for the mesh study, 1 mm fill it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "canal = load(\"ear_canal_transfer.step\")\n",
    "faces = canal.boundaries\n",
    "sizes = (0.0015, 0.0010)\n",
    "meshes = {\n",
    "    h: TetrahedralMesher(target_size=h, geometry_order=2).generate(canal) for h in sizes\n",
    "}\n",
    "\n",
    "view = plots.Camera(elevation=15, azimuth=-80)\n",
    "fig = plots.figure(1, 2, size=(15, 6.5))\n",
    "plots.geometry(\n",
    "    canal,\n",
    "    selection={\n",
    "        \"entrance\": faces.entrance,\n",
    "        \"eardrum\": faces.eardrum,\n",
    "        \"canal wall\": faces.wall,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Ear canal, 25 mm along its centre line (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0.0015],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{meshes[0.0015].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 volume forms and the\n",
    "traces of entrance and eardrum come from the space's `trace_data`. The eardrum carries the\n",
    "admittance $1/Z_d$, the entrance the load $i\\omega U\\int\\phi_i\\,\\mathrm dS$;\n",
    "`AcousticHarmonicPressure` sweeps the 121 frequencies. The mean pressures on entrance and eardrum\n",
    "give the input impedance $\\bar p_\\mathrm{entrance}/U$ and the gain\n",
    "$\\bar p_\\mathrm{drum}/\\bar p_\\mathrm{entrance}$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def solve_canal(h):\n",
    "    \"\"\"Mean pressure on entrance and eardrum over the sweep on one mesh.\"\"\"\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",
    "    traces = {\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 (\"entrance\", \"eardrum\")\n",
    "    }\n",
    "    weights = {face: trace @ np.ones(space.dof_count) for face, trace in traces.items()}\n",
    "    pressure = (\n",
    "        AcousticHarmonicPressure(\n",
    "            operator=ComplexPressurePencil(\n",
    "                volume,\n",
    "                boundary=PressureAdmittanceBoundary(\n",
    "                    lambda omega: traces[\"eardrum\"] / eardrum(omega.real / (2 * np.pi))\n",
    "                ),\n",
    "            ),\n",
    "            angular_frequencies=2 * np.pi * frequencies,\n",
    "            load=lambda omega: 1j * omega * velocity * weights[\"entrance\"],\n",
    "            linear_solver=spsolve,\n",
    "        )\n",
    "        .run()\n",
    "        .pressure\n",
    "    )\n",
    "    return dict(\n",
    "        space=space,\n",
    "        mesh=mesh,\n",
    "        pressure=pressure,\n",
    "        dofs=space.dof_count,\n",
    "        **{face: pressure @ weight / weight.sum() for face, weight in weights.items()}\n",
    "    )\n",
    "\n",
    "\n",
    "runs = {h: solve_canal(h) for h in sizes}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Input impedance and gain against the transmission line, in decibels, the frequency and height of\n",
    "the gain maximum, and the change between the two meshes. The largest deviations sit on the steep\n",
    "flanks of the sharp resonances, where a frequency shift of a few hertz - from the bend - changes\n",
    "the level a lot."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "k = 2 * np.pi * frequencies / c0\n",
    "Zd = eardrum(frequencies)\n",
    "line = dict(\n",
    "    z_in=impedance\n",
    "    * (Zd + 1j * impedance * np.tan(k * length))\n",
    "    / (impedance + 1j * Zd * np.tan(k * length)),\n",
    "    gain=Zd / (Zd * np.cos(k * length) + 1j * impedance * np.sin(k * length)),\n",
    ")\n",
    "fine = runs[sizes[-1]]\n",
    "result = dict(z_in=fine[\"entrance\"] / velocity, gain=fine[\"eardrum\"] / fine[\"entrance\"])\n",
    "print(\n",
    "    f\"centre-line length {1e3 * length:.2f} mm; unknowns {runs[sizes[0]]['dofs']} and {fine['dofs']}\"\n",
    ")\n",
    "for name, label in (\n",
    "    (\"z_in\", \"input impedance\"),\n",
    "    (\"gain\", \"pressure gain eardrum / entrance\"),\n",
    "):\n",
    "    decibels = np.abs(20 * np.log10(np.abs(result[name] / line[name])))\n",
    "    print(\n",
    "        f\"{label}: deviation from the transmission line median {np.median(decibels):.3f} dB, \"\n",
    "        f\"largest {np.max(decibels):.2f} dB at {frequencies[np.argmax(decibels)]:.0f} Hz\"\n",
    "    )\n",
    "level, line_level = 20 * np.log10(np.abs(result[\"gain\"])), 20 * np.log10(\n",
    "    np.abs(line[\"gain\"])\n",
    ")\n",
    "print(\n",
    "    f\"gain maximum: {level.max():.2f} dB at {frequencies[np.argmax(level)]:.0f} Hz; transmission line {line_level.max():.2f} dB at \"\n",
    "    f\"{frequencies[np.argmax(line_level)]:.0f} Hz (frequency grid 1/26 octave)\"\n",
    ")\n",
    "print(\n",
    "    f\"change between the meshes: input impedance {np.max(np.abs(fine['entrance'] / runs[sizes[0]]['entrance'] - 1)):.1e}, \"\n",
    "    f\"gain {np.max(np.abs(fine['eardrum'] / fine['entrance'] / (runs[sizes[0]]['eardrum'] / runs[sizes[0]]['entrance']) - 1)):.1e}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left: the sound pressure level on the canal wall at the gain maximum, for a velocity of 1 mm/s at\n",
    "the entrance. Middle and right: the input impedance and the gain against the transmission line."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "i = int(np.argmax(level))\n",
    "points = np.asarray(fine[\"mesh\"].coordinates)\n",
    "spl = 20 * np.log10(\n",
    "    np.abs(np.asarray(fine[\"space\"].evaluate(fine[\"pressure\"][i], points))) / 2e-5\n",
    ")\n",
    "fig = plots.figure(1, 3, size=(22, 6.5))\n",
    "plots.trisurface(\n",
    "    points,\n",
    "    np.asarray(fine[\"mesh\"].facets(faces.all)),\n",
    "    spl,\n",
    "    camera=view,\n",
    "    label=\"sound pressure level [dB]\",\n",
    "    title=f\"Sound pressure level at {frequencies[i]:.0f} Hz\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    frequencies,\n",
    "    {\"|Z_in| / rho c, simulation\": np.abs(result[\"z_in\"]) / impedance},\n",
    "    reference={\"|Z_in| / rho c, simulation\": np.abs(line[\"z_in\"]) / impedance},\n",
    "    scale=\"loglog\",\n",
    "    xlabel=\"frequency [Hz]\",\n",
    "    ylabel=\"|Z_in| / rho c\",\n",
    "    title=\"Input impedance (dashed: transmission line)\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    frequencies,\n",
    "    {\"simulation\": level},\n",
    "    reference={\"transmission line\": line_level},\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"frequency [Hz]\",\n",
    "    ylabel=\"20 log10 |p_drum / p_entrance| [dB]\",\n",
    "    title=\"Pressure gain from entrance to eardrum\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Replace the swept tube in `ear_canal_transfer_geometry.py` by a canal with a measured, varying\n",
    "cross-section and an eardrum inclined at 45°, and write the STEP file again; the transmission\n",
    "line then needs the area function and stops being exact, while the finite-element model stays as\n",
    "it is."
   ]
  }
 ]
}
