{
 "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 warpage of a printed circuit board\n",
    "\n",
    "A board is a laminate of materials with different thermal expansion: glass-fibre epoxy (FR-4),\n",
    "copper, solder mask. If the stack is not symmetric about its mid-plane, heating bends it. Warpage\n",
    "during reflow soldering (peak around 260 °C) lifts component leads off their pads and is limited\n",
    "by industry standards to a fraction of a percent of the board diagonal.\n",
    "\n",
    "Here a square board of 40 mm side consists of 1.0 mm FR-4 with a full 0.1 mm copper layer on\n",
    "top, stress free at 25 °C and heated uniformly to 260 °C:\n",
    "\n",
    "| layer | $E$ | $\\nu$ | $\\alpha$ (in-plane) |\n",
    "|---|---|---|---|\n",
    "| FR-4 | 22 GPa | 0.15 | $14\\cdot10^{-6}$ 1/K |\n",
    "| copper | 117 GPa | 0.34 | $17\\cdot10^{-6}$ 1/K |\n",
    "\n",
    "The copper expands more, so the board bows with its copper side outwards. One quarter of the\n",
    "board comes from the CAD file `pcb_thermal_warpage.step` (faces `x_min` ... `z_max`; `x_min` and\n",
    "`y_min` are the symmetry planes), the copper layer from `pcb_thermal_warpage_copper.step`; the\n",
    "script `pcb_thermal_warpage_geometry.py` builds both with the CAD objects of OneSimulation.\n",
    "\n",
    "| face | mechanics |\n",
    "|---|---|\n",
    "| `x_min` / `y_min` | symmetry, $u_x=0$ / $u_y=0$ |\n",
    "| centre point of the lower face | $u_z=0$ |\n",
    "| all other faces | traction free |\n",
    "\n",
    "**Reference.** Away from the edges a thin laminate under a uniform temperature change takes a\n",
    "spherical shape (classical laminate theory; Timoshenko, *J. Opt. Soc. Am.* 11, 233, 1925, for the\n",
    "bimetal strip). With the biaxial moduli $E_i/(1-\\nu_i)$ the in-plane stress of each layer is\n",
    "\n",
    "$$\\sigma(z)=\\frac{E_i}{1-\\nu_i}\\bigl(\\varepsilon_0+\\kappa z-\\alpha_i\\Delta T\\bigr),\\qquad\n",
    "  \\int\\sigma\\,dz=0,\\quad\\int\\sigma\\,z\\,dz=0,$$\n",
    "\n",
    "the two balances fix the mid-plane strain $\\varepsilon_0$ and the curvature $\\kappa$, and the\n",
    "corners move by $-\\kappa\\,(L/\\sqrt2)^2/2=-\\kappa L^2/4$ relative to the centre."
   ]
  },
  {
   "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 Geometric, Piecewise, StructuredHexahedralMesher, Uniform\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, regionwise\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",
    "The hexahedral mesh has four cells through the laminate and two through the copper and gets finer\n",
    "towards the free edges, on two in-plane resolutions."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "board, copper = load(\"pcb_thermal_warpage.step\"), load(\n",
    "    \"pcb_thermal_warpage_copper.step\"\n",
    ")\n",
    "faces = board.boundaries\n",
    "half, _, thickness = board.size\n",
    "layer = copper.size[2]\n",
    "laminate = thickness - layer\n",
    "meshes = [\n",
    "    StructuredHexahedralMesher(\n",
    "        cells=(n, n, 6),\n",
    "        grading=(\n",
    "            Geometric(n, ratio=4.0, toward=\"end\"),\n",
    "            Geometric(n, ratio=4.0, toward=\"end\"),\n",
    "            Piecewise(((laminate, Uniform(4)), (layer, Uniform(2)))),\n",
    "        ),\n",
    "    ).generate(board)\n",
    "    for n in (12, 24)\n",
    "]\n",
    "\n",
    "view = plots.Camera(elevation=30, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(14, 5.5))\n",
    "plots.geometry(\n",
    "    [board.named(\"FR-4 laminate\"), copper.named(\"copper layer\")],\n",
    "    camera=view,\n",
    "    title=\"Quarter of the board\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[-1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{meshes[-1].cell_count} hexahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The layer properties are assigned region by region. The uniform reflow temperature comes from a\n",
    "heat-conduction model and enters the mechanics as thermal strain through a field coupling."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "layers = {\"FR-4\": (22e9, 0.15, 14e-6), \"copper\": (117e9, 0.34, 17e-6)}\n",
    "room, reflow = 298.15, 533.15\n",
    "stack = lambda index, unit: regionwise(\n",
    "    ((copper, layers[\"copper\"][index]),), default=layers[\"FR-4\"][index], unit=unit\n",
    ")\n",
    "material = replace(\n",
    "    IsotropicSolid(\n",
    "        density=1900.0,\n",
    "        specific_heat_capacity=1100.0,\n",
    "        thermal_conductivity=0.3,\n",
    "        youngs_modulus=1e9,\n",
    "        poisson_ratio=0.3,\n",
    "        thermal_expansion_coefficient=1e-6,\n",
    "    ),\n",
    "    youngs_modulus=stack(0, \"Pa\"),\n",
    "    poisson_ratio=stack(1, \"1\"),\n",
    "    thermal_expansion_coefficient=stack(2, \"1/K\"),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "heat = HeatConduction(domain=board.volume, material=material)\n",
    "solid = LinearElasticity(\n",
    "    domain=board.volume,\n",
    "    material=material,\n",
    "    thermal_strain=IsotropicThermalExpansion(reference_temperature=room),\n",
    ")\n",
    "displacements, stresses = [], []\n",
    "for mesh in meshes:\n",
    "    heated = Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Reflow temperature\",\n",
    "            geometry=board,\n",
    "            physics=(heat,),\n",
    "            boundary_conditions=(\n",
    "                FixedTemperature(boundary=faces.all, physics=heat, value=reflow),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=mesh,\n",
    "        numerics=numerics,\n",
    "    ).solve_stationary()\n",
    "    result = Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Board warpage\",\n",
    "            geometry=board,\n",
    "            physics=(solid,),\n",
    "            boundary_conditions=(\n",
    "                FixedDisplacementComponents(\n",
    "                    boundary=faces.x_min, physics=solid, components=(\"x\",)\n",
    "                ),\n",
    "                FixedDisplacementComponents(\n",
    "                    boundary=faces.y_min, physics=solid, components=(\"y\",)\n",
    "                ),\n",
    "                FixedDisplacementComponents(\n",
    "                    boundary=faces.z_min,\n",
    "                    physics=solid,\n",
    "                    components=(\"z\",),\n",
    "                    where={\"z\": lambda x, y, z: (x < 1e-9) & (y < 1e-9)},\n",
    "                ),\n",
    "                TractionFree(\n",
    "                    boundary=faces.x_max | faces.y_max | faces.z_max | faces.z_min,\n",
    "                    physics=solid,\n",
    "                ),\n",
    "            ),\n",
    "            couplings=(\n",
    "                FieldCoupling(\n",
    "                    source=heated.field(heat.temperature),\n",
    "                    target=solid.temperature,\n",
    "                    transfer=FiniteElementEvaluation(),\n",
    "                ),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=mesh,\n",
    "        numerics=numerics,\n",
    "    ).solve_stationary()\n",
    "    displacements.append(result.field(solid.displacement))\n",
    "    stresses.append(result.field(solid.stress))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The curvature from laminate theory, the deflection of the corner against the centre on both\n",
    "meshes and the in-plane stress through the thickness at the centre."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "delta = reflow - room\n",
    "bounds = {\"FR-4\": (0.0, laminate), \"copper\": (laminate, thickness)}\n",
    "moments = {\n",
    "    name: [(top**k - bottom**k) / k for k in (1, 2, 3)]\n",
    "    for name, (bottom, top) in bounds.items()\n",
    "}\n",
    "biaxial = {name: E / (1 - nu) for name, (E, nu, alpha) in layers.items()}\n",
    "strain, curvature = np.linalg.solve(\n",
    "    sum(biaxial[n] * np.array([moments[n][:2], moments[n][1:]]) for n in layers),\n",
    "    sum(biaxial[n] * layers[n][2] * delta * np.array(moments[n][:2]) for n in layers),\n",
    ")\n",
    "laminate_stress = lambda z: np.where(\n",
    "    z > laminate, biaxial[\"copper\"], biaxial[\"FR-4\"]\n",
    ") * (\n",
    "    strain\n",
    "    + curvature * z\n",
    "    - np.where(z > laminate, layers[\"copper\"][2], layers[\"FR-4\"][2]) * delta\n",
    ")\n",
    "corner = [\n",
    "    field.evaluate([[half, half, 0.0]])[0, 2] - field.evaluate([[0.0, 0.0, 0.0]])[0, 2]\n",
    "    for field in displacements\n",
    "]\n",
    "print(\n",
    "    f\"laminate theory: curvature {curvature:.4f} 1/m, corner deflection -kappa L^2/4 = {1e6 * -curvature * (2 * half) ** 2 / 4:.2f} µm\"\n",
    ")\n",
    "for mesh, value in zip(meshes, corner):\n",
    "    print(\n",
    "        f\"{mesh.cell_count:6d} hexahedra: corner deflection {1e6 * value:.2f} µm ({100 * (value / (-curvature * (2 * half) ** 2 / 4) - 1):+.2f} %)\"\n",
    "    )\n",
    "heights = {\n",
    "    \"bottom of the FR-4\": 1e-7,\n",
    "    \"FR-4 at the copper\": laminate - 1e-7,\n",
    "    \"copper at the FR-4\": laminate + 1e-7,\n",
    "    \"top of the copper\": thickness - 1e-7,\n",
    "}\n",
    "centre = stresses[-1].evaluate([[1e-6, 1e-6, z] for z in heights.values()])[:, 0]\n",
    "print(f\"{'position':22s} σ_xx simulation [MPa]   laminate theory [MPa]\")\n",
    "for (label, z), value in zip(heights.items(), centre):\n",
    "    print(f\"{label:22s} {value / 1e6:20.3f} {laminate_stress(z) / 1e6:22.3f}\")\n",
    "print(\n",
    "    f\"warpage over the diagonal: {100 * abs(corner[-1]) / (2 * np.sqrt(2) * half):.3f} % of the diagonal length\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The deflection of the board, the deflection along the diagonal against the spherical shape, and\n",
    "the in-plane stress through the thickness at the centre."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "d = np.linspace(0.0, np.sqrt(2) * half, 41)\n",
    "diagonal = np.column_stack((d / np.sqrt(2), d / np.sqrt(2), np.zeros_like(d)))\n",
    "z = np.linspace(1e-7, thickness - 1e-7, 89)\n",
    "fig = plots.figure(1, 3, size=(18, 5.5))\n",
    "plots.surface(\n",
    "    displacements[-1],\n",
    "    boundary=faces.z_min,\n",
    "    component=lambda u, position: 1e6\n",
    "    * (u[:, 2] - displacements[-1].evaluate([[0, 0, 0]])[0, 2]),\n",
    "    contours=10,\n",
    "    subdivisions=2,\n",
    "    symmetry={\"planes\": [((1, 0, 0), (0, 0, 0)), ((0, 1, 0), (0, 0, 0))]},\n",
    "    label=\"deflection [µm]\",\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    title=\"Deflection relative to the centre\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"simulation\": (\n",
    "            1e3 * d,\n",
    "            1e6\n",
    "            * (\n",
    "                displacements[-1].evaluate(diagonal)[:, 2]\n",
    "                - displacements[-1].evaluate([[0, 0, 0]])[0, 2]\n",
    "            ),\n",
    "        )\n",
    "    },\n",
    "    reference={\"laminate theory, sphere\": (1e3 * d, -1e6 * curvature * d**2 / 2)},\n",
    "    xlabel=\"distance from the centre along the diagonal [mm]\",\n",
    "    ylabel=\"deflection [µm]\",\n",
    "    title=\"Warpage along the diagonal\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"simulation\": (\n",
    "            stresses[-1].evaluate(\n",
    "                np.column_stack((np.full_like(z, 1e-6), np.full_like(z, 1e-6), z))\n",
    "            )[::4, 0]\n",
    "            / 1e6,\n",
    "            1e3 * z[::4],\n",
    "        )\n",
    "    },\n",
    "    reference={\"laminate theory\": (laminate_stress(z) / 1e6, 1e3 * z)},\n",
    "    hlines={\"copper / FR-4\": 1e3 * laminate},\n",
    "    xlabel=\"σ_xx at the centre [MPa]\",\n",
    "    ylabel=\"height [mm]\",\n",
    "    title=\"Stress through the thickness\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add a copper layer on the bottom in `pcb_thermal_warpage_geometry.py` and the warpage vanishes\n",
    "for a balanced stack; give FR-4 its much larger expansion above the glass transition by a\n",
    "temperature-dependent coefficient; or heat the board from below and couple a transient\n",
    "temperature field to see the warpage during the reflow ramp."
   ]
  }
 ]
}
