{
 "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": [
    "# A helical spring driven by a global displacement constraint\n",
    "\n",
    "Often the quantity that is known is not a load but a kinematic condition: a spring has to be\n",
    "compressed by a given amount, a bolt stretched to a given length. The force needed for it then\n",
    "follows from the solution. A *global equation* adds one unknown and one equation to the model,\n",
    "\n",
    "$$\\frac1A\\int_{\\Gamma}u_z\\,dA=\\delta ,$$\n",
    "\n",
    "the area-weighted mean axial displacement of the boundary $\\Gamma$ equals $\\delta$. Its Lagrange\n",
    "multiplier is a uniform axial traction on $\\Gamma$, and its resultant is the force $F$ that holds the\n",
    "constraint.\n",
    "\n",
    "**Setup.** A spring of steel wire, $d=6$ mm, mean coil diameter $D=40$ mm, pitch 12 mm, six turns;\n",
    "$E=206$ GPa, $\\nu=0.3$. One wire end is clamped; at the other the mean axial displacement is\n",
    "$\\delta=5$ mm and all else is free. The spring comes from the CAD file\n",
    "`loaded_spring_global_constraint.step`, written by `loaded_spring_global_constraint_geometry.py`\n",
    "with the CAD objects of OneSimulation.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `fixed_end` | clamped |\n",
    "| `loaded_end` | mean axial displacement $\\delta$ (global equation) |\n",
    "| `wire` | free |\n",
    "\n",
    "**Reference.** (1) An independent model of the same spring: 3D Euler-Bernoulli beam elements along\n",
    "the helix of the wire centre line, clamped at the start and loaded by an axial force at the end,\n",
    "which bends and twists the wire exactly as the solid does. (2) The classical formula for a close-\n",
    "coiled spring loaded along its axis, $k=Gd^4/(8D^3n)$ with $n=6$ turns (Wahl, *Mechanical Springs*,\n",
    "1963), which assumes the force on the spring axis; here it acts at the wire end, so the two models\n",
    "are compared with each other and the formula gives the order of magnitude."
   ]
  },
  {
   "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\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",
    "    AverageDisplacement,\n",
    "    FixedDisplacement,\n",
    "    FrameMember,\n",
    "    LinearElasticity,\n",
    "    SpatialFrame,\n",
    "    TractionFree,\n",
    "    average_displacement_force,\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 spring with its named faces; tetrahedra of 3 mm carry quadratic shape functions."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "spring = load(\"loaded_spring_global_constraint.step\")\n",
    "faces = spring.boundaries\n",
    "mesh = TetrahedralMesher(target_size=0.003).generate(spring)\n",
    "\n",
    "view = plots.Camera(elevation=20, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(13, 7))\n",
    "plots.geometry(\n",
    "    spring,\n",
    "    selection={\n",
    "        \"clamped end\": faces.fixed_end,\n",
    "        \"loaded end\": faces.loaded_end,\n",
    "        \"wire\": faces.wire,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Helical spring with its named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{mesh.cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model with the global equation\n",
    "\n",
    "`AverageDisplacement` adds the mean-displacement equation to the problem; after the solve,\n",
    "`average_displacement_force` returns its multiplier as the axial force on the loaded end."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "youngs_modulus, poisson_ratio, wire, coil, pitch, turns, stroke = (\n",
    "    206e9,\n",
    "    0.3,\n",
    "    0.006,\n",
    "    0.040,\n",
    "    0.012,\n",
    "    6,\n",
    "    0.005,\n",
    ")\n",
    "steel = IsotropicSolid(\n",
    "    density=7850.0,\n",
    "    specific_heat_capacity=460.0,\n",
    "    thermal_conductivity=50.0,\n",
    "    youngs_modulus=youngs_modulus,\n",
    "    poisson_ratio=poisson_ratio,\n",
    "    thermal_expansion_coefficient=12e-6,\n",
    ")\n",
    "model = LinearElasticity(domain=spring.volume, material=steel)\n",
    "problem = Problem(\n",
    "    name=\"Spring with a global equation\",\n",
    "    geometry=spring,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        FixedDisplacement(\n",
    "            boundary=faces.fixed_end, physics=model, value=(0.0, 0.0, 0.0)\n",
    "        ),\n",
    "        TractionFree(boundary=faces.wire | faces.loaded_end, physics=model),\n",
    "    ),\n",
    "    constraints=(\n",
    "        AverageDisplacement(\n",
    "            boundary=faces.loaded_end, physics=model, component=\"z\", value=stroke\n",
    "        ),\n",
    "    ),\n",
    ")\n",
    "result = Simulation(\n",
    "    problem=problem,\n",
    "    mesh=mesh,\n",
    "    numerics=Numerics(\n",
    "        spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    "    ),\n",
    ").solve_stationary()\n",
    "force = average_displacement_force(result, model)\n",
    "displacement = result.field(model.displacement)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Beam model of the same helix\n",
    "\n",
    "36 beam elements per turn along the wire centre line, with the circular wire section."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "angles = np.linspace(0.0, 2 * np.pi * turns, 36 * turns + 1)\n",
    "centre_line = np.column_stack(\n",
    "    (coil / 2 * np.cos(angles), coil / 2 * np.sin(angles), pitch * angles / (2 * np.pi))\n",
    ")\n",
    "section = dict(\n",
    "    youngs_modulus=youngs_modulus,\n",
    "    area=np.pi * wire**2 / 4,\n",
    "    bending_inertia_y=np.pi * wire**4 / 64,\n",
    "    bending_inertia_z=np.pi * wire**4 / 64,\n",
    "    torsion_constant=np.pi * wire**4 / 32,\n",
    "    shear_modulus=youngs_modulus / (2 * (1 + poisson_ratio)),\n",
    ")\n",
    "helix = SpatialFrame(\n",
    "    joints=centre_line,\n",
    "    members=tuple(\n",
    "        FrameMember(\n",
    "            name=f\"wire {k}\", start=k, end=k + 1, local_y=(0.0, 0.0, 1.0), **section\n",
    "        )\n",
    "        for k in range(len(angles) - 1)\n",
    "    ),\n",
    ")\n",
    "beam = helix.solve(\n",
    "    supports=[(0, dof, 0.0) for dof in (\"x\", \"y\", \"z\", \"rx\", \"ry\", \"rz\")],\n",
    "    forces={len(angles) - 1: (0.0, 0.0, 1.0)},\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison\n",
    "\n",
    "The constraint is checked on the end face, the force against the clamped end, and the stiffness\n",
    "against the beam model and the classical formula. Straight tetrahedra cut off a little of the round\n",
    "wire; its torsion and bending constants scale with the square of the section area, which explains\n",
    "the difference to the beam model."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "end_points = displacement.sample(along=faces.loaded_end, subdivisions=2)\n",
    "reaction = displacement.reaction(faces.fixed_end)\n",
    "stiffness = {\n",
    "    \"solid with global equation\": force / stroke,\n",
    "    \"beam model of the helix\": 1.0 / beam.displacement[-1, 2],\n",
    "    \"classical formula G d⁴/(8 D³ n)\": section[\"shear_modulus\"]\n",
    "    * wire**4\n",
    "    / (8 * coil**3 * turns),\n",
    "}\n",
    "print(\n",
    "    f\"mean axial displacement of the loaded end {1e3 * np.mean(end_points.values[:, 2]):.4f} mm (prescribed {1e3 * stroke:.4f} mm, simple mean of samples)\"\n",
    ")\n",
    "print(\n",
    "    f\"force of the global equation {force:.2f} N; axial reaction at the clamped end {reaction[2]:.2f} N\"\n",
    ")\n",
    "for name, value in stiffness.items():\n",
    "    print(\n",
    "        f\"stiffness, {name:32s} {value / 1e3:8.3f} N/mm   ({100 * (value / stiffness['beam model of the helix'] - 1):+6.2f} % against the beam model)\"\n",
    "    )\n",
    "corners = np.asarray(mesh.coordinates)[np.asarray(mesh.cells)[:, :4]]\n",
    "mesh_volume = (\n",
    "    np.abs(\n",
    "        np.einsum(\n",
    "            \"ij,ij->i\",\n",
    "            np.cross(corners[:, 1] - corners[:, 0], corners[:, 2] - corners[:, 0]),\n",
    "            corners[:, 3] - corners[:, 0],\n",
    "        )\n",
    "    ).sum()\n",
    "    / 6\n",
    ")\n",
    "faceting = mesh_volume / (np.pi * wire**2 / 4 * turns * np.hypot(np.pi * coil, pitch))\n",
    "print(\n",
    "    f\"the straight tetrahedra facet the wire: its section is {100 * faceting:.2f} % of the circle; with the torsion and bending constants scaled \"\n",
    "    f\"by its square the beam model gives {faceting**2 * stiffness['beam model of the helix'] / 1e3:.3f} N/mm \"\n",
    "    f\"(solid {100 * (stiffness['solid with global equation'] / (faceting**2 * stiffness['beam model of the helix']) - 1):+.2f} %)\"\n",
    ")\n",
    "print(\n",
    "    f\"lateral motion of the loaded end: {1e3 * np.abs(end_points.values[:, :2]).max():.3f} mm in the solid, \"\n",
    "    f\"{1e3 * np.abs(beam.displacement[-1, :2]).max() * force:.3f} mm in the beam model\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The deformed spring, 5 times enlarged, coloured by the displacement magnitude."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plots.surface(\n",
    "    displacement,\n",
    "    component=lambda u, position: 1e3 * np.linalg.norm(u, axis=1),\n",
    "    deformation=displacement,\n",
    "    deformation_scale=5.0,\n",
    "    camera=view,\n",
    "    label=\"displacement [mm]\",\n",
    "    title=f\"Spring compressed by {1e3 * stroke:.0f} mm (×5), F = {force:.0f} N\",\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Replace the constraint value by a function of time to follow a stroke history, prescribe the mean\n",
    "rotation instead, or add ground end coils and plates to load the spring on its axis."
   ]
  }
 ]
}
