{
 "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": [
    "# Submodel with plasticity at a hole\n",
    "\n",
    "An elastic analysis of a whole structure often shows a few small spots where the stress lies\n",
    "above the yield limit. Making the whole model elastoplastic and fine enough for those spots is\n",
    "expensive; a **submodel** is cheaper. A small region around the spot is cut out, meshed finely,\n",
    "given the plastic material, and driven on its cut faces by the displacements of the global\n",
    "model. As long as the plastic zone stays small, the displacements far from it are hardly\n",
    "changed by plasticity, which is what makes the transfer valid.\n",
    "\n",
    "**Setup.** A steel plate 100 mm wide, 200 mm long and 10 mm thick with a central hole of 20 mm\n",
    "diameter, pulled by $S=150$ MPa at its ends. Steel: $E=200$ GPa, $\\nu=0.3$, J2 plasticity\n",
    "with yield stress $\\sigma_y=250$ MPa and linear isotropic hardening $H=2$ GPa. One eighth of the\n",
    "plate (three symmetry planes) comes from `plate_hole_plastic_submodel.step`, the submodel, a\n",
    "25 mm × 25 mm block around the hole cut from the same eighth, from\n",
    "`plate_hole_plastic_submodel_detail.step`; `plate_hole_plastic_submodel_geometry.py` writes both\n",
    "with the CAD objects of OneSimulation.\n",
    "\n",
    "| face | plate model (elastic) | submodel (J2 plasticity) |\n",
    "|---|---|---|\n",
    "| `x_min`, `y_min`, `z_min` | symmetry | symmetry |\n",
    "| `y_max` | traction $S$ | displacement of the plate model × load factor |\n",
    "| `x_max` | free | displacement of the plate model × load factor |\n",
    "| `z_max`, `hole.outer_wall` | free | free |\n",
    "\n",
    "**References.** The elastic stress concentration of a finite-width plate with a hole,\n",
    "$K_t=\\big(2+(1-d/W)^3\\big)/(1-d/W)$ on the gross stress (Heywood's fit to Peterson's chart; W.D.\n",
    "Pilkey, D.F. Pilkey, *Peterson's Stress Concentration Factors*, 3rd ed., Wiley 2008). For the\n",
    "elastoplastic notch root, Neuber's rule $\\sigma\\,\\varepsilon=(K_tS)^2/E$ with the bilinear\n",
    "stress-strain curve $\\varepsilon=\\sigma/E+(\\sigma-\\sigma_y)/H$ (H. Neuber, J. Appl. Mech. 28,\n",
    "1961, 544-550), an engineering estimate that is usually somewhat conservative."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials.solids import IsotropicHardening, J2Plasticity\n",
    "from onesim.meshing import LocalRefinement, TetrahedralMesher\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 both parts with their named faces. Curved quadratic tetrahedra: 8 mm in the\n",
    "plate with 3 mm at the hole; the submodel with 1.2 mm and, for the mesh study, 0.8 mm at the hole."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plate, detail = load(\"plate_hole_plastic_submodel.step\"), load(\n",
    "    \"plate_hole_plastic_submodel_detail.step\"\n",
    ")\n",
    "outer, inner = plate.boundaries, detail.boundaries\n",
    "radius, width = 0.010, 0.100\n",
    "plate_mesh = TetrahedralMesher(\n",
    "    target_size=0.008,\n",
    "    geometry_order=2,\n",
    "    refinements=(LocalRefinement(region=outer[\"hole.outer_wall\"], target_size=0.003),),\n",
    ").generate(plate)\n",
    "hole_sizes = [0.0012, 0.0008]\n",
    "detail_meshes = [\n",
    "    TetrahedralMesher(\n",
    "        target_size=0.003,\n",
    "        geometry_order=2,\n",
    "        refinements=(\n",
    "            LocalRefinement(region=inner[\"hole.outer_wall\"], target_size=size),\n",
    "        ),\n",
    "    ).generate(detail)\n",
    "    for size in hole_sizes\n",
    "]\n",
    "\n",
    "view = plots.Camera(elevation=40, azimuth=-60)\n",
    "fig = plots.figure(2, 2, size=(14, 11))\n",
    "plots.geometry(\n",
    "    plate,\n",
    "    selection={\n",
    "        \"pulled end\": outer.y_max,\n",
    "        \"hole\": outer[\"hole.outer_wall\"],\n",
    "        \"symmetry\": outer.x_min | outer.y_min | outer.z_min,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"One eighth of the plate\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.geometry(\n",
    "    detail,\n",
    "    selection={\n",
    "        \"cut faces\": inner.x_max | inner.y_max,\n",
    "        \"hole\": inner[\"hole.outer_wall\"],\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Submodel around the hole\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.mesh(\n",
    "    plate_mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Plate: {plate_mesh.cell_count} tetrahedra\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.mesh(\n",
    "    detail_meshes[-1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Submodel: {detail_meshes[-1].cell_count} tetrahedra\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Global model\n",
    "\n",
    "The whole plate, elastic, under the full load."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "youngs_modulus, poisson, stress, yield_stress, hardening = 200e9, 0.3, 150e6, 250e6, 2e9\n",
    "whole = SmallStrainSolid(\n",
    "    youngs_modulus=youngs_modulus, poisson_ratio=poisson, kinematics=\"volume\"\n",
    ").solve(\n",
    "    mesh=plate_mesh,\n",
    "    times=(1.0,),\n",
    "    order=2,\n",
    "    displacements=(\n",
    "        (outer.x_min, \"x\", 0.0),\n",
    "        (outer.y_min, \"y\", 0.0),\n",
    "        (outer.z_min, \"z\", 0.0),\n",
    "    ),\n",
    "    tractions=((outer.y_max, (0.0, stress, 0.0)),),\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Submodel\n",
    "\n",
    "The cut faces take the displacement of the plate model, evaluated at their own nodes and scaled\n",
    "by the load factor $t$, which rises in eight steps to 1. The steel is elastoplastic."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "transfer = (\n",
    "    lambda component: lambda x, y, z, t: t\n",
    "    * whole.evaluate_displacement(np.column_stack((x, y, z)))[:, component]\n",
    ")\n",
    "factors = np.linspace(0.0, 1.0, 9)\n",
    "steel = SmallStrainSolid(\n",
    "    youngs_modulus=youngs_modulus,\n",
    "    poisson_ratio=poisson,\n",
    "    kinematics=\"volume\",\n",
    "    material=J2Plasticity(\n",
    "        shear_modulus=youngs_modulus / (2 * (1 + poisson)),\n",
    "        hardening=IsotropicHardening(yield_stress, hardening),\n",
    "    ),\n",
    ")\n",
    "submodels = [\n",
    "    steel.solve(\n",
    "        mesh=mesh,\n",
    "        times=factors,\n",
    "        order=2,\n",
    "        displacements=(\n",
    "            (inner.x_min, \"x\", 0.0),\n",
    "            (inner.y_min, \"y\", 0.0),\n",
    "            (inner.z_min, \"z\", 0.0),\n",
    "        )\n",
    "        + tuple(\n",
    "            (face, axis, transfer(k))\n",
    "            for face in (inner.x_max, inner.y_max)\n",
    "            for k, axis in enumerate(\"xyz\")\n",
    "        ),\n",
    "    )\n",
    "    for mesh in detail_meshes\n",
    "]\n",
    "plastic = [\n",
    "    np.array(\n",
    "        [\n",
    "            [[point.equivalent_plastic_strain for point in cell] for cell in step]\n",
    "            for step in result.material_history\n",
    "        ]\n",
    "    ).reshape(len(factors), -1)\n",
    "    for result in submodels\n",
    "]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the references\n",
    "\n",
    "The elastic peak stress of the plate model and of the submodel in its last elastic step against\n",
    "Peterson's chart, then at full load the largest plastic strain and the stress at the same point\n",
    "against Neuber's rule."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "peterson = (2 + (1 - 2 * radius / width) ** 3) / (1 - 2 * radius / width)\n",
    "neuber = lambda elastic: np.where(\n",
    "    elastic <= yield_stress,\n",
    "    elastic,\n",
    "    (\n",
    "        yield_stress / hardening\n",
    "        + np.sqrt(\n",
    "            (yield_stress / hardening) ** 2\n",
    "            + 4 * (1 / youngs_modulus + 1 / hardening) * elastic**2 / youngs_modulus\n",
    "        )\n",
    "    )\n",
    "    / (2 * (1 / youngs_modulus + 1 / hardening)),\n",
    ")\n",
    "print(\n",
    "    f\"elastic stress concentration: plate model {whole.stress[0, :, 1, 1].max() / stress:.3f}, \"\n",
    "    f\"submodel at t = 0.25 {[result.stress[2, :, 1, 1].max() / (0.25 * stress) for result in submodels][-1]:.3f}, Peterson's chart {peterson:.3f}\"\n",
    ")\n",
    "print(\n",
    "    f\"elastic peak at full load K_t S = {peterson * stress / 1e6:.0f} MPa, yield stress {yield_stress / 1e6:.0f} MPa; \"\n",
    "    f\"Neuber at full load: σ = {neuber(peterson * stress) / 1e6:.1f} MPa, ε_p = {1e3 * (neuber(peterson * stress) - yield_stress) / hardening:.3f}e-3\"\n",
    ")\n",
    "print(\n",
    "    f\"{'hole mesh':>9s} {'tetrahedra':>10s} {'largest ε_p [1e-3]':>19s} {'σ_yy there [MPa]':>17s} {'plastic points [%]':>19s} {'first yield at t':>17s}\"\n",
    ")\n",
    "for size, mesh, result, values in zip(hole_sizes, detail_meshes, submodels, plastic):\n",
    "    worst = values[-1].argmax()\n",
    "    print(\n",
    "        f\"{1e3 * size:6.1f} mm {mesh.cell_count:10d} {1e3 * values[-1].max():19.3f} {result.stress[-1, worst, 1, 1] / 1e6:17.1f}\"\n",
    "        f\" {100 * np.mean(values[-1] > 0):19.2f} {factors[np.argmax(values.max(axis=1) > 0)]:17.3f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The largest plastic strain over the load factor for both submodel meshes, and the stress at the\n",
    "point where it occurs, with Neuber's rule and the purely elastic stress."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "line = np.linspace(0.0, 1.0, 201)\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"submodel, {mesh.cell_count} tetrahedra\": (factors, 1e3 * values.max(axis=1))\n",
    "        for mesh, values in zip(detail_meshes, plastic)\n",
    "    },\n",
    "    reference={\n",
    "        \"Neuber's rule\": (\n",
    "            line,\n",
    "            1e3\n",
    "            * (\n",
    "                neuber(peterson * stress * line)\n",
    "                - np.minimum(neuber(peterson * stress * line), yield_stress)\n",
    "            )\n",
    "            / hardening,\n",
    "        )\n",
    "    },\n",
    "    xlabel=\"load factor t\",\n",
    "    ylabel=\"largest plastic strain ε_p [1e-3]\",\n",
    "    title=\"Plastic strain at the hole\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"submodel, {mesh.cell_count} tetrahedra\": (\n",
    "            factors,\n",
    "            result.stress[:, values[-1].argmax(), 1, 1] / 1e6,\n",
    "        )\n",
    "        for mesh, result, values in zip(detail_meshes, submodels, plastic)\n",
    "    },\n",
    "    reference={\n",
    "        \"Neuber's rule\": (line, neuber(peterson * stress * line) / 1e6),\n",
    "        \"elastic, K_t S t\": (line, peterson * stress * line / 1e6),\n",
    "    },\n",
    "    hlines={\"yield stress\": yield_stress / 1e6},\n",
    "    xlabel=\"load factor t\",\n",
    "    ylabel=\"σ_yy at the point of largest plastic strain [MPa]\",\n",
    "    title=\"Stress at the hole\",\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",
    "Raise the load until the plastic zone reaches the cut faces: then the submodel assumption fails\n",
    "and the submodel must grow. Use kinematic hardening and unload to see the residual compressive\n",
    "stress that a notch keeps after an overload; or replace the plate by your own part and cut the\n",
    "submodel from it in the geometry script."
   ]
  }
 ]
}
