{
 "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": [
    "# Turbulent heat transfer from a heated flat plate\n",
    "\n",
    "A uniform stream of air flows along a flat plate whose surface is kept at a temperature\n",
    "$T_w$ above the stream temperature $T_\\infty$. Downstream of a short laminar start the boundary\n",
    "layer is turbulent; the heat it carries away from the plate is set by the turbulent mixing across\n",
    "the layer, so the local Nusselt number $Nu_x=q_w x/(k(T_w-T_\\infty))$ grows like $Re_x^{0.8}$.\n",
    "\n",
    "The flow obeys the Reynolds-averaged Navier-Stokes equations with the eddy viscosity $\\mu_t$ of\n",
    "Menter's shear-stress transport (SST) $k$-$\\omega$ model. The temperature, with constant\n",
    "properties a passive scalar, obeys\n",
    "\n",
    "$$\\rho c_p\\,\\mathbf u\\cdot\\nabla T=\\nabla\\cdot\\big[(k+\\rho c_p\\,\\alpha_t)\\nabla T\\big],\\qquad \\alpha_t=\\frac{\\nu_t}{Pr_t},\\quad Pr_t=0.85 ,$$\n",
    "\n",
    "the Reynolds analogy for the turbulent heat flux. The heat model takes the velocity and the\n",
    "turbulent diffusivity from the solved flow through field couplings; `EddyDiffusivity(prandtl=0.85)`\n",
    "turns the eddy viscosity into $\\alpha_t=\\mu_t/(\\rho Pr_t)$.\n",
    "\n",
    "| side | flow | heat |\n",
    "|---|---|---|\n",
    "| `inflow` | $u=U=75$ m/s, intensity 0.04 %, $\\mu_t/\\mu=0.009$ | $T=T_\\infty=293.15$ K |\n",
    "| `plate` | no slip, resolved viscous sublayer | $T=T_w=333.15$ K |\n",
    "| `lead`, `top` | symmetry | insulated |\n",
    "| `outflow` | traction free | insulated |\n",
    "\n",
    "**Reference.** For the turbulent flat plate with constant wall temperature the Colburn analogy\n",
    "gives $Nu_x=0.0296\\,Re_x^{0.8}Pr^{1/3}$ (F. P. Incropera et al., *Fundamentals of Heat and Mass\n",
    "Transfer*, 6th ed., eq. 7.36, $0.6<Pr<60$, $Re_x\\le10^8$), consistent with Schlichting's skin\n",
    "friction $c_f=0.0592\\,Re_x^{-1/5}$; Kays and Crawford give $St\\,Pr^{0.4}=0.0287\\,Re_x^{-0.2}$ for\n",
    "gases (W. M. Kays, M. E. Crawford, *Convective Heat and Mass Transfer*, 3rd ed., eq. 13-14)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import NewtonianFluid, ThermalFluid\n",
    "from onesim.meshing import BoundaryLayers, TriangularMesher\n",
    "from onesim.numerics import Numerics\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",
    "    ConvectiveHeatTransfer,\n",
    "    FixedTemperature,\n",
    "    HeatFlux,\n",
    ")\n",
    "from onesim.physics.hydrodynamics import (\n",
    "    EddyDiffusivity,\n",
    "    FixedVelocity,\n",
    "    FlowTraction,\n",
    "    FreeSlipLaw,\n",
    "    IncompressibleNavierStokes,\n",
    "    InflowTurbulence,\n",
    "    KOmegaSST,\n",
    "    NoSlipWall,\n",
    "    WallShear,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.field_connections import FieldCoupling\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 CAD part `turbulent_flat_plate_heat_transfer.step` (from\n",
    "`turbulent_flat_plate_heat_transfer_geometry.py`) is the air above the plate, a slab 0.05 m thick:\n",
    "the stream enters 0.33 m ahead of the leading edge, the far field lies 1 m above the plate. The\n",
    "example computes on its mid-plane. Thirty-two rows of flat cells line the plate, the first 5 µm\n",
    "high ($y^+\\approx0.3$), growing by 25 % per row; the triangles are finest at the leading edge."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "part = load(\"turbulent_flat_plate_heat_transfer.step\")\n",
    "section = part.section((0, 0, 1), origin=(0, 0, 0.025))\n",
    "faces = section.boundaries\n",
    "mesh = TriangularMesher(\n",
    "    target_size=0.24,\n",
    "    size_field=lambda p: np.clip(\n",
    "        0.008 + 0.06 * np.abs(p[:, 0]) + 0.2 * p[:, 1], 0.008, 0.24\n",
    "    ),\n",
    "    boundary_layers=(\n",
    "        BoundaryLayers(walls=faces.plate, count=32, first_height=5e-6, growth=1.25),\n",
    "    ),\n",
    ").generate(section)\n",
    "\n",
    "fig = plots.figure(layout=[[\"geometry\"], [\"mesh\"]], size=(15, 9))\n",
    "plots.geometry(\n",
    "    section,\n",
    "    selection={\n",
    "        \"plate\": faces.plate,\n",
    "        \"inflow\": faces.inflow,\n",
    "        \"symmetry\": faces.lead | faces.top,\n",
    "    },\n",
    "    labels=False,\n",
    "    title=\"Cross-section of the CAD part: air above the heated plate\",\n",
    "    ax=fig[\"geometry\"],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"{mesh.cell_count} cells, refined towards the leading edge and the plate\",\n",
    "    ax=fig[\"mesh\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Turbulent flow\n",
    "\n",
    "`turbulence=KOmegaSST(...)` adds $k$, $\\omega$ and $\\mu_t$ to the incompressible Navier-Stokes\n",
    "equations; the steady state is reached by pseudo-time continuation and finished by Newton. The\n",
    "Reynolds number is five million per metre."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "stream, density, viscosity = 75.0, 1.2, 1.8e-5\n",
    "model = IncompressibleNavierStokes(\n",
    "    domain=section.domain(),\n",
    "    material=NewtonianFluid(density=density, dynamic_viscosity=viscosity),\n",
    "    turbulence=KOmegaSST(\n",
    "        inflow=InflowTurbulence(intensity=3.9e-4, viscosity_ratio=0.009)\n",
    "    ),\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Turbulent flat plate\",\n",
    "    geometry=section,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        FixedVelocity(boundary=faces.inflow, physics=model, value=(stream, 0.0)),\n",
    "        NoSlipWall(boundary=faces.plate, physics=model),\n",
    "        WallShear(boundary=faces.lead | faces.top, physics=model, law=FreeSlipLaw()),\n",
    "        FlowTraction(boundary=faces.outflow, physics=model, value=(0.0, 0.0)),\n",
    "    ),\n",
    ")\n",
    "flow = Simulation(\n",
    "    problem=problem,\n",
    "    mesh=mesh,\n",
    "    numerics=Numerics(\n",
    "        spatial=FiniteElement(element=TaylorHood()),\n",
    "        initial_guess={model.velocity: (stream, 0.0)},\n",
    "        nonlinear_solver=Newton(\n",
    "            linear_solver=SparseDirect(), absolute_tolerance=1e-8, maximum_iterations=10\n",
    "        ),\n",
    "    ),\n",
    ").solve_stationary()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Heat transfer\n",
    "\n",
    "The heat model gets the solved velocity and the turbulent diffusivity through two field\n",
    "couplings and is solved on the same mesh with quadratic elements."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "cold, hot, prandtl = 293.15, 333.15, 0.71\n",
    "air = ThermalFluid(\n",
    "    density=density,\n",
    "    dynamic_viscosity=viscosity,\n",
    "    specific_heat_capacity=1005.0,\n",
    "    thermal_conductivity=viscosity * 1005.0 / prandtl,\n",
    ")\n",
    "heat = ConvectiveHeatTransfer(domain=section.domain(), material=air, velocity=None)\n",
    "heat_problem = Problem(\n",
    "    name=\"Heated flat plate\",\n",
    "    geometry=section,\n",
    "    physics=(heat,),\n",
    "    boundary_conditions=(\n",
    "        FixedTemperature(boundary=faces.inflow, physics=heat, value=cold),\n",
    "        FixedTemperature(boundary=faces.plate, physics=heat, value=hot),\n",
    "        HeatFlux(\n",
    "            boundary=faces.lead | faces.top | faces.outflow, physics=heat, value=0.0\n",
    "        ),\n",
    "    ),\n",
    "    couplings=(\n",
    "        FieldCoupling(\n",
    "            source=flow.field(model.velocity),\n",
    "            target=heat.advecting_velocity,\n",
    "            transfer=FieldInterpolation(),\n",
    "        ),\n",
    "        FieldCoupling(\n",
    "            source=flow.field(model.eddy_viscosity),\n",
    "            target=heat.eddy_diffusivity,\n",
    "            transfer=EddyDiffusivity(prandtl=0.85),\n",
    "        ),\n",
    "    ),\n",
    ")\n",
    "temperature = (\n",
    "    Simulation(\n",
    "        problem=heat_problem,\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": [
    "## Results\n",
    "\n",
    "The wall heat flux is read from the temperature 0.2 µm above the plate, inside the conductive\n",
    "sublayer: $q_w=k\\,(T_w-T(y))/y$; the skin friction likewise from the velocity."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x = np.linspace(0.05, 1.95, 96)\n",
    "reynolds = stream * density * x / viscosity\n",
    "gap = 2e-7\n",
    "nusselt = (\n",
    "    (hot - temperature.evaluate(np.column_stack((x, np.full_like(x, gap)))))\n",
    "    / gap\n",
    "    * x\n",
    "    / (hot - cold)\n",
    ")\n",
    "friction = (\n",
    "    2\n",
    "    * viscosity\n",
    "    * flow.field(model.velocity).evaluate(np.column_stack((x, np.full_like(x, gap))))[\n",
    "        :, 0\n",
    "    ]\n",
    "    / gap\n",
    "    / (density * stream**2)\n",
    ")\n",
    "colburn = 0.0296 * reynolds**0.8 * prandtl ** (1 / 3)\n",
    "kays = 0.0287 * reynolds**0.8 * prandtl**0.6\n",
    "print(\n",
    "    \"  x [m]    Re_x       Nu_x    Colburn   Kays-Crawford   c_f·10³  Schlichting   St·Pr^(2/3) / (c_f/2)\"\n",
    ")\n",
    "for position in (0.25, 0.5, 0.97, 1.5, 1.9):\n",
    "    n, c = np.interp(position, x, nusselt), np.interp(position, x, friction)\n",
    "    r = stream * density * position / viscosity\n",
    "    print(\n",
    "        f\"{position:6.2f} {r:10.3g} {n:9.0f} {0.0296 * r**0.8 * prandtl ** (1 / 3):9.0f} ({100 * (n / (0.0296 * r**0.8 * prandtl ** (1 / 3)) - 1):+5.1f} %)\"\n",
    "        f\" {0.0287 * r**0.8 * prandtl**0.6:7.0f} ({100 * (n / (0.0287 * r**0.8 * prandtl**0.6) - 1):+5.1f} %)\"\n",
    "        f\" {1e3 * c:8.3f} {1e3 * 0.0592 * r**-0.2:8.3f}   {n / (r * prandtl ** (1 / 3)) / (c / 2):10.3f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Temperature in the boundary layer along the plate, and the local Nusselt number with the\n",
    "correlations."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(layout=[[\"temperature\"], [\"nusselt\"]], size=(15, 10))\n",
    "plots.surface(\n",
    "    temperature,\n",
    "    component=lambda value, position: value - 273.15,\n",
    "    xlimits=(0.0, 2.0),\n",
    "    ylimits=(0.0, 0.04),\n",
    "    aspect=10,\n",
    "    label=\"T [°C]\",\n",
    "    title=\"Temperature in the thermal boundary layer\",\n",
    "    ax=fig[\"temperature\"],\n",
    ")\n",
    "plots.line(\n",
    "    y={\"SST, Pr_t = 0.85\": (reynolds, nusselt)},\n",
    "    reference={\n",
    "        \"Colburn 0.0296 Re^0.8 Pr^1/3\": (reynolds, colburn),\n",
    "        \"Kays & Crawford 0.0287 Re^0.8 Pr^0.6\": (reynolds, kays),\n",
    "    },\n",
    "    xlabel=\"Re_x\",\n",
    "    ylabel=\"Nu_x\",\n",
    "    scale=\"loglog\",\n",
    "    xlimits=(5e5, 1e7),\n",
    "    title=\"Local Nusselt number along the plate\",\n",
    "    ax=fig[\"nusselt\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "`EddyDiffusivity(prandtl=...)` sets the turbulent Prandtl number; the same coupling into\n",
    "`SpeciesTransport(...).eddy_diffusivity` gives turbulent mass transfer with a turbulent Schmidt\n",
    "number. A `HeatFlux` on the plate instead of the fixed temperature gives the constant-flux case."
   ]
  }
 ]
}
