{
 "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": [
    "# Deformation of a feeder clamp\n",
    "\n",
    "A feeder carrying high-frequency power must run as straight as possible: any kink changes its\n",
    "impedance. It is held every few metres by clamps like this one, a base plate bolted to the\n",
    "mounting, an upright web, and an eye of 25 mm bore in which the feeder sits. The feeder pulls on\n",
    "the eye: its weight, a sideways pull of the line and a pull along the line that the eye takes by\n",
    "friction,\n",
    "\n",
    "$$\\mathbf F=(F_x,F_y,F_z)=(300,\\,600,\\,-200)\\ \\text{N}.$$\n",
    "\n",
    "The clamp comes from the CAD file `feeder_clamp_deformation.step` with four named face groups:\n",
    "`bolts`, `bore`, `root` and `neck`. The script `feeder_clamp_deformation_geometry.py` builds the\n",
    "part with the CAD objects of OneSimulation and writes the file.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `bolts`: walls of the two bolt holes | $\\mathbf u=0$ |\n",
    "| bottom of the base plate | rests on the mounting, $u_z=0$ |\n",
    "| `bore`: seat of the feeder | bearing pressure $p_{max}\\cos\\varphi$ towards $(F_x,F_z)$, uniform shear $F_y/A$ |\n",
    "| all other faces | traction free |\n",
    "\n",
    "The quantities that matter for the feeder are the displacement of the seat and its **tilt**: the\n",
    "rotation of the bore axis, which bends the feeder where it leaves the clamp.\n",
    "\n",
    "**Reference.** The reaction in the bolts and on the mounting must balance $\\mathbf F$ (global\n",
    "equilibrium). The tilt and the peak stresses in the root and neck fillets have no closed form;\n",
    "a mesh study on three meshes shows how far they are converged, with Richardson extrapolation\n",
    "of the tilt."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import LocalRefinement, 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",
    "    FixedDisplacement,\n",
    "    FixedDisplacementComponents,\n",
    "    LinearElasticity,\n",
    "    Traction,\n",
    "    TractionFree,\n",
    ")\n",
    "from onesim.results.comparisons import convergence\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 solid with its named face groups in `clamp.boundaries`. Three meshes of\n",
    "curved quadratic tetrahedra differ in the cell size on the fillets; the bore gets 2 mm cells,\n",
    "the rest 4 mm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "clamp = load(\"feeder_clamp_deformation.step\")\n",
    "faces = clamp.boundaries\n",
    "bottom = clamp.select(faces=lambda face: abs(face.center[2]) < 1e-9)\n",
    "sizes = [0.0016, 0.0011, 0.00075]\n",
    "meshes = [\n",
    "    TetrahedralMesher(\n",
    "        target_size=0.004,\n",
    "        geometry_order=2,\n",
    "        refinements=(\n",
    "            LocalRefinement(region=faces.bore, target_size=0.002),\n",
    "            LocalRefinement(region=faces.root | faces.neck, target_size=size),\n",
    "        ),\n",
    "    ).generate(clamp)\n",
    "    for size in sizes\n",
    "]\n",
    "\n",
    "view = plots.Camera(elevation=24, azimuth=-58)\n",
    "fig = plots.figure(1, 2, size=(15, 6.5))\n",
    "plots.geometry(\n",
    "    clamp,\n",
    "    selection={\n",
    "        \"bolts\": faces.bolts,\n",
    "        \"bore\": faces.bore,\n",
    "        \"root\": faces.root,\n",
    "        \"neck\": faces.neck,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Feeder clamp 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\"Finest mesh: {meshes[-1].cell_count} curved tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Aluminium alloy 6061-T6. On the bore, the radial part of the feeder force presses as a cosine\n",
    "bearing pressure on the half facing $(F_x,F_z)$, with $p_{max}=2F_{xz}/(\\pi r L)$; the axial part\n",
    "is a uniform shear."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "force, axis, radius, depth = (\n",
    "    np.array([300.0, 600.0, -200.0]),\n",
    "    np.array([0.0, 0.070]),\n",
    "    0.0125,\n",
    "    0.040,\n",
    ")\n",
    "aluminium = IsotropicSolid(\n",
    "    density=2700.0,\n",
    "    specific_heat_capacity=896.0,\n",
    "    thermal_conductivity=167.0,\n",
    "    youngs_modulus=68.9e9,\n",
    "    poisson_ratio=0.33,\n",
    "    thermal_expansion_coefficient=23.6e-6,\n",
    ")\n",
    "radial = np.hypot(force[0], force[2])\n",
    "\n",
    "\n",
    "def seat(x, y, z):\n",
    "    \"\"\"Traction of the feeder on the bore: bearing pressure plus axial shear.\"\"\"\n",
    "    nx, nz = (np.asarray(x) - axis[0]) / radius, (np.asarray(z) - axis[1]) / radius\n",
    "    pressure = (\n",
    "        2\n",
    "        * radial\n",
    "        / (np.pi * radius * depth)\n",
    "        * np.maximum((nx * force[0] + nz * force[2]) / radial, 0.0)\n",
    "    )\n",
    "    return np.stack(\n",
    "        (\n",
    "            pressure * nx,\n",
    "            np.full_like(nx, force[1] / (2 * np.pi * radius * depth)),\n",
    "            pressure * nz,\n",
    "        ),\n",
    "        axis=-1,\n",
    "    )\n",
    "\n",
    "\n",
    "model = LinearElasticity(domain=clamp.volume, material=aluminium)\n",
    "problem = Problem(\n",
    "    name=\"Feeder clamp\",\n",
    "    geometry=clamp,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        FixedDisplacement(boundary=faces.bolts, physics=model, value=(0.0, 0.0, 0.0)),\n",
    "        FixedDisplacementComponents(boundary=bottom, physics=model, components=(\"z\",)),\n",
    "        Traction(boundary=faces.bore, physics=model, value=seat),\n",
    "        TractionFree(\n",
    "            boundary=faces.all - faces.bolts - bottom - faces.bore, physics=model\n",
    "        ),\n",
    "    ),\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",
    "displacement, mises = (\n",
    "    results[-1].field(f) for f in (model.displacement, model.von_mises_stress)\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The motion of the seat follows from the displacement on the bore: its mean is the shift of the\n",
    "feeder axis, the slope of $u_x$ and $u_z$ along the bore its tilt."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "seats = [\n",
    "    result.field(model.displacement).sample(along=faces.bore, subdivisions=3)\n",
    "    for result in results\n",
    "]\n",
    "shift = [s.values.mean(axis=0) for s in seats]\n",
    "tilt = [\n",
    "    np.hypot(\n",
    "        np.polyfit(s.positions[:, 1], s.values[:, 0], 1)[0],\n",
    "        np.polyfit(s.positions[:, 1], s.values[:, 2], 1)[0],\n",
    "    )\n",
    "    for s in seats\n",
    "]\n",
    "peaks = {\n",
    "    name: [\n",
    "        result.field(model.von_mises_stress)\n",
    "        .sample(along=group, subdivisions=3)\n",
    "        .values.max()\n",
    "        for result in results\n",
    "    ]\n",
    "    for name, group in ((\"root\", faces.root), (\"neck\", faces.neck))\n",
    "}\n",
    "studies = {\n",
    "    \"tilt\": convergence(tilt, sizes),\n",
    "    **{name: convergence(values, sizes) for name, values in peaks.items()},\n",
    "}\n",
    "reaction = displacement.reaction(faces.bolts | bottom)\n",
    "\n",
    "print(\n",
    "    f\"reaction of bolts and mounting: ({reaction[0]:.1f}, {reaction[1]:.1f}, {reaction[2]:.1f}) N \"\n",
    "    f\"against the feeder force ({force[0]:.0f}, {force[1]:.0f}, {force[2]:.0f}) N\"\n",
    ")\n",
    "print(\n",
    "    f\"shift of the feeder axis: ({1e6 * shift[-1][0]:.2f}, {1e6 * shift[-1][1]:.2f}, {1e6 * shift[-1][2]:.2f}) µm\"\n",
    ")\n",
    "print(\n",
    "    \"fillet cell size [mm]  tetrahedra  tilt [µrad]  peak stress root [MPa]  peak stress neck [MPa]\"\n",
    ")\n",
    "for size, mesh, t, root, neck in zip(sizes, meshes, tilt, peaks[\"root\"], peaks[\"neck\"]):\n",
    "    print(\n",
    "        f\"{1e3 * size:19.2f} {mesh.cell_count:11d} {1e6 * t:12.2f} {root / 1e6:23.2f} {neck / 1e6:23.2f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"tilt: change between the two finest meshes {100 * studies['tilt'].change:.3f} %, \"\n",
    "    f\"observed order {studies['tilt'].order:.1f}, extrapolated {1e6 * studies['tilt'].extrapolated:.2f} µrad\"\n",
    ")\n",
    "for name in peaks:\n",
    "    print(\n",
    "        f\"peak stress in the {name} fillets: change between the two finest meshes {100 * studies[name].change:+.1f} %\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The von Mises stress on the deformed clamp (displacement magnified 300 times) and in the\n",
    "mid-plane of the web, and the mesh study of the tilt and of the two fillet peaks."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "megapascal = lambda s, position: s / 1e6\n",
    "fig = plots.figure(2, 2, size=(15, 12))\n",
    "plots.surface(\n",
    "    mises,\n",
    "    component=megapascal,\n",
    "    deformation=displacement,\n",
    "    deformation_scale=300.0,\n",
    "    limits=(0, 12),\n",
    "    camera=view,\n",
    "    label=\"von Mises stress [MPa]\",\n",
    "    title=\"Deformed clamp (×300)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.section(\n",
    "    mises,\n",
    "    plane=Plane(origin=(0, 0, 0), normal=(0, 1, 0)),\n",
    "    component=megapascal,\n",
    "    limits=(0, 12),\n",
    "    subdivisions=3,\n",
    "    label=\"von Mises stress [MPa]\",\n",
    "    title=\"Mid-plane y = 0\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    1e3 * np.array(sizes),\n",
    "    {\"simulation\": 1e6 * np.array(tilt)},\n",
    "    markers=True,\n",
    "    hlines={\"extrapolated\": 1e6 * studies[\"tilt\"].extrapolated},\n",
    "    xlabel=\"cell size in the fillets [mm]\",\n",
    "    ylabel=\"tilt of the feeder axis [µrad]\",\n",
    "    title=\"Mesh study: tilt\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    1e3 * np.array(sizes),\n",
    "    {f\"{name} fillets\": np.array(values) / 1e6 for name, values in peaks.items()},\n",
    "    markers=True,\n",
    "    ylimits=(0, 45),\n",
    "    xlabel=\"cell size in the fillets [mm]\",\n",
    "    ylabel=\"peak von Mises stress [MPa]\",\n",
    "    title=\"Mesh study: fillet peaks\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the web thicker or the root fillet larger in `feeder_clamp_deformation_geometry.py`, write\n",
    "the STEP file again and follow the tilt; or let the base plate lift off the mounting with\n",
    "frictional contact (`onesim.physics.solid_mechanics`)."
   ]
  }
 ]
}
