{
 "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": [
    "# Stresses in a rotating pulley\n",
    "\n",
    "A driving pulley of outer radius $R=125$ mm and thickness $t=10$ mm sits on a shaft (bore radius\n",
    "25 mm) and drives a flat belt that wraps it over the angle $\\beta=170^\\circ$. Eight rounded,\n",
    "trapezoidal cut-outs leave a hub, eight tapered spokes and a rim. The shaft power $P$ is constant,\n",
    "so the torque $M=P/\\omega$ falls as the speed rises, while the centrifugal load grows with\n",
    "$\\omega^2$: at low speed the belt dominates, at high speed the inertia does.\n",
    "\n",
    "The plate is thin and loaded in its plane, so it is a **plane-stress** problem on the mid-plane\n",
    "section. The pulley comes from the CAD file `rotating_pulley_stresses.step`, written by\n",
    "`rotating_pulley_stresses_geometry.py` with the CAD objects of OneSimulation; `section` cuts it at\n",
    "half thickness and keeps the face groups `bore`, `rim` and `cutouts` as named edges.\n",
    "\n",
    "**Belt load.** With friction coefficient $\\mu$ and impending slip, the strand tensions obey the\n",
    "capstan relation $F_1/F_2=e^{\\mu\\beta}$ and $F_1-F_2=M/R$. Along the contact, measured by the\n",
    "angle $\\theta$ from the point where the slack strand leaves, the belt presses on the rim with\n",
    "\n",
    "$$p(\\theta)=\\frac{F_2}{R\\,t}\\,e^{\\mu\\theta}\\ \\text{(inward)},\\qquad\n",
    "  \\tau(\\theta)=\\mu\\,p(\\theta)\\ \\text{(against the rotation)}.$$\n",
    "\n",
    "**Inertia.** In the rotating frame every material point carries the centrifugal body force\n",
    "$\\rho\\,\\omega^2\\,\\mathbf r$, given by `BodyForce.centrifugal`.\n",
    "\n",
    "| edge | condition |\n",
    "|---|---|\n",
    "| `bore` | held, $u_x=u_y=0$ |\n",
    "| `rim` | belt traction over the wrap angle, free elsewhere |\n",
    "| `cutouts` | traction free |\n",
    "\n",
    "**Reference.** There is no closed-form solution for the spoked pulley. The notebook uses\n",
    "(i) global equilibrium: the shaft reaction must balance the two strand forces, (ii) the exact\n",
    "plane-stress solution of a rotating annular disc held at the bore (S. Timoshenko and J. N. Goodier,\n",
    "*Theory of Elasticity*, 3rd ed., McGraw-Hill 1970, §32) on the pulley blank, and (iii) a three-level\n",
    "mesh study of the peak stress."
   ]
  },
  {
   "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\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.solid_mechanics import (\n",
    "    BodyForce,\n",
    "    FixedDisplacementComponents,\n",
    "    LinearElasticity,\n",
    "    Traction,\n",
    "    TractionFree,\n",
    ")\n",
    "from onesim.results.derived import von_mises\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",
    "Three meshes of quadratic triangles differ in the size along the walls of the cut-outs, where the\n",
    "rounded corners carry the peak stress."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "pulley = load(\"rotating_pulley_stresses.step\")\n",
    "thickness = pulley.size[2]\n",
    "plate = pulley.section((0, 0, 1), origin=(0, 0, thickness / 2))\n",
    "edges = plate.boundaries\n",
    "outer_radius = plate.size[0] / 2\n",
    "sizes = [0.0040, 0.0028, 0.0020]\n",
    "meshes = [\n",
    "    TriangularMesher(target_size=0.008, local_sizes={\"cutouts\": size}).generate(plate)\n",
    "    for size in sizes\n",
    "]\n",
    "\n",
    "fig = plots.figure(1, 2, size=(15, 6.5))\n",
    "plots.geometry(\n",
    "    pulley,\n",
    "    selection={\n",
    "        \"bore\": pulley.boundaries.bore,\n",
    "        \"rim\": pulley.boundaries.rim,\n",
    "        \"cutouts\": pulley.boundaries.cutouts,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=55, azimuth=-90),\n",
    "    title=\"Pulley with its named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[-1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Mid-plane section, finest mesh: {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",
    "Aluminium. Both loads depend on the speed: the centrifugal body force grows with $\\omega^2$, the\n",
    "belt traction falls with the torque $P/\\omega$. The problem is solved at 1000 and 9000 rpm on the\n",
    "three meshes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "power, friction, wrap, speeds, bore_radius = (\n",
    "    30e3,\n",
    "    0.3,\n",
    "    np.radians(170.0),\n",
    "    (1000.0, 9000.0),\n",
    "    0.025,\n",
    ")\n",
    "aluminium = IsotropicSolid(\n",
    "    density=2700.0,\n",
    "    specific_heat_capacity=900.0,\n",
    "    thermal_conductivity=200.0,\n",
    "    youngs_modulus=70e9,\n",
    "    poisson_ratio=0.33,\n",
    "    thermal_expansion_coefficient=23e-6,\n",
    ")\n",
    "angular = lambda rpm: 2 * np.pi * rpm / 60\n",
    "slack_force = (\n",
    "    lambda rpm: power / angular(rpm) / outer_radius / (np.exp(friction * wrap) - 1)\n",
    ")\n",
    "pressure = lambda rpm, angle: np.where(\n",
    "    np.abs(angle) < wrap / 2,\n",
    "    slack_force(rpm)\n",
    "    / (outer_radius * thickness)\n",
    "    * np.exp(friction * (angle + wrap / 2)),\n",
    "    0.0,\n",
    ")\n",
    "belt = lambda rpm: lambda x, y: -pressure(rpm, np.arctan2(y, x))[..., None] * np.stack(\n",
    "    (\n",
    "        np.cos(np.arctan2(y, x)) + friction * np.sin(np.arctan2(y, x)),\n",
    "        np.sin(np.arctan2(y, x)) - friction * np.cos(np.arctan2(y, x)),\n",
    "    ),\n",
    "    axis=-1,\n",
    ")\n",
    "models = {\n",
    "    rpm: LinearElasticity(\n",
    "        domain=plate.domain(),\n",
    "        material=aluminium,\n",
    "        kinematics=\"plane_stress\",\n",
    "        loading=BodyForce.centrifugal(\n",
    "            density=aluminium.density, angular_velocity=angular(rpm)\n",
    "        ),\n",
    "    )\n",
    "    for rpm in speeds\n",
    "}\n",
    "problems = {\n",
    "    rpm: Problem(\n",
    "        name=\"Pulley in plane stress\",\n",
    "        geometry=plate,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            FixedDisplacementComponents(\n",
    "                boundary=edges.bore, physics=model, components=(\"x\", \"y\")\n",
    "            ),\n",
    "            Traction(boundary=edges.rim, physics=model, value=belt(rpm)),\n",
    "            TractionFree(boundary=edges.all - edges.bore - edges.rim, physics=model),\n",
    "        ),\n",
    "    )\n",
    "    for rpm, model in models.items()\n",
    "}\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "results = {\n",
    "    (rpm, size): Simulation(\n",
    "        problem=problems[rpm], mesh=mesh, numerics=numerics\n",
    "    ).solve_stationary()\n",
    "    for rpm in speeds\n",
    "    for size, mesh in zip(sizes, meshes)\n",
    "}\n",
    "stress = {rpm: results[rpm, sizes[-1]].field(models[rpm].stress) for rpm in speeds}\n",
    "mises = {\n",
    "    rpm: results[rpm, sizes[-1]].field(models[rpm].von_mises_stress) for rpm in speeds\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Global equilibrium and mesh study\n",
    "\n",
    "The reaction of the shaft on the bore must balance the two strand forces\n",
    "$F_1\\mathbf t_1+F_2\\mathbf t_2$; the plane-stress model carries the load per unit thickness. The\n",
    "peak von Mises stress sits on the walls of the cut-outs."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "for rpm in speeds:\n",
    "    tight, slack = slack_force(rpm) * np.exp(friction * wrap), slack_force(rpm)\n",
    "    strands = tight * np.array(\n",
    "        [-np.sin(wrap / 2), np.cos(wrap / 2)]\n",
    "    ) + slack * np.array([-np.sin(wrap / 2), -np.cos(wrap / 2)])\n",
    "    reaction = (\n",
    "        thickness\n",
    "        * np.asarray(\n",
    "            results[rpm, sizes[-1]].field(models[rpm].displacement).reaction(edges.bore)\n",
    "        )[:2]\n",
    "    )\n",
    "    print(\n",
    "        f\"{rpm:5.0f} rpm: torque {power / angular(rpm):6.1f} N m, strand forces {tight:6.1f} and {slack:5.1f} N; \"\n",
    "        f\"shaft reaction ({reaction[0]:8.2f}, {reaction[1]:8.2f}) N against ({-strands[0]:8.2f}, {-strands[1]:8.2f}) N\"\n",
    "    )\n",
    "\n",
    "peaks = {\n",
    "    rpm: [\n",
    "        results[rpm, size]\n",
    "        .field(models[rpm].von_mises_stress)\n",
    "        .sample(along=edges.cutouts, subdivisions=3)\n",
    "        .values.max()\n",
    "        for size in sizes\n",
    "    ]\n",
    "    for rpm in speeds\n",
    "}\n",
    "print(\n",
    "    \"size on the cut-outs [mm]   triangles   peak von Mises stress [MPa] at 1000 / 9000 rpm\"\n",
    ")\n",
    "for index, (size, mesh) in enumerate(zip(sizes, meshes)):\n",
    "    print(\n",
    "        f\"{1e3 * size:25.1f} {mesh.cell_count:11d} {peaks[speeds[0]][index] / 1e6:21.2f} / {peaks[speeds[1]][index] / 1e6:.2f}\"\n",
    "    )\n",
    "for rpm in speeds:\n",
    "    print(\n",
    "        f\"{rpm:5.0f} rpm: change between the two finest meshes {100 * abs(peaks[rpm][-1] / peaks[rpm][-2] - 1):.2f} %\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Speed sweep\n",
    "\n",
    "The problem is linear, so the stress at any speed is a combination of the two solved states: one\n",
    "part grows with $\\omega^2$, the other with $P/\\omega$. `von_mises` evaluates the combined tensors on\n",
    "the walls of the cut-outs and at a point on a spoke."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "sweep = np.arange(1000.0, 9001.0, 250.0)\n",
    "weights = np.linalg.inv([[angular(rpm) ** 2, power / angular(rpm)] for rpm in speeds])\n",
    "probe = [[0.019, 0.054]]\n",
    "on_walls = np.stack(\n",
    "    [stress[rpm].sample(along=edges.cutouts, subdivisions=3).values for rpm in speeds]\n",
    ")\n",
    "at_probe = np.stack([stress[rpm].evaluate(probe) for rpm in speeds])\n",
    "combined = lambda states, rpm: np.tensordot(\n",
    "    np.array([angular(rpm) ** 2, power / angular(rpm)]) @ weights, states, axes=1\n",
    ")\n",
    "sweep_peak = np.array([von_mises(combined(on_walls, rpm)).max() for rpm in sweep])\n",
    "sweep_probe = np.array([von_mises(combined(at_probe, rpm))[0] for rpm in sweep])\n",
    "print(\n",
    "    f\"lowest peak stress {sweep_peak.min() / 1e6:.1f} MPa at {sweep[sweep_peak.argmin()]:.0f} rpm\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Rotating disc\n",
    "\n",
    "The section of the pulley blank at 9000 rpm without belt is compared with the exact plane-stress\n",
    "solution of the rotating annular disc held at the bore, $u(a)=0$, free at $r=b$:\n",
    "\n",
    "$$\\sigma_r=c\\Big(-k(3+\\nu)r^2+C_1(1+\\nu)-\\frac{C_2(1-\\nu)}{r^2}\\Big),\\qquad\n",
    "  \\sigma_\\theta=c\\Big(-k(1+3\\nu)r^2+C_1(1+\\nu)+\\frac{C_2(1-\\nu)}{r^2}\\Big),$$\n",
    "\n",
    "with $c=E/(1-\\nu^2)$, $k=(1-\\nu^2)\\rho\\omega^2/(8E)$ and $C_1$, $C_2$ from the two edge conditions.\n",
    "Radial and hoop stress follow from the Cartesian components along a ray."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "blank = load(\"rotating_pulley_stresses_blank.step\").section(\n",
    "    (0, 0, 1), origin=(0, 0, thickness / 2)\n",
    ")\n",
    "disc = LinearElasticity(\n",
    "    domain=blank.domain(),\n",
    "    material=aluminium,\n",
    "    kinematics=\"plane_stress\",\n",
    "    loading=BodyForce.centrifugal(\n",
    "        density=aluminium.density, angular_velocity=angular(speeds[1])\n",
    "    ),\n",
    ")\n",
    "disc_mesh = TriangularMesher(target_size=0.006, local_sizes={\"bore\": 0.002}).generate(\n",
    "    blank\n",
    ")\n",
    "disc_stress = (\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Pulley blank\",\n",
    "            geometry=blank,\n",
    "            physics=(disc,),\n",
    "            boundary_conditions=(\n",
    "                FixedDisplacementComponents(\n",
    "                    boundary=blank.boundaries.bore, physics=disc, components=(\"x\", \"y\")\n",
    "                ),\n",
    "                TractionFree(boundary=blank.boundaries.rim, physics=disc),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=disc_mesh,\n",
    "        numerics=numerics,\n",
    "    )\n",
    "    .solve_stationary()\n",
    "    .field(disc.stress)\n",
    ")\n",
    "E, nu, w = aluminium.youngs_modulus, aluminium.poisson_ratio, angular(speeds[1])\n",
    "k, c = (1 - nu**2) * aluminium.density * w**2 / (8 * E), E / (1 - nu**2)\n",
    "C1, C2 = np.linalg.solve(\n",
    "    [[bore_radius, 1 / bore_radius], [c * (1 + nu), -c * (1 - nu) / outer_radius**2]],\n",
    "    [k * bore_radius**3, c * k * (3 + nu) * outer_radius**2],\n",
    ")\n",
    "r = np.linspace(bore_radius + 5e-4, outer_radius - 5e-4, 60)\n",
    "direction = np.array([np.cos(0.35), np.sin(0.35)])\n",
    "components = disc_stress.evaluate(r[:, None] * direction)\n",
    "radial = (\n",
    "    components[:, 0] * direction[0] ** 2\n",
    "    + components[:, 1] * direction[1] ** 2\n",
    "    + 2 * components[:, 3] * direction[0] * direction[1]\n",
    ")\n",
    "hoop = (\n",
    "    components[:, 0] * direction[1] ** 2\n",
    "    + components[:, 1] * direction[0] ** 2\n",
    "    - 2 * components[:, 3] * direction[0] * direction[1]\n",
    ")\n",
    "exact_radial = c * (-k * (3 + nu) * r**2 + C1 * (1 + nu) - C2 * (1 - nu) / r**2)\n",
    "exact_hoop = c * (-k * (1 + 3 * nu) * r**2 + C1 * (1 + nu) + C2 * (1 - nu) / r**2)\n",
    "print(\n",
    "    f\"rotating disc at 9000 rpm, {disc_mesh.cell_count} triangles: hoop stress near the bore {hoop[0] / 1e6:.3f} MPa \"\n",
    "    f\"(exact {exact_hoop[0] / 1e6:.3f}), near the rim {hoop[-1] / 1e6:.3f} MPa (exact {exact_hoop[-1] / 1e6:.3f}); \"\n",
    "    f\"largest deviation along the radius {100 * max(np.abs(hoop - exact_hoop).max(), np.abs(radial - exact_radial).max()) / exact_hoop.max():.2f} % of the peak\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The von Mises stress in the plate at both speeds, the speed sweep, the rotating disc against its\n",
    "exact solution and the mesh study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(2, 2, size=(15, 12))\n",
    "for index, rpm in enumerate(speeds):\n",
    "    plots.surface(\n",
    "        mises[rpm],\n",
    "        component=lambda s, position: s / 1e6,\n",
    "        limits=(0, 10 * round(0.075 * peaks[rpm][-1] / 1e6)),\n",
    "        subdivisions=3,\n",
    "        label=\"von Mises stress [MPa]\",\n",
    "        title=f\"{rpm:.0f} rpm: torque {power / angular(rpm):.0f} N m, peak {peaks[rpm][-1] / 1e6:.1f} MPa\",\n",
    "        ax=fig[index],\n",
    "    )\n",
    "plots.line(\n",
    "    sweep,\n",
    "    {\"peak on the cut-outs\": sweep_peak / 1e6, \"point on a spoke\": sweep_probe / 1e6},\n",
    "    xlabel=\"rotational speed [rpm]\",\n",
    "    ylabel=\"von Mises stress [MPa]\",\n",
    "    title=\"Constant power: belt against inertia\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"hoop\": (1e3 * r[::3], hoop[::3] / 1e6),\n",
    "        \"radial\": (1e3 * r[::3], radial[::3] / 1e6),\n",
    "    },\n",
    "    reference={\n",
    "        \"hoop\": (1e3 * r, exact_hoop / 1e6),\n",
    "        \"radial\": (1e3 * r, exact_radial / 1e6),\n",
    "    },\n",
    "    xlabel=\"radius [mm]\",\n",
    "    ylabel=\"stress [MPa]\",\n",
    "    title=\"Blank at 9000 rpm: simulation (markers), exact (dashed)\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the cut-outs or their corner radii in `rotating_pulley_stresses_geometry.py`, write the STEP\n",
    "files again and follow the peak stress; raise the friction coefficient or the wrap angle to see the\n",
    "belt load move."
   ]
  }
 ]
}
