{
 "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": [
    "# Free vibration modes of a turbocharger rotor\n",
    "\n",
    "The rotor of a turbocharger spins at more than 100 000 rpm. Its natural frequencies decide where\n",
    "critical speeds can occur, and the first step of every rotordynamic analysis is the free-free\n",
    "modal analysis of the rotor alone, which can be checked against a modal test on a soft suspension.\n",
    "A free body has six rigid-body modes at zero frequency; above them follow pairs of bending modes\n",
    "(an axisymmetric rotor bends equally in every plane), the torsional modes and the axial modes.\n",
    "\n",
    "**Setup.** A steel rotor ($E=205$ GPa, $\\nu=0.29$, $\\rho=7850$ kg/m³): a shaft of 10 mm diameter\n",
    "and 150 mm length, the turbine wheel as a 44 mm disk, 16 mm thick, at one end, the compressor wheel\n",
    "as a 50 mm disk, 12 mm thick, at the other, and a 18 mm thrust collar near the compressor. The\n",
    "wheels are solid disks here, without blades. The rotor comes from the CAD file\n",
    "`turbocharger_rotor_free_modes.step`, written by `turbocharger_rotor_free_modes_geometry.py` with\n",
    "the CAD objects of OneSimulation. The analysis is at standstill: gyroscopic effects of the spinning\n",
    "rotor are not included.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| all faces | free (free-free rotor) |\n",
    "\n",
    "**Reference.** An independent 1D model of the rotor: 3D Euler-Bernoulli beam elements along the\n",
    "axis with the stepped cross-sections of shaft, wheels and collar, consistent mass with rotary\n",
    "inertia, and also free at both ends. It represents the bending of the shaft well; the wheels act\n",
    "in it as rigid, heavy sections. Its torsional and axial modes are exact for a stepped bar."
   ]
  },
  {
   "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, 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",
    "    FrameMember,\n",
    "    LinearElasticity,\n",
    "    SpatialFrame,\n",
    "    TractionFree,\n",
    "    frame_modes,\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",
    "`load` returns the rotor with its named faces; two meshes of curved quadratic tetrahedra, 5 mm\n",
    "and 3.5 mm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "rotor = load(\"turbocharger_rotor_free_modes.step\")\n",
    "faces = rotor.boundaries\n",
    "sizes = [0.005, 0.0035]\n",
    "meshes = [\n",
    "    with_order(\n",
    "        TetrahedralMesher(target_size=size, curvature_angle=0.4).generate(rotor), 2\n",
    "    )\n",
    "    for size in sizes\n",
    "]\n",
    "\n",
    "view = plots.Camera(elevation=20, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.geometry(\n",
    "    rotor,\n",
    "    selection={\n",
    "        \"turbine wheel\": faces.turbine,\n",
    "        \"compressor wheel\": faces.compressor,\n",
    "        \"shaft\": faces.shaft,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Turbocharger rotor 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\"Finer mesh: {meshes[-1].cell_count} curved tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3D model\n",
    "\n",
    "`LinearElasticity` without supports; `structural_modes` keeps the six rigid-body modes apart and\n",
    "returns the lowest eight elastic modes with them."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "youngs_modulus, poisson_ratio, density = 205e9, 0.29, 7850.0\n",
    "steel = IsotropicSolid(\n",
    "    density=density,\n",
    "    specific_heat_capacity=460.0,\n",
    "    thermal_conductivity=40.0,\n",
    "    youngs_modulus=youngs_modulus,\n",
    "    poisson_ratio=poisson_ratio,\n",
    "    thermal_expansion_coefficient=12e-6,\n",
    ")\n",
    "model = LinearElasticity(domain=rotor.volume, material=steel)\n",
    "problem = Problem(\n",
    "    name=\"Free rotor\",\n",
    "    geometry=rotor,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(TractionFree(boundary=faces.all, physics=model),),\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=14,\n",
    "        target_frequency=0.0,\n",
    "        zero_eigenvalue_tolerance=1.0,\n",
    "        eigensolver=SparseSymmetricEigenSolver(tolerance=1e-10),\n",
    "    )\n",
    "    for result in results\n",
    "]\n",
    "solid = [np.sort(np.asarray(mode_set.frequencies))[6:] for mode_set in modes]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Beam model of the rotor\n",
    "\n",
    "The axis is divided at every change of section; long shaft pieces get extra joints. Each member\n",
    "carries the area, second moment and torsion constant of its circular section. The beam model is\n",
    "solved free-free as well (`supports=()` with a zero-eigenvalue tolerance), and each mode is\n",
    "classified by the joint motion that dominates it (rotations weighted with a 10 mm radius)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "sections = [\n",
    "    (0.000, 0.016, 0.022),\n",
    "    (0.016, 0.110, 0.005),\n",
    "    (0.110, 0.116, 0.009),\n",
    "    (0.116, 0.138, 0.005),\n",
    "    (0.138, 0.150, 0.025),\n",
    "]\n",
    "stations = np.unique(\n",
    "    np.concatenate(\n",
    "        [\n",
    "            np.linspace(start, end, max(2, int(round((end - start) / 0.004)) + 1))\n",
    "            for start, end, _ in sections\n",
    "        ]\n",
    "    )\n",
    ")\n",
    "radius_at = lambda z: next(\n",
    "    r for start, end, r in sections if start - 1e-12 <= z <= end + 1e-12\n",
    ")\n",
    "beam = SpatialFrame(\n",
    "    joints=np.column_stack((0 * stations, 0 * stations, stations)),\n",
    "    members=tuple(\n",
    "        FrameMember(\n",
    "            name=f\"segment {i}\",\n",
    "            start=i,\n",
    "            end=i + 1,\n",
    "            youngs_modulus=youngs_modulus,\n",
    "            area=np.pi * radius_at(z) ** 2,\n",
    "            bending_inertia_y=np.pi * radius_at(z) ** 4 / 4,\n",
    "            bending_inertia_z=np.pi * radius_at(z) ** 4 / 4,\n",
    "            torsion_constant=np.pi * radius_at(z) ** 4 / 2,\n",
    "            shear_modulus=youngs_modulus / (2 * (1 + poisson_ratio)),\n",
    "            local_y=(1.0, 0.0, 0.0),\n",
    "        )\n",
    "        for i, z in enumerate(0.5 * (stations[1:] + stations[:-1]))\n",
    "    ),\n",
    ")\n",
    "beam_modes = frame_modes(\n",
    "    beam,\n",
    "    supports=(),\n",
    "    density=density,\n",
    "    mode_count=14,\n",
    "    target_frequency=1.0,\n",
    "    zero_eigenvalue_tolerance=1.0,\n",
    "    eigensolver=SparseSymmetricEigenSolver(tolerance=1e-12),\n",
    ")\n",
    "ranking = np.argsort(beam_modes.frequencies)[6:]\n",
    "kind = lambda u: (\"bending\", \"axial\", \"torsion\")[\n",
    "    int(\n",
    "        np.argmax(\n",
    "            [\n",
    "                np.linalg.norm(u[:, :2]) + 0.01 * np.linalg.norm(u[:, 3:5]),\n",
    "                np.linalg.norm(u[:, 2]),\n",
    "                0.01 * np.linalg.norm(u[:, 5]),\n",
    "            ]\n",
    "        )\n",
    "    )\n",
    "]\n",
    "beam_frequencies = np.asarray(beam_modes.frequencies)[ranking]\n",
    "beam_kinds = [kind(beam_modes.mode_displacements(int(k))) for k in ranking]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison of the two models\n",
    "\n",
    "Each beam mode is paired with the nearest 3D frequency; bending modes appear twice in both models.\n",
    "The torsional and the first bending pair agree within 2 %. In the higher bending pairs the wheels\n",
    "wobble and bend themselves, and shear deformation of the short shaft pieces grows; the beam model\n",
    "keeps the wheels rigid and the sections plane without shear, so it is stiffer there by 6-10 %."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "print(\n",
    "    f\"rigid-body modes found: {[int(np.sum(np.asarray(mode_set.frequencies) < 1.0)) for mode_set in modes]} (3D, both meshes), \"\n",
    "    f\"{int(np.sum(np.asarray(beam_modes.frequencies) < 1.0))} (beam model)\"\n",
    ")\n",
    "print(\n",
    "    f\"{'beam mode':>18s} {'beam [Hz]':>10s} \"\n",
    "    + \" \".join(f\"{f'3D, {1e3 * size:.1f} mm [Hz]':>18s}\" for size in sizes)\n",
    "    + f\" {'beam / 3D':>10s}\"\n",
    ")\n",
    "for f, label in zip(beam_frequencies, beam_kinds):\n",
    "    nearest = [values[np.argmin(np.abs(values - f))] for values in solid]\n",
    "    print(\n",
    "        f\"{label:>18s} {f:10.1f} \"\n",
    "        + \" \".join(f\"{value:18.1f}\" for value in nearest)\n",
    "        + f\" {100 * (f / nearest[-1] - 1):+9.2f} %\"\n",
    "    )\n",
    "print(\n",
    "    f\"change of the 3D frequencies between the meshes: at most {100 * np.abs(solid[1] / solid[0] - 1).max():.3f} %\"\n",
    ")\n",
    "print(\n",
    "    f\"first bending mode {solid[-1][np.argmin(np.abs(solid[-1] - beam_frequencies[beam_kinds.index('bending')]))] * 60:.0f} per minute at standstill\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The first bending mode and the first torsional mode of the 3D rotor, and the frequencies of both\n",
    "models side by side."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "displacement = results[-1].field(model.displacement)\n",
    "order = np.argsort(modes[-1].frequencies)\n",
    "first_bending = int(\n",
    "    order[\n",
    "        6\n",
    "        + int(\n",
    "            np.argmin(np.abs(solid[-1] - beam_frequencies[beam_kinds.index(\"bending\")]))\n",
    "        )\n",
    "    ]\n",
    ")\n",
    "first_torsion = int(\n",
    "    order[\n",
    "        6\n",
    "        + int(\n",
    "            np.argmin(np.abs(solid[-1] - beam_frequencies[beam_kinds.index(\"torsion\")]))\n",
    "        )\n",
    "    ]\n",
    ")\n",
    "shape = lambda k: displacement.with_states(\n",
    "    (0.0,), (modes[-1].mode_displacements(k).reshape(np.shape(displacement.values)),)\n",
    ")\n",
    "fig = plots.figure(1, 3, size=(19, 6))\n",
    "for k, (index, title) in enumerate(\n",
    "    ((first_bending, \"First bending mode\"), (first_torsion, \"First torsional mode\"))\n",
    "):\n",
    "    plots.surface(\n",
    "        shape(index),\n",
    "        component=lambda u, position: np.linalg.norm(u, axis=1),\n",
    "        deformation=shape(index),\n",
    "        deformation_scale=0.012 / np.abs(modes[-1].mode_displacements(index)).max(),\n",
    "        camera=view,\n",
    "        label=\"relative amplitude\",\n",
    "        title=f\"{title}, {np.asarray(modes[-1].frequencies)[index]:.0f} Hz\",\n",
    "        ax=fig[k],\n",
    "    )\n",
    "plots.bars(\n",
    "    [f\"{i + 1}\\n{label}\" for i, label in enumerate(beam_kinds)],\n",
    "    {\n",
    "        f\"3D, {1e3 * sizes[-1]:.1f} mm\": [\n",
    "            solid[-1][np.argmin(np.abs(solid[-1] - f))] for f in beam_frequencies\n",
    "        ]\n",
    "    },\n",
    "    reference={\"beam model\": list(beam_frequencies)},\n",
    "    ylabel=\"natural frequency [Hz]\",\n",
    "    title=\"Free-free natural frequencies\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Give the compressor wheel the density and stiffness of aluminium as a separate STEP part, add the\n",
    "blades, or support the rotor on bearing springs and follow the critical speeds. With rotation the\n",
    "gyroscopic moments of the wheels split each bending pair into a forward and a backward whirl."
   ]
  }
 ]
}
