{
 "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 heat exchanger\n",
    "\n",
    "Two water streams flow in opposite directions through parallel channels (1 mm gap, 2 mm wide,\n",
    "45 mm long) separated by a 1.2 mm polypropylene wall. Heat crosses the wall from the hot to the\n",
    "cold stream; the outer faces are insulated. Each channel obeys\n",
    "\n",
    "$$\\rho c_p\\,\\mathbf u\\cdot\\nabla T=k\\,\\nabla^2 T ,$$\n",
    "\n",
    "and exchanges the heat flux $h_w\\,(T_h-T_c)$ with the other one through the wall conductance\n",
    "$h_w=k_w/t_w$.\n",
    "\n",
    "Both streams use the channel from the CAD file `counterflow_heat_exchanger_ntu.step` with the\n",
    "faces `x_min` and `x_max` (the two ends), `y_min` and `y_max` (across the gap) and the group\n",
    "`ends` across the width. The script `counterflow_heat_exchanger_ntu_geometry.py` builds it with\n",
    "the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference.** With the capacity rates $C=\\rho c_p u\\,t\\,w$ of the two streams,\n",
    "$C_r=C_\\min/C_\\max$ and $\\mathrm{NTU}=UA/C_\\min$, the effectiveness of a counterflow exchanger is\n",
    "\n",
    "$$\\varepsilon=\\frac{1-e^{-\\mathrm{NTU}(1-C_r)}}{1-C_r\\,e^{-\\mathrm{NTU}(1-C_r)}} ,$$\n",
    "\n",
    "and the temperature difference between the streams decays as $e^{-mx}$ with\n",
    "$m=Uw\\,(1/C_h-1/C_c)$. The overall coefficient combines the wall with the two fluid films,\n",
    "$1/U=t_w/k_w+2t/(3k_f)$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import StructuredHexahedralMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, GalerkinAdvection, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.heat_transfer import (\n",
    "    ConvectiveHeatFlux,\n",
    "    ConvectiveHeatTransfer,\n",
    "    FixedTemperature,\n",
    "    HeatFlux,\n",
    ")\n",
    "from onesim.results.integration import mean_value\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",
    "One quadratic element across the gap and 80 along the flow."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "duct = load(\"counterflow_heat_exchanger_ntu.step\")\n",
    "faces = duct.boundaries\n",
    "length, gap, width = duct.size\n",
    "mesh = StructuredHexahedralMesher(cells=(80, 1, 1)).generate(duct)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 4.5))\n",
    "plots.geometry(\n",
    "    duct,\n",
    "    selection={\"wall to the cold stream\": faces.y_max, \"hot inlet\": faces.x_min},\n",
    "    labels=False,\n",
    "    title=\"Channel of the hot stream\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh, groups=(\"all\",), legend=False, title=f\"{mesh.cell_count} hexahedra\", ax=fig[1]\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`solve` computes one stream for a given wall temperature of the other stream. The two streams are\n",
    "solved in turn until the temperatures settle."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "water = IsotropicSolid(\n",
    "    density=1000.0,\n",
    "    specific_heat_capacity=4180.0,\n",
    "    thermal_conductivity=0.6,\n",
    "    youngs_modulus=2e9,\n",
    "    poisson_ratio=0.3,\n",
    "    thermal_expansion_coefficient=1e-5,\n",
    ")\n",
    "wall_conductance = 0.12 / 1.2e-3\n",
    "hot_inlet, cold_inlet, ntu, capacity_ratio = 350.0, 290.0, 1.5, 0.6\n",
    "overall = 1 / (1 / wall_conductance + 2 * gap / (3 * water.thermal_conductivity))\n",
    "hot_capacity = overall * length * width / ntu\n",
    "cold_capacity = hot_capacity / capacity_ratio\n",
    "speed = lambda capacity: capacity / (\n",
    "    water.density * water.specific_heat_capacity * gap * width\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2), convection=GalerkinAdvection()),\n",
    "    linear_solver=SparseDirect(),\n",
    ")\n",
    "\n",
    "\n",
    "def solve(velocity, inlet, outlet, wall, outer, inlet_temperature, other_stream):\n",
    "    \"\"\"Temperature of one stream; `other_stream(x)` is the wall temperature of the other one.\"\"\"\n",
    "    model = ConvectiveHeatTransfer(\n",
    "        domain=duct.volume, material=water, velocity=(velocity, 0.0, 0.0)\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"Exchanger channel\",\n",
    "        geometry=duct,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            FixedTemperature(boundary=inlet, physics=model, value=inlet_temperature),\n",
    "            HeatFlux(boundary=outlet | outer | faces.ends, physics=model, value=0.0),\n",
    "            ConvectiveHeatFlux(\n",
    "                boundary=wall,\n",
    "                physics=model,\n",
    "                heat_transfer_coefficient=wall_conductance,\n",
    "                ambient_temperature=other_stream,\n",
    "            ),\n",
    "        ),\n",
    "    )\n",
    "    return (\n",
    "        Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "        .solve_stationary()\n",
    "        .field(model.temperature)\n",
    "    )\n",
    "\n",
    "\n",
    "def at_wall(field, y):\n",
    "    \"\"\"Temperature of a stream on its wall face as a function of x.\"\"\"\n",
    "    return lambda x: field.evaluate(\n",
    "        np.column_stack(\n",
    "            (np.ravel(x), np.full(np.size(x), y), np.full(np.size(x), width / 2))\n",
    "        )\n",
    "    ).reshape(np.shape(x))\n",
    "\n",
    "\n",
    "cold_wall = lambda x: cold_inlet + 0.0 * np.asarray(x)\n",
    "for sweep in range(12):\n",
    "    hot = solve(\n",
    "        speed(hot_capacity),\n",
    "        faces.x_min,\n",
    "        faces.x_max,\n",
    "        faces.y_max,\n",
    "        faces.y_min,\n",
    "        hot_inlet,\n",
    "        cold_wall,\n",
    "    )\n",
    "    cold = solve(\n",
    "        -speed(cold_capacity),\n",
    "        faces.x_max,\n",
    "        faces.x_min,\n",
    "        faces.y_min,\n",
    "        faces.y_max,\n",
    "        cold_inlet,\n",
    "        at_wall(hot, gap),\n",
    "    )\n",
    "    cold_wall = at_wall(cold, 0.0)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The bulk temperature of each stream is its mean over the channel cross-section. The\n",
    "effectiveness-NTU solution gives the heat flow, the decay rate $m$ and from them both bulk\n",
    "temperatures along the exchanger."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x = length * np.linspace(1e-6, 1 - 1e-6, 31)\n",
    "hot_bulk, cold_bulk = (\n",
    "    np.array(\n",
    "        [\n",
    "            mean_value(field, plane=Plane(origin=(position, 0, 0), normal=(1, 0, 0)))\n",
    "            for position in x\n",
    "        ]\n",
    "    )\n",
    "    for field in (hot, cold)\n",
    ")\n",
    "decay = np.exp(-ntu * (1 - capacity_ratio))\n",
    "effectiveness = (1 - decay) / (1 - capacity_ratio * decay)\n",
    "m = overall * width * (1 / hot_capacity - 1 / cold_capacity)\n",
    "difference = (\n",
    "    hot_inlet\n",
    "    - cold_inlet\n",
    "    - effectiveness * hot_capacity / cold_capacity * (hot_inlet - cold_inlet)\n",
    ")\n",
    "hot_exact = (\n",
    "    hot_inlet - overall * width / hot_capacity * difference * (1 - np.exp(-m * x)) / m\n",
    ")\n",
    "cold_exact = hot_exact - difference * np.exp(-m * x)\n",
    "power = hot_capacity * (hot_inlet - hot_bulk[-1])\n",
    "\n",
    "print(\n",
    "    f\"hot outlet    simulation {hot_bulk[-1]:.2f} K   effectiveness-NTU {hot_exact[-1]:.2f} K\"\n",
    ")\n",
    "print(\n",
    "    f\"cold outlet   simulation {cold_bulk[0]:.2f} K   effectiveness-NTU {cold_exact[0]:.2f} K\"\n",
    ")\n",
    "print(\n",
    "    f\"effectiveness simulation {power / (hot_capacity * (hot_inlet - cold_inlet)):.4f}     effectiveness-NTU {effectiveness:.4f}\"\n",
    ")\n",
    "print(\n",
    "    f\"heat given off by the hot stream {power:.4f} W, taken up by the cold stream \"\n",
    "    f\"{cold_capacity * (cold_bulk[0] - cold_inlet):.4f} W\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plots.line(\n",
    "    1e3 * x,\n",
    "    points={\n",
    "        \"hot stream (flows to the right)\": hot_bulk,\n",
    "        \"cold stream (flows to the left)\": cold_bulk,\n",
    "    },\n",
    "    reference={\n",
    "        \"hot stream (flows to the right)\": hot_exact,\n",
    "        \"cold stream (flows to the left)\": cold_exact,\n",
    "    },\n",
    "    xlabel=\"position along the exchanger [mm]\",\n",
    "    ylabel=\"bulk temperature [K]\",\n",
    "    legend=\"upper right\",\n",
    "    title=\"Counterflow heat exchanger: simulation (markers) and effectiveness-NTU (dashed)\",\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the two capacity rates equal: the temperature difference is then uniform and both profiles\n",
    "become straight lines. Reverse the cold stream to obtain a parallel-flow exchanger, whose\n",
    "effectiveness is lower at the same NTU. Lengthen the channel in\n",
    "`counterflow_heat_exchanger_ntu_geometry.py` and write the STEP file again to raise the NTU."
   ]
  }
 ]
}
