{
 "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": [
    "# Four-point bending test of a layered module\n",
    "\n",
    "The four-point bending test is a standard reliability test for electronic packages: two\n",
    "supports below and two load rollers above leave the span between the rollers under a constant\n",
    "bending moment, free of shear force, so every layer of the stack sees a clean, known stress.\n",
    "Here a 60 mm × 10 mm strip of a power module is tested: a thick copper baseplate, a solder\n",
    "layer, an alumina substrate of the direct-bonded-copper type and its top copper layer.\n",
    "\n",
    "| layer (bottom to top) | thickness | $E$ | $\\nu$ |\n",
    "|---|---|---|---|\n",
    "| copper baseplate | 3.0 mm | 120 GPa | 0.34 |\n",
    "| solder (SnAgCu) | 0.2 mm | 50 GPa | 0.36 |\n",
    "| alumina ceramic | 0.63 mm | 370 GPa | 0.22 |\n",
    "| copper top layer | 0.3 mm | 120 GPa | 0.34 |\n",
    "\n",
    "Support span $L=50$ mm, roller span 20 mm, so the rollers sit $a=15$ mm inside the supports;\n",
    "total load $F=200$ N, $P=F/2$ per roller.\n",
    "\n",
    "The strip is symmetric about both mid-planes, so one quarter is modelled. It comes from the CAD\n",
    "file `four_point_bending_layered_module.step` with the face names `x_min` ... `z_max`; the files\n",
    "`..._solder.step`, `..._ceramic.step` and `..._copper.step` mark the regions of the other\n",
    "materials. The script `four_point_bending_layered_module_geometry.py` writes all four.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `x_min`, `y_min` (mid-planes) | symmetry: $u_x=0$, $u_y=0$ |\n",
    "| `z_min` along the support line $x=L/2$ | $u_z=0$ |\n",
    "| `z_max` under the roller, 1 mm wide at $x=10$ mm | pressure, resultant $P$ |\n",
    "| all other faces | traction free |\n",
    "\n",
    "**Reference.** Between the rollers the moment is $M=Pa$. Laminated beam theory with the\n",
    "transformed section (Timoshenko & Gere, *Mechanics of Materials*, composite beams) puts the\n",
    "neutral axis at $z_n=\\sum E_it_iz_i/\\sum E_it_i$ and gives the bending stiffness, the curvature\n",
    "and the stress in layer $i$,\n",
    "\n",
    "$$EI=b\\sum_i E_i\\Bigl(\\frac{t_i^3}{12}+t_i(z_i-z_n)^2\\Bigr),\\qquad \\kappa=\\frac{M}{EI},\\qquad\n",
    "  \\sigma_{xx}=E_i\\,\\kappa\\,(z-z_n),$$\n",
    "\n",
    "and the elastic curve of the four-point bending beam gives the mid-span deflection\n",
    "$\\delta=Pa(3L^2-4a^2)/(24\\,EI)$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "from dataclasses import replace\n",
    "\n",
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import Piecewise, StructuredHexahedralMesher, Uniform\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.solid_mechanics import (\n",
    "    FixedDisplacementComponents,\n",
    "    LinearElasticity,\n",
    "    Traction,\n",
    "    TractionFree,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation, regionwise\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 strip and the three layer regions. The hexahedra follow every\n",
    "interface, put nodes on the support line and resolve the 1 mm roller strip."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "strip = load(\"four_point_bending_layered_module.step\")\n",
    "regions = {\n",
    "    name: load(f\"four_point_bending_layered_module_{name}.step\")\n",
    "    for name in (\"solder\", \"ceramic\", \"copper\")\n",
    "}\n",
    "faces = strip.boundaries\n",
    "half_length, half_width, thickness = strip.size\n",
    "along = Piecewise(\n",
    "    (\n",
    "        (0.0095, Uniform(12)),\n",
    "        (0.001, Uniform(2)),\n",
    "        (0.014, Uniform(14)),\n",
    "        (0.001, Uniform(2)),\n",
    "        (0.0045, Uniform(5)),\n",
    "    )\n",
    ")\n",
    "across = Piecewise(\n",
    "    (\n",
    "        (0.003, Uniform(8)),\n",
    "        (0.0002, Uniform(1)),\n",
    "        (0.00063, Uniform(2)),\n",
    "        (0.0003, Uniform(1)),\n",
    "    )\n",
    ")\n",
    "mesh = StructuredHexahedralMesher(\n",
    "    cells=(35, 5, 12), grading=(along, Uniform(5), across)\n",
    ").generate(strip)\n",
    "\n",
    "view = plots.Camera(elevation=28, azimuth=-62)\n",
    "fig = plots.figure(1, 2, size=(15, 5.5))\n",
    "plots.geometry(\n",
    "    [\n",
    "        strip.named(\"copper baseplate\"),\n",
    "        *(region.named(name) for name, region in regions.items()),\n",
    "    ],\n",
    "    camera=view,\n",
    "    title=\"Quarter of the layered strip\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{mesh.cell_count} hexahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Elastic constants per layer through `regionwise`; quadratic hexahedra."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "layers = {\n",
    "    \"baseplate\": (3.0e-3, 120e9, 0.34),\n",
    "    \"solder\": (0.2e-3, 50e9, 0.36),\n",
    "    \"ceramic\": (0.63e-3, 370e9, 0.22),\n",
    "    \"copper\": (0.3e-3, 120e9, 0.34),\n",
    "}\n",
    "force, support, roller, strip_width = 200.0, 0.025, 0.010, 0.001\n",
    "layered = lambda index, unit: regionwise(\n",
    "    tuple((region, layers[name][index]) for name, region in regions.items()),\n",
    "    default=layers[\"baseplate\"][index],\n",
    "    unit=unit,\n",
    ")\n",
    "material = replace(\n",
    "    IsotropicSolid(\n",
    "        density=8000.0,\n",
    "        specific_heat_capacity=400.0,\n",
    "        thermal_conductivity=100.0,\n",
    "        youngs_modulus=1e9,\n",
    "        poisson_ratio=0.3,\n",
    "        thermal_expansion_coefficient=1e-5,\n",
    "    ),\n",
    "    youngs_modulus=layered(1, \"Pa\"),\n",
    "    poisson_ratio=layered(2, \"1\"),\n",
    ")\n",
    "pressure = force / 4 / (strip_width * half_width)\n",
    "\n",
    "model = LinearElasticity(domain=strip.volume, material=material)\n",
    "problem = Problem(\n",
    "    name=\"Four-point bending\",\n",
    "    geometry=strip,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        FixedDisplacementComponents(\n",
    "            boundary=faces.x_min, physics=model, components=(\"x\",)\n",
    "        ),\n",
    "        FixedDisplacementComponents(\n",
    "            boundary=faces.y_min, physics=model, components=(\"y\",)\n",
    "        ),\n",
    "        FixedDisplacementComponents(\n",
    "            boundary=faces.z_min,\n",
    "            physics=model,\n",
    "            components=(\"z\",),\n",
    "            where={\"z\": lambda x, y, z: np.abs(x - support) < 1e-7},\n",
    "        ),\n",
    "        Traction(\n",
    "            boundary=faces.z_max,\n",
    "            physics=model,\n",
    "            value=lambda x, y, z: np.stack(\n",
    "                (\n",
    "                    0 * x,\n",
    "                    0 * x,\n",
    "                    np.where(\n",
    "                        np.abs(x - roller) < strip_width / 2 + 1e-9, -pressure, 0.0\n",
    "                    ),\n",
    "                ),\n",
    "                axis=-1,\n",
    "            ),\n",
    "        ),\n",
    "        TractionFree(boundary=faces.x_max | faces.y_max, physics=model),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "result = Simulation(problem=problem, mesh=mesh, numerics=numerics).solve_stationary()\n",
    "displacement, stress = result.field(model.displacement), result.field(model.stress)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The transformed section of the stack, the stress through the layers at mid-span, the curvature\n",
    "fitted to the deflection between the rollers and the mid-span deflection."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "thick, moduli = np.array([t for t, _, _ in layers.values()]), np.array(\n",
    "    [e for _, e, _ in layers.values()]\n",
    ")\n",
    "tops = np.cumsum(thick)\n",
    "centres = tops - thick / 2\n",
    "neutral = (moduli * thick) @ centres / (moduli @ thick)\n",
    "bending_stiffness = (\n",
    "    2 * half_width * moduli @ (thick**3 / 12 + thick * (centres - neutral) ** 2)\n",
    ")\n",
    "moment, span, arm = force / 2 * (support - roller), 2 * support, support - roller\n",
    "curvature = moment / bending_stiffness\n",
    "laminate = lambda z: moduli[np.searchsorted(tops, z)] * curvature * (neutral - z)\n",
    "elastic_curve = (\n",
    "    lambda s: force\n",
    "    / 2\n",
    "    * np.where(\n",
    "        s < arm,\n",
    "        s * (3 * span * arm - 3 * arm**2 - s**2),\n",
    "        arm\n",
    "        * (\n",
    "            3 * span * np.minimum(s, span - s)\n",
    "            - 3 * np.minimum(s, span - s) ** 2\n",
    "            - arm**2\n",
    "        ),\n",
    "    )\n",
    "    / (6 * bending_stiffness)\n",
    ")\n",
    "\n",
    "points = {\n",
    "    \"bottom of the baseplate\": 1e-6,\n",
    "    \"top of the baseplate\": tops[0] - 1e-6,\n",
    "    \"bottom of the ceramic\": tops[1] + 1e-6,\n",
    "    \"top of the ceramic\": tops[2] - 1e-6,\n",
    "    \"top of the copper layer\": tops[3] - 1e-6,\n",
    "}\n",
    "at_mid_span = stress.evaluate([[1e-6, 1e-6, z] for z in points.values()])[:, 0]\n",
    "x = np.linspace(0, roller - strip_width, 25)\n",
    "inner = displacement.evaluate(\n",
    "    np.column_stack((x, np.full_like(x, 1e-6), np.full_like(x, neutral)))\n",
    ")[:, 2]\n",
    "fitted = 2 * np.polyfit(x, inner, 2)[0]\n",
    "x_line = np.linspace(0, support, 101)\n",
    "line = displacement.evaluate(\n",
    "    np.column_stack((x_line, np.full_like(x_line, 1e-6), np.full_like(x_line, neutral)))\n",
    ")[:, 2]\n",
    "seat = line[-1]\n",
    "\n",
    "print(\n",
    "    f\"neutral axis {1e3 * neutral:.3f} mm above the bottom, bending stiffness {bending_stiffness:.4f} N m²\"\n",
    ")\n",
    "print(\n",
    "    f\"{'position at mid-span':26s} simulation [MPa]   laminated beam [MPa]   deviation\"\n",
    ")\n",
    "for (label, z), value in zip(points.items(), at_mid_span):\n",
    "    print(\n",
    "        f\"{label:26s} {value / 1e6:16.2f} {laminate(z) / 1e6:22.2f} {100 * (value / laminate(z) - 1):+10.2f} %\"\n",
    "    )\n",
    "print(\n",
    "    f\"curvature between the rollers: simulation {fitted:.5f} 1/m, laminated beam {curvature:.5f} 1/m, \"\n",
    "    f\"deviation {100 * (fitted / curvature - 1):+.2f} %\"\n",
    ")\n",
    "print(\n",
    "    f\"mid-span deflection relative to the supports: simulation {1e6 * (seat - line[0]):.2f} µm, elastic curve \"\n",
    "    f\"{1e6 * elastic_curve(support):.2f} µm, deviation {100 * ((seat - line[0]) / elastic_curve(support) - 1):+.2f} %\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The axial stress on the deformed quarter strip (displacement magnified 100 times) and in its\n",
    "mid-plane, the stress through the stack at mid-span, and the deflection along the strip."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "z = np.linspace(1e-6, thickness - 1e-6, 400)\n",
    "through = stress.evaluate(\n",
    "    np.column_stack((np.full_like(z, 1e-6), np.full_like(z, 1e-6), z))\n",
    ")[:, 0]\n",
    "axial_stress = lambda s, position: s[:, 0] / 1e6\n",
    "fig = plots.figure(2, 2, size=(16, 11))\n",
    "plots.surface(\n",
    "    stress,\n",
    "    component=axial_stress,\n",
    "    deformation=displacement,\n",
    "    deformation_scale=100.0,\n",
    "    colormap=\"diverging\",\n",
    "    limits=(-90, 90),\n",
    "    camera=view,\n",
    "    label=\"σ_xx [MPa]\",\n",
    "    title=\"Deformed quarter strip (×100)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.section(\n",
    "    stress,\n",
    "    plane=Plane(origin=(0, 1e-6, 0), normal=(0, 1, 0)),\n",
    "    component=axial_stress,\n",
    "    colormap=\"diverging\",\n",
    "    limits=(-90, 90),\n",
    "    subdivisions=3,\n",
    "    aspect=2.0,\n",
    "    xlimits=(0.0, 0.030),\n",
    "    label=\"σ_xx [MPa]\",\n",
    "    title=\"Mid-plane y = 0 (thickness stretched 2×)\",\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"simulation\": (through[::10] / 1e6, 1e3 * z[::10])},\n",
    "    reference={\"laminated beam\": (laminate(z) / 1e6, 1e3 * z)},\n",
    "    hlines=list(1e3 * tops[:3]),\n",
    "    xlabel=\"σ_xx at mid-span [MPa]\",\n",
    "    ylabel=\"height [mm]\",\n",
    "    title=\"Stress through the stack\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    1e3 * x_line,\n",
    "    {\"simulation\": 1e6 * (seat - line)},\n",
    "    reference={\"elastic curve\": 1e6 * elastic_curve(support - x_line)},\n",
    "    vlines={\"roller\": 1e3 * roller, \"support\": 1e3 * support},\n",
    "    xlabel=\"x from mid-span [mm]\",\n",
    "    ylabel=\"deflection [µm]\",\n",
    "    title=\"Deflection of the neutral axis\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the ceramic thicker or the baseplate thinner in the geometry script, write the files again\n",
    "and watch the neutral axis move into the ceramic; add the chips on top as further layer regions,\n",
    "or cool the stack from the soldering temperature first to add the residual thermal stresses."
   ]
  }
 ]
}
