{
 "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": [
    "# Natural frequencies of a free cylinder (NAFEMS FV41)\n",
    "\n",
    "A thick-walled steel tube, inner radius 1.8 m, outer radius 2.2 m and 10 m long, is free in\n",
    "space. Its axisymmetric vibrations, in which every point moves only radially and axially, are a\n",
    "standard test of axisymmetric dynamic elements. Because the tube is unsupported, the first mode\n",
    "is the rigid motion along the axis at zero frequency; the elastic modes follow from\n",
    "\n",
    "$$K\\boldsymbol\\phi=\\omega^2M\\boldsymbol\\phi$$\n",
    "\n",
    "assembled on the meridian section with the volume element $2\\pi r\\,dr\\,dz$.\n",
    "\n",
    "Steel, $E=200$ GPa, $\\nu=0.3$, $\\rho=8000$ kg/m³. All faces are free.\n",
    "\n",
    "The cylinder comes from the CAD file `free_cylinder_axisymmetric_modes.step`, a 90-degree sector\n",
    "with the faces `inner`, `outer`, `bottom` and `top`; the script\n",
    "`free_cylinder_axisymmetric_modes_geometry.py` builds it with the CAD objects of OneSimulation.\n",
    "The model is two-dimensional: it lives on the meridian section $y=0$, where $x$ is the radius\n",
    "$r$.\n",
    "\n",
    "**Reference.** NAFEMS, *Selected Benchmarks for Natural Frequency Analysis*, test FV41 (free\n",
    "cylinder, axisymmetric vibration): 0, 243.53, 377.41, 394.11, 397.72 and 405.28 Hz. As a rough\n",
    "independent check, the first axial mode of a free bar of the same length has\n",
    "$f=\\sqrt{E/\\rho}\\,/(2L)=250$ Hz; the lateral inertia of the thick wall lowers it slightly."
   ]
  },
  {
   "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 TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange, RevolvedH1SpaceFactory\n",
    "from onesim.numerics.linear import SparseDirect, SparseSymmetricEigenSolver\n",
    "from onesim.physics.solid_mechanics import (\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",
    "`load` returns the sector, `section` its meridian section. Three meshes of triangles with cells of\n",
    "0.2 m, 0.1 m and 0.05 m."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "cylinder = load(\"free_cylinder_axisymmetric_modes.step\")\n",
    "faces = cylinder.boundaries\n",
    "meridian = cylinder.section((0, 1, 0), origin=(0, 0, 0))\n",
    "sizes = [0.2, 0.1, 0.05]\n",
    "meshes = [TriangularMesher(target_size=size).generate(meridian) for size in sizes]\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 7))\n",
    "plots.geometry(\n",
    "    cylinder,\n",
    "    selection={\n",
    "        \"inner\": faces.inner,\n",
    "        \"outer\": faces.outer,\n",
    "        \"ends\": faces.bottom | faces.top,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=25, azimuth=-60),\n",
    "    title=\"Sector of the tube with its named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Meridian section: {meshes[1].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`LinearElasticity` with axisymmetric kinematics: displacement components $u_r$ and $u_z$, strains\n",
    "$\\varepsilon_{rr},\\varepsilon_{zz},\\varepsilon_{\\theta\\theta}=u_r/r,\\gamma_{rz}$. The revolved\n",
    "finite-element space adds the factor $2\\pi r$ to every integral. The free tube has the rigid axial\n",
    "motion as a null mode, which the modal analysis keeps; a sparse shift-invert solve returns the\n",
    "eight modes nearest 300 Hz."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "steel = IsotropicSolid(\n",
    "    density=8000.0,\n",
    "    specific_heat_capacity=460.0,\n",
    "    thermal_conductivity=50.0,\n",
    "    youngs_modulus=200e9,\n",
    "    poisson_ratio=0.3,\n",
    "    thermal_expansion_coefficient=12e-6,\n",
    ")\n",
    "model = LinearElasticity(\n",
    "    domain=meridian.domain(), material=steel, kinematics=\"axisymmetric\"\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Free cylinder\",\n",
    "    geometry=meridian,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        TractionFree(boundary=meridian.boundaries.all, physics=model),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2), provider=RevolvedH1SpaceFactory()),\n",
    "    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=8,\n",
    "        target_frequency=300.0,\n",
    "        zero_eigenvalue_tolerance=1.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 six lowest frequencies on each mesh against the NAFEMS targets."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "target = np.array([0.0, 243.53, 377.41, 394.11, 397.72, 405.28])\n",
    "lowest = [np.sort(mode_set.frequencies)[:6] for mode_set in modes]\n",
    "print(\n",
    "    \"mode   NAFEMS [Hz]   \"\n",
    "    + \"   \".join(f\"{size:.2f} m mesh\" for size in sizes)\n",
    "    + \"   deviation on the finest mesh\"\n",
    ")\n",
    "for k, reference in enumerate(target):\n",
    "    print(\n",
    "        f\"{k + 1:4d} {reference:12.2f} \"\n",
    "        + \" \".join(f\"{frequencies[k]:13.2f}\" for frequencies in lowest)\n",
    "        + (\n",
    "            f\" {100 * (lowest[-1][k] / reference - 1):+14.3f} %\"\n",
    "            if reference\n",
    "            else f\" {'(rigid axial motion)':>22s}\"\n",
    "        )\n",
    "    )\n",
    "print(\n",
    "    f\"free-bar estimate of the first axial mode: {np.sqrt(200e9 / 8000.0) / 20:.1f} Hz\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The frequencies of the elastic modes on the three meshes against the targets, and the deviation\n",
    "over the cell size: already on the coarsest mesh the quadratic elements are converged, and what\n",
    "is left, a few parts in ten thousand, is of the order of the rounding of the published values."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(15, 5))\n",
    "plots.bars(\n",
    "    [f\"mode {k}\" for k in range(2, 7)],\n",
    "    {f\"{size:.2f} m mesh\": frequencies[1:] for size, frequencies in zip(sizes, lowest)},\n",
    "    reference={\"NAFEMS FV41\": target[1:]},\n",
    "    ylabel=\"natural frequency [Hz]\",\n",
    "    title=\"Axisymmetric modes of the free cylinder\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    sizes,\n",
    "    {\n",
    "        f\"mode {k}\": [\n",
    "            abs(frequencies[k - 1] / target[k - 1] - 1) for frequencies in lowest\n",
    "        ]\n",
    "        for k in range(2, 7)\n",
    "    },\n",
    "    markers=True,\n",
    "    scale=\"loglog\",\n",
    "    xlabel=\"cell size [m]\",\n",
    "    ylabel=\"relative deviation from NAFEMS\",\n",
    "    title=\"Mesh study\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the wall thinner in `free_cylinder_axisymmetric_modes_geometry.py` and write the STEP file\n",
    "again: the breathing mode near the ring frequency $\\sqrt{E/\\rho}/(2\\pi R)$ separates from the\n",
    "axial modes. Clamp one end to compare with the supported variants of the benchmark."
   ]
  }
 ]
}
