{
 "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 an in-plane frame with a mass and its rotary inertia\n",
    "\n",
    "A heavy component on a light supporting structure, such as a motor on a bracket or a camera on\n",
    "a mast, dominates the dynamics: the structure acts as a spring, the component as a mass. A compact\n",
    "component does not only translate but also rotates, so besides its mass $m$ its mass moment of\n",
    "inertia $J$ enters the natural frequencies.\n",
    "\n",
    "**Setup.** A frame in the $xz$ plane: a column of height $H=2$ m, clamped at the base, and a\n",
    "horizontal arm of length $L=1.5$ m, rigidly connected at the corner. Both are steel sections with\n",
    "$E=210$ GPa, $A=5\\cdot10^{-3}$ m² and $I=8\\cdot10^{-6}$ m⁴ for in-plane bending. At the end of\n",
    "the arm sits a machine of $m=200$ kg and $J=60$ kg m². Only in-plane motion is allowed: at every\n",
    "joint the out-of-plane translation and the two out-of-plane rotations are held.\n",
    "\n",
    "| joint | condition |\n",
    "|---|---|\n",
    "| base | clamped |\n",
    "| corner | rigid connection of column and arm |\n",
    "| arm end | point mass $m$ and rotary inertia $J$ |\n",
    "| all joints | in-plane motion only ($u_y=0$, $\\theta_x=\\theta_z=0$) |\n",
    "\n",
    "**Reference.** If the frame's own mass is neglected, the arm end has three degrees of freedom,\n",
    "$(u_x, u_z, \\theta_y)$. The unit-load method gives the flexibility matrix of the clamped L-frame at\n",
    "that point (e.g. Hibbeler, *Structural Analysis*, Ch. 9), from bending and the axial strain of arm\n",
    "and column,\n",
    "\n",
    "$$\\mathbf F=\\frac1{EI}\\begin{pmatrix} H^3/3 & LH^2/2 & H^2/2\\\\ LH^2/2 & L^3/3+L^2H & L^2/2+LH\\\\\n",
    "  H^2/2 & L^2/2+LH & L+H\\end{pmatrix}+\\frac1{EA}\\begin{pmatrix}L&0&0\\\\0&H&0\\\\0&0&0\\end{pmatrix},$$\n",
    "\n",
    "and the natural frequencies follow from $\\det\\!\\big(\\mathbf F^{-1}-\\omega^2\\,\\mathrm{diag}(m,m,J)\\big)=0$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.numerics.linear import SparseSymmetricEigenSolver\n",
    "from onesim.physics.solid_mechanics import FrameMember, SpatialFrame, frame_modes\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Frame model\n",
    "\n",
    "The column and the arm are divided into $n$ beam elements each; the joints lie in the $xz$\n",
    "plane. Four meshes, $n=1$ to $8$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "height, arm, youngs_modulus, area, inertia = 2.0, 1.5, 210e9, 5e-3, 8e-6\n",
    "mass, rotary = 200.0, 60.0\n",
    "joints = lambda n: np.vstack(\n",
    "    (\n",
    "        np.column_stack(\n",
    "            (np.zeros(n + 1), np.zeros(n + 1), np.linspace(0, height, n + 1))\n",
    "        ),\n",
    "        np.column_stack(\n",
    "            (np.linspace(0, arm, n + 1)[1:], np.zeros(n), np.full(n, height))\n",
    "        ),\n",
    "    )\n",
    ")\n",
    "frame = lambda n: SpatialFrame(\n",
    "    joints=joints(n),\n",
    "    members=tuple(\n",
    "        FrameMember(\n",
    "            name=f\"member {i}\",\n",
    "            start=i,\n",
    "            end=i + 1,\n",
    "            youngs_modulus=youngs_modulus,\n",
    "            area=area,\n",
    "            bending_inertia_y=inertia,\n",
    "            bending_inertia_z=inertia,\n",
    "            torsion_constant=2 * inertia,\n",
    "            shear_modulus=81e9,\n",
    "        )\n",
    "        for i in range(2 * n)\n",
    "    ),\n",
    ")\n",
    "supports = lambda n: (\n",
    "    *((0, dof, 0.0) for dof in (\"x\", \"y\", \"z\", \"rx\", \"ry\", \"rz\")),\n",
    "    *((joint, dof, 0.0) for joint in range(1, 2 * n + 1) for dof in (\"y\", \"rx\", \"rz\")),\n",
    ")\n",
    "divisions = [1, 2, 4, 8]\n",
    "solve = lambda n, density: frame_modes(\n",
    "    frame(n),\n",
    "    supports=supports(n),\n",
    "    density=density,\n",
    "    mode_count=3,\n",
    "    target_frequency=0.0,\n",
    "    eigensolver=SparseSymmetricEigenSolver(tolerance=1e-12),\n",
    "    joint_masses={2 * n: (mass, (0.0, rotary, 0.0))},\n",
    ")\n",
    "light = {n: solve(n, 1e-6) for n in divisions}\n",
    "steel = {n: solve(n, 7850.0) for n in divisions}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the massless frame\n",
    "\n",
    "With a negligible member density the frame is exactly the massless spring of the reference, for\n",
    "any number of elements. With the steel density the column adds 79 kg and the arm 59 kg of distributed mass and\n",
    "lower the frequencies; the refined meshes converge to the frame with its own mass."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "flexibility = np.array(\n",
    "    [\n",
    "        [height**3 / 3, arm * height**2 / 2, height**2 / 2],\n",
    "        [arm * height**2 / 2, arm**3 / 3 + arm**2 * height, arm**2 / 2 + arm * height],\n",
    "        [height**2 / 2, arm**2 / 2 + arm * height, arm + height],\n",
    "    ]\n",
    ") / (youngs_modulus * inertia) + np.diag([arm, height, 0.0]) / (youngs_modulus * area)\n",
    "reference = np.sort(\n",
    "    np.sqrt(\n",
    "        np.linalg.eigvals(\n",
    "            np.linalg.inv(flexibility) @ np.diag([1 / mass, 1 / mass, 1 / rotary])\n",
    "        ).real\n",
    "    )\n",
    ") / (2 * np.pi)\n",
    "print(f\"{'':28s} {'f1 [Hz]':>10s} {'f2 [Hz]':>10s} {'f3 [Hz]':>10s}\")\n",
    "print(\n",
    "    f\"{'closed form, massless frame':28s} \" + \" \".join(f\"{f:10.3f}\" for f in reference)\n",
    ")\n",
    "for n, modes in light.items():\n",
    "    print(\n",
    "        f\"{f'massless members, n = {n}':28s} \"\n",
    "        + \" \".join(f\"{f:10.3f}\" for f in np.sort(modes.frequencies))\n",
    "        + \"   deviation \"\n",
    "        + \", \".join(\n",
    "            f\"{100 * (f / r - 1):+.1e} %\"\n",
    "            for f, r in zip(np.sort(modes.frequencies), reference)\n",
    "        )\n",
    "    )\n",
    "for n, modes in steel.items():\n",
    "    print(\n",
    "        f\"{f'steel members, n = {n}':28s} \"\n",
    "        + \" \".join(f\"{f:10.3f}\" for f in np.sort(modes.frequencies))\n",
    "    )\n",
    "point_only = frame_modes(\n",
    "    frame(8),\n",
    "    supports=supports(8),\n",
    "    density=1e-6,\n",
    "    mode_count=3,\n",
    "    target_frequency=0.0,\n",
    "    eigensolver=SparseSymmetricEigenSolver(tolerance=1e-12),\n",
    "    joint_masses={16: mass},\n",
    ")\n",
    "print(\n",
    "    \"the rotary inertia matters: without J the massless frame would have \"\n",
    "    + \", \".join(f\"{f:.3f} Hz\" for f in np.sort(point_only.frequencies)[:2])\n",
    "    + \" instead of \"\n",
    "    + \", \".join(f\"{f:.3f} Hz\" for f in reference[:2])\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The two lowest mode shapes of the steel frame ($n=8$) drawn over the undeformed frame, and the\n",
    "frequencies of both models against the number of elements."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "shape = lambda k: steel[8].mode_displacements(int(np.argsort(steel[8].frequencies)[k]))\n",
    "scale = lambda k: 0.4 / np.abs(shape(k)[:, [0, 2]]).max()\n",
    "fig = plots.figure(1, 3, size=(18, 6))\n",
    "for k in range(2):\n",
    "    plots.line(\n",
    "        y={\n",
    "            \"undeformed\": (joints(8)[:, 0], joints(8)[:, 2]),\n",
    "            f\"mode {k + 1}, {np.sort(steel[8].frequencies)[k]:.2f} Hz\": (\n",
    "                joints(8)[:, 0] + scale(k) * shape(k)[:, 0],\n",
    "                joints(8)[:, 2] + scale(k) * shape(k)[:, 2],\n",
    "            ),\n",
    "        },\n",
    "        styles={\"undeformed\": \"dashed\"},\n",
    "        xlimits=(-0.8, 2.3),\n",
    "        ylimits=(-0.2, 2.8),\n",
    "        xlabel=\"x [m]\",\n",
    "        ylabel=\"z [m]\",\n",
    "        title=f\"Mode {k + 1} of the steel frame\",\n",
    "        legend=\"lower right\",\n",
    "        ax=fig[k],\n",
    "    )\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"mode {k + 1}, massless members\": (\n",
    "            divisions,\n",
    "            [np.sort(light[n].frequencies)[k] for n in divisions],\n",
    "        )\n",
    "        for k in range(2)\n",
    "    }\n",
    "    | {\n",
    "        f\"mode {k + 1}, steel members\": (\n",
    "            divisions,\n",
    "            [np.sort(steel[n].frequencies)[k] for n in divisions],\n",
    "        )\n",
    "        for k in range(2)\n",
    "    },\n",
    "    hlines={f\"closed form, mode {k + 1}\": reference[k] for k in range(2)},\n",
    "    markers=True,\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"elements per member\",\n",
    "    ylabel=\"natural frequency [Hz]\",\n",
    "    title=\"Frequencies and mesh\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Move the machine to the corner and watch the rotary inertia lose its influence on the first mode,\n",
    "add a second mass on the column, or replace the clamped base by a rotational spring."
   ]
  }
 ]
}
