{
 "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": [
    "# Elastoplastic perforated plate in plane stress\n",
    "\n",
    "A hole concentrates the stress in a loaded plate. As the load grows, the material at the edge of\n",
    "the hole yields first; a plastic zone spreads across the ligament between hole and edge, and the\n",
    "plate stiffens again only through hardening once the whole net section is plastic. On unloading\n",
    "the elastic spring-back of the surrounding plate puts the plastic zone into compression: residual\n",
    "stresses remain at the hole edge.\n",
    "\n",
    "The case follows the classical perforated strip of Zienkiewicz, Valliappan and King (Int. J.\n",
    "Numer. Meth. Eng. 1, 1969, 75-100), also in O.C. Zienkiewicz and R.L. Taylor, *The Finite Element\n",
    "Method*, Vol. 2. In plane stress the out-of-plane stress vanishes; the von Mises yield condition\n",
    "with linear isotropic hardening is\n",
    "\n",
    "$$\\sqrt{\\tfrac32\\,\\mathbf s:\\mathbf s}=\\sigma_y+H\\,\\bar\\varepsilon_p ,$$\n",
    "\n",
    "and the out-of-plane strain is found at every quadrature point so that $\\sigma_{zz}=0$.\n",
    "\n",
    "**Setup.** A strip 200 mm wide, 360 mm long and 1 mm thick with a central hole of $d=100$ mm;\n",
    "$E=68.7$ GPa, $\\nu=0.2$, $\\sigma_y=238$ MPa, $H=2.21$ GPa (the values of the original study,\n",
    "7000, 24.3 and 225 kgf/mm²). The ends carry a uniform tension $\\sigma$ that rises to\n",
    "$0.55\\,\\sigma_y$ and returns to zero. A quarter of the plate comes from the CAD file\n",
    "`holed_plate_elastoplastic_plane_stress.step`, written by\n",
    "`holed_plate_elastoplastic_plane_stress_geometry.py` with the CAD objects of OneSimulation; the\n",
    "computation uses its mid-plane section.\n",
    "\n",
    "| edge of the section | condition |\n",
    "|---|---|\n",
    "| `symmetry_x` | $u_x=0$ |\n",
    "| `symmetry_y` | $u_y=0$ |\n",
    "| `loaded` | traction $\\sigma$ in $y$ |\n",
    "| `hole`, `side` | free |\n",
    "\n",
    "**Reference.** (1) For an elastic strip with $d/W=0.5$ the stress at the hole edge is\n",
    "$K_{t,n}\\,\\sigma_\\text{net}$ with $\\sigma_\\text{net}=\\sigma\\,W/(W-d)$ and $K_{t,n}=2.156$ (Pilkey and\n",
    "Pilkey, *Peterson's Stress Concentration Factors*, 3rd ed., Chart 4.1). (2) Yield therefore starts\n",
    "at $\\sigma=\\sigma_y(1-d/W)/K_{t,n}$. (3) Without hardening the plate collapses when the whole net\n",
    "section yields, at $\\sigma=\\sigma_y(1-d/W)=0.5\\,\\sigma_y$. (4) Wherever the material yields, the\n",
    "von Mises stress equals the current yield stress $\\sigma_y+H\\bar\\varepsilon_p$. (5) If the plate\n",
    "unloads elastically, the residual stress is the peak stress minus the elastic solution for the\n",
    "peak load (Melan's superposition)."
   ]
  },
  {
   "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 TriangularMesher\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import DampedNewton\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 quarter plate with its named faces; `section` cuts its mid-plane. The\n",
    "quadratic triangles are 3 mm at the hole and grow to 15 mm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "quarter = load(\"holed_plate_elastoplastic_plane_stress.step\")\n",
    "faces = quarter.boundaries\n",
    "plane = quarter.section((0, 0, 1), origin=(0, 0, quarter.size[2] / 2))\n",
    "edges = plane.boundaries\n",
    "mesh = TriangularMesher(\n",
    "    target_size=0.015,\n",
    "    size_field=lambda p: np.minimum(\n",
    "        0.003 + 0.08 * np.abs(np.hypot(p[:, 0], p[:, 1]) - 0.05), 0.015\n",
    "    ),\n",
    ").generate(plane)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 7))\n",
    "plots.geometry(\n",
    "    quarter,\n",
    "    selection={\n",
    "        \"hole\": faces.hole,\n",
    "        \"loaded end\": faces.loaded,\n",
    "        \"symmetry\": faces.symmetry_x | faces.symmetry_y,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=60, azimuth=-70),\n",
    "    title=\"Quarter of the perforated strip\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Mid-plane 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",
    "`SmallStrainSolid` in plane stress with a `J2Plasticity` material; the out-of-plane condensation\n",
    "runs at every quadrature point. The end traction follows the load history step by step."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "youngs_modulus, poisson_ratio, yield_stress, hardening = 68.7e9, 0.2, 238e6, 2.21e9\n",
    "width, diameter = 0.200, 0.100\n",
    "history = np.r_[0.0, np.arange(0.2, 0.551, 0.025), 0.40, 0.25, 0.10, 0.0] * yield_stress\n",
    "result = SmallStrainSolid(\n",
    "    youngs_modulus=youngs_modulus,\n",
    "    poisson_ratio=poisson_ratio,\n",
    "    kinematics=\"plane_stress\",\n",
    "    thickness=quarter.size[2],\n",
    "    material=J2Plasticity(\n",
    "        youngs_modulus / (2 * (1 + poisson_ratio)),\n",
    "        IsotropicHardening(yield_stress, hardening),\n",
    "    ),\n",
    ").solve(\n",
    "    mesh=mesh,\n",
    "    times=np.arange(len(history), dtype=float),\n",
    "    order=2,\n",
    "    displacements=((edges.symmetry_x, \"x\", 0.0), (edges.symmetry_y, \"y\", 0.0)),\n",
    "    tractions=((edges.loaded, lambda x, y, t: (0.0, history[int(round(t))])),),\n",
    "    nonlinear=DampedNewton(\n",
    "        linear_solver=SparseDirect(),\n",
    "        relative_tolerance=1e-12,\n",
    "        absolute_tolerance=1e-6,\n",
    "        maximum_iterations=40,\n",
    "    ),\n",
    ")\n",
    "points = result.quadrature_coordinates\n",
    "edge = int(np.argmin(np.hypot(points[:, 0] - diameter / 2, points[:, 1])))\n",
    "plastic = np.array(\n",
    "    [\n",
    "        [point.material.equivalent_plastic_strain for cell in step for point in cell]\n",
    "        for step in result.material_history\n",
    "    ]\n",
    ")\n",
    "deviator = (\n",
    "    result.stress\n",
    "    - np.trace(result.stress, axis1=2, axis2=3)[..., None, None] * np.eye(3) / 3\n",
    ")\n",
    "mises = np.sqrt(1.5 * np.sum(deviator**2, axis=(2, 3)))\n",
    "top = np.isclose(result.space.dof_coordinates[:, 1], 0.180)\n",
    "stretch = result.displacement[:, top, 1].mean(axis=1)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the handbook values\n",
    "\n",
    "The stress at the hole edge in the first, still elastic step; the load at which the edge yields;\n",
    "the net-section limit; and the von Mises stress at the hole edge against the hardened yield stress\n",
    "at peak load and after unloading."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "peterson, ratio = 2.156, 1 - diameter / width\n",
    "onset = yield_stress * ratio / peterson\n",
    "peak, final = int(np.argmax(history)), len(history) - 1\n",
    "print(\n",
    "    f\"hole edge at σ = {history[1] / 1e6:.1f} MPa: σ_yy = {result.stress[1, edge, 1, 1] / 1e6:.1f} MPa, \"\n",
    "    f\"K_t,n = {result.stress[1, edge, 1, 1] * ratio / history[1]:.3f} (Peterson {peterson}, point {1e3 * (np.hypot(*points[edge]) - diameter / 2):.2f} mm inside the edge)\"\n",
    ")\n",
    "first = int(np.argmax(plastic.max(axis=1) > 0))\n",
    "print(\n",
    "    f\"first yield between σ = {history[first - 1] / yield_stress:.3f} σ_y and {history[first] / yield_stress:.3f} σ_y (reference {onset / yield_stress:.3f} σ_y)\"\n",
    ")\n",
    "ligament = np.abs(points[:, 1]) < 0.004\n",
    "print(\n",
    "    f\"net section without hardening collapses at σ = {ratio:.2f} σ_y; at peak load {history[peak] / yield_stress:.3f} σ_y \"\n",
    "    f\"{100 * np.mean(plastic[peak][ligament] > 0):.0f} % of the ligament points have yielded\"\n",
    ")\n",
    "for k, label in ((peak, \"peak load\"), (final, \"after unloading\")):\n",
    "    print(\n",
    "        f\"{label}: hole edge σ_yy = {result.stress[k, edge, 1, 1] / 1e6:7.1f} MPa, von Mises {mises[k, edge] / 1e6:6.1f} MPa, \"\n",
    "        f\"current yield stress σ_y + H ε_p = {(yield_stress + hardening * plastic[k, edge]) / 1e6:6.1f} MPa, ε_p = {100 * plastic[k, edge]:.3f} %\"\n",
    "    )\n",
    "print(\n",
    "    f\"residual stress at the hole edge by elastic superposition: {(result.stress[peak, edge, 1, 1] - result.stress[1, edge, 1, 1] / history[1] * history[peak]) / 1e6:.1f} MPa \"\n",
    "    f\"(simulation {result.stress[final, edge, 1, 1] / 1e6:.1f} MPa): the unloading stayed elastic\"\n",
    ")\n",
    "print(\n",
    "    f\"permanent elongation of the quarter after unloading: {1e6 * stretch[-1]:.1f} µm; largest out-of-plane stress {np.abs(result.stress[..., 2, 2]).max() / 1e3:.2f} kPa\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left the end tension against the stress at the hole edge, with the elastic concentration, the\n",
    "onset of yield and the net-section limit; in the middle against the elongation of the quarter;\n",
    "right the yielded quadrature points at three loads. The plastic zone starts at the hole edge and\n",
    "crosses the ligament around the net-section limit, where the plate softens to the hardening slope.\n",
    "On unloading the hole edge springs back elastically into compression."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(19, 6))\n",
    "plots.line(\n",
    "    y={\n",
    "        \"simulation, loading and unloading\": (\n",
    "            result.stress[:, edge, 1, 1] / 1e6,\n",
    "            history / 1e6,\n",
    "        )\n",
    "    },\n",
    "    markers=True,\n",
    "    reference={\n",
    "        \"elastic concentration\": (\n",
    "            np.array([0.0, 1.1 * yield_stress]) / 1e6,\n",
    "            np.array([0.0, 1.1 * yield_stress]) * ratio / peterson / 1e6,\n",
    "        )\n",
    "    },\n",
    "    hlines={\n",
    "        \"onset of yield\": onset / 1e6,\n",
    "        \"net-section limit\": ratio * yield_stress / 1e6,\n",
    "    },\n",
    "    xlabel=\"σ_yy at the hole edge [MPa]\",\n",
    "    ylabel=\"end tension σ [MPa]\",\n",
    "    title=\"Stress at the hole edge\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\"simulation, loading and unloading\": (1e6 * stretch, history / 1e6)},\n",
    "    markers=True,\n",
    "    hlines={\n",
    "        \"onset of yield\": onset / 1e6,\n",
    "        \"net-section limit\": ratio * yield_stress / 1e6,\n",
    "    },\n",
    "    xlabel=\"elongation of the quarter [µm]\",\n",
    "    ylabel=\"end tension σ [MPa]\",\n",
    "    title=\"Load-elongation curve\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"yielded at σ = {history[k] / yield_stress:.3f} σ_y\": (\n",
    "            1e3 * points[plastic[k] > 0, 0],\n",
    "            1e3 * points[plastic[k] > 0, 1],\n",
    "        )\n",
    "        for k in (peak, 9, first + 1)\n",
    "    },\n",
    "    xlimits=(0, 100),\n",
    "    ylimits=(0, 100),\n",
    "    xlabel=\"x [mm]\",\n",
    "    ylabel=\"y [mm]\",\n",
    "    title=\"Spread of the plastic zone\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Set the hardening modulus to zero and drive the end by displacement to see the load level off at\n",
    "the net-section limit, add kinematic hardening to model the Bauschinger effect on unloading, or\n",
    "repeat the cycle and watch whether the hole edge shakes down or keeps yielding."
   ]
  }
 ]
}
