{
 "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 model of a microchannel heat sink\n",
    "\n",
    "Microchannel heat sinks (Tuckerman and Pease, *IEEE Electron Device Lett.* 2, 126, 1981) cool\n",
    "chips with very high heat flux. Here parallel channels, 50 µm wide and 300 µm deep, are etched\n",
    "100 µm apart into a silicon block with a 100 µm base and closed by a glass cover; they are 4 mm\n",
    "long. Water enters at 20 °C with a mean velocity of 0.5 m/s, and the chip below delivers a\n",
    "uniform heat flux of $q=100$ W/cm².\n",
    "\n",
    "The flow is laminar ($Re\\approx40$) and obeys the steady Navier-Stokes equations in the channel.\n",
    "The heat is conducted through the silicon and carried by the water,\n",
    "\n",
    "$$\\rho c_p\\,\\mathbf u\\cdot\\nabla T=\\nabla\\cdot(k\\nabla T)\\quad\\text{in water and silicon (}\\mathbf u=0\\text{ there)},$$\n",
    "\n",
    "with continuous temperature and heat flux across the walls (conjugate heat transfer).\n",
    "Properties are constant, so the flow drives the heat one way.\n",
    "\n",
    "One symmetry cell, half a channel and half a fin, comes from the CAD file\n",
    "`microchannel_heat_sink.step`; `microchannel_heat_sink_channel.step` holds the water channel and\n",
    "`microchannel_heat_sink_envelope.step` the box around the cell. The\n",
    "script `microchannel_heat_sink_geometry.py` builds them with the CAD objects of OneSimulation.\n",
    "\n",
    "| face | flow | heat |\n",
    "|---|---|---|\n",
    "| `channel.x_min` | fully developed profile, 0.5 m/s | $T=293.15$ K |\n",
    "| `channel.x_max` | traction free | no conduction |\n",
    "| `solid.z_min` | — | heat flux $q$ |\n",
    "| `channel.y_min`, `solid.y_min`, `solid.y_max` | symmetry (free slip) | no flux |\n",
    "| channel walls, cover, silicon ends | no slip | no flux |\n",
    "\n",
    "**Reference.** All heat leaves with the water, so the outlet bulk temperature is fixed by the\n",
    "energy balance, $T_{b,\\mathrm{out}}=T_\\mathrm{in}+q\\,s\\,L/(\\dot m c_p)$ for the cell width $s$\n",
    "(Incropera et al., *Fundamentals of Heat and Mass Transfer*, Sec. 8.3). The base temperature is\n",
    "estimated with the classical fin model of the channel walls: a heat transfer coefficient\n",
    "$h=Nu\\,k/D_h$ from the fully developed Nusselt number of a rectangular duct of aspect ratio 6\n",
    "heated on three sides, $Nu\\approx5.4$ (Shah and London, 1978), and the fin efficiency\n",
    "$\\eta=\\tanh(mH)/(mH)$, $m=\\sqrt{2h/(k_s w_f)}$."
   ]
  },
  {
   "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, NewtonianFluid\n",
    "from onesim.meshing import (\n",
    "    Geometric,\n",
    "    Piecewise,\n",
    "    StructuredHexahedralMesher,\n",
    "    TwoSided,\n",
    "    Uniform,\n",
    "    region_mesh,\n",
    ")\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, GalerkinAdvection, Lagrange, TaylorHood\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import Newton\n",
    "from onesim.physics.heat_transfer import (\n",
    "    ConvectiveHeatTransfer,\n",
    "    FixedTemperature,\n",
    "    HeatFlux,\n",
    ")\n",
    "from onesim.physics.hydrodynamics import (\n",
    "    FixedVelocity,\n",
    "    FlowTraction,\n",
    "    FreeSlipLaw,\n",
    "    IncompressibleNavierStokes,\n",
    "    NoSlipWall,\n",
    "    WallShear,\n",
    "    fully_developed_inflow,\n",
    ")\n",
    "from onesim.results.derived import derived_field\n",
    "from onesim.results.integration import integrate_plane\n",
    "from onesim.results.sampling import field_function\n",
    "from onesim.simulation import Problem, Simulation, regionwise\n",
    "from onesim.simulation.initial_conditions import InitialValue\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 water channel gets its own hexahedral flow mesh. The heat mesh is laid on the box enclosing\n",
    "the cell (`microchannel_heat_sink_envelope.step`); its grading puts cell faces exactly on the\n",
    "channel walls, and `region_mesh` names its faces after the cell."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "cell, channel = load(\"microchannel_heat_sink.step\"), load(\n",
    "    \"microchannel_heat_sink_channel.step\"\n",
    ")\n",
    "envelope = load(\"microchannel_heat_sink_envelope.step\")\n",
    "faces, walls = cell.boundaries, channel.boundaries\n",
    "length, width, total = cell.size\n",
    "half_channel, depth = channel.size[1], channel.size[2]\n",
    "base = total - depth\n",
    "flow_mesh = StructuredHexahedralMesher(\n",
    "    cells=(40, 5, 16),\n",
    "    grading=(\n",
    "        Uniform(40),\n",
    "        Geometric(5, ratio=2.0, toward=\"end\"),\n",
    "        TwoSided(16, ratio=2.5),\n",
    "    ),\n",
    ").generate(channel)\n",
    "heat_mesh = region_mesh(\n",
    "    StructuredHexahedralMesher(\n",
    "        cells=(40, 10, 22),\n",
    "        grading=(\n",
    "            Uniform(40),\n",
    "            Piecewise(\n",
    "                (\n",
    "                    (half_channel, Geometric(5, ratio=2.0, toward=\"end\")),\n",
    "                    (width - half_channel, Uniform(5)),\n",
    "                )\n",
    "            ),\n",
    "            Piecewise(((base, Uniform(6)), (depth, TwoSided(16, ratio=2.5)))),\n",
    "        ),\n",
    "    ).generate(envelope),\n",
    "    cell,\n",
    "    geometry=cell,\n",
    ")\n",
    "\n",
    "view = plots.Camera(elevation=25, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(14, 5.5))\n",
    "plots.geometry(\n",
    "    [cell.named(\"silicon\"), channel.named(\"water channel\")],\n",
    "    camera=view,\n",
    "    title=\"Symmetry cell of the heat sink\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    heat_mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Heat mesh: {heat_mesh.cell_count} hexahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Flow"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "water = NewtonianFluid(density=998.0, dynamic_viscosity=1.0e-3)\n",
    "mean_speed = 0.5\n",
    "channel_walls = walls.y_max | walls.z_min | walls.z_max\n",
    "flow = IncompressibleNavierStokes(domain=channel.volume, material=water)\n",
    "velocity = (\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Channel flow\",\n",
    "            geometry=channel,\n",
    "            physics=(flow,),\n",
    "            boundary_conditions=(\n",
    "                FixedVelocity(\n",
    "                    boundary=walls.x_min,\n",
    "                    physics=flow,\n",
    "                    value=fully_developed_inflow(\n",
    "                        flow_mesh,\n",
    "                        walls.x_min,\n",
    "                        mean_velocity=mean_speed,\n",
    "                        no_slip=channel_walls,\n",
    "                    ),\n",
    "                ),\n",
    "                FlowTraction(\n",
    "                    boundary=walls.x_max,\n",
    "                    physics=flow,\n",
    "                    value=lambda x, y, z: np.zeros((len(x), 3)),\n",
    "                ),\n",
    "                NoSlipWall(boundary=channel_walls, physics=flow),\n",
    "                WallShear(boundary=walls.y_min, physics=flow, law=FreeSlipLaw()),\n",
    "            ),\n",
    "            initial_conditions=(InitialValue(flow.velocity, (0.0, 0.0, 0.0)),),\n",
    "        ),\n",
    "        mesh=flow_mesh,\n",
    "        numerics=Numerics(\n",
    "            spatial=FiniteElement(element=TaylorHood()),\n",
    "            initial_guess={flow.velocity: (0.0, 0.0, 0.0)},\n",
    "            nonlinear_solver=Newton(\n",
    "                linear_solver=SparseDirect(),\n",
    "                absolute_tolerance=1e-14,\n",
    "                relative_tolerance=1e-10,\n",
    "            ),\n",
    "        ),\n",
    "    )\n",
    "    .solve_stationary()\n",
    "    .field(flow.velocity)\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Conjugate heat transfer\n",
    "\n",
    "Water and silicon properties are assigned region by region. Outside the channel the velocity is\n",
    "that of the nearest point of the flow mesh, which lies on a no-slip wall: zero."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "properties = {\"water\": (998.0, 4182.0, 0.6), \"silicon\": (2330.0, 700.0, 148.0)}\n",
    "by_region = lambda index, unit: regionwise(\n",
    "    ((channel, properties[\"water\"][index]),),\n",
    "    default=properties[\"silicon\"][index],\n",
    "    unit=unit,\n",
    ")\n",
    "material = replace(\n",
    "    IsotropicSolid(\n",
    "        density=1.0,\n",
    "        specific_heat_capacity=1.0,\n",
    "        thermal_conductivity=1.0,\n",
    "        youngs_modulus=1.0,\n",
    "        poisson_ratio=0.3,\n",
    "        thermal_expansion_coefficient=0.0,\n",
    "    ),\n",
    "    density=by_region(0, \"kg/m^3\"),\n",
    "    specific_heat_capacity=by_region(1, \"J/(kg*K)\"),\n",
    "    thermal_conductivity=by_region(2, \"W/(m*K)\"),\n",
    ")\n",
    "inlet, flux = 293.15, 1.0e6\n",
    "heat = ConvectiveHeatTransfer(\n",
    "    domain=cell.volume, material=material, velocity=field_function(velocity)\n",
    ")\n",
    "temperature = (\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Heat sink\",\n",
    "            geometry=cell,\n",
    "            physics=(heat,),\n",
    "            boundary_conditions=(\n",
    "                FixedTemperature(\n",
    "                    boundary=faces[\"channel.x_min\"], physics=heat, value=inlet\n",
    "                ),\n",
    "                HeatFlux(boundary=faces[\"solid.z_min\"], physics=heat, value=-flux),\n",
    "                HeatFlux(\n",
    "                    boundary=faces.all - faces[\"channel.x_min\"] - faces[\"solid.z_min\"],\n",
    "                    physics=heat,\n",
    "                    value=0.0,\n",
    "                ),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=heat_mesh,\n",
    "        numerics=Numerics(\n",
    "            spatial=FiniteElement(\n",
    "                element=Lagrange(order=2), convection=GalerkinAdvection()\n",
    "            ),\n",
    "            linear_solver=SparseDirect(),\n",
    "        ),\n",
    "    )\n",
    "    .solve_stationary()\n",
    "    .field(heat.temperature)\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The bulk temperature at the outlet from the enthalpy flux, the energy balance, and the\n",
    "temperatures of the heated base. Part of the heat is conducted upstream through the silicon and\n",
    "leaves through the inlet face, where the water temperature is held; the `reaction` of the inlet\n",
    "temperature measures it, and with it the balance closes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "outlet_plane = Plane(origin=(length - 1e-7, 0, 0), normal=(1, 0, 0))\n",
    "carried = derived_field(\n",
    "    velocity,\n",
    "    lambda u, points: u[:, 0] * np.ravel(temperature.evaluate(points)),\n",
    "    name=\"enthalpy_flux\",\n",
    "    unit=\"K*m/s\",\n",
    ")\n",
    "flow_rate = integrate_plane(velocity, outlet_plane, normal_component=True).value\n",
    "outlet = integrate_plane(carried, outlet_plane).value / flow_rate\n",
    "balance = inlet + flux * width * length / (\n",
    "    properties[\"water\"][0] * flow_rate * properties[\"water\"][1]\n",
    ")\n",
    "x = np.linspace(0.0, length, 81)\n",
    "bottom = temperature.evaluate(\n",
    "    np.column_stack((x, np.full_like(x, width / 2), np.full_like(x, 1e-7)))\n",
    ")\n",
    "diameter = 4 * (2 * half_channel * depth) / (2 * (2 * half_channel + depth))\n",
    "h = 5.4 * properties[\"water\"][2] / diameter\n",
    "m = np.sqrt(2 * h / (properties[\"silicon\"][2] * 2 * (width - half_channel)))\n",
    "efficiency = np.tanh(m * depth) / (m * depth)\n",
    "resistance = (\n",
    "    2 * width / (h * (2 * half_channel + 2 * efficiency * depth))\n",
    "    + base / properties[\"silicon\"][2]\n",
    ")\n",
    "print(\n",
    "    f\"Reynolds number {water.density * mean_speed * diameter / water.dynamic_viscosity:.1f}, flow rate per cell {1e9 * flow_rate:.4f} µl/s\"\n",
    ")\n",
    "print(\n",
    "    f\"outlet bulk temperature {outlet - 273.15:.3f} °C, energy balance {balance - 273.15:.3f} °C (rise {outlet - inlet:.3f} K against \"\n",
    "    f\"{balance - inlet:.3f} K, {100 * ((outlet - inlet) / (balance - inlet) - 1):+.2f} %)\"\n",
    ")\n",
    "heat_in = flux * width * length\n",
    "carried_away = (\n",
    "    properties[\"water\"][0] * properties[\"water\"][1] * flow_rate * (outlet - inlet)\n",
    ")\n",
    "conducted = abs(temperature.reaction(faces[\"channel.x_min\"]))\n",
    "print(\n",
    "    f\"heat from the chip {1e3 * heat_in:.3f} mW = carried off by the water {1e3 * carried_away:.3f} mW + conducted out through the \"\n",
    "    f\"fixed-temperature inlet {1e3 * conducted:.3f} mW; balance {100 * ((carried_away + conducted) / heat_in - 1):+.2f} %\"\n",
    ")\n",
    "print(\n",
    "    f\"base temperature: inlet end {bottom[0] - 273.15:.2f} °C, outlet end {bottom[-1] - 273.15:.2f} °C, highest {bottom.max() - 273.15:.2f} °C\"\n",
    ")\n",
    "print(\n",
    "    f\"fin model at the outlet: base {balance + flux * resistance - 273.15:.2f} °C with h = {h / 1e3:.1f} kW/(m² K) and fin efficiency \"\n",
    "    f\"{efficiency:.3f}; simulation {bottom[-1] - 273.15:.2f} °C\"\n",
    ")\n",
    "print(\n",
    "    f\"thermal resistance (highest base temperature - inlet) / q = {1e4 * (bottom.max() - inlet) / flux:.4f} K cm²/W\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The temperature over the cross-section at the outlet, mirrored to two channels, the velocity\n",
    "there, and the temperatures along the heat sink."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(\n",
    "    layout=[[\"temperature\", \"velocity\"], [\"along\", \"along\"]], size=(15, 11)\n",
    ")\n",
    "plots.section(\n",
    "    temperature,\n",
    "    plane=outlet_plane,\n",
    "    component=lambda T, p: np.ravel(T) - 273.15,\n",
    "    contours=12,\n",
    "    subdivisions=2,\n",
    "    symmetry={\"planes\": [((0, 1, 0), (0, 0, 0))]},\n",
    "    label=\"T [°C]\",\n",
    "    xlabel=\"y [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    title=\"Temperature at the outlet\",\n",
    "    ax=fig[\"temperature\"],\n",
    ")\n",
    "plots.section(\n",
    "    velocity,\n",
    "    plane=outlet_plane,\n",
    "    component=lambda u, p: u[:, 0],\n",
    "    contours=10,\n",
    "    subdivisions=2,\n",
    "    symmetry={\"planes\": [((0, 1, 0), (0, 0, 0))]},\n",
    "    label=\"u [m/s]\",\n",
    "    xlabel=\"y [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    title=\"Velocity at the outlet\",\n",
    "    ax=fig[\"velocity\"],\n",
    ")\n",
    "plots.line(\n",
    "    1e3 * x,\n",
    "    {\"heated base\": bottom - 273.15},\n",
    "    reference={\n",
    "        \"bulk water, energy balance\": (\n",
    "            1e3 * x,\n",
    "            inlet - 273.15 + (balance - inlet) * x / length,\n",
    "        )\n",
    "    },\n",
    "    points={\"bulk water at the outlet\": ([1e3 * length], [outlet - 273.15])},\n",
    "    xlabel=\"distance from the inlet [mm]\",\n",
    "    ylabel=\"temperature [°C]\",\n",
    "    title=\"Temperatures along the heat sink\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[\"along\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the channels narrower and deeper in `microchannel_heat_sink_geometry.py`, the classical\n",
    "optimisation of the fin aspect ratio; raise the flow and watch the outlet temperature fall while\n",
    "the pressure drop grows; or let the water viscosity fall with temperature and couple both ways."
   ]
  }
 ]
}
