{
 "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 parameters from a cyclic shear test\n",
    "\n",
    "Metals loaded beyond the yield stress and then unloaded in the opposite direction yield again\n",
    "earlier than in the first loading: the **Bauschinger effect**. A combined hardening law captures\n",
    "it by letting the elastic range both grow (isotropic hardening, modulus $H_\\mathrm{iso}$) and move\n",
    "with the plastic flow (kinematic hardening, backstress modulus $H_\\mathrm{kin}$). With von Mises\n",
    "(J2) plasticity the yield function and the evolution laws are\n",
    "\n",
    "$$f=\\sqrt{\\tfrac32}\\,\\|\\mathbf s-\\boldsymbol\\alpha\\|-\\big(\\sigma_y+H_\\mathrm{iso}\\,\\bar\\varepsilon_p\\big)\\le0,\\qquad\n",
    "  \\dot{\\boldsymbol\\alpha}=\\tfrac23H_\\mathrm{kin}\\,\\dot{\\boldsymbol\\varepsilon}_p ,$$\n",
    "\n",
    "with the stress deviator $\\mathbf s$, the backstress $\\boldsymbol\\alpha$ and the accumulated plastic\n",
    "strain $\\bar\\varepsilon_p$ (J.C. Simo and T.J.R. Hughes, *Computational Inelasticity*, Springer\n",
    "1998, Ch. 2-3).\n",
    "\n",
    "A **cyclic shear test** drives the engineering shear strain $\\gamma$ between $\\pm1$ % for two\n",
    "cycles while all other strains are held at zero, and records the shear stress $\\tau$. The first\n",
    "loading sets $E$ (through $G=E/2(1+\\nu)$ with $\\nu=0.3$ fixed) and the yield stress; the reverse\n",
    "yield points separate the isotropic from the kinematic hardening.\n",
    "\n",
    "**The measurements.** There is no laboratory record here: the \"measured\" stresses are the model\n",
    "with $E=200$ GPa, $\\sigma_y=250$ MPa, $H_\\mathrm{iso}=1$ GPa and $H_\\mathrm{kin}=10$ GPa, plus\n",
    "Gaussian noise with a standard deviation of 2 MPa. **Reference:** these values; the fit should\n",
    "return them within its standard errors."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.materials.solids import (\n",
    "    CombinedHardening,\n",
    "    IsotropicHardening,\n",
    "    IsotropicHookeMaterial,\n",
    "    J2Plasticity,\n",
    "    KinematicHardening,\n",
    ")\n",
    "from onesim.physics.solid_mechanics import HomogeneousSmallStrainTest, J2MaterialPoint\n",
    "from onesim.simulation.studies import (\n",
    "    MaterialPointStudy,\n",
    "    SimulationStudyService,\n",
    "    StudyParameter,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The material test\n",
    "\n",
    "A homogeneous material point under prescribed strain: no mesh, no spatial solver, the J2 return\n",
    "mapping runs step by step through the cycle. `specimen` builds the test for one set of\n",
    "parameters, `MaterialPointStudy` binds it to the loading path."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "poisson = 0.3\n",
    "shear_strain = np.r_[\n",
    "    np.linspace(0, 0.01, 21),\n",
    "    np.linspace(0.01, -0.01, 41)[1:],\n",
    "    np.linspace(-0.01, 0.01, 41)[1:],\n",
    "    np.linspace(0.01, -0.01, 41)[1:],\n",
    "]\n",
    "loading = dict(\n",
    "    times=np.arange(len(shear_strain), dtype=float),\n",
    "    strain={\n",
    "        name: shear_strain if name == \"xy\" else 0.0\n",
    "        for name in (\"xx\", \"yy\", \"zz\", \"xy\", \"yz\", \"xz\")\n",
    "    },\n",
    ")\n",
    "specimen = lambda E, Y, H_iso, H_kin: MaterialPointStudy(\n",
    "    loading=loading,\n",
    "    test=HomogeneousSmallStrainTest(\n",
    "        elasticity=IsotropicHookeMaterial(E, poisson),\n",
    "        material=J2MaterialPoint(\n",
    "            plasticity=J2Plasticity(\n",
    "                shear_modulus=E / (2 * (1 + poisson)),\n",
    "                hardening=CombinedHardening(\n",
    "                    IsotropicHardening(Y, H_iso), KinematicHardening(modulus=H_kin)\n",
    "                ),\n",
    "            )\n",
    "        ),\n",
    "    ),\n",
    ")\n",
    "truth = {\"E\": 200e9, \"Y\": 250e6, \"H_iso\": 1e9, \"H_kin\": 10e9}\n",
    "noise = 2e6\n",
    "measured = specimen(**truth).solve_stationary().stress[\n",
    "    :, 3\n",
    "] + noise * np.random.default_rng(7).standard_normal(len(shear_strain))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The fit\n",
    "\n",
    "The study service runs the material test for every trial set and minimises the noise-weighted\n",
    "residuals $(\\tau_\\mathrm{sim}-\\tau_\\mathrm{meas})/s$ with the Levenberg-Marquardt method,\n",
    "starting 20-40 % away from the true values inside generous bounds. The covariance of the\n",
    "estimate follows from the Jacobian at the optimum."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "study = SimulationStudyService(\n",
    "    (\n",
    "        StudyParameter(\"E\", 120e9, 300e9),\n",
    "        StudyParameter(\"Y\", 100e6, 500e6),\n",
    "        StudyParameter(\"H_iso\", 0.1e9, 5e9),\n",
    "        StudyParameter(\"H_kin\", 2e9, 40e9),\n",
    "    ),\n",
    "    build=lambda values: specimen(**values),\n",
    "    measure=lambda result: {\n",
    "        f\"tau_{k}\": float(value) for k, value in enumerate(result.stress[:, 3])\n",
    "    },\n",
    ")\n",
    "fit = study.fit(\n",
    "    residuals=lambda values: (\n",
    "        np.array([values[f\"tau_{k}\"] for k in range(len(shear_strain))]) - measured\n",
    "    )\n",
    "    / noise,\n",
    "    start={\"E\": 160e9, \"Y\": 320e6, \"H_iso\": 1.4e9, \"H_kin\": 6e9},\n",
    "    method=\"levenberg_marquardt\",\n",
    "    maximum_runs=300,\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "The fitted parameters against the values behind the data, in units of their standard errors, and\n",
    "the misfit, which should be close to the number of measurements less the four parameters when\n",
    "the fit is as good as the noise."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "print(\n",
    "    f\"{'parameter':10s} {'true':>10s} {'fitted':>10s} {'standard error':>15s} {'deviation':>10s} {'in standard errors':>19s}\"\n",
    ")\n",
    "for name, unit in ((\"E\", 1e9), (\"Y\", 1e6), (\"H_iso\", 1e9), (\"H_kin\", 1e9)):\n",
    "    value, error = fit.parameters[name], fit.standard_errors[name]\n",
    "    print(\n",
    "        f\"{name:10s} {truth[name] / unit:10.3f} {value / unit:10.3f} {error / unit:15.4f} {100 * (value / truth[name] - 1):+9.2f} %\"\n",
    "        f\" {(value - truth[name]) / error:+19.2f}\"\n",
    "        + (\"   [GPa]\" if unit == 1e9 else \"   [MPa]\")\n",
    "    )\n",
    "print(\n",
    "    f\"χ² = {fit.residuals @ fit.residuals:.1f} for {len(shear_strain)} measurements and 4 parameters; \"\n",
    "    f\"converged: {fit.converged}, rank {fit.rank}, {fit.run_count} material tests\"\n",
    ")\n",
    "correlation = np.asarray(fit.covariance) / np.outer(\n",
    "    np.sqrt(np.diag(fit.covariance)), np.sqrt(np.diag(fit.covariance))\n",
    ")\n",
    "print(\"correlation of the estimates (E, Y, H_iso, H_kin):\")\n",
    "print(np.array2string(correlation, precision=2, suppress_small=True))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The measured and fitted hysteresis loops, and the normalised residuals along the test."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fitted = specimen(**fit.parameters).solve_stationary().stress[:, 3]\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.line(\n",
    "    y={\"fitted combined hardening\": (100 * shear_strain, fitted / 1e6)},\n",
    "    points={\"measured (synthetic)\": (100 * shear_strain, measured / 1e6)},\n",
    "    xlabel=\"shear strain γ [%]\",\n",
    "    ylabel=\"shear stress τ [MPa]\",\n",
    "    title=\"Cyclic shear test\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"(τ_fit - τ_meas) / s\": (\n",
    "            np.arange(len(shear_strain)),\n",
    "            (fitted - measured) / noise,\n",
    "        )\n",
    "    },\n",
    "    hlines=0.0,\n",
    "    ylimits=(-4, 4),\n",
    "    xlabel=\"load step\",\n",
    "    ylabel=\"normalised residual\",\n",
    "    title=\"Residuals of the fit\",\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",
    "Fit only isotropic hardening to the same data and see the reverse yielding missed; add the\n",
    "recovery term of the kinematic law, `KinematicHardening(modulus, recovery)`, for an\n",
    "Armstrong-Frederick backstress; or replace the shear test by `uniaxial_stress` loading."
   ]
  }
 ]
}
