{
 "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": [
    "# Bulk temperature in a heated square duct\n",
    "\n",
    "Water (density 1000 kg/m³, viscosity $10^{-3}$ Pa s, conductivity 0.6 W/(m K), heat capacity\n",
    "4180 J/(kg K), $Pr=7$) flows through a square duct of side $a=2$ mm at $Re=20$ and enters at\n",
    "293.15 K with a fully developed velocity profile. All four walls take up the uniform heat flux\n",
    "$q=2000$ W/m². The flow is solved with the steady Navier-Stokes equations and carries the heat,\n",
    "\n",
    "$$\\rho c_p\\,\\mathbf u\\cdot\\nabla T=\\nabla\\cdot(k\\nabla T).$$\n",
    "\n",
    "A heat transfer coefficient is always defined with the **bulk temperature**, the temperature the\n",
    "fluid would reach if the cross-section were collected and mixed,\n",
    "\n",
    "$$T_b(z)=\\frac{\\int_A u_z\\,T\\,dA}{\\int_A u_z\\,dA},$$\n",
    "\n",
    "not with the plain area mean: the fast core carries more enthalpy than the slow fluid near the\n",
    "hot walls.\n",
    "\n",
    "One quarter of the duct comes from the CAD file `bulk_temperature_square_duct.step` (faces\n",
    "`z_min` inlet, `z_max` outlet, `x_max` and `y_max` walls, `x_min` and `y_min` symmetry planes);\n",
    "the script `bulk_temperature_square_duct_geometry.py` builds it with the CAD objects of\n",
    "OneSimulation.\n",
    "\n",
    "| face | flow | heat |\n",
    "|---|---|---|\n",
    "| `z_min` | fully developed profile, $Re=20$ | $T=293.15$ K |\n",
    "| `z_max` | traction free | no conduction |\n",
    "| `x_max`, `y_max` | no slip | heat flux $q$ |\n",
    "| `x_min`, `y_min` | free slip | no flux |\n",
    "\n",
    "**Reference.** The energy balance fixes the bulk temperature exactly at every station,\n",
    "$T_b(z)=T_\\mathrm{in}+q\\,P\\,z/(\\dot m c_p)$ with the perimeter $P=4a$. Far from the inlet the\n",
    "temperature profile no longer changes shape; for a square duct with peripherally uniform wall\n",
    "flux the Nusselt number based on the mean wall temperature is $Nu_{H2}=3.091$ (Shah and London,\n",
    "*Laminar Flow Forced Convection in Ducts*, 1978, Table 42)."
   ]
  },
  {
   "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, NewtonianFluid\n",
    "from onesim.meshing import Geometric, Piecewise, StructuredHexahedralMesher, Uniform\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, mean_value\n",
    "from onesim.results.sampling import field_function\n",
    "from onesim.simulation import Problem, Simulation\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",
    "A hexahedral mesh, finer towards the heated walls and towards the inlet."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "duct = load(\"bulk_temperature_square_duct.step\")\n",
    "faces = duct.boundaries\n",
    "half, _, length = duct.size\n",
    "side = 2 * half\n",
    "mesh = StructuredHexahedralMesher(\n",
    "    cells=(8, 8, 40),\n",
    "    grading=(\n",
    "        Geometric(8, ratio=3.0, toward=\"end\"),\n",
    "        Geometric(8, ratio=3.0, toward=\"end\"),\n",
    "        Piecewise(\n",
    "            (\n",
    "                (0.2 * length, Geometric(12, ratio=4.0, toward=\"start\")),\n",
    "                (0.8 * length, Uniform(28)),\n",
    "            )\n",
    "        ),\n",
    "    ),\n",
    ").generate(duct)\n",
    "\n",
    "view = plots.Camera(elevation=25, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(14, 5.5))\n",
    "plots.geometry(\n",
    "    duct,\n",
    "    selection={\n",
    "        \"inlet\": faces.z_min,\n",
    "        \"heated walls\": faces.x_max | faces.y_max,\n",
    "        \"symmetry\": faces.x_min | faces.y_min,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Quarter of the duct\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{mesh.cell_count} hexahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Flow and heat transfer\n",
    "\n",
    "The solved velocity drives the heat transport one way (constant properties)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "water = NewtonianFluid(density=1000.0, dynamic_viscosity=1.0e-3)\n",
    "conductivity, capacity, flux, inlet = 0.6, 4180.0, 2000.0, 293.15\n",
    "mean_speed = 20.0 * water.dynamic_viscosity / (water.density * side)\n",
    "walls, symmetry = faces.x_max | faces.y_max, faces.x_min | faces.y_min\n",
    "flow = IncompressibleNavierStokes(domain=duct.volume, material=water)\n",
    "velocity = (\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Duct flow\",\n",
    "            geometry=duct,\n",
    "            physics=(flow,),\n",
    "            boundary_conditions=(\n",
    "                FixedVelocity(\n",
    "                    boundary=faces.z_min,\n",
    "                    physics=flow,\n",
    "                    value=fully_developed_inflow(\n",
    "                        mesh, faces.z_min, mean_velocity=mean_speed, no_slip=walls\n",
    "                    ),\n",
    "                ),\n",
    "                FlowTraction(\n",
    "                    boundary=faces.z_max,\n",
    "                    physics=flow,\n",
    "                    value=lambda x, y, z: np.zeros((len(x), 3)),\n",
    "                ),\n",
    "                NoSlipWall(boundary=walls, physics=flow),\n",
    "                WallShear(boundary=symmetry, physics=flow, law=FreeSlipLaw()),\n",
    "            ),\n",
    "            initial_conditions=(InitialValue(flow.velocity, (0.0, 0.0, 0.0)),),\n",
    "        ),\n",
    "        mesh=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",
    ")\n",
    "heat = ConvectiveHeatTransfer(\n",
    "    domain=duct.volume,\n",
    "    velocity=field_function(velocity),\n",
    "    material=IsotropicSolid(\n",
    "        density=water.density,\n",
    "        specific_heat_capacity=capacity,\n",
    "        thermal_conductivity=conductivity,\n",
    "        youngs_modulus=1.0,\n",
    "        poisson_ratio=0.3,\n",
    "        thermal_expansion_coefficient=0.0,\n",
    "    ),\n",
    ")\n",
    "temperature = (\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Duct heat transfer\",\n",
    "            geometry=duct,\n",
    "            physics=(heat,),\n",
    "            boundary_conditions=(\n",
    "                FixedTemperature(boundary=faces.z_min, physics=heat, value=inlet),\n",
    "                HeatFlux(boundary=walls, physics=heat, value=-flux),\n",
    "                HeatFlux(boundary=faces.z_max | symmetry, physics=heat, value=0.0),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=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": [
    "## Bulk temperature\n",
    "\n",
    "`derived_field` forms $u_zT$, `integrate_plane` integrates it and the axial velocity over a cut\n",
    "across the duct, and their ratio is the bulk temperature. `mean_value` on the same cut gives the\n",
    "area mean, and on the wall line the mean wall temperature."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "stations = np.linspace(1e-3, length - 1e-3, 29)\n",
    "cut = lambda z: Plane(origin=(0, 0, z), normal=(0, 0, 1))\n",
    "carried = derived_field(\n",
    "    velocity,\n",
    "    lambda u, points: u[:, 2] * np.ravel(temperature.evaluate(points)),\n",
    "    name=\"enthalpy_flux\",\n",
    "    unit=\"K*m/s\",\n",
    ")\n",
    "bulk = np.array(\n",
    "    [\n",
    "        integrate_plane(carried, cut(z)).value\n",
    "        / integrate_plane(velocity, cut(z), normal_component=True).value\n",
    "        for z in stations\n",
    "    ]\n",
    ")\n",
    "area_mean = np.array([mean_value(temperature, plane=cut(z)) for z in stations])\n",
    "s = np.linspace(0.0, half, 21)\n",
    "wall = np.array(\n",
    "    [\n",
    "        np.mean(\n",
    "            np.r_[\n",
    "                temperature.evaluate(\n",
    "                    np.column_stack((np.full_like(s, half), s, np.full_like(s, z)))\n",
    "                ),\n",
    "                temperature.evaluate(\n",
    "                    np.column_stack((s, np.full_like(s, half), np.full_like(s, z)))\n",
    "                ),\n",
    "            ]\n",
    "        )\n",
    "        for z in stations\n",
    "    ]\n",
    ")\n",
    "balance = inlet + flux * 4 * side * stations / (\n",
    "    water.density * mean_speed * side**2 * capacity\n",
    ")\n",
    "nusselt = flux * side / (conductivity * (wall - bulk))\n",
    "developed = stations > 0.6 * length\n",
    "print(\n",
    "    f\"Re = 20, Pr = {water.dynamic_viscosity * capacity / conductivity:.2f}; flow rate through the quarter \"\n",
    "    f\"{integrate_plane(velocity, cut(length / 2), normal_component=True).value / (mean_speed * half**2):.5f} x the prescribed\"\n",
    ")\n",
    "print(\n",
    "    \"z [mm]   bulk T [K]   energy balance [K]   deviation [mK]   area mean [K]   mean wall T [K]\"\n",
    ")\n",
    "for z, tb, te, ta, tw in list(zip(stations, bulk, balance, area_mean, wall))[::4]:\n",
    "    print(\n",
    "        f\"{1e3 * z:6.1f} {tb:12.4f} {te:18.4f} {1e3 * (tb - te):14.2f} {ta:15.4f} {tw:15.4f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"largest deviation of the bulk temperature from the energy balance: {1e3 * np.abs(bulk - balance).max():.2f} mK \"\n",
    "    f\"of {balance[-1] - inlet:.3f} K rise\"\n",
    ")\n",
    "print(\n",
    "    f\"fully developed Nusselt number (last 40 %): {nusselt[developed].mean():.4f}, tabulated Nu_H2 = 3.091 \"\n",
    "    f\"({100 * (nusselt[developed].mean() / 3.091 - 1):+.2f} %)\"\n",
    ")\n",
    "print(\n",
    "    f\"using the area mean instead of the bulk temperature would give Nu = \"\n",
    "    f\"{(flux * side / (conductivity * (wall - area_mean)))[developed].mean():.3f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The temperature on the outlet cross-section, the three temperatures along the duct and the local\n",
    "Nusselt number."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(\n",
    "    layout=[[\"outlet\", \"temperatures\"], [\"outlet\", \"nusselt\"]], size=(15, 9)\n",
    ")\n",
    "plots.section(\n",
    "    temperature,\n",
    "    plane=cut(length - 1e-6),\n",
    "    contours=10,\n",
    "    subdivisions=3,\n",
    "    symmetry={\"planes\": [((1, 0, 0), (0, 0, 0)), ((0, 1, 0), (0, 0, 0))]},\n",
    "    label=\"T [K]\",\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    title=\"Temperature at the outlet\",\n",
    "    ax=fig[\"outlet\"],\n",
    ")\n",
    "plots.line(\n",
    "    1e3 * stations,\n",
    "    {\"mean wall temperature\": wall, \"area mean\": area_mean},\n",
    "    points={\"bulk temperature\": (1e3 * stations, bulk)},\n",
    "    reference={\"energy balance\": (1e3 * stations, balance)},\n",
    "    xlabel=\"z along the duct [mm]\",\n",
    "    ylabel=\"temperature [K]\",\n",
    "    title=\"Bulk, area mean and wall temperature\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[\"temperatures\"],\n",
    ")\n",
    "plots.line(\n",
    "    1e3 * stations,\n",
    "    {\"simulation\": nusselt},\n",
    "    hlines={\"Nu_H2 = 3.091\": 3.091},\n",
    "    ylimits=(2.5, 8),\n",
    "    xlabel=\"z along the duct [mm]\",\n",
    "    ylabel=\"local Nusselt number\",\n",
    "    title=\"Thermal development\",\n",
    "    ax=fig[\"nusselt\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Hold the walls at a fixed temperature instead and compare with $Nu_T=2.976$; make the duct\n",
    "rectangular in `bulk_temperature_square_duct_geometry.py` and follow the Nusselt number with the\n",
    "aspect ratio; or heat only one wall, as in a cold plate."
   ]
  }
 ]
}
