{
 "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": [
    "# Heat transfer in a surface-mount package\n",
    "\n",
    "Circuit-board designers keep heat-sensitive chips away from heat sources. Here the footprint of a\n",
    "voltage regulator is held at 50 °C. Next to it a copper ground plane in the board surface carries\n",
    "lead 1 of a small-outline package (SOIC-16), and a copper strip inside the package connects that\n",
    "lead to the silicon die, which dissipates 20 mW itself. How hot does the die get?\n",
    "\n",
    "| part (dimensions in mm) | conductivity [W/(m K)] |\n",
    "|---|---|\n",
    "| circuit board $20\\times10\\times1$ with the regulator footprint $2\\times4$ | 0.3 |\n",
    "| copper ground plane $4\\times4\\times0.1$ | 400 |\n",
    "| plastic package body $9.9\\times3.9\\times1.5$ with tapered side walls | 0.2 |\n",
    "| silicon die $1\\times1\\times0.1$ | 130 |\n",
    "| copper interconnect strip, 0.4 mm wide | 40 (see below) |\n",
    "| 16 aluminium gull-wing leads, $0.4\\times0.2$ cross-section | 238 |\n",
    "\n",
    "The real strip is a 5 µm copper film. It conducts heat only along its length, so it is modelled\n",
    "50 µm thick with a tenth of the conductivity: the same conductance per width, $kd=2\\times10^{-3}$ W/K,\n",
    "with a thickness the tetrahedra can resolve.\n",
    "\n",
    "The heat equation $\\nabla\\cdot(k\\nabla T)+Q=0$ holds with $Q=2\\times10^8$ W/m³ in the die. The\n",
    "regulator footprint (`footprint.regulator`) is fixed at 50 °C; every other outer face is cooled by\n",
    "air at 30 °C with $h=50$ W/(m² K). All 22 parts are named bodies of the CAD file\n",
    "`surface_mount_package_heating.step`, written by `surface_mount_package_heating_geometry.py` with the\n",
    "CAD objects of OneSimulation; `load` returns the assembly, and the conductivity is assigned by the\n",
    "names of its parts.\n",
    "\n",
    "**Reference.** The maximum die temperature of this benchmark configuration is 47.6 °C. A mesh study\n",
    "and the heat given off to the air accompany the comparison."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid, regionwise\n",
    "from onesim.meshing import LocalRefinement, TetrahedralMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import AlgebraicMultigrid, ConjugateGradient\n",
    "from onesim.physics.heat_transfer import (\n",
    "    ConvectiveHeatFlux,\n",
    "    FixedTemperature,\n",
    "    HeatConduction,\n",
    ")\n",
    "from onesim.results.integration import mean_value, measure\n",
    "from onesim.simulation import Problem, Simulation\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",
    "Conforming tetrahedra over all parts; the mesh is refined in the die, the strip and the ground plane.\n",
    "Two meshes differ in the size there."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "assembly = load(\"surface_mount_package_heating.step\")\n",
    "regulator = assembly.boundaries[\"footprint.regulator\"]\n",
    "air = assembly.boundaries.all - regulator\n",
    "leads = [f\"lead_{k}\" for k in range(1, 17)]\n",
    "fine_parts = {\"die\": 1.0, \"strip\": 0.5, \"ground_plane\": 1.0}\n",
    "mesh_for = lambda scale: TetrahedralMesher(\n",
    "    target_size=1.5e-3,\n",
    "    refinements=tuple(\n",
    "        LocalRefinement(\n",
    "            region=assembly.volume_of(name), target_size=0.1e-3 * size * scale\n",
    "        )\n",
    "        for name, size in fine_parts.items()\n",
    "    ),\n",
    ").generate(assembly)\n",
    "meshes = {scale: mesh_for(scale) for scale in (2.0, 1.0)}\n",
    "\n",
    "view = plots.Camera(elevation=35, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.geometry(\n",
    "    assembly,\n",
    "    selection={\n",
    "        \"board\": assembly.volume_of(\"board\"),\n",
    "        \"regulator footprint\": assembly.volume_of(\"footprint\"),\n",
    "        \"ground plane\": assembly.volume_of(\"ground_plane\"),\n",
    "        \"package\": assembly.volume_of(\"package\"),\n",
    "        \"lead 1 (heat path)\": assembly.volume_of(\"lead_1\"),\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Package on the board next to the regulator\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[1.0],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Finer mesh: {meshes[1.0].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model and solution\n",
    "\n",
    "`regionwise` takes the names of the assembly parts as mesh regions. Linear elements on both meshes,\n",
    "solved by conjugate gradients with an algebraic-multigrid preconditioner."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "conductivity = {\n",
    "    \"die\": 130.0,\n",
    "    \"strip\": 40.0,\n",
    "    \"ground_plane\": 400.0,\n",
    "    \"board\": 0.3,\n",
    "    \"footprint\": 0.3,\n",
    "    \"package\": 0.2,\n",
    "    **{name: 238.0 for name in leads},\n",
    "}\n",
    "material = IsotropicSolid(\n",
    "    density=1000.0,\n",
    "    specific_heat_capacity=1000.0,\n",
    "    youngs_modulus=1e9,\n",
    "    poisson_ratio=0.3,\n",
    "    thermal_expansion_coefficient=0.0,\n",
    "    thermal_conductivity=regionwise(tuple(conductivity.items()), unit=\"W/m/K\"),\n",
    ")\n",
    "heat = HeatConduction(\n",
    "    domain=assembly.domain(),\n",
    "    material=material,\n",
    "    heating=regionwise(((\"die\", 2e8),), default=0.0, unit=\"W/m^3\"),\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"SOIC-16 package next to a voltage regulator\",\n",
    "    geometry=assembly,\n",
    "    physics=(heat,),\n",
    "    boundary_conditions=(\n",
    "        FixedTemperature(physics=heat, boundary=regulator, value=323.15),\n",
    "        ConvectiveHeatFlux(\n",
    "            physics=heat,\n",
    "            boundary=air,\n",
    "            heat_transfer_coefficient=50.0,\n",
    "            ambient_temperature=303.15,\n",
    "        ),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=1)),\n",
    "    linear_solver=ConjugateGradient(\n",
    "        preconditioner=AlgebraicMultigrid(),\n",
    "        relative_tolerance=1e-10,\n",
    "        maximum_iterations=3000,\n",
    "    ),\n",
    ")\n",
    "fields = {\n",
    "    scale: Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "    .solve_stationary()\n",
    "    .field(heat.temperature)\n",
    "    for scale, mesh in meshes.items()\n",
    "}\n",
    "field = fields[1.0]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The die temperature is the largest value on a grid through the die. The heat given off to the air,\n",
    "$h\\,(\\bar T_\\text{surface}-T_\\infty)\\,A$, follows from the mean temperature of the cooled faces; it must\n",
    "exceed the die power by the heat drawn from the regulator."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "g = np.linspace(-0.5, 0.5, 21) * 1e-3\n",
    "die_points = (\n",
    "    np.array(np.meshgrid(g, g, np.linspace(-0.05, 0.05, 5) * 1e-3, indexing=\"ij\"))\n",
    "    .reshape(3, -1)\n",
    "    .T\n",
    ")\n",
    "die_power = 2e8 * 1e-3 * 1e-3 * 0.1e-3\n",
    "print(\n",
    "    \"tetrahedra   maximum die temperature [°C]   against 47.6 °C   heat to the air   of which from the regulator\"\n",
    ")\n",
    "for scale, f in fields.items():\n",
    "    heat_out = 50.0 * (mean_value(f, boundary=air) - 303.15) * measure(f, boundary=air)\n",
    "    print(\n",
    "        f\"{meshes[scale].cell_count:10d} {f.evaluate(die_points).max() - 273.15:22.3f} {f.evaluate(die_points).max() - 273.15 - 47.6:+18.3f} K\"\n",
    "        f\" {1e3 * heat_out:14.2f} mW {1e3 * (heat_out - die_power):17.2f} mW\"\n",
    "    )\n",
    "print(\n",
    "    f\"lead 1 at the board: {field.evaluate(np.array([[-4.445e-3, -2.6e-3, -0.8e-3]]))[0] - 273.15:.2f} °C, \"\n",
    "    f\"lead 9 on the far side: {field.evaluate(np.array([[4.445e-3, 2.6e-3, -0.8e-3]]))[0] - 273.15:.2f} °C\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The surface temperature, the plane $z=0$ through die, strip and lead stubs, and the vertical section\n",
    "through lead 1: the heat runs from the regulator through the ground plane into lead 1 and along the\n",
    "strip to the die."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "view_options = dict(\n",
    "    component=lambda T, position: T - 273.15, limits=(30.0, 50.0), label=\"T [°C]\"\n",
    ")\n",
    "fig = plots.figure(1, 3, size=(18, 5.5))\n",
    "plots.surface(\n",
    "    field,\n",
    "    camera=plots.Camera(elevation=30, azimuth=-60),\n",
    "    title=\"Surface temperature\",\n",
    "    ax=fig[0],\n",
    "    **view_options\n",
    ")\n",
    "plots.section(\n",
    "    field,\n",
    "    plane=Plane(origin=(0.0, 0.0, 0.0), normal=(0.0, 0.0, 1.0)),\n",
    "    contours=20,\n",
    "    xlimits=(-6e-3, 6e-3),\n",
    "    ylimits=(-3e-3, 3e-3),\n",
    "    title=\"Plane z = 0: die, strip and lead stubs\",\n",
    "    ax=fig[1],\n",
    "    **view_options\n",
    ")\n",
    "plots.section(\n",
    "    field,\n",
    "    plane=Plane(origin=(-4.445e-3, 0.0, 0.0), normal=(1.0, 0.0, 0.0)),\n",
    "    contours=20,\n",
    "    xlimits=(-5e-3, 0.6e-3),\n",
    "    ylimits=(-1.9e-3, 0.8e-3),\n",
    "    title=\"Section through lead 1\",\n",
    "    ax=fig[2],\n",
    "    **view_options\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Move the heat path in `surface_mount_package_heating_geometry.py`: connect the strip to a lead on the\n",
    "far side of the package, or widen the ground plane, write the STEP file again and compare the die\n",
    "temperature. Without the die power the package only conducts regulator heat to the air."
   ]
  }
 ]
}
