{
 "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 sink in a forced air flow\n",
    "\n",
    "A component dissipating $Q=1$ W sits under an aluminium heat sink (base 20 x 18 x 3 mm set flush\n",
    "into the floor of an air duct, three fins 2 mm thick and 10 mm high). Air at 20 °C flows through\n",
    "the duct (30 mm wide, 20 mm high) with a mean velocity of 0.1 m/s; the flow is laminar\n",
    "($Re\\approx110$). The air flow obeys the steady Navier-Stokes equations; the heat is conducted\n",
    "through the aluminium and carried by the air,\n",
    "\n",
    "$$\\rho c_p\\,\\mathbf u\\cdot\\nabla T=\\nabla\\cdot(k\\nabla T),$$\n",
    "\n",
    "with constant properties, so the flow drives the heat one way (no buoyancy).\n",
    "\n",
    "Half of the duct (symmetry plane $y=0$) comes from the CAD file `heat_sink_forced_air.step`, the\n",
    "air alone from `heat_sink_forced_air_air.step` and the heat sink from\n",
    "`heat_sink_forced_air_sink.step`; the script `heat_sink_forced_air_geometry.py` builds them with\n",
    "the CAD objects of OneSimulation.\n",
    "\n",
    "| face | flow | heat |\n",
    "|---|---|---|\n",
    "| inlet `x_min` | fully developed duct profile, 0.1 m/s | $T=293.15$ K |\n",
    "| outlet `x_max` | traction free | no conduction |\n",
    "| bottom of the base | — | $Q/2$ over the half base (1 W in total) |\n",
    "| symmetry plane $y=0$ | free slip | no flux |\n",
    "| duct walls, fins | no slip | insulated walls |\n",
    "\n",
    "**Reference.** All heat leaves with the air, so the outlet bulk temperature follows from the\n",
    "energy balance $T_{b,\\mathrm{out}}=T_\\mathrm{in}+Q/(\\dot m c_p)$ (Incropera et al., *Fundamentals of\n",
    "Heat and Mass Transfer*, Sec. 8.3). The thermal resistance $(T_\\mathrm{base}-T_\\mathrm{in})/Q$ is\n",
    "the number a designer reads off."
   ]
  },
  {
   "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 LocalRefinement, TetrahedralMesher\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 air gets a tetrahedral flow mesh, 2 mm around the fins and at the inlet; the heat mesh covers\n",
    "duct and heat sink, with the heat sink embedded so that its surface consists of cell faces."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "duct, air, sink = (\n",
    "    load(\"heat_sink_forced_air.step\"),\n",
    "    load(\"heat_sink_forced_air_air.step\"),\n",
    "    load(\"heat_sink_forced_air_sink.step\"),\n",
    ")\n",
    "faces, walls = duct.boundaries, air.boundaries\n",
    "length, half_width, height = air.size\n",
    "near_sink = lambda points: np.clip(\n",
    "    np.minimum(\n",
    "        0.002\n",
    "        + 0.4 * np.maximum(np.abs(points[:, 0] - 0.03) - 0.012, 0)\n",
    "        + 0.25 * np.maximum(points[:, 2] - 0.012, 0),\n",
    "        0.002 + 0.3 * points[:, 0],\n",
    "    ),\n",
    "    0.002,\n",
    "    0.006,\n",
    ")\n",
    "flow_mesh = TetrahedralMesher(\n",
    "    target_size=0.006, minimum_size=0.001, size_field=near_sink\n",
    ").generate(air)\n",
    "heat_mesh = TetrahedralMesher(\n",
    "    target_size=0.006,\n",
    "    minimum_size=0.001,\n",
    "    embedded_regions=(sink,),\n",
    "    size_field=near_sink,\n",
    ").generate(duct)\n",
    "\n",
    "view = plots.Camera(elevation=30, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    [air.named(\"air\"), sink.named(\"heat sink\")],\n",
    "    camera=view,\n",
    "    title=\"Half of the duct with the heat sink\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    flow_mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Flow mesh: {flow_mesh.cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Flow"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "air_fluid = NewtonianFluid(density=1.204, dynamic_viscosity=1.81e-5)\n",
    "mean_speed = 0.1\n",
    "no_slip = walls.all - walls.x_min - walls.x_max - walls.y_min\n",
    "flow = IncompressibleNavierStokes(domain=air.volume, material=air_fluid)\n",
    "velocity = (\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Duct flow\",\n",
    "            geometry=air,\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=walls.y_max | walls.z_min | walls.z_max,\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=no_slip, 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-12,\n",
    "                relative_tolerance=1e-9,\n",
    "                maximum_iterations=15,\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",
    "Aluminium and air properties are assigned region by region; in the heat sink the velocity of the\n",
    "nearest point of the flow mesh, on a no-slip wall, is zero."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "properties = {\"air\": (1.204, 1006.0, 0.0257), \"aluminium\": (2700.0, 900.0, 200.0)}\n",
    "by_region = lambda index, unit: regionwise(\n",
    "    ((sink, properties[\"aluminium\"][index]),),\n",
    "    default=properties[\"air\"][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",
    "power, inlet = 1.0, 293.15\n",
    "bottom = duct.select(faces=lambda face: face.center[2] < -0.0029)\n",
    "inflow = duct.select(faces=lambda face: face.center[0] < 1e-9 and face.center[2] > 0)\n",
    "heat = ConvectiveHeatTransfer(\n",
    "    domain=duct.volume, material=material, velocity=field_function(velocity)\n",
    ")\n",
    "temperature = (\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Heat sink\",\n",
    "            geometry=duct,\n",
    "            physics=(heat,),\n",
    "            boundary_conditions=(\n",
    "                FixedTemperature(boundary=inflow, physics=heat, value=inlet),\n",
    "                HeatFlux(\n",
    "                    boundary=bottom, physics=heat, value=-power / 2 / (0.020 * 0.009)\n",
    "                ),\n",
    "                HeatFlux(boundary=faces.all - inflow - bottom, physics=heat, value=0.0),\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 outlet bulk temperature from the enthalpy flux against the energy balance, and the\n",
    "temperatures of the heat sink."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "outlet_plane = Plane(origin=(length - 1e-6, 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 + power / 2 / (properties[\"air\"][0] * flow_rate * properties[\"air\"][1])\n",
    "base = temperature.evaluate([[0.03, 0.0045, -0.0029]])[0]\n",
    "tip = temperature.evaluate([[0.03, 0.008, 0.0099]])[0]\n",
    "print(\n",
    "    f\"Reynolds number {air_fluid.density * mean_speed * 4 * (2 * half_width * height) / (2 * (2 * half_width + height)) / air_fluid.dynamic_viscosity:.0f}, \"\n",
    "    f\"air flow {2e3 * flow_rate * 60:.3f} l/min\"\n",
    ")\n",
    "print(\n",
    "    f\"outlet bulk temperature {outlet - 273.15:.3f} °C, energy balance {balance - 273.15:.3f} °C \"\n",
    "    f\"(rise {outlet - inlet:.3f} K against {balance - inlet:.3f} K, {100 * ((outlet - inlet) / (balance - inlet) - 1):+.2f} %)\"\n",
    ")\n",
    "print(\n",
    "    f\"base centre {base - 273.15:.2f} °C, tip of the outer fin {tip - 273.15:.2f} °C; thermal resistance {(base - inlet) / power:.1f} K/W\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The temperature on the symmetry plane and in a cross-section through the fins, and the air speed\n",
    "in a cross-section 5 mm behind the heat sink, where the wakes of the fins are still visible."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "across = Plane(origin=(0.03, 0, 0), normal=(1, 0, 0))\n",
    "fig = plots.figure(layout=[[\"side\", \"side\"], [\"temperature\", \"speed\"]], size=(15, 11))\n",
    "plots.section(\n",
    "    temperature,\n",
    "    plane=Plane(origin=(0, 1e-6, 0), normal=(0, 1, 0)),\n",
    "    component=lambda T, p: np.ravel(T) - 273.15,\n",
    "    contours=12,\n",
    "    subdivisions=2,\n",
    "    label=\"T [°C]\",\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    title=\"Temperature on the symmetry plane\",\n",
    "    ax=fig[\"side\"],\n",
    ")\n",
    "plots.section(\n",
    "    temperature,\n",
    "    plane=across,\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 across the fins\",\n",
    "    ax=fig[\"temperature\"],\n",
    ")\n",
    "plots.section(\n",
    "    velocity,\n",
    "    plane=Plane(origin=(0.045, 0, 0), normal=(1, 0, 0)),\n",
    "    component=lambda u, p: np.linalg.norm(u, axis=1),\n",
    "    contours=10,\n",
    "    subdivisions=2,\n",
    "    symmetry={\"planes\": [((0, 1, 0), (0, 0, 0))]},\n",
    "    label=\"speed [m/s]\",\n",
    "    xlabel=\"y [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    title=\"Air speed 5 mm behind the fins\",\n",
    "    ax=fig[\"speed\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add fins or make them taller in `heat_sink_forced_air_geometry.py` and follow the thermal\n",
    "resistance; raise the air speed; or switch the flow off and add buoyancy for natural convection."
   ]
  }
 ]
}
