{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "tuning_fork_prong_length_optim-1",
   "source": [
    "# Tuning a fork to concert A\n",
    "\n",
    "The pitch of a free steel tuning fork depends on the length of its prongs. Starting from round 78 mm prongs joined by a semicircular bend, change their length until the opening mode reaches 440 Hz. Every pitch in the search comes from a three-dimensional elastic eigenmode calculation."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "id": "tuning_fork_prong_length_optim-2",
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d3 import Box\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import TetrahedralMesher, with_order\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",
    "    FixedDisplacementComponents, LinearElasticity, TractionFree, 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": {},
   "id": "tuning_fork_prong_length_optim-3",
   "source": [
    "## Round prongs and an unrestrained handle\n",
    "\n",
    "The STEP file contains a fork with 2.5 mm prong radius and 7.5 mm bend radius. In the opening mode both arms bend equally in opposite directions. Two mirror planes let a quarter of the solid represent the full fork. On each cut face only the displacement normal to that plane is zero. The handle is free to vibrate."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "id": "tuning_fork_prong_length_optim-4",
   "source": [
    "mm, target = 1e-3, 440.0\n",
    "fork = load(\"tuning_fork_prong_length_optimization.step\")\n",
    "window = Box(length=0.02, width=0.02, height=0.15, origin=(0, 0, -0.05))\n",
    "steel = IsotropicSolid(density=7850, specific_heat_capacity=460, thermal_conductivity=44,\n",
    "                       youngs_modulus=205e9, poisson_ratio=0.285, thermal_expansion_coefficient=12e-6)\n",
    "fine_size = 0.85*mm\n",
    "method = Numerics(spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect())\n",
    "view = plots.Camera(elevation=16, azimuth=-67, roll=-28, distance=1.24)\n",
    "fig = plots.figure(1, 2, size=(9.5, 4.6))\n",
    "plots.geometry(fork, selection={\"Steel\": fork.boundaries.all-fork.boundaries.tips, \"Tips\": fork.boundaries.tips}, labels=False, camera=view,\n",
    "               title=\"Round prongs and handle\", ax=fig[0])\n",
    "plots.mesh(with_order(TetrahedralMesher(target_size=fine_size).generate(fork & window), 2), groups=(\"all\",), legend=False, camera=view,\n",
    "           title=\"Refined quarter of the starting fork\", ax=fig[1])\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "tuning_fork_prong_length_optim-5",
   "source": [
    "## Find the prong length\n",
    "\n",
    "The target is the concert A of ISO 16. Start at two lengths on opposite sides of the target. Each secant update interpolates the latest two pitch errors and then remeshes the proposed geometry. The proposed lengths are rounded to the nearest micrometre. A second search on a denser mesh starts at the first optimum. Its first correction uses the pitch slope from the coarser solve. For an independent starting estimate, Euler–Bernoulli theory treats each arm as a circular cantilever with effective length equal to the straight prong plus one quarter of the bend circumference."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "id": "tuning_fork_prong_length_optim-6",
   "source": [
    "effective = np.sqrt(1.875104**2 * 2.5*mm/2 * np.sqrt(205e9/7850) / (2*np.pi*target))\n",
    "beam_length = effective/mm - np.pi*7.5/2\n",
    "print(f\"Isolated-cantilever estimate: {beam_length:.2f} mm\")\n",
    "search = {}\n",
    "slope = None\n",
    "for size, label in ((3*mm, \"Coarse\"), (fine_size, \"Refined\")):\n",
    "    lengths, pitches = ([77.8, 80.0] if slope is None else [length]), []\n",
    "    for trial in range(5):\n",
    "        length = lengths[trial]\n",
    "        quarter = fork.move_faces(fork.boundaries.tips, (0, 0, (length-78)*mm)) & window\n",
    "        faces = [quarter.select(faces=lambda face, k=k: face.kind == \"plane\" and abs(face.center[k]) < 1e-8)\n",
    "                 for k in (0, 1)]\n",
    "        model = LinearElasticity(domain=quarter.volume, material=steel)\n",
    "        symmetry = tuple(FixedDisplacementComponents(physics=model, boundary=face, components=(axis,), value=0)\n",
    "                         for face, axis in zip(faces, (\"x\", \"y\")))\n",
    "        free = TractionFree(physics=model, boundary=quarter.boundaries.all-(faces[0] | faces[1]))\n",
    "        problem = Problem(name=\"Free tuning fork\", geometry=quarter, physics=(model,), boundary_conditions=(*symmetry, free))\n",
    "        mesh = with_order(TetrahedralMesher(target_size=size).generate(quarter), 2)\n",
    "        result = Simulation(problem=problem, mesh=mesh, numerics=method).solve_stationary()\n",
    "        modes = structural_modes(result, model, mode_count=2, target_frequency=target, zero_eigenvalue_tolerance=1.0,\n",
    "                                 eigensolver=SparseSymmetricEigenSolver(tolerance=1e-8))\n",
    "        index = int(np.argmin(abs(np.asarray(modes.frequencies)-target)))\n",
    "        pitch = modes.frequencies[index]\n",
    "        pitches.append(pitch)\n",
    "        print(f\"{label}: {length:.3f} mm, {pitch:.3f} Hz ({len(mesh.coordinates)} nodes, {mesh.cell_count} tetrahedra)\")\n",
    "        if len(pitches) >= 2:\n",
    "            slope = (pitches[-1]-pitches[-2]) / (lengths[-1]-lengths[-2])\n",
    "        if abs(pitch-target) < 0.05:\n",
    "            break\n",
    "        if len(pitches) == len(lengths) and trial < 4:\n",
    "            lengths.append(round(length-(pitch-target)/slope, 3))\n",
    "    order = np.argsort(lengths)\n",
    "    search[label] = (np.asarray(lengths)[order], np.asarray(pitches)[order])\n",
    "print(f\"Final length {length:.3f} mm, {length-beam_length:+.2f} mm from the cantilever estimate.\")\n",
    "print(f\"Pitch error {pitch-target:+.3f} Hz\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "tuning_fork_prong_length_optim-7",
   "source": [
    "## The tuned mode\n",
    "\n",
    "The mode is displayed at arbitrary amplitude. The second panel shows the solved designs and their target pitch."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "id": "tuning_fork_prong_length_optim-8",
   "source": [
    "displacement = result.field(model.displacement)\n",
    "motion = modes.mode_displacements(index)\n",
    "amplitude = np.linalg.norm(motion, axis=1).max()\n",
    "shape = displacement.with_states((0.0,), (motion.reshape(displacement.values.shape),))\n",
    "fig = plots.figure(1, 2, size=(10.5, 4.6))\n",
    "plots.surface(shape, component=lambda u, position: np.linalg.norm(u, axis=1)/amplitude,\n",
    "              deformation=shape, deformation_scale=0.003/abs(motion).max(), camera=view,\n",
    "              title=\"Opening mode of one prong\", label=\"Relative amplitude\", ax=fig[0])\n",
    "plots.line(y=search, markers=True,\n",
    "           hlines={\"Concert A\": target}, xlabel=\"Straight prong length [mm]\", ylabel=\"Frequency [Hz]\",\n",
    "           title=\"Choosing the prong length\", ax=fig[1])\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
