{
 "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": [
    "# Tuning fork: the 440 Hz prong mode\n",
    "\n",
    "A tuning fork sounds in its **prong mode**: the two prongs swing towards and away from each\n",
    "other in the plane of the fork, so the forces at the bridge cancel and the stem barely moves.\n",
    "Treating each prong as a cantilever of length $L$ and thickness $h$ in the direction of motion,\n",
    "clamped at the bottom of the gap, gives the classical estimate\n",
    "\n",
    "$$f=\\frac{\\beta_1^2}{2\\pi}\\,\\frac{h}{L^2}\\sqrt{\\frac{E}{12\\rho}},\\qquad \\beta_1=1.8751 .$$\n",
    "\n",
    "For steel ($E=200$ GPa, $\\rho=7850$ kg/m³) and $h=5$ mm the estimate gives 440 Hz for\n",
    "$L=96.3$ mm, and the prongs of this fork are 96 mm long. The real prongs, however, are not\n",
    "clamped: the bridge and the U-shaped bend between them flex as well, and the fork sounds lower.\n",
    "The fork is held at the lower end of its stem.\n",
    "\n",
    "The fork comes from the CAD file `tuning_fork_440_hz.step` with the face groups `tips` and\n",
    "`stem_end`; the script `tuning_fork_440_hz_geometry.py` builds it with the CAD objects of\n",
    "OneSimulation.\n",
    "\n",
    "**Reference.** T. D. Rossing, F. R. Moore and P. A. Wheeler, *The Science of Sound*, 3rd ed.,\n",
    "Addison-Wesley (2002), Sec. 13.4 (tuning forks); the cantilever factor $\\beta_1$ from\n",
    "W. Weaver, S. P. Timoshenko and D. H. Young, *Vibration Problems in Engineering*, 5th ed., Wiley\n",
    "(1990), Sec. 5.3."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import TetrahedralMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect, SparseSymmetricEigenSolver\n",
    "from onesim.physics.solid_mechanics import (\n",
    "    FixedDisplacement,\n",
    "    LinearElasticity,\n",
    "    TractionFree,\n",
    "    structural_modes,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "Two meshes of quadratic tetrahedra with cells of 4 mm and 3 mm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fork = load(\"tuning_fork_440_hz.step\")\n",
    "faces = fork.boundaries\n",
    "sizes = [0.004, 0.003]\n",
    "meshes = [TetrahedralMesher(target_size=size).generate(fork) for size in sizes]\n",
    "\n",
    "view = plots.Camera(elevation=20, azimuth=-60, distance=1.25)\n",
    "fig = plots.figure(1, 2, size=(13, 7))\n",
    "plots.geometry(\n",
    "    fork,\n",
    "    selection={\"prong tips\": faces.tips, \"held stem end\": faces.stem_end},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Tuning fork with its named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[-1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{meshes[-1].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The stem end is clamped; the modal analysis solves $K\\boldsymbol\\phi=\\omega^2M\\boldsymbol\\phi$\n",
    "with a sparse shift-invert eigen solve for the four modes closest to 440 Hz on each mesh."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "youngs_modulus, density, prong, length = 200e9, 7850.0, 0.005, 0.096\n",
    "steel = IsotropicSolid(\n",
    "    density=density,\n",
    "    specific_heat_capacity=460.0,\n",
    "    thermal_conductivity=50.0,\n",
    "    youngs_modulus=youngs_modulus,\n",
    "    poisson_ratio=0.29,\n",
    "    thermal_expansion_coefficient=12e-6,\n",
    ")\n",
    "model = LinearElasticity(domain=fork.volume, material=steel)\n",
    "problem = Problem(\n",
    "    name=\"Tuning fork\",\n",
    "    geometry=fork,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        FixedDisplacement(\n",
    "            boundary=faces.stem_end, physics=model, value=(0.0, 0.0, 0.0)\n",
    "        ),\n",
    "        TractionFree(boundary=faces.all - faces.stem_end, physics=model),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "results = [\n",
    "    Simulation(problem=problem, mesh=mesh, numerics=numerics).solve_stationary()\n",
    "    for mesh in meshes\n",
    "]\n",
    "modes = [\n",
    "    structural_modes(\n",
    "        result,\n",
    "        model,\n",
    "        mode_count=4,\n",
    "        target_frequency=440.0,\n",
    "        eigensolver=SparseSymmetricEigenSolver(tolerance=1e-10),\n",
    "    )\n",
    "    for result in results\n",
    "]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The prong mode is the one in which the two prong tips move furthest apart along $x$, the\n",
    "direction of the prong thickness."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "coordinates = [\n",
    "    np.asarray(result.operators[model.model_id].space.dof_coordinates)\n",
    "    for result in results\n",
    "]\n",
    "spreads = [\n",
    "    [\n",
    "        abs(\n",
    "            mode_set.mode_displacements(i)[\n",
    "                (nodes[:, 2] > length - 1e-6) & (nodes[:, 0] > 0), 0\n",
    "            ].mean()\n",
    "            - mode_set.mode_displacements(i)[\n",
    "                (nodes[:, 2] > length - 1e-6) & (nodes[:, 0] < 0), 0\n",
    "            ].mean()\n",
    "        )\n",
    "        for i in range(mode_set.mode_count)\n",
    "    ]\n",
    "    for mode_set, nodes in zip(modes, coordinates)\n",
    "]\n",
    "frequencies = [\n",
    "    mode_set.frequencies[int(np.argmax(spread))]\n",
    "    for mode_set, spread in zip(modes, spreads)\n",
    "]\n",
    "spread, prong_mode = spreads[-1], int(np.argmax(spreads[-1]))\n",
    "estimate = (\n",
    "    1.8751**2\n",
    "    / (2 * np.pi)\n",
    "    * prong\n",
    "    / length**2\n",
    "    * np.sqrt(youngs_modulus / (12 * density))\n",
    ")\n",
    "\n",
    "print(\"mode   frequency [Hz]   tip spread along x\")\n",
    "for i, (frequency, motion) in enumerate(zip(modes[-1].frequencies, spread), start=1):\n",
    "    print(\n",
    "        f\"{i:4d} {frequency:16.1f} {motion / max(spread):18.3f}\"\n",
    "        + (\"   <- prong mode\" if i - 1 == prong_mode else \"\")\n",
    "    )\n",
    "print(\n",
    "    f\"prong mode: {frequencies[0]:.1f} Hz on the 4 mm mesh, {frequencies[1]:.1f} Hz on the 3 mm mesh \"\n",
    "    f\"(change {100 * (frequencies[1] / frequencies[0] - 1):+.2f} %)\"\n",
    ")\n",
    "print(\n",
    "    f\"cantilever estimate {estimate:.1f} Hz: the fork sounds {100 * (1 - frequencies[-1] / estimate):.1f} % lower, \"\n",
    "    f\"{12 * np.log2(estimate / frequencies[-1]):.2f} semitones below the design pitch\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The prong mode on the fork (arbitrary amplitude) and the four natural frequencies next to 440 Hz\n",
    "with the cantilever estimate."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "displacement = results[-1].field(model.displacement)\n",
    "shape = displacement.with_states(\n",
    "    (0.0,),\n",
    "    (modes[-1].mode_displacements(prong_mode).reshape(np.shape(displacement.values)),),\n",
    ")\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.surface(\n",
    "    shape,\n",
    "    component=lambda u, position: np.linalg.norm(u, axis=1),\n",
    "    deformation=shape,\n",
    "    deformation_scale=0.004 / np.abs(modes[-1].mode_displacements(prong_mode)).max(),\n",
    "    camera=view,\n",
    "    label=\"relative amplitude\",\n",
    "    title=f\"Prong mode, {frequencies[-1]:.0f} Hz\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.bars(\n",
    "    [f\"{i}\" for i in range(1, modes[-1].mode_count + 1)],\n",
    "    {\"simulation\": modes[-1].frequencies},\n",
    "    reference={\n",
    "        \"cantilever estimate of the prong mode\": [\n",
    "            estimate if i == prong_mode else np.nan for i in range(modes[-1].mode_count)\n",
    "        ]\n",
    "    },\n",
    "    ylabel=\"natural frequency [Hz]\",\n",
    "    title=\"Natural frequencies of the held fork next to 440 Hz\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "The example \"Tuning a fork to 440 Hz by optimising the prong length\" shortens the prongs until the\n",
    "fork sounds exactly at concert pitch. Change the material in the model to brass or aluminium:\n",
    "the pitch scales with $\\sqrt{E/\\rho}$."
   ]
  }
 ]
}
