{
 "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": [
    "# Multiaxial high-cycle fatigue of a cylindrical specimen\n",
    "\n",
    "Shafts, axles and springs are often loaded by bending or tension and by torsion at the same time.\n",
    "When the two loads do not rise and fall together, the principal directions rotate during a cycle\n",
    "and the load is *non-proportional*. Uniaxial fatigue data then no longer apply directly.\n",
    "Critical-plane criteria look at every plane through a material point, follow the normal stress\n",
    "$\\sigma_n(t)$ and the shear traction $\\boldsymbol\\tau(t)$ on it, and combine them into a scalar\n",
    "fatigue parameter:\n",
    "\n",
    "| criterion | parameter on a plane | critical plane |\n",
    "|---|---|---|\n",
    "| Findley | $\\tau_a+k\\,\\sigma_{n,\\max}$ | plane with the largest parameter |\n",
    "| Matake | $\\tau_a+k\\,\\sigma_{n,\\max}$ | plane with the largest shear amplitude $\\tau_a$ |\n",
    "| normal stress | $\\sigma_{n,a}$ | plane with the largest normal stress amplitude |\n",
    "\n",
    "with the shear amplitude $\\tau_a$ (half the diameter of the shear traction path), the largest normal\n",
    "stress $\\sigma_{n,\\max}$ during the cycle and a material constant $k$ (here $k=0.3$ for both).\n",
    "\n",
    "**Setup.** A specimen of diameter 10 mm and length 60 mm, steel with $E=210$ GPa, $\\nu=0.3$,\n",
    "clamped at the bottom. The top carries an alternating axial stress\n",
    "$\\sigma(t)=\\sigma_a\\sin\\omega t$ with $\\sigma_a=200$ MPa and an alternating torque that gives the\n",
    "surface shear stress $\\tau(t)=\\tau_a\\sin(\\omega t-\\varphi)$ with $\\tau_a=120$ MPa. The phase shift\n",
    "$\\varphi$ runs from 0 (proportional) to 90° (fully out of phase). The specimen comes from the CAD file\n",
    "`cylindrical_specimen_multiaxial_hcf.step`, written by `cylindrical_specimen_multiaxial_hcf_geometry.py`\n",
    "with the CAD objects of OneSimulation.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `clamped` | fixed |\n",
    "| `loaded` | axial traction $\\sigma$, or the torsional traction $\\tau\\,r/R$ along the circumference |\n",
    "| `mantle` | free |\n",
    "\n",
    "**Reference.** Away from the ends the surface is in plane stress with $\\sigma_{zz}=\\sigma(t)$ and\n",
    "$\\tau_{\\theta z}=\\tau(t)$ (Saint-Venant). On a plane whose normal lies in the $\\theta z$ plane at the\n",
    "angle $\\theta$ to the axis, both tractions are sums of two sinusoids,\n",
    "\n",
    "$$\\sigma_n=\\sigma\\cos^2\\theta+\\tau\\sin2\\theta,\\qquad \\tau_n=-\\tfrac12\\sigma\\sin2\\theta+\\tau\\cos2\\theta ,$$\n",
    "\n",
    "whose amplitudes follow from $|A\\sin\\omega t+B\\sin(\\omega t-\\varphi)|=\\sqrt{A^2+B^2+2AB\\cos\\varphi}$.\n",
    "Maximising over $\\theta$ gives the Findley and normal-stress values for every phase shift. For\n",
    "proportional loading the closed forms are (Socie and Marquis, *Multiaxial Fatigue*, SAE 2000)\n",
    "\n",
    "$$f_\\text{Findley}=\\frac{k\\sigma_a}{2}+\\sqrt{1+k^2}\\,\\sqrt{\\frac{\\sigma_a^2}{4}+\\tau_a^2},\\qquad\n",
    "  f_\\text{Matake}=\\sqrt{\\frac{\\sigma_a^2}{4}+\\tau_a^2}+\\frac{k\\sigma_a}{2} .$$"
   ]
  },
  {
   "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, with_order\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",
    "    FindleyCriterion,\n",
    "    FixedDisplacement,\n",
    "    LinearElasticity,\n",
    "    Traction,\n",
    "    TractionFree,\n",
    "    critical_plane,\n",
    "    matake_parameter,\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 specimen with its named faces; two meshes of curved quadratic tetrahedra, 1.5 mm\n",
    "and 1.0 mm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "specimen = load(\"cylindrical_specimen_multiaxial_hcf.step\")\n",
    "faces = specimen.boundaries\n",
    "radius, length = specimen.size[0] / 2, specimen.size[2]\n",
    "sizes = [0.0015, 0.0010]\n",
    "meshes = [\n",
    "    with_order(\n",
    "        TetrahedralMesher(target_size=size, curvature_angle=0.3).generate(specimen), 2\n",
    "    )\n",
    "    for size in sizes\n",
    "]\n",
    "\n",
    "view = plots.Camera(elevation=20, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(12, 7))\n",
    "plots.geometry(\n",
    "    specimen,\n",
    "    selection={\n",
    "        \"clamped\": faces.clamped,\n",
    "        \"loaded\": faces.loaded,\n",
    "        \"mantle\": faces.mantle,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Specimen 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\"Finer 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",
    "Two linear load cases on each mesh: an axial traction of 1 MPa and the torsional traction that\n",
    "gives 1 MPa shear at the surface. Because the specimen is linear elastic, the stress at any time\n",
    "is the sum of the two unit fields scaled by $\\sigma(t)$ and $\\tau(t)$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "steel = IsotropicSolid(\n",
    "    density=7850.0,\n",
    "    specific_heat_capacity=460.0,\n",
    "    thermal_conductivity=50.0,\n",
    "    youngs_modulus=210e9,\n",
    "    poisson_ratio=0.3,\n",
    "    thermal_expansion_coefficient=12e-6,\n",
    ")\n",
    "model = LinearElasticity(domain=specimen.volume, material=steel)\n",
    "unit_loads = {\n",
    "    \"tension\": lambda x, y, z: np.column_stack((0 * x, 0 * x, np.full_like(x, 1e6))),\n",
    "    \"torsion\": lambda x, y, z: np.column_stack((-y, x, 0 * x)) * 1e6 / radius,\n",
    "}\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "fields = [\n",
    "    {\n",
    "        name: Simulation(\n",
    "            problem=Problem(\n",
    "                name=f\"Unit {name}\",\n",
    "                geometry=specimen,\n",
    "                physics=(model,),\n",
    "                boundary_conditions=(\n",
    "                    FixedDisplacement(\n",
    "                        boundary=faces.clamped, physics=model, value=(0.0, 0.0, 0.0)\n",
    "                    ),\n",
    "                    Traction(boundary=faces.loaded, physics=model, value=traction),\n",
    "                    TractionFree(boundary=faces.mantle, physics=model),\n",
    "                ),\n",
    "            ),\n",
    "            mesh=mesh,\n",
    "            numerics=numerics,\n",
    "        )\n",
    "        .solve_stationary()\n",
    "        .field(model.stress)\n",
    "        for name, traction in unit_loads.items()\n",
    "    }\n",
    "    for mesh in meshes\n",
    "]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Stress history at the surface\n",
    "\n",
    "The unit stresses are evaluated at the surface point $(R, 0, L/2)$, where the circumferential\n",
    "direction is $y$. One load cycle is sampled at 72 steps for each phase shift; the candidate planes\n",
    "are 4000 normals spread evenly over the half sphere."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "point = np.array([[radius * (1 - 1e-4), 0.0, length / 2]])\n",
    "tensor = lambda v: np.array(\n",
    "    [[v[0], v[3], v[5]], [v[3], v[1], v[4]], [v[5], v[4], v[2]]]\n",
    ")\n",
    "unit = [\n",
    "    {\n",
    "        name: tensor(np.asarray(field.evaluate(point))[0]) / 1e6\n",
    "        for name, field in mesh_fields.items()\n",
    "    }\n",
    "    for mesh_fields in fields\n",
    "]\n",
    "amplitude_axial, amplitude_shear, k = 200e6, 120e6, 0.3\n",
    "cycle = np.linspace(0.0, 2 * np.pi, 73)\n",
    "phases = np.radians(np.arange(0.0, 90.1, 7.5))\n",
    "history = lambda stresses, phase: (\n",
    "    amplitude_axial * np.sin(cycle)[:, None, None] * stresses[\"tension\"]\n",
    "    + amplitude_shear * np.sin(cycle - phase)[:, None, None] * stresses[\"torsion\"]\n",
    ")\n",
    "count = np.arange(4000) + 0.5\n",
    "normals = np.column_stack(\n",
    "    (\n",
    "        np.sqrt(1 - (count / 4000) ** 2) * np.cos(np.pi * (1 + 5**0.5) * count),\n",
    "        np.sqrt(1 - (count / 4000) ** 2) * np.sin(np.pi * (1 + 5**0.5) * count),\n",
    "        count / 4000,\n",
    "    )\n",
    ")\n",
    "findley = [\n",
    "    [\n",
    "        critical_plane(\n",
    "            history(stresses, phase), normals, criterion=FindleyCriterion(k)\n",
    "        ).scores.max()\n",
    "        for phase in phases\n",
    "    ]\n",
    "    for stresses in unit\n",
    "]\n",
    "shear_plane = [\n",
    "    critical_plane(history(unit[-1], phase), normals, criterion=FindleyCriterion(0.0))\n",
    "    for phase in phases\n",
    "]\n",
    "peak_normal = [\n",
    "    critical_plane(\n",
    "        history(unit[-1], phase),\n",
    "        normals,\n",
    "        criterion=lambda normal, shear: normal.max(axis=1),\n",
    "    ).scores\n",
    "    for phase in phases\n",
    "]\n",
    "matake = [\n",
    "    matake_parameter(plane.scores[plane.index], peak[plane.index], sensitivity=k)\n",
    "    for plane, peak in zip(shear_plane, peak_normal)\n",
    "]\n",
    "normal_amplitude = [\n",
    "    critical_plane(\n",
    "        history(unit[-1], phase),\n",
    "        normals,\n",
    "        criterion=lambda normal, shear: (normal.max(axis=1) - normal.min(axis=1)) / 2,\n",
    "    ).scores.max()\n",
    "    for phase in phases\n",
    "]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the closed-form values\n",
    "\n",
    "First the surface stresses of the unit cases against Saint-Venant, then the three parameters for\n",
    "each phase shift against the plane-by-plane closed form."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "theta = np.linspace(0.0, np.pi, 3601)\n",
    "sine_sum = lambda a, b, phase: np.sqrt(a**2 + b**2 + 2 * a * b * np.cos(phase))\n",
    "shear_reference = [\n",
    "    sine_sum(\n",
    "        -amplitude_axial * np.sin(theta) * np.cos(theta),\n",
    "        amplitude_shear * np.cos(2 * theta),\n",
    "        phase,\n",
    "    )\n",
    "    for phase in phases\n",
    "]\n",
    "normal_reference = [\n",
    "    sine_sum(\n",
    "        amplitude_axial * np.cos(theta) ** 2, amplitude_shear * np.sin(2 * theta), phase\n",
    "    )\n",
    "    for phase in phases\n",
    "]\n",
    "findley_reference = np.array(\n",
    "    [(tau + k * sigma).max() for tau, sigma in zip(shear_reference, normal_reference)]\n",
    ")\n",
    "normal_stress_reference = np.array([sigma.max() for sigma in normal_reference])\n",
    "resolved = np.hypot(amplitude_axial / 2, amplitude_shear)\n",
    "for size, stresses in zip(sizes, unit):\n",
    "    print(\n",
    "        f\"mesh {1e3 * size:.1f} mm: σ_zz per MPa of tension {stresses['tension'][2, 2]:.4f}, \"\n",
    "        f\"τ_θz per MPa of surface shear {stresses['torsion'][1, 2]:.4f} (Saint-Venant: 1 and {1 - 1e-4:.4f})\"\n",
    "    )\n",
    "print(\n",
    "    f\"proportional loading: Findley {findley[-1][0] / 1e6:.2f} MPa (closed form {(k * amplitude_axial / 2 + np.sqrt(1 + k**2) * resolved) / 1e6:.2f}), \"\n",
    "    f\"Matake {matake[0] / 1e6:.2f} MPa (closed form {(resolved + k * amplitude_axial / 2) / 1e6:.2f})\"\n",
    ")\n",
    "print(\n",
    "    f\"{'phase [°]':>9s} {'Findley, coarse':>16s} {'Findley, fine':>14s} {'reference':>10s} {'Matake':>8s} {'normal stress':>14s} {'reference':>10s}   [MPa]\"\n",
    ")\n",
    "for j, phase in enumerate(phases):\n",
    "    print(\n",
    "        f\"{np.degrees(phase):9.1f} {findley[0][j] / 1e6:16.2f} {findley[1][j] / 1e6:14.2f} {findley_reference[j] / 1e6:10.2f} \"\n",
    "        f\"{matake[j] / 1e6:8.2f} {normal_amplitude[j] / 1e6:14.2f} {normal_stress_reference[j] / 1e6:10.2f}\"\n",
    "    )\n",
    "print(\n",
    "    \"largest deviation from the reference on the finer mesh: \"\n",
    "    f\"Findley {100 * np.abs(np.array(findley[-1]) / findley_reference - 1).max():.2f} %, \"\n",
    "    f\"normal stress {100 * np.abs(np.array(normal_amplitude) / normal_stress_reference - 1).max():.2f} %\"\n",
    ")\n",
    "print(\n",
    "    f\"Matake at 90°: the shear amplitude is {shear_reference[-1][0] / 1e6:.1f} MPa both on the transverse plane (θ = 0, σ_n,max = \"\n",
    "    f\"{normal_reference[-1][0] / 1e6:.0f} MPa) and on the longitudinal plane (θ = 90°, σ_n,max = 0); the parameter is \"\n",
    "    f\"{(shear_reference[-1][0] + k * normal_reference[-1][0]) / 1e6:.0f} or {shear_reference[-1][0] / 1e6:.0f} MPa, depending on the plane chosen\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The three fatigue parameters over the phase shift with the closed-form curves, and the stress path\n",
    "$(\\sigma_{zz},\\tau_{\\theta z})$ at the surface point for three phase shifts. With growing phase\n",
    "shift the path opens from a line into an ellipse: the principal directions rotate, the largest\n",
    "normal stress amplitude falls and the Findley parameter falls less. The Matake parameter jumps\n",
    "where its plane of largest shear amplitude changes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "degrees = np.degrees(phases)\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.line(\n",
    "    points={\n",
    "        \"Findley\": (degrees, np.array(findley[-1]) / 1e6),\n",
    "        \"Matake\": (degrees, np.array(matake) / 1e6),\n",
    "        \"normal stress amplitude\": (degrees, np.array(normal_amplitude) / 1e6),\n",
    "    },\n",
    "    reference={\n",
    "        \"Findley, closed form\": (degrees, findley_reference / 1e6),\n",
    "        \"normal stress, closed form\": (degrees, normal_stress_reference / 1e6),\n",
    "    },\n",
    "    xlabel=\"phase shift φ [°]\",\n",
    "    ylabel=\"fatigue parameter [MPa]\",\n",
    "    title=\"Critical-plane parameters at the surface\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"φ = {angle:.0f}°\": (\n",
    "            history(unit[-1], np.radians(angle))[:, 2, 2] / 1e6,\n",
    "            history(unit[-1], np.radians(angle))[:, 1, 2] / 1e6,\n",
    "        )\n",
    "        for angle in (0.0, 45.0, 90.0)\n",
    "    },\n",
    "    xlabel=\"axial stress σ_zz [MPa]\",\n",
    "    ylabel=\"shear stress τ_θz [MPa]\",\n",
    "    title=\"Stress path during one cycle\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add a mean stress to the tension and watch the Findley parameter rise through $\\sigma_{n,\\max}$\n",
    "while the normal stress amplitude stays; or replace the smooth specimen by a notched one and\n",
    "evaluate the parameters at the notch root, where the stress state is no longer plane."
   ]
  }
 ]
}
