{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "language": "python",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Notch approximation for the low-cycle fatigue of a shaft with a transverse hole\n",
    "\n",
    "When a notch yields locally, a full elastic-plastic analysis is the accurate way to its local\n",
    "strain. A much cheaper estimate starts from the linear-elastic notch stress $\\sigma_e$ and\n",
    "corrects it with the cyclic stress-strain curve\n",
    "$\\varepsilon=\\sigma/E+(\\sigma/K')^{1/n'}$ (Ramberg-Osgood):\n",
    "\n",
    "$$\\text{Neuber:}\\quad \\sigma\\,\\varepsilon=\\frac{\\sigma_e^2}{E},\\qquad\n",
    "  \\text{Glinka:}\\quad \\int_0^{\\varepsilon}\\sigma\\,d\\varepsilon=\\frac{\\sigma_e^2}{2E} .$$\n",
    "\n",
    "Neuber's rule assumes the total strain energy of the notch to be redistributed, Glinka's only the\n",
    "strain energy density; Neuber therefore predicts more local strain, Glinka less. For a fully\n",
    "reversed cycle the amplitudes enter, and with $\\sigma_{\\max}=\\sigma_a$ the Smith-Watson-Topper\n",
    "parameter $\\sigma_a\\varepsilon_a$ gives the life on the strain-life curve\n",
    "$\\sigma_{\\max}\\varepsilon_a=\\frac{\\sigma_f'^2}{E}(2N)^{2b}+\\sigma_f'\\varepsilon_f'(2N)^{b+c}$. Under combined\n",
    "loading the von Mises equivalent of the elastic stress amplitude is corrected.\n",
    "\n",
    "**Setup.** Shaft diameter $D=30$ mm, length 120 mm, transverse hole of $d=6$ mm at mid-length.\n",
    "Fully reversed, in-phase loading: axial force with a nominal stress amplitude of 180 MPa and a\n",
    "torque with a nominal surface shear amplitude of 100 MPa (gross section). Steel of the SAE 1045 type:\n",
    "$E=206$ GPa, $\\nu=0.3$, $K'=1258$ MPa, $n'=0.208$, $\\sigma_f'=948$ MPa, $b=-0.092$, $\\varepsilon_f'=0.26$,\n",
    "$c=-0.445$. The shaft comes from the CAD file `cylinder_hole_neuber_notch_fatigue.step`, written by\n",
    "`cylinder_hole_neuber_notch_fatigue_geometry.py` with the CAD objects of OneSimulation.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `clamped` | all displacements 0 |\n",
    "| `loaded` | traction of the force and torque amplitudes |\n",
    "| `hole`, `mantle` | free |\n",
    "\n",
    "**Checks.** (1) At 25 mm from the loaded end the stresses are the nominal ones, $F/A$ and\n",
    "$T r/J$. (2) The peak stress at the hole on a finer mesh. (3) The local states fulfil the two\n",
    "notch rules on the Ramberg-Osgood curve."
   ],
   "id": "markdown-01"
  },
  {
   "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 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 (FixedDisplacement, LinearElasticity, RambergOsgood, StrainLifeCurve, Traction,\n",
    "                                            TractionFree, glinka_notch, neuber_notch)\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "code-02"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and meshes\n",
    "\n",
    "Curved quadratic tetrahedra of 5 mm, with local resolutions of 0.5 mm and 0.35 mm at the hole."
   ],
   "id": "markdown-03"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "shaft = load(\"cylinder_hole_neuber_notch_fatigue.step\")\n",
    "faces = shaft.boundaries\n",
    "meshes = [TetrahedralMesher(target_size=0.005, geometry_order=2, refinements=(LocalRefinement(region=faces.hole, target_size=size),)).generate(shaft)\n",
    "          for size in (0.0005, 0.00035)]\n",
    "\n",
    "for mesh in meshes:\n",
    "    print(f\"Mesh: {len(mesh.coordinates):,} nodes, {mesh.cell_count:,} elements\")\n",
    "\n",
    "view = plots.Camera(elevation=30, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(15, 5.5))\n",
    "plots.geometry(shaft, selection={\"clamped\": faces.clamped, \"loaded\": faces.loaded, \"hole\": faces.hole}, labels=False, camera=view,\n",
    "               title=\"Shaft with a transverse hole\", ax=fig[0])\n",
    "plots.mesh(meshes[-1], groups=(\"all\",), legend=False, camera=view, title=f\"{meshes[-1].cell_count} curved quadratic tetrahedra\", ax=fig[1])\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "code-04"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Linear-elastic analysis at the load amplitude\n",
    "\n",
    "The loading is proportional, so one elastic solution at the amplitude gives the whole cycle."
   ],
   "id": "markdown-05"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "radius, length, hole = 0.015, 0.120, 0.003\n",
    "modulus, poisson = 206e9, 0.3\n",
    "area, polar = np.pi * radius**2, np.pi * radius**4 / 2\n",
    "force, torque = 180e6 * area, 100e6 * polar / radius\n",
    "steel = IsotropicSolid(density=7850.0, specific_heat_capacity=460.0, thermal_conductivity=50.0, youngs_modulus=modulus,\n",
    "                       poisson_ratio=poisson, thermal_expansion_coefficient=12e-6)\n",
    "model = LinearElasticity(domain=shaft.volume, material=steel)\n",
    "problem = Problem(name=\"Shaft with a hole\", geometry=shaft, physics=(model,), boundary_conditions=(\n",
    "    FixedDisplacement(boundary=faces.clamped, physics=model, value=(0.0, 0.0, 0.0)),\n",
    "    Traction(boundary=faces.loaded, physics=model, value=lambda x, y, z: np.column_stack((force / area + 0 * x, -z * torque / polar, y * torque / polar))),\n",
    "    TractionFree(boundary=faces.hole | faces.mantle, physics=model)))\n",
    "numerics = Numerics(spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect())\n",
    "results = [Simulation(problem=problem, mesh=mesh, numerics=numerics).solve_stationary() for mesh in meshes]\n",
    "mises = [result.field(model.von_mises_stress) for result in results]\n",
    "stress = results[-1].field(model.stress)"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "code-06"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Nominal stresses and the peak at the hole\n",
    "\n",
    "Stresses at 25 mm from the loaded end on the axis and at the surface; the peak von Mises stress\n",
    "on the hole surface on both meshes."
   ],
   "id": "markdown-07"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "station = np.array([[length - 0.025, 0.0, 0.0], [length - 0.025, 0.0, radius * (1 - 1e-4)]])\n",
    "components = np.asarray(stress.evaluate(station))\n",
    "print(f\"25 mm from the loaded end: σ_xx {components[0, 0] / 1e6:.2f} MPa (F/A = {force / area / 1e6:.2f}), surface shear \"\n",
    "      f\"{abs(components[1, 3]) / 1e6:.2f} MPa (T r/J = {torque * radius / polar / 1e6:.2f})\")\n",
    "samples = [field.sample(along=faces.hole, subdivisions=3) for field in mises]\n",
    "peaks = [float(np.max(sample.values)) for sample in samples]\n",
    "print(f\"peak von Mises stress at the hole: {peaks[0] / 1e6:.1f} MPa on {meshes[0].cell_count} cells, {peaks[1] / 1e6:.1f} MPa on \"\n",
    "      f\"{meshes[1].cell_count} cells (difference {100 * (peaks[0] / peaks[1] - 1):+.2f} %)\")"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "code-08"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Neuber and Glinka at the hole surface\n",
    "\n",
    "Every sampled point of the hole surface: the elastic von Mises amplitude corrected by both rules\n",
    "on the cyclic curve, the SWT parameter $\\sigma_a\\varepsilon_a$ and the life."
   ],
   "id": "markdown-09"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "cyclic = RambergOsgood(youngs_modulus=modulus, strength_coefficient=1258e6, hardening_exponent=0.208)\n",
    "life_curve = StrainLifeCurve(youngs_modulus=modulus, fatigue_strength_coefficient=948e6, fatigue_strength_exponent=-0.092,\n",
    "                             fatigue_ductility_coefficient=0.26, fatigue_ductility_exponent=-0.445)\n",
    "elastic = np.asarray(samples[-1].values, dtype=float)\n",
    "local = {name: rule(elastic, cyclic) for name, rule in ((\"Neuber\", neuber_notch), (\"Glinka\", glinka_notch))}\n",
    "lives = {name: life_curve.cycles_from_smith_watson_topper(s * e) for name, (s, e) in local.items()}\n",
    "hot = int(np.argmax(elastic))\n",
    "spot = samples[-1].positions[hot]\n",
    "print(f\"hot spot at x = {1e3 * spot[0]:.2f} mm, y = {1e3 * spot[1]:.2f} mm, z = {1e3 * spot[2]:.2f} mm; elastic amplitude {elastic[hot] / 1e6:.1f} MPa \"\n",
    "      f\"(elastic strain {100 * elastic[hot] / modulus:.4f} %)\")\n",
    "for name, (s, e) in local.items():\n",
    "    print(f\"{name:6s}: local stress amplitude {s[hot] / 1e6:6.1f} MPa, strain amplitude {100 * e[hot]:.4f} % \"\n",
    "          f\"(rule check {s[hot] * e[hot] / (elastic[hot] ** 2 / modulus):.6f} / {float(cyclic.strain_energy_density(s[hot])) / (elastic[hot] ** 2 / (2 * modulus)):.6f}), \"\n",
    "          f\"SWT {s[hot] * e[hot] / 1e6:.4f} MPa → {float(lives[name][hot]):,.0f} cycles\")\n",
    "print(f\"shortest lives over the hole surface: Neuber {np.min(lives['Neuber']):,.0f}, Glinka {np.min(lives['Glinka']):,.0f} cycles; \"\n",
    "      f\"Glinka/Neuber {np.min(lives['Glinka']) / np.min(lives['Neuber']):.2f}\")"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "code-10"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figures\n",
    "\n",
    "Left the von Mises stress amplitude on the surface; middle the cyclic curve with the Neuber\n",
    "hyperbola through the hot spot and both local states; right the life along the edge of the\n",
    "hole against the angle around it."
   ],
   "id": "markdown-11"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "curve_stress = np.linspace(1e6, 1.2 * elastic[hot], 300)\n",
    "angle = np.degrees(np.arctan2(samples[-1].positions[:, 1], samples[-1].positions[:, 0] - length / 2))\n",
    "fig = plots.figure(1, 3, size=(20, 6))\n",
    "plots.surface(mises[-1], camera=plots.Camera(elevation=60, azimuth=-90), title=\"Elastic von Mises stress amplitude\", ax=fig[0])\n",
    "plots.line(y={\"cyclic Ramberg-Osgood curve\": (100 * cyclic.strain(curve_stress), curve_stress / 1e6),\n",
    "              \"Neuber hyperbola σε = σ_e²/E\": (100 * elastic[hot] ** 2 / modulus / curve_stress, curve_stress / 1e6),\n",
    "              \"linear-elastic line\": (100 * curve_stress / modulus, curve_stress / 1e6)},\n",
    "           points={name: (100 * e[hot : hot + 1], s[hot : hot + 1] / 1e6) for name, (s, e) in local.items()},\n",
    "           styles={\"Neuber hyperbola σε = σ_e²/E\": \"dashed\", \"linear-elastic line\": \"dotted\"}, xlimits=(0, 1.2), ylimits=(0, 1.2 * elastic[hot] / 1e6),\n",
    "           xlabel=\"strain amplitude [%]\", ylabel=\"stress amplitude [MPa]\", title=\"Local state at the hot spot\", legend=\"lower right\", ax=fig[1])\n",
    "plots.line(points={name: (angle, life) for name, life in lives.items()}, scale=\"logy\", ylimits=(1e3, 1e9), xlabel=\"angle around the hole [°]\",\n",
    "           ylabel=\"cycles to crack initiation\", title=\"Life over the hole surface\", legend=\"lower right\", ax=fig[2])\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "code-12"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Compare with the full elastic-plastic analysis of the same shaft (example \"Low-cycle fatigue of a\n",
    "shaft with a transverse hole\"); add a mean load and use the Morrow form\n",
    "`life_curve.strain_amplitude(cycles, mean_stress=...)`; or evaluate the critical plane of the\n",
    "corrected strain tensor."
   ],
   "id": "markdown-13"
  }
 ]
}
