{
 "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": [
    "# Free-convection cooling of vertical circuit boards\n",
    "\n",
    "Two vertical circuit boards (1.6 mm thick, 100 mm high) stand 10 mm apart in a rack. The left\n",
    "board carries three chips (2 mm thick, 12 mm high) on the side facing the channel; each chip\n",
    "produces 3 W per metre of board depth inside its volume. Without a fan the air (25 °C) is driven by\n",
    "buoyancy alone. The steady Boussinesq equations hold in the air,\n",
    "\n",
    "$$\\rho(\\mathbf u\\cdot\\nabla)\\mathbf u=-\\nabla p+\\mu\\nabla^2\\mathbf u-\\rho\\beta(T-T_0)\\mathbf g,\n",
    "  \\qquad \\nabla\\cdot\\mathbf u=0,$$\n",
    "\n",
    "and one heat balance $\\rho c_p\\,\\mathbf u\\cdot\\nabla T=\\nabla\\cdot(k\\nabla T)+\\dot q$ holds everywhere,\n",
    "with $\\mathbf u=0$ in the solids and the chip heat $\\dot q$ in the chips. Air at 25 °C:\n",
    "$\\rho=1.184$ kg/m³, $\\mu=1.849\\cdot10^{-5}$ Pa s, $k=0.02551$ W/(m K), $c_p=1007$ J/(kg K),\n",
    "$\\beta=1/T_0$; boards of glass-fibre epoxy, $k=0.3$ W/(m K); chip packages $k=1$ W/(m K). The\n",
    "heat spreads from the chips into the board and leaves through all faces in the air. The outer\n",
    "faces of the boards face neighbouring channels of the same rack and take up no heat. The model\n",
    "includes 20 mm of air below and 30 mm above the boards, so that the air enters and leaves the\n",
    "channel freely.\n",
    "\n",
    "The geometry comes from the CAD files `vertical_circuit_boards_free_convection*.step`, written by\n",
    "`vertical_circuit_boards_free_convection_geometry.py` with the CAD objects of OneSimulation: the\n",
    "whole channel (domain of the heat transport), the air (domain of the flow, with the faces of every\n",
    "board and chip named after them), and the boards and chips as parts of their own.\n",
    "\n",
    "| boundary | flow | heat |\n",
    "|---|---|---|\n",
    "| `inlet` (bottom) | open, no traction | $T=25$ °C |\n",
    "| `outlet` (top) | open, no traction (backflow damped) | no conduction |\n",
    "| `sides` | free slip | no flux |\n",
    "| board and chip faces in the air | no slip | continuous temperature and heat flux |\n",
    "| outer board faces | – | no flux |\n",
    "\n",
    "**Reference.** In the steady state the 9 W/m of the chips leave with the air: the enthalpy flow\n",
    "through the top plus the heat conducted back through the inlet. For a vertical channel with one\n",
    "wall heated at a uniform flux $q''$ and the other insulated, Bar-Cohen and Rohsenow give the wall\n",
    "temperature at the channel exit (F. P. Incropera et al., *Fundamentals of Heat and Mass Transfer*,\n",
    "Eq. 9.46 and Table 9.3),\n",
    "\n",
    "$$Nu_{S,L}=\\frac{q''S}{k\\,(T_{s,L}-T_0)}=\\left[\\frac{48}{Ra_S^*S/L}+\\frac{2.51}{(Ra_S^*S/L)^{2/5}}\\right]^{-1/2},\n",
    "  \\qquad Ra_S^*=\\frac{g\\beta q''S^4}{k\\alpha\\nu},$$\n",
    "\n",
    "with the gap $S$, the board height $L$ and the mean flux $q''=9\\,\\mathrm{W/m}/L$. The conducting\n",
    "board spreads the chip heat along its height, much closer to the uniform flux of the correlation\n",
    "than chips on an insulating board."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import ThermalFluid, regionwise\n",
    "from onesim.meshing import TriangularMesher, region_mesh\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.coupled_systems import MonolithicStationaryCoupling\n",
    "from onesim.numerics.fem import FiniteElement, GalerkinAdvection, Lagrange, TaylorHood\n",
    "from onesim.numerics.field_transfer import FieldInterpolation\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import Newton\n",
    "from onesim.physics.heat_transfer import (\n",
    "    BoussinesqBuoyancy,\n",
    "    ConvectiveHeatTransfer,\n",
    "    FixedTemperature,\n",
    "    HeatFlux,\n",
    ")\n",
    "from onesim.physics.hydrodynamics import (\n",
    "    BackflowTraction,\n",
    "    FreeSlipLaw,\n",
    "    IncompressibleNavierStokes,\n",
    "    NoSlipWall,\n",
    "    OpenBoundaryTraction,\n",
    "    WallShear,\n",
    ")\n",
    "from onesim.results.derived import derived_field\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.field_connections import FieldCoupling\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 meshes\n",
    "\n",
    "Every part is cut at half depth. The whole channel is meshed with boards and chips as embedded\n",
    "regions, so that the triangles follow every interface (0.7 mm in boards and chips, growing to\n",
    "3.5 mm in the open air; a second mesh is coarser by a factor 1.4). `region_mesh` takes the air\n",
    "cells out of it for the flow, with the face names of the air part."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "slug = \"vertical_circuit_boards_free_convection\"\n",
    "names = (\"air\", \"board_left\", \"board_right\", \"chip_1\", \"chip_2\", \"chip_3\")\n",
    "cut = lambda part: part.section((0, 0, 1), origin=(0, 0, part.size[2] / 2))\n",
    "channel = cut(load(f\"{slug}.step\"))\n",
    "regions = {name: cut(load(f\"{slug}_{name}.step\")).named(name) for name in names}\n",
    "air, faces = regions[\"air\"], channel.boundaries\n",
    "meshes = [\n",
    "    TriangularMesher(\n",
    "        target_size=2.5e-3 * scale,\n",
    "        embedded_regions=tuple(regions[name] for name in names[1:]),\n",
    "        grading=0.25,\n",
    "        region_sizes={name: 5e-4 * scale for name in names[1:]},\n",
    "    ).generate(channel)\n",
    "    for scale in (2.0, 1.4)\n",
    "]\n",
    "air_meshes = [region_mesh(mesh, air) for mesh in meshes]\n",
    "\n",
    "fig = plots.figure(1, 2, size=(12, 8))\n",
    "plots.geometry(\n",
    "    [load(f\"{slug}_{name}.step\").named(name) for name in names],\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=60, azimuth=-75),\n",
    "    title=\"Air channel, boards and chips\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[-1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Finer mesh: {meshes[-1].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The flow (Taylor-Hood elements) lives on the air, the heat transport (quadratic elements) on the\n",
    "whole channel, with region-wise conductivity and the chip heat as region-wise source.\n",
    "`BoussinesqBuoyancy` turns the temperature into the body force of the air; the air velocity\n",
    "carries the heat, and `FieldInterpolation(outside=0.0)` makes it zero in boards and chips, where\n",
    "the heat model meets no air. `MonolithicStationaryCoupling` solves flow and heat together with one\n",
    "Newton method whose Jacobian holds both coupling blocks; it starts from one sweep of the two\n",
    "solvers with the heat carried by an assumed uniform updraught of 5 cm/s. Inlet and outlet are\n",
    "open boundaries; `BackflowTraction` controls the energy of any air re-entering through them."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "ambient, gravity, power = 298.15, 9.81, 3.0\n",
    "chip_area = 2e-3 * 12e-3\n",
    "properties = dict(\n",
    "    density=1.184,\n",
    "    dynamic_viscosity=1.849e-5,\n",
    "    specific_heat_capacity=1007.0,\n",
    "    thermal_expansion_coefficient=1 / ambient,\n",
    ")\n",
    "air_properties = ThermalFluid(thermal_conductivity=0.02551, **properties)\n",
    "channel_properties = ThermalFluid(\n",
    "    thermal_conductivity=regionwise(\n",
    "        tuple((regions[name], 0.3) for name in (\"board_left\", \"board_right\"))\n",
    "        + tuple((regions[f\"chip_{index}\"], 1.0) for index in (1, 2, 3)),\n",
    "        default=0.02551,\n",
    "        unit=\"W/m/K\",\n",
    "    ),\n",
    "    **properties,\n",
    ")\n",
    "flow = IncompressibleNavierStokes(domain=air.domain(), material=air_properties)\n",
    "heat = ConvectiveHeatTransfer(\n",
    "    domain=channel.domain(),\n",
    "    material=channel_properties,\n",
    "    velocity=None,\n",
    "    heating=regionwise(\n",
    "        tuple((regions[f\"chip_{index}\"], power / chip_area) for index in (1, 2, 3)),\n",
    "        default=0.0,\n",
    "        unit=\"W/m^3\",\n",
    "    ),\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Vertical circuit boards\",\n",
    "    geometry=channel,\n",
    "    additional_geometries=(air,),\n",
    "    physics=(flow, heat),\n",
    "    boundary_conditions=(\n",
    "        OpenBoundaryTraction(\n",
    "            physics=flow,\n",
    "            boundary=air.boundaries.inlet | air.boundaries.outlet,\n",
    "            value=0.0,\n",
    "            law=BackflowTraction(),\n",
    "        ),\n",
    "        WallShear(physics=flow, boundary=air.boundaries.sides, law=FreeSlipLaw()),\n",
    "        NoSlipWall(physics=flow, boundary=air.boundaries.solids),\n",
    "        FixedTemperature(physics=heat, boundary=faces.inlet, value=ambient),\n",
    "        HeatFlux(physics=heat, boundary=faces.outlet | faces.sides, value=0.0),\n",
    "    ),\n",
    "    initial_conditions=(\n",
    "        InitialValue(heat.temperature, ambient),\n",
    "        InitialValue(flow.velocity, (0.0, 0.05)),\n",
    "    ),\n",
    "    couplings=(\n",
    "        FieldCoupling(\n",
    "            source=heat.temperature,\n",
    "            target=flow.field(\"body_force\"),\n",
    "            transfer=BoussinesqBuoyancy(\n",
    "                gravity=(0, -gravity), reference_temperature=ambient\n",
    "            ),\n",
    "        ),\n",
    "        FieldCoupling(\n",
    "            source=flow.velocity,\n",
    "            target=heat.advecting_velocity,\n",
    "            transfer=FieldInterpolation(outside=0.0),\n",
    "        ),\n",
    "    ),\n",
    ")\n",
    "numerics = {\n",
    "    flow: Numerics(\n",
    "        spatial=FiniteElement(element=TaylorHood()),\n",
    "        initial_guess={flow.velocity: (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=50,\n",
    "        ),\n",
    "    ),\n",
    "    heat: Numerics(\n",
    "        spatial=FiniteElement(\n",
    "            element=Lagrange(order=2), convection=GalerkinAdvection()\n",
    "        ),\n",
    "        linear_solver=SparseDirect(),\n",
    "    ),\n",
    "}\n",
    "results = [\n",
    "    Simulation(\n",
    "        problem=problem,\n",
    "        mesh={flow: air_mesh, heat: mesh},\n",
    "        numerics=numerics,\n",
    "        coupling_solver=MonolithicStationaryCoupling(\n",
    "            stationary_systems=(heat, flow),\n",
    "            nonlinear_solver=Newton(\n",
    "                linear_solver=SparseDirect(),\n",
    "                relative_tolerance=1e-8,\n",
    "                absolute_tolerance=1e-12,\n",
    "                maximum_iterations=30,\n",
    "            ),\n",
    "        ),\n",
    "    ).solve_stationary()\n",
    "    for air_mesh, mesh in zip(air_meshes, meshes)\n",
    "]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Heat balance and temperatures\n",
    "\n",
    "`derived_field` forms the enthalpy flux $\\rho c_p v\\,(T-T_0)$ of the air, integrated over the\n",
    "outlet; a chip temperature is the largest value in the chip, the board temperature is read along\n",
    "its face towards the channel."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "gap, height = 10e-3, 0.1\n",
    "nu, alpha = (\n",
    "    air_properties.dynamic_viscosity / air_properties.density,\n",
    "    air_properties.thermal_conductivity\n",
    "    / (air_properties.density * air_properties.specific_heat_capacity),\n",
    ")\n",
    "flux = 3 * power / height\n",
    "rayleigh = (\n",
    "    gravity\n",
    "    * air_properties.thermal_expansion_coefficient\n",
    "    * flux\n",
    "    * gap**4\n",
    "    / (air_properties.thermal_conductivity * alpha * nu)\n",
    "    * gap\n",
    "    / height\n",
    ")\n",
    "exit_rise = (\n",
    "    flux\n",
    "    * gap\n",
    "    / air_properties.thermal_conductivity\n",
    "    * np.sqrt(48 / rayleigh + 2.51 / rayleigh**0.4)\n",
    ")\n",
    "hottest = []\n",
    "for name, mesh, result in zip((\"coarser\", \"finer\"), meshes, results):\n",
    "    temperature, velocity = result.field(heat.temperature), result.field(flow.velocity)\n",
    "    enthalpy = derived_field(\n",
    "        velocity,\n",
    "        lambda u, points, T=temperature: air_properties.density\n",
    "        * air_properties.specific_heat_capacity\n",
    "        * u[:, 1]\n",
    "        * (np.ravel(T.evaluate(points)) - ambient),\n",
    "        name=\"enthalpy_flux\",\n",
    "        unit=\"W/m^2\",\n",
    "    )\n",
    "    carried, back = enthalpy.integrate(\n",
    "        boundary=air.boundaries.outlet\n",
    "    ).value, temperature.boundary_flux(faces.inlet)\n",
    "    inflow = velocity.integrate(\n",
    "        boundary=air.boundaries.inlet, normal_component=True\n",
    "    ).value\n",
    "    hottest.append(\n",
    "        [\n",
    "            temperature.evaluate(\n",
    "                np.array(\n",
    "                    [\n",
    "                        [x, y]\n",
    "                        for x in np.linspace(box[0][0], box[1][0], 9)\n",
    "                        for y in np.linspace(box[0][1], box[1][1], 25)\n",
    "                    ]\n",
    "                )\n",
    "            ).max()\n",
    "            - 273.15\n",
    "            for box in (regions[f\"chip_{index}\"].bounding_box for index in (1, 2, 3))\n",
    "        ]\n",
    "    )\n",
    "    steps = result.result_set.solver_report[\"coupling\"][\"continuation\"][-1][\n",
    "        \"iterations\"\n",
    "    ]\n",
    "    print(f\"{name} mesh ({mesh.cell_count} triangles, {steps} Newton steps)\")\n",
    "    print(\n",
    "        f\"  chip power {3 * power:.3f} W/m; enthalpy through the outlet {carried:.4f} W/m, conducted back through the inlet \"\n",
    "        f\"{back:.4f} W/m; balance {100 * (carried + back - 3 * power) / (3 * power):+.3f} %\"\n",
    "    )\n",
    "    print(\n",
    "        f\"  air drawn through the channel {-1e3 * inflow:.4f} l/(s m), mean speed in the gap {-1e3 * inflow / gap:.1f} mm/s, mixed outlet \"\n",
    "        f\"temperature rise {3 * power / (air_properties.density * air_properties.specific_heat_capacity * -inflow):.2f} K\"\n",
    "    )\n",
    "    print(\n",
    "        \"  chip temperatures (bottom to top): \"\n",
    "        + \", \".join(f\"{value:.2f} °C\" for value in hottest[-1])\n",
    "    )\n",
    "print(\n",
    "    f\"\\nRa*_S S/L = {rayleigh:.1f}; channel correlation: wall {exit_rise:.2f} K above ambient at the channel exit\"\n",
    ")\n",
    "print(\n",
    "    f\"top chip {hottest[-1][-1] - 25:.2f} K above ambient ({100 * ((hottest[-1][-1] - 25) / exit_rise - 1):+.1f} % from the correlation); \"\n",
    "    f\"change from the coarser mesh {hottest[-1][-1] - hottest[0][-1]:+.3f} K\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Temperature in air, boards and chips (the heat spreads up and down the left board) and speed of\n",
    "the air, and the temperature along the channel faces of the left board (with its chips) and of the\n",
    "right board."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "temperature, velocity = results[-1].field(heat.temperature), results[-1].field(\n",
    "    flow.velocity\n",
    ")\n",
    "(bx0, by0, _), (bx1, by1, _) = regions[\"board_left\"].bounding_box\n",
    "right_face = regions[\"board_right\"].bounding_box[0][0]\n",
    "along = np.linspace(by0, by1, 500)\n",
    "fig = plots.figure(\n",
    "    layout=[[\"temperature\", \"speed\", \"profiles\", \"profiles\"]], size=(15, 9)\n",
    ")\n",
    "plots.surface(\n",
    "    temperature,\n",
    "    component=lambda T, position: T - 273.15,\n",
    "    limits=(25.0, np.ceil(max(hottest[-1]))),\n",
    "    contours=12,\n",
    "    subdivisions=2,\n",
    "    label=\"T [°C]\",\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    title=\"Temperature\",\n",
    "    ax=fig[\"temperature\"],\n",
    ")\n",
    "plots.surface(\n",
    "    velocity,\n",
    "    component=lambda u, position: 1e3 * np.linalg.norm(u, axis=1),\n",
    "    contours=8,\n",
    "    subdivisions=2,\n",
    "    label=\"speed [mm/s]\",\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    title=\"Speed of the air\",\n",
    "    ax=fig[\"speed\"],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        \"left board, channel face\": (\n",
    "            temperature.evaluate(\n",
    "                np.column_stack((np.full_like(along, bx1 - 1e-7), along))\n",
    "            ).ravel()\n",
    "            - 273.15,\n",
    "            1e3 * (along - by0),\n",
    "        ),\n",
    "        \"right board, channel face\": (\n",
    "            temperature.evaluate(\n",
    "                np.column_stack((np.full_like(along, right_face + 1e-7), along))\n",
    "            ).ravel()\n",
    "            - 273.15,\n",
    "            1e3 * (along - by0),\n",
    "        ),\n",
    "    },\n",
    "    points={\"correlation, channel exit\": ([25.0 + exit_rise], [1e3 * (by1 - by0)])},\n",
    "    vlines={\"ambient\": 25.0},\n",
    "    xlabel=\"temperature [°C]\",\n",
    "    ylabel=\"height along the board [mm]\",\n",
    "    title=\"Temperature of the board faces towards the channel\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[\"profiles\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the board spacing in `vertical_circuit_boards_free_convection_geometry.py` and look for\n",
    "the spacing with the coolest chips (too narrow chokes the flow, too wide wastes rack space); move\n",
    "the hottest chip to the bottom of the board; or impose an inflow at the inlet, as a fan would, to\n",
    "compare free and forced cooling; or give the boards a copper layer (a larger conductivity) and watch the chips cool down."
   ]
  }
 ]
}
