{
 "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 and secondary creep combined in a hot thick-walled tube\n",
    "\n",
    "Real creep curves start with a primary stage, in which the creep rate falls, before the steady\n",
    "secondary stage. A common model adds the two contributions to the equivalent creep strain rate,\n",
    "\n",
    "$$\\dot{\\bar\\varepsilon}_c=\\underbrace{m\\,A_p^{1/m}\\,q^{n_p/m}\\,\\bar\\varepsilon_p^{(m-1)/m}}_{\\text{Norton-Bailey, strain hardening}}\n",
    "  +\\underbrace{A_s\\,q^{n_s}}_{\\text{Norton}},\\qquad\n",
    "  \\dot{\\boldsymbol\\varepsilon}_c=\\tfrac32\\,\\dot{\\bar\\varepsilon}_c\\,\\frac{\\mathbf s}{q},$$\n",
    "\n",
    "where each law keeps its own accumulated strain. Under constant stress the primary part dies out\n",
    "and the secondary law alone remains.\n",
    "\n",
    "**Setup.** The tube of the companion example: inner radius $a=50$ mm, outer radius $b=100$ mm,\n",
    "internal pressure $p=40$ MPa, long pipe (plane strain), $E=180$ GPa, $\\nu=0.3$, temperature 850 K.\n",
    "Secondary creep: $A_s=2\\cdot10^{-48}$ Pa$^{-5}$s$^{-1}$, $n_s=5$. Primary creep:\n",
    "$A_p=10^{-44}$ Pa$^{-5}$s$^{-0.3}$, $n_p=5$, $m=0.3$. Two runs over 1000 h: secondary\n",
    "creep alone and both laws together. The ring comes from the CAD file\n",
    "`combined_primary_secondary_creep.step`, written by `combined_primary_secondary_creep_geometry.py`\n",
    "with the CAD objects of OneSimulation; the computation uses its meridian section.\n",
    "\n",
    "| edge of the section | condition |\n",
    "|---|---|\n",
    "| `inner` | pressure $p$ |\n",
    "| `outer` | free |\n",
    "| `bottom`, `top` | axial displacement 0 (long pipe) |\n",
    "\n",
    "**Reference.** With the same stress exponent $n=5$ in both laws, the creep strain rate is\n",
    "proportional to $q^5$ at every point at any time, so the stresses tend to the stationary Norton\n",
    "distribution of the thick tube (Kraus, *Creep Analysis*, Wiley 1980, Sec. 4.2), with $\\beta=2/n$,\n",
    "\n",
    "$$\\sigma_\\theta=p\\,\\frac{1+(\\beta-1)(b/r)^\\beta}{(b/a)^\\beta-1},\\qquad\n",
    "  \\sigma_r=-p\\,\\frac{(b/r)^\\beta-1}{(b/a)^\\beta-1},\\qquad \\sigma_z=\\tfrac12(\\sigma_r+\\sigma_\\theta),$$\n",
    "\n",
    "starting from the elastic Lamé stresses. The primary stage only changes how fast it gets there."
   ]
  },
  {
   "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 TriangularMesher\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 sector of the ring with its named faces; `section` cuts the meridian plane\n",
    "$y=0$, whose $x$ coordinate is the radius. Quadratic triangles of 3 mm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "ring = load(\"combined_primary_secondary_creep.step\")\n",
    "faces = ring.boundaries\n",
    "meridian = ring.section((0, 1, 0), origin=(0, 0, 0))\n",
    "edges = meridian.boundaries\n",
    "mesh = TriangularMesher(target_size=0.003).generate(meridian)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    ring,\n",
    "    selection={\n",
    "        \"inner (pressure)\": faces.inner,\n",
    "        \"outer\": faces.outer,\n",
    "        \"ends\": faces.bottom | faces.top,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=30, azimuth=-60),\n",
    "    title=\"Sector of the pipe ring\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Meridian section: {mesh.cell_count} quadratic triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Two `CreepMaterialPoint`s for `SmallStrainSolid` with axisymmetric kinematics: one with the Norton\n",
    "law alone, one with the Norton-Bailey law added (strain hardening). The load steps grow\n",
    "logarithmically from 36 s to 1000 h."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "inner, outer, pressure, exponent = 0.050, 0.100, 40e6, 5.0\n",
    "secondary = PowerLawCreep(coefficient=2e-48, stress_exponent=exponent)\n",
    "primary = PowerLawCreep(coefficient=1e-44, stress_exponent=exponent, time_exponent=0.3)\n",
    "hour = 3600.0\n",
    "times = np.r_[0.0, np.geomspace(0.01, 1000.0, 45)] * hour\n",
    "materials = {\n",
    "    \"secondary only\": (secondary,),\n",
    "    \"primary + secondary\": (primary, secondary),\n",
    "}\n",
    "results = {\n",
    "    name: SmallStrainSolid(\n",
    "        youngs_modulus=180e9,\n",
    "        poisson_ratio=0.3,\n",
    "        kinematics=\"axisymmetric\",\n",
    "        material_point=CreepMaterialPoint(laws=laws, hardening=\"strain\"),\n",
    "    ).solve(\n",
    "        mesh=mesh,\n",
    "        times=times,\n",
    "        order=2,\n",
    "        displacements=((edges.bottom, \"z\", 0.0), (edges.top, \"z\", 0.0)),\n",
    "        tractions=((edges.inner, (pressure, 0.0)),),\n",
    "    )\n",
    "    for name, laws in materials.items()\n",
    "}\n",
    "radius = results[\"secondary only\"].quadrature_coordinates[:, 0]\n",
    "bore, mantle = np.argmin(radius), np.argmax(radius)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the closed form\n",
    "\n",
    "The stresses at the quadrature points after 1000 h against the stationary creep solution, the\n",
    "time at which the bore hoop stress has relaxed halfway, and the creep strain carried by each law."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "beta, ratio = 2 / exponent, outer / inner\n",
    "lame_hoop = lambda r: pressure / (ratio**2 - 1) * (1 + (outer / r) ** 2)\n",
    "creep = {\n",
    "    \"σ_r\": lambda r: -pressure * ((outer / r) ** beta - 1) / (ratio**beta - 1),\n",
    "    \"σ_z\": lambda r: pressure\n",
    "    * (1 + (beta / 2 - 1) * (outer / r) ** beta)\n",
    "    / (ratio**beta - 1),\n",
    "    \"σ_θ\": lambda r: pressure\n",
    "    * (1 + (beta - 1) * (outer / r) ** beta)\n",
    "    / (ratio**beta - 1),\n",
    "}\n",
    "deviation = lambda values, reference: np.abs(values - reference(radius)) / pressure\n",
    "for name, result in results.items():\n",
    "    print(\n",
    "        f\"{name}: after 1000 h \"\n",
    "        + \", \".join(\n",
    "            f\"{component} within {100 * deviation(result.stress[-1, :, k, k], creep[component]).max():.2f} % of p \"\n",
    "            f\"(rms {100 * np.sqrt(np.mean(deviation(result.stress[-1, :, k, k], creep[component]) ** 2)):.2f} %)\"\n",
    "            for k, component in enumerate(creep)\n",
    "        )\n",
    "    )\n",
    "for name, result in results.items():\n",
    "    halfway = (\n",
    "        times[\n",
    "            np.argmax(\n",
    "                result.stress[:, bore, 2, 2]\n",
    "                <= 0.5 * (lame_hoop(radius[bore]) + creep[\"σ_θ\"](radius[bore]))\n",
    "            )\n",
    "        ]\n",
    "        / hour\n",
    "    )\n",
    "    print(f\"{name}: bore hoop stress halfway relaxed after {halfway:.2f} h\")\n",
    "state = results[\"primary + secondary\"].material_history[-1][0][0]\n",
    "print(\n",
    "    f\"creep strain at the bore after 1000 h: primary {100 * state.accumulated[0]:.3f} %, secondary {100 * state.accumulated[1]:.3f} % \"\n",
    "    f\"(secondary-only run: {100 * results['secondary only'].material_history[-1][0][0].equivalent_creep_strain:.3f} %)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left the hoop stress at the bore and at the outer surface over time for both materials, with the\n",
    "stationary values; right the hoop stress across the wall after 1 h and after 1000 h. The primary\n",
    "stage carries most of the early redistribution, the secondary law the final state."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "early = int(np.argmin(np.abs(times - hour)))\n",
    "line = np.linspace(inner, outer, 200)\n",
    "mid = np.abs(results[\"secondary only\"].quadrature_coordinates[:, 1] - 0.010) < 0.004\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"{where}, {name}\": (times[1:] / hour, result.stress[1:, index, 2, 2] / 1e6)\n",
    "        for name, result in results.items()\n",
    "        for where, index in ((\"bore\", bore), (\"outer surface\", mantle))\n",
    "    },\n",
    "    hlines={\n",
    "        \"stationary, bore\": creep[\"σ_θ\"](radius[bore]) / 1e6,\n",
    "        \"stationary, outer surface\": creep[\"σ_θ\"](radius[mantle]) / 1e6,\n",
    "    },\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"time [h]\",\n",
    "    ylabel=\"hoop stress σ_θ [MPa]\",\n",
    "    title=\"Relaxation of the hoop stress\",\n",
    "    legend=\"center left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"{name}, {times[k] / hour:.3g} h\": (\n",
    "            1e3 * radius[mid],\n",
    "            result.stress[k, mid, 2, 2] / 1e6,\n",
    "        )\n",
    "        for name, result in results.items()\n",
    "        for k in (early, len(times) - 1)\n",
    "    },\n",
    "    reference={\n",
    "        \"Lamé\": (1e3 * line, lame_hoop(line) / 1e6),\n",
    "        \"stationary creep\": (1e3 * line, creep[\"σ_θ\"](line) / 1e6),\n",
    "    },\n",
    "    xlabel=\"radius r [mm]\",\n",
    "    ylabel=\"hoop stress σ_θ [MPa]\",\n",
    "    title=\"Hoop stress across the wall\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Give the two laws different stress exponents: the stationary distribution then follows the\n",
    "secondary exponent, while the transient shows a mixture of both. Switch the primary law to time\n",
    "hardening to compare the two hardening rules in a non-uniform stress field."
   ]
  }
 ]
}
