{
 "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": [
    "# Thermal stresses in a coated plate\n",
    "\n",
    "A substrate plate (10 mm thick) carries a coating (2 mm thick). The coating is deposited at\n",
    "800 °C, where both layers are stress free, and the plate is then cooled to 150 °C. The substrate\n",
    "contracts more than the coating, so the coating ends up in compression and the plate bends. Near\n",
    "the free ends the stresses must turn around, which concentrates peel and shear stress at the\n",
    "interface.\n",
    "\n",
    "| layer | $E$ | $\\nu$ | $\\alpha$ |\n",
    "|---|---|---|---|\n",
    "| substrate | 130 GPa | 0.28 | $3\\cdot10^{-6}$ 1/K |\n",
    "| coating | 70 GPa | 0.17 | $5\\cdot10^{-7}$ 1/K |\n",
    "\n",
    "The plate is long in the third direction and is in plane strain, $u_z=0$.\n",
    "\n",
    "A thin slab of one half of the 60 mm long plate comes from the CAD file\n",
    "`layered_plate_thermal_stress.step`; `layered_plate_thermal_stress_coating.step` holds the\n",
    "coating, which marks the region of the second material. The script\n",
    "`layered_plate_thermal_stress_geometry.py` builds both with the CAD objects of OneSimulation. The\n",
    "model is two-dimensional: it lives on the cross-section of the slab, with one region and one\n",
    "material per layer.\n",
    "\n",
    "**Reference.** Away from the ends the plate behaves like a bilayer beam (Timoshenko, 1925). With\n",
    "$E_i'=E_i/(1-\\nu_i^2)$ and the thermal strain $e_i=(1+\\nu_i)\\alpha_i\\Delta T$,\n",
    "\n",
    "$$\\sigma_{xx}(y)=E_i'\\,\\bigl(\\varepsilon_0+\\kappa y-e_i\\bigr),\\qquad\n",
    "  \\sum_i\\int_i\\sigma_{xx}\\,dy=0,\\qquad \\sum_i\\int_i\\sigma_{xx}\\,y\\,dy=0 ,$$\n",
    "\n",
    "where the two balances fix the strain $\\varepsilon_0$ and the curvature $\\kappa$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid, regionwise\n",
    "from onesim.meshing import Geometric, cartesian\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.field_transfer import FiniteElementEvaluation\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.heat_transfer import FixedTemperature, HeatConduction\n",
    "from onesim.physics.solid_mechanics import (\n",
    "    FixedDisplacementComponents,\n",
    "    IsotropicThermalExpansion,\n",
    "    LinearElasticity,\n",
    "    TractionFree,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.field_connections import FieldCoupling\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 slab and the coating, `section` cuts both at half depth; the regions keep the\n",
    "side names `x_min` (mid-span), `x_max` (free end), `y_min` and `y_max`. The quadrilateral mesh has\n",
    "a node line on the interface and is graded towards it and towards the free end."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plate, coat = load(\"layered_plate_thermal_stress.step\"), load(\n",
    "    \"layered_plate_thermal_stress_coating.step\"\n",
    ")\n",
    "half_length, thickness, slab = plate.size\n",
    "coating = coat.size[1]\n",
    "substrate = thickness - coating\n",
    "section = plate.section((0, 0, 1), origin=(0, 0, slab / 2))\n",
    "coating_region = coat.section((0, 0, 1), origin=(0, 0, slab / 2))\n",
    "sides = section.boundaries\n",
    "along = half_length * Geometric(25, ratio=50.0, toward=\"end\").reference()\n",
    "across = np.r_[\n",
    "    substrate * Geometric(13, ratio=40.0, toward=\"end\").reference(),\n",
    "    substrate + coating * Geometric(7, ratio=8.0).reference()[1:],\n",
    "]\n",
    "mesh = cartesian(\n",
    "    geometry=section,\n",
    "    shape=(along.size - 1, across.size - 1),\n",
    "    extents=(half_length, thickness),\n",
    "    node_axes=(tuple(along), tuple(across)),\n",
    ").build()\n",
    "\n",
    "fig = plots.figure(1, 2, size=(15, 5))\n",
    "plots.geometry(\n",
    "    [plate.named(\"substrate\"), coat.named(\"coating\")],\n",
    "    camera=plots.Camera(elevation=35, azimuth=-60),\n",
    "    title=\"Slab of the half plate\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.geometry(\n",
    "    section,\n",
    "    title=f\"Cross-section with its named sides, meshed with {mesh.cell_count} quadrilaterals\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Plane strain on the cross-section. The mid-span $x=0$ is a symmetry line, held vertically at its\n",
    "lower end. The material properties are given region by region. The uniform final temperature\n",
    "comes from a heat-conduction model on the same section and enters the mechanics as thermal\n",
    "strain."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "layers = {\"substrate\": (130e9, 0.28, 3.0e-6), \"coating\": (70e9, 0.17, 5.0e-7)}\n",
    "deposition, final = 1073.15, 423.15\n",
    "layered = lambda index, unit: regionwise(\n",
    "    ((coating_region, layers[\"coating\"][index]),),\n",
    "    default=layers[\"substrate\"][index],\n",
    "    unit=unit,\n",
    ")\n",
    "material = IsotropicSolid(\n",
    "    density=3000.0,\n",
    "    specific_heat_capacity=700.0,\n",
    "    thermal_conductivity=30.0,\n",
    "    youngs_modulus=layered(0, \"Pa\"),\n",
    "    poisson_ratio=layered(1, \"1\"),\n",
    "    thermal_expansion_coefficient=layered(2, \"1/K\"),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "\n",
    "heat = HeatConduction(domain=section.domain(), material=material)\n",
    "cooled = Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"Final temperature\",\n",
    "        geometry=section,\n",
    "        physics=(heat,),\n",
    "        boundary_conditions=(\n",
    "            FixedTemperature(boundary=sides.all, physics=heat, value=final),\n",
    "        ),\n",
    "    ),\n",
    "    mesh=mesh,\n",
    "    numerics=numerics,\n",
    ").solve_stationary()\n",
    "\n",
    "solid = LinearElasticity(\n",
    "    domain=section.domain(),\n",
    "    material=material,\n",
    "    kinematics=\"plane_strain\",\n",
    "    thermal_strain=IsotropicThermalExpansion(reference_temperature=deposition),\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Coated plate\",\n",
    "    geometry=section,\n",
    "    physics=(solid,),\n",
    "    boundary_conditions=(\n",
    "        TractionFree(boundary=sides.x_max | sides.y_min | sides.y_max, physics=solid),\n",
    "        FixedDisplacementComponents(\n",
    "            boundary=sides.x_min,\n",
    "            physics=solid,\n",
    "            components=(\"x\", \"y\"),\n",
    "            where={\"y\": lambda x, y: y < 1e-9},\n",
    "        ),\n",
    "    ),\n",
    "    couplings=(\n",
    "        FieldCoupling(\n",
    "            source=cooled.field(heat.temperature),\n",
    "            target=solid.temperature,\n",
    "            transfer=FiniteElementEvaluation(),\n",
    "        ),\n",
    "    ),\n",
    ")\n",
    "stress = (\n",
    "    Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "    .solve_stationary()\n",
    "    .field(solid.stress)\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The axial stress at mid-span against the bilayer solution of Timoshenko."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def bilayer_stress(y):\n",
    "    \"\"\"Axial stress of the bilayer beam at the height y.\"\"\"\n",
    "    stiffness, load_vector = np.zeros((2, 2)), np.zeros(2)\n",
    "    for (E, nu, alpha), (lower, upper) in zip(\n",
    "        layers.values(), ((0, substrate), (substrate, substrate + coating))\n",
    "    ):\n",
    "        moments = [(upper**k - lower**k) / k for k in (1, 2, 3)]\n",
    "        stiffness += E / (1 - nu**2) * np.array([moments[:2], moments[1:]])\n",
    "        load_vector += (\n",
    "            E\n",
    "            / (1 - nu**2)\n",
    "            * (1 + nu)\n",
    "            * alpha\n",
    "            * (final - deposition)\n",
    "            * np.array(moments[:2])\n",
    "        )\n",
    "    strain, curvature = np.linalg.solve(stiffness, load_vector)\n",
    "    E, nu, alpha = (\n",
    "        np.where(np.asarray(y) > substrate, c, s) for s, c in zip(*layers.values())\n",
    "    )\n",
    "    return (\n",
    "        E\n",
    "        / (1 - nu**2)\n",
    "        * (strain + curvature * np.asarray(y) - (1 + nu) * alpha * (final - deposition))\n",
    "    )\n",
    "\n",
    "\n",
    "heights = {\n",
    "    \"lower face\": 2e-6,\n",
    "    \"substrate at the interface\": substrate - 2e-6,\n",
    "    \"coating at the interface\": substrate + 2e-6,\n",
    "    \"upper face\": substrate + coating - 2e-6,\n",
    "}\n",
    "at_mid_span = stress.evaluate([[1e-6, y] for y in heights.values()])[:, 0]\n",
    "print(f\"{'position':28s} simulation [MPa]   bilayer [MPa]\")\n",
    "for (label, y), value in zip(heights.items(), at_mid_span):\n",
    "    print(f\"{label:28s} {value / 1e6:16.2f} {bilayer_stress(y) / 1e6:15.2f}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The axial stress near one end of the plate, the stress through the thickness at mid-span, and\n",
    "the peel and shear stress along the interface towards the free end."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "megapascal = lambda s, position: s[:, 0] / 1e6\n",
    "y = np.linspace(1e-6, substrate + coating - 1e-6, 121)\n",
    "through = stress.evaluate(np.column_stack((np.full_like(y, 1e-6), y)))[:, 0]\n",
    "distance = np.geomspace(1e-4, 0.01, 80)\n",
    "interface = stress.evaluate(\n",
    "    np.column_stack((half_length - distance, np.full_like(distance, substrate - 2e-6)))\n",
    ")\n",
    "\n",
    "fig = plots.figure(1, 3, size=(17, 5))\n",
    "plots.surface(\n",
    "    stress,\n",
    "    component=megapascal,\n",
    "    colormap=\"diverging\",\n",
    "    limits=(-110, 110),\n",
    "    subdivisions=3,\n",
    "    label=\"σ_xx [MPa]\",\n",
    "    title=\"Axial stress near the free end\",\n",
    "    xlimits=(0.01, 0.03),\n",
    "    xlabel=\"x from mid-span [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"simulation\": (through[::4] / 1e6, 1e3 * y[::4])},\n",
    "    reference={\"bilayer solution\": (bilayer_stress(y) / 1e6, 1e3 * y)},\n",
    "    hlines={\"interface\": 1e3 * substrate},\n",
    "    xlabel=\"σ_xx at mid-span [MPa]\",\n",
    "    ylabel=\"height [mm]\",\n",
    "    title=\"Stress through the thickness\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    1e3 * distance,\n",
    "    {\n",
    "        \"peel stress σ_yy\": interface[:, 1] / 1e6,\n",
    "        \"shear stress σ_xy\": interface[:, 3] / 1e6,\n",
    "    },\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"distance from the free end [mm]\",\n",
    "    ylabel=\"stress at the interface [MPa]\",\n",
    "    title=\"Stress concentration at the free edge\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the coating thinner in `layered_plate_thermal_stress_geometry.py`, write the files again,\n",
    "and the stress in it approaches the film limit\n",
    "$E_c'(1+\\nu)\\,\\Delta\\alpha\\,\\Delta T$; add a compliant interlayer and watch the edge stresses\n",
    "drop."
   ]
  }
 ]
}
