{
 "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": [
    "# Counterflow MEMS heat exchanger\n",
    "\n",
    "Micro heat exchangers in lab-on-a-chip devices and micro reactors bring two liquids to the same\n",
    "temperature on a few millimetres. Here two channels, 0.3 mm wide and 0.2 mm high, run side by side\n",
    "through a stainless-steel chip, 10 mm long, separated by a 0.1 mm wall. Hot water enters one\n",
    "channel at 80 °C, cold water the other one from the opposite end at 20 °C, both with a mean\n",
    "velocity of 0.1 m/s ($Re\\approx24$).\n",
    "\n",
    "The flows obey the steady Navier-Stokes equations; the heat is conducted through the steel and\n",
    "carried by the water (conjugate heat transfer, constant properties, one-way coupling):\n",
    "\n",
    "$$\\rho c_p\\,\\mathbf u\\cdot\\nabla T=\\nabla\\cdot(k\\nabla T).$$\n",
    "\n",
    "The chip is symmetric about its mid-plane; the lower half comes from the CAD file\n",
    "`mems_counterflow_heat_exchanger.step` (faces named after the bodies `hot`, `cold`, `steel`), the\n",
    "channels from `..._hot.step` and `..._cold.step`. The script\n",
    "`mems_counterflow_heat_exchanger_geometry.py` builds them with the CAD objects of OneSimulation.\n",
    "\n",
    "| face | flow | heat |\n",
    "|---|---|---|\n",
    "| `hot.x_min` / `cold.x_max` | inlet, fully developed, 0.1 m/s | $T=353.15$ K / $293.15$ K |\n",
    "| `hot.x_max` / `cold.x_min` | outlet, traction free | no conduction |\n",
    "| `hot.z_max`, `cold.z_max`, `steel.z_max` (mid-plane) | free slip | no flux |\n",
    "| outer steel faces | — | insulated |\n",
    "\n",
    "**Reference.** Without losses the heat given off by the hot stream equals the heat taken up by\n",
    "the cold one. For two equal heat capacity rates $C$ the effectiveness of a counterflow exchanger is\n",
    "$\\varepsilon=NTU/(1+NTU)$ with $NTU=UA/C$ (Incropera et al., *Fundamentals of Heat and Mass\n",
    "Transfer*, Sec. 11.4); $UA$ is estimated from the fully developed Nusselt number of the channels,\n",
    "$Nu\\approx3.0$, on the whole wetted perimeter of each channel: the well-conducting steel around\n",
    "the channels carries the heat from every wall, so its own resistance is neglected."
   ]
  },
  {
   "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",
    "Each channel has its own hexahedral flow mesh. The heat mesh is laid on the box enclosing the chip\n",
    "(`mems_counterflow_heat_exchanger_envelope.step`) and graded so that cell faces lie on all channel\n",
    "walls; `region_mesh` names its faces after the chip."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "chip = load(\"mems_counterflow_heat_exchanger.step\")\n",
    "channels = {\n",
    "    \"hot\": load(\"mems_counterflow_heat_exchanger_hot.step\"),\n",
    "    \"cold\": load(\"mems_counterflow_heat_exchanger_cold.step\"),\n",
    "}\n",
    "faces = chip.boundaries\n",
    "envelope = load(\"mems_counterflow_heat_exchanger_envelope.step\")\n",
    "length, width, height = chip.size\n",
    "mm = 1e-3\n",
    "flow_meshes = {\n",
    "    name: StructuredHexahedralMesher(\n",
    "        cells=(60, 8, 4),\n",
    "        grading=(\n",
    "            Uniform(60),\n",
    "            TwoSided(8, ratio=2.0),\n",
    "            Geometric(4, ratio=2.0, toward=\"start\"),\n",
    "        ),\n",
    "    ).generate(channel)\n",
    "    for name, channel in channels.items()\n",
    "}\n",
    "heat_mesh = region_mesh(\n",
    "    StructuredHexahedralMesher(\n",
    "        cells=(60, 24, 8),\n",
    "        grading=(\n",
    "            Uniform(60),\n",
    "            Piecewise(\n",
    "                (\n",
    "                    (0.1 * mm, Uniform(2)),\n",
    "                    (0.3 * mm, TwoSided(8, ratio=2.0)),\n",
    "                    (0.1 * mm, Uniform(4)),\n",
    "                    (0.3 * mm, TwoSided(8, ratio=2.0)),\n",
    "                    (0.1 * mm, Uniform(2)),\n",
    "                )\n",
    "            ),\n",
    "            Piecewise(\n",
    "                (\n",
    "                    (0.15 * mm, Uniform(4)),\n",
    "                    (0.1 * mm, Geometric(4, ratio=2.0, toward=\"start\")),\n",
    "                )\n",
    "            ),\n",
    "        ),\n",
    "    ).generate(envelope),\n",
    "    chip,\n",
    "    geometry=chip,\n",
    ")\n",
    "\n",
    "view = plots.Camera(elevation=35, azimuth=-70)\n",
    "fig = plots.figure(1, 2, size=(14, 5.5))\n",
    "plots.geometry(\n",
    "    [\n",
    "        chip.named(\"steel\"),\n",
    "        channels[\"hot\"].named(\"hot channel\"),\n",
    "        channels[\"cold\"].named(\"cold channel\"),\n",
    "    ],\n",
    "    camera=view,\n",
    "    title=\"Lower half of the chip\",\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\n",
    "\n",
    "The two channels are solved one after the other; the cold water enters at the far end."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "water = NewtonianFluid(density=990.0, dynamic_viscosity=0.6e-3)\n",
    "mean_speed = 0.1\n",
    "velocities = {}\n",
    "for name, channel in channels.items():\n",
    "    walls = channel.boundaries\n",
    "    inlet, outlet = (\n",
    "        (walls.x_min, walls.x_max) if name == \"hot\" else (walls.x_max, walls.x_min)\n",
    "    )\n",
    "    flow = IncompressibleNavierStokes(domain=channel.volume, material=water)\n",
    "    velocities[name] = (\n",
    "        Simulation(\n",
    "            problem=Problem(\n",
    "                name=f\"{name} channel\",\n",
    "                geometry=channel,\n",
    "                physics=(flow,),\n",
    "                boundary_conditions=(\n",
    "                    FixedVelocity(\n",
    "                        boundary=inlet,\n",
    "                        physics=flow,\n",
    "                        value=fully_developed_inflow(\n",
    "                            flow_meshes[name],\n",
    "                            inlet,\n",
    "                            mean_velocity=mean_speed,\n",
    "                            no_slip=walls.y_min | walls.y_max | walls.z_min,\n",
    "                        ),\n",
    "                    ),\n",
    "                    FlowTraction(\n",
    "                        boundary=outlet,\n",
    "                        physics=flow,\n",
    "                        value=lambda x, y, z: np.zeros((len(x), 3)),\n",
    "                    ),\n",
    "                    NoSlipWall(\n",
    "                        boundary=walls.y_min | walls.y_max | walls.z_min, physics=flow\n",
    "                    ),\n",
    "                    WallShear(boundary=walls.z_max, physics=flow, law=FreeSlipLaw()),\n",
    "                ),\n",
    "                initial_conditions=(InitialValue(flow.velocity, (0.0, 0.0, 0.0)),),\n",
    "            ),\n",
    "            mesh=flow_meshes[name],\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",
    "The velocity in the chip is the sum of both channel flows, each zero outside its channel (the\n",
    "nearest point of its flow mesh lies on a no-slip wall)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "properties = {\"water\": (990.0, 4180.0, 0.62), \"steel\": (7900.0, 500.0, 16.0)}\n",
    "by_region = lambda index, unit: regionwise(\n",
    "    (\n",
    "        (channels[\"hot\"], properties[\"water\"][index]),\n",
    "        (channels[\"cold\"], properties[\"water\"][index]),\n",
    "    ),\n",
    "    default=properties[\"steel\"][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",
    "hot_in, cold_in = 353.15, 293.15\n",
    "moving = {name: field_function(field) for name, field in velocities.items()}\n",
    "heat = ConvectiveHeatTransfer(\n",
    "    domain=chip.volume,\n",
    "    material=material,\n",
    "    velocity=lambda x, y, z: moving[\"hot\"](x, y, z) + moving[\"cold\"](x, y, z),\n",
    ")\n",
    "temperature = (\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Heat exchanger\",\n",
    "            geometry=chip,\n",
    "            physics=(heat,),\n",
    "            boundary_conditions=(\n",
    "                FixedTemperature(\n",
    "                    boundary=faces[\"hot.x_min\"], physics=heat, value=hot_in\n",
    "                ),\n",
    "                FixedTemperature(\n",
    "                    boundary=faces[\"cold.x_max\"], physics=heat, value=cold_in\n",
    "                ),\n",
    "                HeatFlux(\n",
    "                    boundary=faces.all - faces[\"hot.x_min\"] - faces[\"cold.x_max\"],\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",
    "Bulk temperatures at the outlets from the enthalpy flux, the heat exchanged by each stream and the\n",
    "effectiveness."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "bulk = (\n",
    "    lambda name, x: integrate_plane(\n",
    "        derived_field(\n",
    "            velocities[name],\n",
    "            lambda u, p: u[:, 0] * np.ravel(temperature.evaluate(p)),\n",
    "            name=\"enthalpy_flux\",\n",
    "            unit=\"K*m/s\",\n",
    "        ),\n",
    "        Plane(origin=(x, 0, 0), normal=(1, 0, 0)),\n",
    "    ).value\n",
    "    / integrate_plane(\n",
    "        velocities[name],\n",
    "        Plane(origin=(x, 0, 0), normal=(1, 0, 0)),\n",
    "        normal_component=True,\n",
    "    ).value\n",
    ")\n",
    "hot_out, cold_out = bulk(\"hot\", length - 1e-7), bulk(\"cold\", 1e-7)\n",
    "capacity = (\n",
    "    2\n",
    "    * properties[\"water\"][0]\n",
    "    * properties[\"water\"][1]\n",
    "    * abs(\n",
    "        integrate_plane(\n",
    "            velocities[\"hot\"],\n",
    "            Plane(origin=(length / 2, 0, 0), normal=(1, 0, 0)),\n",
    "            normal_component=True,\n",
    "        ).value\n",
    "    )\n",
    ")\n",
    "given, taken = capacity * (hot_in - hot_out), capacity * (cold_out - cold_in)\n",
    "effectiveness = given / (capacity * (hot_in - cold_in))\n",
    "diameter = 4 * (0.3 * mm * 0.2 * mm) / (2 * (0.3 * mm + 0.2 * mm))\n",
    "h = 3.0 * properties[\"water\"][2] / diameter\n",
    "ua = 1 / (2 / (h * 2 * (0.3 * mm + 0.2 * mm) * length))\n",
    "ntu = ua / capacity\n",
    "print(\n",
    "    f\"hot stream:  in {hot_in - 273.15:.2f} °C, out {hot_out - 273.15:.3f} °C, heat given off {1e3 * given:.3f} mW\"\n",
    ")\n",
    "print(\n",
    "    f\"cold stream: in {cold_in - 273.15:.2f} °C, out {cold_out - 273.15:.3f} °C, heat taken up {1e3 * taken:.3f} mW\"\n",
    ")\n",
    "print(f\"energy balance: (given - taken) / given = {(given - taken) / given:+.2e}\")\n",
    "print(\n",
    "    f\"effectiveness {effectiveness:.4f}; effectiveness-NTU estimate with NTU = {ntu:.3f}: {ntu / (1 + ntu):.4f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The temperature over the mid-plane of the chip, where hot (left inlet) and cold (right inlet)\n",
    "water pass each other, and the bulk temperatures along both channels."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x = np.linspace(1e-6, length - 1e-6, 21)\n",
    "profiles = {name: [bulk(name, xi) for xi in x] for name in channels}\n",
    "fig = plots.figure(layout=[[\"map\"], [\"along\"]], size=(14, 10))\n",
    "plots.surface(\n",
    "    temperature,\n",
    "    boundary=faces[\"steel.z_max\"] | faces[\"hot.z_max\"] | faces[\"cold.z_max\"],\n",
    "    component=lambda T, p: np.ravel(T) - 273.15,\n",
    "    limits=(20, 80),\n",
    "    contours=13,\n",
    "    subdivisions=2,\n",
    "    label=\"T [°C]\",\n",
    "    aspect=4.0,\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    title=\"Temperature on the mid-plane of the chip\",\n",
    "    ax=fig[\"map\"],\n",
    ")\n",
    "plots.line(\n",
    "    1e3 * x,\n",
    "    {\n",
    "        f\"{name} water, bulk\": np.array(values) - 273.15\n",
    "        for name, values in profiles.items()\n",
    "    },\n",
    "    xlabel=\"x along the chip [mm]\",\n",
    "    ylabel=\"bulk temperature [°C]\",\n",
    "    title=\"Counterflow temperature profiles\",\n",
    "    ax=fig[\"along\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Lengthen the chip in `mems_counterflow_heat_exchanger_geometry.py` and watch the effectiveness\n",
    "approach one; replace stainless steel by silicon and see the axial conduction in the chip spoil\n",
    "the counterflow; or run both streams in the same direction for comparison."
   ]
  }
 ]
}
