{
 "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": [
    "# Primary creep under a changing load\n",
    "\n",
    "At high temperature metals creep: they keep straining under constant stress. In the primary stage\n",
    "the creep rate falls with time, which the Norton-Bailey law describes for constant stress as\n",
    "\n",
    "$$\\bar\\varepsilon_c=A\\,q^n\\,t^m ,\\qquad m<1 ,$$\n",
    "\n",
    "with the von Mises stress $q$ and the equivalent creep strain $\\bar\\varepsilon_c$. The creep strain\n",
    "rate is deviatoric and follows the stress deviator $\\mathbf s$,\n",
    "$\\dot{\\boldsymbol\\varepsilon}_c=\\tfrac32\\,\\dot{\\bar\\varepsilon}_c\\,\\mathbf s/q$.\n",
    "\n",
    "When the stress changes, the law has to say what the material \"remembers\". Two classical rules\n",
    "differentiate the law differently:\n",
    "\n",
    "| rule | creep rate | memory |\n",
    "|---|---|---|\n",
    "| time hardening | $\\dot{\\bar\\varepsilon}_c=m\\,A\\,q^n\\,t^{m-1}$ | time since the start of creep |\n",
    "| strain hardening | $\\dot{\\bar\\varepsilon}_c=m\\,A^{1/m}q^{n/m}\\,\\bar\\varepsilon_c^{(m-1)/m}$ | creep strain accumulated so far |\n",
    "\n",
    "Under constant stress both give the same curve; after a load change they differ.\n",
    "\n",
    "**Setup.** A block of 10 mm × 10 mm × 2 mm with $E=200$ GPa, $\\nu=0.3$ and the creep constants\n",
    "$A=8\\cdot10^{-30}$ Pa$^{-3}$s$^{-1/2}$, $n=3$, $m=0.5$. For the first 50 h the block carries a\n",
    "tensile stress $\\sigma_x=100$ MPa; from 50 h to 100 h a compressive stress $\\sigma_y=-100$ MPa is\n",
    "added, which raises the von Mises stress to $100\\sqrt3$ MPa and turns the creep direction. The block\n",
    "comes from the CAD file `primary_creep_nonconstant_load.step`, written by\n",
    "`primary_creep_nonconstant_load_geometry.py` with the CAD objects of OneSimulation.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `x_min`, `y_min`, `z_min` | symmetry (normal displacement 0) |\n",
    "| `x_max` | traction $\\sigma_x=100$ MPa |\n",
    "| `y_max` | traction $\\sigma_y=0$, from 50 h on $-100$ MPa |\n",
    "| `z_max` | free |\n",
    "\n",
    "**Reference.** The stress is uniform and constant within each stage, so the equivalent creep strain\n",
    "has closed forms (e.g. Kraus, *Creep Analysis*, Wiley 1980, Ch. 2): with $t_1=50$ h,\n",
    "$\\bar\\varepsilon_1=A q_1^n t_1^m$ and $t>t_1$,\n",
    "\n",
    "$$\\text{time hardening: }\\bar\\varepsilon_c=\\bar\\varepsilon_1+A q_2^n\\,(t^m-t_1^m),\\qquad\n",
    "  \\text{strain hardening: }\\bar\\varepsilon_c=\\big(\\bar\\varepsilon_1^{1/m}+A^{1/m}q_2^{n/m}(t-t_1)\\big)^m .$$\n",
    "\n",
    "The tensor components follow from the flow direction of each stage: $(1,-\\tfrac12,-\\tfrac12)$ in\n",
    "uniaxial tension, $(\\tfrac{\\sqrt3}2,-\\tfrac{\\sqrt3}2,0)$ under the combined load."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials.solids import CreepMaterialPoint, PowerLawCreep\n",
    "from onesim.meshing import CadHexahedralMesher\n",
    "from onesim.physics.solid_mechanics import SmallStrainSolid\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 block with its named faces; it is meshed with quadratic hexahedra."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "block = load(\"primary_creep_nonconstant_load.step\")\n",
    "faces = block.boundaries\n",
    "mesh = CadHexahedralMesher(cells=(4, 4, 1)).generate(block)\n",
    "\n",
    "view = plots.Camera(elevation=35, azimuth=40)\n",
    "fig = plots.figure(1, 2, size=(13, 6))\n",
    "plots.geometry(\n",
    "    block,\n",
    "    selection={\n",
    "        \"σ_x\": faces.x_max,\n",
    "        \"σ_y\": faces.y_max,\n",
    "        \"symmetry\": faces.x_min | faces.y_min | faces.z_min,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Creep block 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} quadratic hexahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`SmallStrainSolid` in 3D carries a `CreepMaterialPoint` with the Norton-Bailey law; the hardening\n",
    "rule is the only difference between the two runs. Each load step is integrated implicitly at\n",
    "every quadrature point. The steps are spaced logarithmically from the start of creep and again from\n",
    "the load change, where the creep rate is highest."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "hour, switch = 3600.0, 50 * 3600.0\n",
    "coefficient, exponent, time_exponent = 8e-30, 3.0, 0.5\n",
    "law = PowerLawCreep(\n",
    "    coefficient=coefficient, stress_exponent=exponent, time_exponent=time_exponent\n",
    ")\n",
    "times = (\n",
    "    np.r_[0.0, np.geomspace(0.01, 50.0, 30), 50.0 + np.geomspace(0.01, 50.0, 30)] * hour\n",
    ")\n",
    "transverse = lambda x, y, z, t: (0.0, -100e6 if t > switch + 1.0 else 0.0, 0.0)\n",
    "results = {\n",
    "    rule: SmallStrainSolid(\n",
    "        youngs_modulus=200e9,\n",
    "        poisson_ratio=0.3,\n",
    "        kinematics=\"volume\",\n",
    "        material_point=CreepMaterialPoint(laws=(law,), hardening=rule),\n",
    "    ).solve(\n",
    "        mesh=mesh,\n",
    "        times=times,\n",
    "        order=2,\n",
    "        displacements=(\n",
    "            (faces.x_min, \"x\", 0.0),\n",
    "            (faces.y_min, \"y\", 0.0),\n",
    "            (faces.z_min, \"z\", 0.0),\n",
    "        ),\n",
    "        tractions=((faces.x_max, (100e6, 0.0, 0.0)), (faces.y_max, transverse)),\n",
    "    )\n",
    "    for rule in (\"time\", \"strain\")\n",
    "}\n",
    "states = {\n",
    "    rule: [step[0][0] for step in result.material_history]\n",
    "    for rule, result in results.items()\n",
    "}\n",
    "creep = {\n",
    "    rule: np.array([state.creep_strain[:3] for state in history])\n",
    "    for rule, history in states.items()\n",
    "}\n",
    "equivalent = {\n",
    "    rule: np.array([state.equivalent_creep_strain for state in history])\n",
    "    for rule, history in states.items()\n",
    "}\n",
    "spread = {\n",
    "    rule: np.ptp(\n",
    "        [\n",
    "            point.equivalent_creep_strain\n",
    "            for cell in result.material_history[-1]\n",
    "            for point in cell\n",
    "        ]\n",
    "    )\n",
    "    for rule, result in results.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the closed-form solution\n",
    "\n",
    "The equivalent creep strain and the three normal creep strains against the closed forms, at the\n",
    "load change and at the end."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "first, second = 100e6, 100e6 * np.sqrt(3)\n",
    "before = (\n",
    "    lambda t: coefficient * first**exponent * np.minimum(t, switch) ** time_exponent\n",
    ")\n",
    "reference = {\n",
    "    \"time\": lambda t: np.where(\n",
    "        t <= switch,\n",
    "        before(t),\n",
    "        before(switch)\n",
    "        + coefficient\n",
    "        * second**exponent\n",
    "        * (np.maximum(t, switch) ** time_exponent - switch**time_exponent),\n",
    "    ),\n",
    "    \"strain\": lambda t: np.where(\n",
    "        t <= switch,\n",
    "        before(t),\n",
    "        (\n",
    "            before(switch) ** (1 / time_exponent)\n",
    "            + coefficient ** (1 / time_exponent)\n",
    "            * second ** (exponent / time_exponent)\n",
    "            * np.maximum(t - switch, 0.0)\n",
    "        )\n",
    "        ** time_exponent,\n",
    "    ),\n",
    "}\n",
    "components = lambda total: (\n",
    "    np.outer(np.minimum(total, before(switch)), [1.0, -0.5, -0.5])\n",
    "    + np.outer(\n",
    "        total - np.minimum(total, before(switch)),\n",
    "        [np.sqrt(3) / 2, -np.sqrt(3) / 2, 0.0],\n",
    "    )\n",
    ")\n",
    "print(\n",
    "    f\"stress at the end: σ_x = {results['strain'].stress[-1, :, 0, 0].mean() / 1e6:.3f} MPa, σ_y = {results['strain'].stress[-1, :, 1, 1].mean() / 1e6:.3f} MPa\"\n",
    ")\n",
    "for rule in results:\n",
    "    exact = reference[rule](times)\n",
    "    print(\n",
    "        f\"{rule} hardening: equivalent creep strain {100 * equivalent[rule][times == switch][0]:.4f} % at 50 h and {100 * equivalent[rule][-1]:.4f} % at 100 h \"\n",
    "        f\"(closed form {100 * exact[times == switch][0]:.4f} % and {100 * exact[-1]:.4f} %), \"\n",
    "        f\"largest deviation {np.abs(equivalent[rule] - exact).max() / exact[-1]:.1e} of the final value, \"\n",
    "        f\"spread over all quadrature points {spread[rule]:.1e}\"\n",
    "    )\n",
    "    print(\n",
    "        f\"   creep strains at 100 h: ε_xx {100 * creep[rule][-1, 0]:.4f} %, ε_yy {100 * creep[rule][-1, 1]:.4f} %, ε_zz {100 * creep[rule][-1, 2]:.4f} %\"\n",
    "        f\"  (closed form {', '.join(f'{100 * value:.4f} %' for value in components(exact)[-1])})\"\n",
    "    )\n",
    "print(\n",
    "    f\"after the load change strain hardening creeps faster: at 100 h it is {100 * (equivalent['strain'][-1] / equivalent['time'][-1] - 1):.1f} % ahead of time hardening\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left the equivalent creep strain of both rules with the closed forms; right the normal creep\n",
    "strains of both rules, with the closed form of the strain-hardening rule as lines. In the first stage the curves coincide. After the load change, time hardening continues\n",
    "on the flat part of the creep curve, whereas strain hardening restarts on a steeper part, because\n",
    "the higher stress has less accumulated creep strain behind it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "line = np.linspace(0.0, times[-1], 600)\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"{rule} hardening\": (times / hour, 100 * equivalent[rule]) for rule in results\n",
    "    },\n",
    "    reference={\n",
    "        f\"{rule} hardening, closed form\": (line / hour, 100 * reference[rule](line))\n",
    "        for rule in results\n",
    "    },\n",
    "    vlines={\"load change\": 50.0},\n",
    "    xlabel=\"time [h]\",\n",
    "    ylabel=\"equivalent creep strain [%]\",\n",
    "    title=\"Equivalent creep strain\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"ε_{axis}, {rule}\": (times / hour, 100 * creep[rule][:, k])\n",
    "        for rule in results\n",
    "        for k, axis in enumerate((\"xx\", \"yy\", \"zz\"))\n",
    "    },\n",
    "    reference={\n",
    "        f\"ε_{axis}, closed form\": (\n",
    "            line / hour,\n",
    "            100 * components(reference[\"strain\"](line))[:, k],\n",
    "        )\n",
    "        for k, axis in enumerate((\"xx\", \"yy\", \"zz\"))\n",
    "    },\n",
    "    vlines={\"load change\": 50.0},\n",
    "    xlabel=\"time [h]\",\n",
    "    ylabel=\"creep strain [%]\",\n",
    "    title=\"Normal creep strains\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add a secondary Norton term as a second law in `laws=(...)`, make the creep constant depend on\n",
    "temperature through an activation energy, or remove the load after 50 h and follow the elastic\n",
    "recovery; under a reversed load strain hardening and time hardening part even further."
   ]
  }
 ]
}
