{
 "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": [
    "# Cycle counting and fatigue damage in a flat specimen\n",
    "\n",
    "A load spectrum that is not a single sinusoid has to be broken into closed stress cycles before\n",
    "an S-N curve can be applied. The standard way is **rainflow counting** (ASTM E1049-85, *Standard\n",
    "Practices for Cycle Counting in Fatigue Analysis*, Sec. 5.4.4). Each counted cycle $i$ (full or\n",
    "half) has an amplitude $\\sigma_{a,i}$, a mean $\\sigma_{m,i}$ and a load ratio\n",
    "$R_i=\\sigma_{\\min}/\\sigma_{\\max}$; the Palmgren-Miner rule then accumulates\n",
    "\n",
    "$$D=m\\sum_i \\frac{n_i}{N(\\sigma_{a,i},R_i)} ,$$\n",
    "\n",
    "where $n_i\\in\\{\\tfrac12,1\\}$, $m$ is the number of repetitions of the load block and $N$ the life\n",
    "from the S-N curve. Failure is predicted at $D=1$.\n",
    "\n",
    "**Setup.** The specimen is a flat bar of thickness 6.25 mm: a central section 12.5 mm wide,\n",
    "circular fillets of radius 12.5 mm and 20 mm wide grips; overall length 200 mm. Aluminium,\n",
    "$E=69$ GPa, $\\nu=0.34$. One unit of the load history is the axial force $F_u=781.25$ N that\n",
    "produces 10 MPa in the central section. The load block is the ASTM E1049 example sequence\n",
    "$-2,1,-3,5,-1,3,-4,4,-2$ units, repeated $m=10^5$ times. The S-N curve depends on the stress\n",
    "amplitude and on $R$,\n",
    "\n",
    "$$\\sigma_a = 94\\,\\mathrm{MPa}\\,\\Big(\\frac{R}{-0.36}\\Big)^{1.15} N^{-0.119},$$\n",
    "\n",
    "and lives $N\\ge 10^8$ count as infinite.\n",
    "\n",
    "The CAD file `fatigue_cycle_counting_component.step` holds one quarter of the specimen with the\n",
    "face groups `symmetry_x`, `symmetry_y`, `grip`, `fillet` and `free`; the script\n",
    "`fatigue_cycle_counting_component_geometry.py` builds it with the CAD objects of OneSimulation.\n",
    "The specimen is thin and loaded in its plane, so the model is plane stress on its mid-plane.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| $x=0$ and $y=0$ (symmetry lines) | no normal displacement |\n",
    "| grip end $y=100$ mm | uniform traction, $F_u/2$ on the quarter per load unit |\n",
    "| central-section edge, fillet, grip edge | traction free |\n",
    "\n",
    "**Reference.** The rainflow table of the ASTM E1049 worked example, the nominal stress and the\n",
    "reaction force, and the bin-based fatigue usage of this benchmark, $D=0.182$ (finite elements)\n",
    "and $D=0.184$ (hand evaluation of the ASTM cycles on the same bins)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.physics.solid_mechanics import SmallStrainSolid, fatigue_cycles\n",
    "from onesim.results.comparisons import convergence\n",
    "from onesim.results.derived import signed_extreme_principal\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry\n",
    "\n",
    "`load` returns the quarter specimen with its named faces; `section` cuts it at half thickness\n",
    "and returns the planar region, whose sides carry the names of the faces they were cut from."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "specimen = load(\"fatigue_cycle_counting_component.step\")\n",
    "faces = specimen.boundaries\n",
    "half_width, half_length, thickness = specimen.size\n",
    "quarter = specimen.section((0, 0, 1), origin=(0, 0, thickness / 2))\n",
    "sides = quarter.boundaries\n",
    "free = sides.x_max | sides[\"beside.x_min\"] | sides[\"fillet.outer_wall\"]\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 6))\n",
    "plots.geometry(\n",
    "    specimen,\n",
    "    selection={\n",
    "        \"grip\": faces.grip,\n",
    "        \"fillet\": faces.fillet,\n",
    "        \"symmetry\": faces.symmetry_x | faces.symmetry_y,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=35, azimuth=-50),\n",
    "    title=\"Quarter specimen with its named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.geometry(quarter, title=\"Mid-plane section\", ax=fig[1])\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Stress per load unit\n",
    "\n",
    "Quadratic triangles, 0.2 mm along the fillet and the central-section edge and 1.6 mm elsewhere;\n",
    "every refinement level splits each triangle into four. The material is linear, so one solve with\n",
    "a unit load gives the stress per load unit. Linear triangles on the same meshes serve as a\n",
    "comparison. The principal stress of largest magnitude is taken at the integration points."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "youngs_modulus, half_neck = 69e9, 0.00625\n",
    "unit_force = 10e6 * 2 * half_neck * thickness\n",
    "solid = SmallStrainSolid(\n",
    "    youngs_modulus=youngs_modulus,\n",
    "    poisson_ratio=0.34,\n",
    "    kinematics=\"plane_stress\",\n",
    "    thickness=thickness,\n",
    ")\n",
    "\n",
    "\n",
    "def solve(order, level):\n",
    "    \"\"\"Mesh, unit-load solution and principal stress on the mesh refined `level` times.\"\"\"\n",
    "    mesh = TriangularMesher(\n",
    "        target_size=1.6e-3,\n",
    "        grading=0.2,\n",
    "        refinements=level,\n",
    "        local_sizes={\"beside.x_min\": 0.2e-3, \"fillet.outer_wall\": 0.2e-3},\n",
    "    ).generate(quarter)\n",
    "    result = solid.solve(\n",
    "        mesh=mesh,\n",
    "        times=(1.0,),\n",
    "        order=order,\n",
    "        displacements=((sides.x_min, \"x\", 0.0), (sides.y_min, \"y\", 0.0)),\n",
    "        tractions=(\n",
    "            (sides.y_max, (0.0, unit_force / 2 / (half_width * thickness))),\n",
    "            (free, (0.0, 0.0)),\n",
    "        ),\n",
    "    )\n",
    "    return mesh, result, signed_extreme_principal(result.stress[0])\n",
    "\n",
    "\n",
    "runs = {(order, level): solve(order, level) for order in (1, 2) for level in (0, 1, 2)}\n",
    "mesh, result, principal = runs[2, 2]\n",
    "peaks = {key: run[2].max() for key, run in runs.items()}\n",
    "elongation = {\n",
    "    key: run[1]\n",
    "    .displacement[0][np.isclose(run[1].coordinates[:, 1], half_length), 1]\n",
    "    .mean()\n",
    "    for key, run in runs.items()\n",
    "}\n",
    "benchmark_point = np.argmin(\n",
    "    np.hypot(*(result.quadrature_coordinates - (0.003, 0.020)).T)\n",
    ")\n",
    "sigma_bench, sigma_hot = result.stress[0][benchmark_point, 1, 1], peaks[2, 2]\n",
    "reaction = -result.reactions[0][np.isclose(result.coordinates[:, 1], 0.0), 1].sum()\n",
    "\n",
    "print(\n",
    "    f\"benchmark point (3, 20) mm: {sigma_bench / 1e6:.5f} MPa per unit, nominal 10 MPa\"\n",
    ")\n",
    "print(f\"reaction on y = 0: {reaction:.4f} N, applied {unit_force / 2:.4f} N\")\n",
    "print(f\"stress concentration of the fillet: {sigma_hot / 10e6:.4f}\")\n",
    "print(\"elements   triangles   elongation [nm]   fillet peak [MPa]\")\n",
    "for (order, level), (cells, _, _) in runs.items():\n",
    "    print(\n",
    "        f\"P{order} {cells.cell_count:15d} {1e9 * elongation[order, level]:17.5f} {peaks[order, level] / 1e6:19.5f}\"\n",
    "    )\n",
    "study = convergence([elongation[2, level] for level in (0, 1, 2)], [4.0, 2.0, 1.0])\n",
    "print(\n",
    "    f\"P2 elongation: observed order {study.order:.2f}, extrapolated {1e9 * study.extrapolated:.5f} nm; \"\n",
    "    f\"P2 fillet peak changes by {100 * abs(peaks[2, 2] / peaks[2, 1] - 1):.4f} % on the last refinement\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Rainflow counting and damage\n",
    "\n",
    "`fatigue_cycles` reduces the load block to its turning points and counts the cycles after\n",
    "ASTM E1049 (full cycles as they close, half cycles from the residue). The load is proportional,\n",
    "so every point sees the same cycles, scaled by its stress per load unit."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "load_block, blocks, infinite_life = (\n",
    "    (-2.0, 1.0, -3.0, 5.0, -1.0, 3.0, -4.0, 4.0, -2.0),\n",
    "    1e5,\n",
    "    1e8,\n",
    ")\n",
    "amplitude, mean, count = np.array(\n",
    "    [\n",
    "        (c.stress_amplitude, c.mean_stress, c.count)\n",
    "        for c in fatigue_cycles(stress=load_block)\n",
    "    ]\n",
    ").T\n",
    "sn_life = lambda amplitude, ratio: (amplitude / (94e6 * (ratio / -0.36) ** 1.15)) ** (\n",
    "    -1 / 0.119\n",
    ")\n",
    "\n",
    "\n",
    "def damage(amplitude, mean):\n",
    "    \"\"\"Miner damage of each counted cycle after all blocks, for its stress amplitude and mean in Pa.\"\"\"\n",
    "    with np.errstate(all=\"ignore\"):\n",
    "        life = sn_life(amplitude, (mean - amplitude) / (mean + amplitude))\n",
    "        return blocks * np.where(life < infinite_life, count / life, 0.0)\n",
    "\n",
    "\n",
    "true_cycles = damage(sigma_bench * amplitude, sigma_bench * mean)\n",
    "amplitude_bins, mean_bins = np.linspace(15e6, 45e6, 8), np.linspace(-10e6, 10e6, 6)\n",
    "centre = (\n",
    "    lambda edges, values: edges[\n",
    "        np.clip(\n",
    "            np.searchsorted(edges, values + 1.0, side=\"right\") - 1, 0, len(edges) - 2\n",
    "        )\n",
    "    ]\n",
    "    + np.diff(edges)[0] / 2\n",
    ")\n",
    "binned = damage(\n",
    "    centre(amplitude_bins, sigma_bench * amplitude),\n",
    "    centre(mean_bins, sigma_bench * mean),\n",
    ")\n",
    "damage_hot = damage(sigma_hot * amplitude, sigma_hot * mean).sum()\n",
    "damage_map = damage(\n",
    "    np.abs(principal)[:, None] * amplitude, principal[:, None] * mean\n",
    ").sum(axis=1)\n",
    "\n",
    "print(\"range [units]   cycles counted   ASTM E1049\")\n",
    "for load_range, astm in ((3, 0.5), (4, 1.5), (6, 0.5), (8, 1.0), (9, 0.5)):\n",
    "    print(\n",
    "        f\"{load_range:13d} {count[np.isclose(2 * amplitude, load_range)].sum():16.1f} {astm:12.1f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"benchmark point after {blocks:.0e} blocks: D = {binned.sum():.4f} on the bin centres (benchmark 0.182, hand evaluation 0.184), \"\n",
    "    f\"D = {true_cycles.sum():.4f} with the true cycles\"\n",
    ")\n",
    "print(\n",
    "    f\"fillet: D = {damage_hot:.3f}, predicted life {blocks / damage_hot:.0f} blocks (benchmark point {blocks / true_cycles.sum():.0f} blocks)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The principal stress per load unit and the damage on the cells of the finest mesh, the stress\n",
    "history of one block, the damage of each counted cycle at the benchmark point (labelled by\n",
    "amplitude/mean in MPa) and the mesh study of the fillet stress."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "per_cell = lambda values: values.reshape(mesh.cell_count, -1).max(axis=1)\n",
    "steps = np.arange(1, len(load_block) + 1)\n",
    "unknowns = {\n",
    "    order: [2 * runs[order, level][1].space.dof_count for level in (0, 1, 2)]\n",
    "    for order in (1, 2)\n",
    "}\n",
    "\n",
    "fig = plots.figure(\n",
    "    layout=[\n",
    "        [\"stress\", \"damage\", \"history\", \"matrix\"],\n",
    "        [\"stress\", \"damage\", \"bars\", \"study\"],\n",
    "    ],\n",
    "    size=(21, 10),\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    cell_values=per_cell(principal) / 1e6,\n",
    "    edges=False,\n",
    "    limits=(6.0, sigma_hot / 1e6),\n",
    "    label=\"MPa per load unit\",\n",
    "    title=\"Principal stress\",\n",
    "    ax=fig[\"stress\"],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    cell_values=np.log10(np.maximum(per_cell(damage_map), 1e-6)),\n",
    "    edges=False,\n",
    "    limits=(-2.0, np.log10(damage_hot)),\n",
    "    label=\"log10 D\",\n",
    "    title=f\"Miner damage, max {damage_hot:.2f}\",\n",
    "    ax=fig[\"damage\"],\n",
    ")\n",
    "plots.line(\n",
    "    steps,\n",
    "    {\n",
    "        \"fillet hot spot\": np.array(load_block) * sigma_hot / 1e6,\n",
    "        \"benchmark point\": np.array(load_block) * sigma_bench / 1e6,\n",
    "    },\n",
    "    markers=True,\n",
    "    hlines=0.0,\n",
    "    xlabel=\"load step in block\",\n",
    "    ylabel=\"stress [MPa]\",\n",
    "    title=\"Stress history of one block\",\n",
    "    ax=fig[\"history\"],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"counted cycles\": (sigma_bench * mean / 1e6, sigma_bench * amplitude / 1e6)\n",
    "    },\n",
    "    vlines=mean_bins / 1e6,\n",
    "    hlines=amplitude_bins / 1e6,\n",
    "    xlabel=\"mean stress [MPa]\",\n",
    "    ylabel=\"stress amplitude [MPa]\",\n",
    "    title=\"Rainflow matrix and benchmark bins\",\n",
    "    ax=fig[\"matrix\"],\n",
    ")\n",
    "plots.bars(\n",
    "    [\n",
    "        f\"{a:.0f}/{m:.0f}\"\n",
    "        for a, m in zip(sigma_bench * amplitude / 1e6, sigma_bench * mean / 1e6)\n",
    "    ],\n",
    "    {\n",
    "        f\"true cycles, D = {true_cycles.sum():.3f}\": true_cycles,\n",
    "        f\"bin centres, D = {binned.sum():.3f} (benchmark 0.182)\": binned,\n",
    "    },\n",
    "    ylabel=\"damage contribution\",\n",
    "    title=\"Damage per cycle at the benchmark point\",\n",
    "    ax=fig[\"bars\"],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"P{order} triangles\": (\n",
    "            unknowns[order],\n",
    "            [peaks[order, level] / 1e6 for level in (0, 1, 2)],\n",
    "        )\n",
    "        for order in (1, 2)\n",
    "    },\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"unknowns\",\n",
    "    ylabel=\"fillet peak stress [MPa per unit]\",\n",
    "    title=\"Mesh study of the critical stress\",\n",
    "    ax=fig[\"study\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the fillet radius in `fatigue_cycle_counting_component_geometry.py`, write the STEP file\n",
    "again and find the radius at which the fillet stops being the critical location. Replace the\n",
    "R-dependent curve by a fully reversed S-N curve with a Goodman or Gerber mean-stress correction\n",
    "(`SNDataset(mean_stress_correction=\"goodman\", ...)` with `linear_damage_field`) and compare the\n",
    "predicted lives."
   ]
  }
 ]
}
