{
 "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 contact between a package and a finned heat sink\n",
    "\n",
    "Two machined surfaces pressed together touch only at the tips of their roughness. Heat crosses\n",
    "the interface through these spots and through the gas in the gaps between them, and the\n",
    "temperature jumps across the interface. The contact conductance $h$ sets the jump,\n",
    "\n",
    "$$q_n=h\\,\\big(T_\\text{package}-T_\\text{sink}\\big),\\qquad h=h_c+h_g .$$\n",
    "\n",
    "**Solid spots** (Cooper, Mikic and Yovanovich 1969, for plastically deformed asperities):\n",
    "$h_c=1.25\\,k_s\\,\\dfrac{m}{\\sigma}\\left(\\dfrac{p}{H_c}\\right)^{0.95}$ with the harmonic mean\n",
    "conductivity $k_s=2k_1k_2/(k_1+k_2)$, the combined surface roughness $\\sigma=2$ µm, the mean\n",
    "asperity slope $m=0.12$ and the contact pressure $p$. The microhardness of the aluminium follows\n",
    "the Vickers correlation $H_c=c_1\\,(1.62\\,\\sigma/(\\sigma_0 m))^{c_2}$ with $c_1=6.23$ GPa,\n",
    "$c_2=-0.23$, $\\sigma_0=1$ µm.\n",
    "\n",
    "**Gas gap** (Yovanovich, in Bejan and Kraus, *Heat Transfer Handbook*, 2003, ch. 4):\n",
    "$h_g=k_g/(Y+M)$ with the mean plane separation $Y=1.53\\,\\sigma\\,(p/H_c)^{-0.097}$ and the gas\n",
    "rarefaction parameter $M=\\frac{2-\\alpha}{\\alpha}\\,\\frac{2\\gamma}{\\gamma+1}\\,\\frac{\\Lambda}{\\Pr}$ for\n",
    "air at 50 Torr ($k_g=0.031$ W/(m K), accommodation $\\alpha=0.78$, mean free path $\\Lambda$).\n",
    "\n",
    "The package is a silicon cylinder ($k=130$ W/(m K)) of 1 cm radius and 5 cm length with a uniform\n",
    "heat source of 5 W. The aluminium sink ($k=238$ W/(m K)) has a hub of 3 mm wall and eight radial\n",
    "fins of 2 mm that reach 2 cm from the axis. Air at 20 °C flows along the fins at $U=8.5$ m/s; the\n",
    "local laminar flat-plate coefficient at the distance $z$ from the leading edge is\n",
    "\n",
    "$$h_\\text{air}(z)=0.332\\,\\frac{k_\\text{air}}{z}\\,\\mathrm{Re}_z^{1/2}\\,\\Pr^{1/3},\\qquad \\mathrm{Re}_z=\\frac{U z}{\\nu}.$$\n",
    "\n",
    "| faces | condition |\n",
    "|---|---|\n",
    "| `cooled`, air side of the sink | $-k\\,\\partial T/\\partial n=h_\\text{air}(z)\\,(T-20\\ \\text{°C})$ |\n",
    "| `contact`, package surface and bore | thermal contact, conductance $h_c+h_g$ |\n",
    "| `symmetry`, the two cut planes | no heat flux |\n",
    "| `ends`, $z=0$ and $z=5$ cm | no heat flux |\n",
    "\n",
    "By symmetry one sixteenth of the device, a sector of 22.5° with half a fin, is modelled. It comes\n",
    "from the CAD file `package_heat_sink_thermal_contact.step`, an assembly of the parts package and\n",
    "sink; the script `package_heat_sink_thermal_contact_geometry.py` builds it with the CAD objects of\n",
    "OneSimulation.\n",
    "\n",
    "**Reference.** The heat that leaves through the cooled faces must equal the 5 W of the package.\n",
    "The mean temperature jump at the contact must equal the mean contact heat flux divided by $h$.\n",
    "The short aluminium fins are nearly isothermal (fin efficiency above 99 %), so the mean sink\n",
    "temperature follows from $T_\\text{air}+P/\\int h_\\text{air}\\,\\mathrm{d}A$."
   ]
  },
  {
   "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.materials.thermal import asperity_contact_conductance\n",
    "from onesim.meshing import TetrahedralMesher, interface\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.heat_transfer import (\n",
    "    ConvectiveHeatFlux,\n",
    "    HeatConduction,\n",
    "    HeatFlux,\n",
    "    ThermalContact,\n",
    ")\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",
    "`load` returns the sector with the parts package and sink as material regions and their named\n",
    "faces. Tetrahedra of 1.2 mm, 0.6 mm at the contact, fill it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "device = load(\"package_heat_sink_thermal_contact.step\")\n",
    "faces = device.boundaries\n",
    "mesh = TetrahedralMesher(\n",
    "    target_size=0.0012,\n",
    "    size_field=lambda p: np.where(\n",
    "        np.abs(np.hypot(p[:, 0], p[:, 1]) - 0.01) < 0.002, 0.0006, 0.0012\n",
    "    ),\n",
    ").generate(device)\n",
    "contact = interface(mesh, \"package_sink\")\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    device,\n",
    "    selection={\n",
    "        \"cooled\": faces[\"sink.cooled\"],\n",
    "        \"contact\": faces[\"package.contact\"],\n",
    "        \"symmetry\": faces[\"sink.symmetry\"] | faces[\"package.symmetry\"],\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=55, azimuth=35),\n",
    "    length_unit=\"mm\",\n",
    "    title=\"One sixteenth: package and half a fin\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=plots.Camera(elevation=55, azimuth=35),\n",
    "    length_unit=\"mm\",\n",
    "    title=f\"{mesh.cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Contact conductance\n",
    "\n",
    "`asperity_contact_conductance` gives the solid-spot part; the gas gap and the microhardness are\n",
    "the short formulas above. Three contact pressures, 15, 25 and 35 kPa, are compared."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "k_si, k_al, power, length, radius = 130.0, 238.0, 5.0, 0.05, 0.01\n",
    "sigma, slope, k_gap = 2e-6, 0.12, 0.031\n",
    "hardness = 6.23e9 * (1.62 * sigma / (1e-6 * slope)) ** -0.23\n",
    "free_path = 0.064e-6 * (300.0 / 288.0) * (760.0 / 50.0)\n",
    "rarefaction = (2 - 0.78) / 0.78 * (2 * 1.4 / 2.4) * free_path / 0.707\n",
    "pressures = (15e3, 25e3, 35e3)\n",
    "conductance = {\n",
    "    p: asperity_contact_conductance(\n",
    "        pressure=p,\n",
    "        conductivity=2 * k_si * k_al / (k_si + k_al),\n",
    "        rms_roughness=sigma,\n",
    "        asperity_slope=slope,\n",
    "        microhardness=hardness,\n",
    "    )\n",
    "    + k_gap / (1.53 * sigma * (p / hardness) ** -0.097 + rarefaction)\n",
    "    for p in pressures\n",
    "}\n",
    "print(\n",
    "    f\"microhardness {hardness / 1e9:.2f} GPa, gas rarefaction parameter {1e6 * rarefaction:.2f} µm\"\n",
    ")\n",
    "for p, h in conductance.items():\n",
    "    print(f\"p = {p / 1e3:4.0f} kPa: contact conductance {h:7.0f} W/(m² K)\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`regionwise` gives each part its conductivity and the package its heat source; `ThermalContact`\n",
    "acts on the faces between the two parts, which `interface` returns. The local air-side\n",
    "coefficient varies along the fins: `ConvectiveHeatFlux` takes it as a function of the position."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "air, speed, nu_air, k_air, prandtl = 293.15, 8.5, 1.59e-5, 0.0263, 0.707\n",
    "h_air = (\n",
    "    lambda x, y, z: 0.332\n",
    "    * k_air\n",
    "    * prandtl ** (1 / 3)\n",
    "    * np.sqrt(speed / (nu_air * np.maximum(z, 1e-3)))\n",
    ")\n",
    "source = power / (np.pi * radius**2 * length)\n",
    "material = IsotropicSolid(\n",
    "    density=2500.0,\n",
    "    specific_heat_capacity=800.0,\n",
    "    youngs_modulus=1e11,\n",
    "    poisson_ratio=0.3,\n",
    "    thermal_expansion_coefficient=0.0,\n",
    "    thermal_conductivity=regionwise({\"package\": k_si, \"sink\": k_al}, unit=\"W/m/K\"),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "models, temperatures = {}, {}\n",
    "for p, h in conductance.items():\n",
    "    model = HeatConduction(\n",
    "        domain=device.domain(),\n",
    "        material=material,\n",
    "        heating=regionwise({\"package\": source}, default=0.0, unit=\"W/m^3\"),\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=f\"Package on a heat sink, {p / 1e3:.0f} kPa\",\n",
    "        geometry=device,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            ConvectiveHeatFlux(\n",
    "                boundary=faces[\"sink.cooled\"],\n",
    "                physics=model,\n",
    "                heat_transfer_coefficient=h_air,\n",
    "                ambient_temperature=air,\n",
    "            ),\n",
    "            HeatFlux(\n",
    "                boundary=faces.all - faces[\"sink.cooled\"], physics=model, value=0.0\n",
    "            ),\n",
    "            ThermalContact(boundary=contact, physics=model, conductance=h),\n",
    "        ),\n",
    "    )\n",
    "    models[p] = model\n",
    "    temperatures[p] = (\n",
    "        Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "        .solve_stationary()\n",
    "        .field(model.temperature)\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The heat leaving the sector through the cooled faces (times 16), the mean jump across the contact\n",
    "between points 0.3 mm on either side along the sector bisector, and the temperature of the fin tip\n",
    "at mid-length against the resistance estimate of the sink surface."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "angle = np.radians(11.25)\n",
    "z = np.linspace(0.002, 0.048, 24)\n",
    "inner = np.column_stack(\n",
    "    (\n",
    "        (radius - 3e-4) * np.cos(angle) * np.ones_like(z),\n",
    "        (radius - 3e-4) * np.sin(angle) * np.ones_like(z),\n",
    "        z,\n",
    "    )\n",
    ")\n",
    "outer = np.column_stack(\n",
    "    (\n",
    "        (radius + 3e-4) * np.cos(angle) * np.ones_like(z),\n",
    "        (radius + 3e-4) * np.sin(angle) * np.ones_like(z),\n",
    "        z,\n",
    "    )\n",
    ")\n",
    "area = 2 * np.pi * radius * length\n",
    "nodes = np.linspace(0, 1, 401)\n",
    "weight = (\n",
    "    np.sqrt(speed / nu_air) * 0.332 * k_air * prandtl ** (1 / 3) * 2 * np.sqrt(length)\n",
    ")\n",
    "cooled_area_per_length = 2 * np.pi * 0.013 - 8 * 0.002 + 8 * 2 * 0.007 + 8 * 0.002\n",
    "estimate = air + power / (weight * cooled_area_per_length)\n",
    "print(\n",
    "    f\"resistance estimate of the mean sink surface temperature: {estimate - 273.15:.2f} °C\"\n",
    ")\n",
    "print(\n",
    "    \"p [kPa]   heat out [W]   jump [K]   q/h [K]   package centre [°C]   sink at the fin tip [°C]\"\n",
    ")\n",
    "for p, field in temperatures.items():\n",
    "    out = 16 * field.boundary_flux(faces[\"sink.cooled\"])\n",
    "    jump = np.mean(field.evaluate(inner) - field.evaluate(outer))\n",
    "    centre = field.evaluate(np.array([[1e-4, 1e-5, length / 2]]))[0]\n",
    "    tip = field.evaluate(np.array([[0.0199, 1e-5, length / 2]]))[0]\n",
    "    print(\n",
    "        f\"{p / 1e3:7.0f} {out:14.4f} {jump:10.4f} {power / area / conductance[p]:9.4f} {centre - 273.15:21.3f} {tip - 273.15:23.3f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The heat source leaves through the cooled faces (the faceted package of the mesh holds a little\n",
    "less volume than the cylinder, and with it a little less of the 5 W), and the jump at the contact\n",
    "is the mean contact flux over the conductance. With these surfaces the gas in the gap carries most\n",
    "of the heat, so the contact pressure changes the jump only a little; the fin tip lies within a\n",
    "few tenths of a kelvin of the resistance estimate.\n",
    "\n",
    "## Figure\n",
    "\n",
    "The temperature on the surface of the sector at 35 kPa, and the temperature along the radius\n",
    "through the fin at mid-length for the three pressures."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.surface(\n",
    "    temperatures[35e3],\n",
    "    component=lambda T, position: T - 273.15,\n",
    "    camera=plots.Camera(elevation=55, azimuth=35),\n",
    "    subdivisions=2,\n",
    "    length_unit=\"mm\",\n",
    "    label=\"T [°C]\",\n",
    "    title=\"Temperature at 35 kPa\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "r = np.linspace(0.0015, 0.0195, 361)\n",
    "line = np.column_stack((r, np.full_like(r, 0.0005), np.full_like(r, length / 2)))\n",
    "plots.line(\n",
    "    x=1e3 * r,\n",
    "    y={\n",
    "        f\"p = {p / 1e3:.0f} kPa\": temperatures[p].evaluate(line) - 273.15\n",
    "        for p in pressures\n",
    "    },\n",
    "    vlines=[10.0, 13.0],\n",
    "    xlabel=\"radius [mm]\",\n",
    "    ylabel=\"T [°C]\",\n",
    "    title=\"Temperature through the fin at mid-length\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Lower the gas pressure towards vacuum, where only the solid spots conduct and the jump grows by\n",
    "an order of magnitude, or make the fins longer in `package_heat_sink_thermal_contact_geometry.py`\n",
    "to see the contact take a larger share of the total resistance."
   ]
  }
 ]
}
