{
 "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 boundary layer on a flat plate\n",
    "\n",
    "A stream of speed $U$ flows along a flat plate. Far from the leading edge the boundary layer is\n",
    "turbulent: the mean velocity follows the law of the wall close to the plate, and the skin\n",
    "friction $c_f=\\tau_w/(\\tfrac12\\rho U^2)$ falls slowly with the Reynolds number\n",
    "$Re_x=Ux/\\nu$. The zero-pressure-gradient flat plate is the first verification case for every\n",
    "turbulence model (NASA Turbulence Modeling Resource, case 2DZP).\n",
    "\n",
    "The mean flow obeys the Reynolds-averaged Navier-Stokes equations, closed with an eddy\n",
    "viscosity $\\mu_t$ from Menter's shear-stress transport model, which transports the turbulent\n",
    "kinetic energy $k$ and its specific dissipation rate $\\omega$:\n",
    "\n",
    "$$\\rho(\\mathbf u\\cdot\\nabla)\\mathbf u=-\\nabla p+\\nabla\\cdot\\big[(\\mu+\\mu_t)(\\nabla\\mathbf u+\\nabla\\mathbf u^T)\\big],\\qquad\\nabla\\cdot\\mathbf u=0,$$\n",
    "\n",
    "$$\\rho\\,\\mathbf u\\cdot\\nabla k=\\nabla\\cdot\\big[(\\mu+\\sigma_k\\mu_t)\\nabla k\\big]+P_k-\\beta^*\\rho k\\omega,\\qquad\n",
    "\\rho\\,\\mathbf u\\cdot\\nabla\\omega=\\nabla\\cdot\\big[(\\mu+\\sigma_\\omega\\mu_t)\\nabla\\omega\\big]+\\frac{\\gamma\\rho}{\\mu_t}P_k-\\beta\\rho\\omega^2+2(1-F_1)\\frac{\\rho\\sigma_{\\omega2}}{\\omega}\\nabla k\\cdot\\nabla\\omega,$$\n",
    "\n",
    "with $\\mu_t=\\rho a_1k/\\max(a_1\\omega,SF_2)$. The air comes from the CAD file\n",
    "`turbulent_flat_plate_zero_pressure_gradient.step`, written by\n",
    "`turbulent_flat_plate_zero_pressure_gradient_geometry.py`: the plate starts at $x=0$ and is 2 m\n",
    "long, the stream enters 0.33 m ahead of it, the far field is 1 m above it.\n",
    "\n",
    "| side | condition |\n",
    "|---|---|\n",
    "| `inflow` | $u=U$, $v=0$, free-stream turbulence $k=\\tfrac32(IU)^2$, $\\mu_t/\\mu=0.009$ |\n",
    "| `lead` (ahead of the plate), `top` | symmetry (no normal flow, no shear) |\n",
    "| `plate` | no slip, $k=0$, $\\omega$ of the viscous sublayer (resolved wall, $y^+<1$) |\n",
    "| `outflow` | traction free |\n",
    "\n",
    "**Reference.** H. Schlichting, *Boundary-Layer Theory*: $c_f=0.0592\\,Re_x^{-1/5}$ for\n",
    "$5\\cdot10^5<Re_x<10^7$; F. M. White, *Viscous Fluid Flow*, 3rd ed. (2006), eq. 6-121:\n",
    "$c_f = 0.455/\\ln^2(0.06\\,Re_x)$. The NASA Turbulence Modeling Resource (case 2DZP) reports\n",
    "$c_f=0.00268$ at $x=0.97$ m for the SST model (CFL3D); the SST model itself lies a few per cent\n",
    "below White's correlation. For the profile Spalding's law of the wall\n",
    "$y^+=u^++e^{-\\kappa B}\\big[e^{\\kappa u^+}-1-\\kappa u^+-\\tfrac12(\\kappa u^+)^2-\\tfrac16(\\kappa u^+)^3\\big]$ with\n",
    "$\\kappa=0.41$, $B=5.0$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import NewtonianFluid\n",
    "from onesim.meshing import BoundaryLayers, TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, TaylorHood\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import Newton\n",
    "from onesim.physics.hydrodynamics import (\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.visualization import plots, theme\n",
    "from scipy.optimize import brentq\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`section` cuts the slab at half its span. Thirty-two rows of flat cells line the plate, the\n",
    "first 5 µm high ($y^+\\approx0.3$), growing by 25 % per row; behind them triangles grow away\n",
    "from the leading edge and the plate."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "part = load(\"turbulent_flat_plate_zero_pressure_gradient.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 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": [
    "## Model\n",
    "\n",
    "The turbulence model is an option of the flow model: `turbulence=KOmegaSST(...)` adds $k$,\n",
    "$\\omega$ and $\\mu_t$ to the incompressible Navier-Stokes equations, and the walls, inflow and\n",
    "symmetry planes of the flow tell it where $k$ vanishes, where turbulence enters and where it\n",
    "has no flux. Taylor-Hood elements carry velocity and pressure, linear elements $k$ and\n",
    "$\\omega$; the steady state is reached by pseudo-time continuation, finished by Newton."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "stream, nu = 1.0, 2.0e-7\n",
    "air = NewtonianFluid(density=1.0, dynamic_viscosity=nu)\n",
    "model = IncompressibleNavierStokes(\n",
    "    domain=section.domain(),\n",
    "    material=air,\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",
    "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",
    "result = Simulation(problem=problem, mesh=mesh, numerics=numerics).solve_stationary()\n",
    "velocity, eddy = result.field(model.velocity), result.field(model.eddy_viscosity)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The wall shear stress $\\tau_w=\\mu\\,\\partial u/\\partial y$ is read from the velocity 0.2 µm above\n",
    "the plate, inside the viscous sublayer. The velocity profile at $x=0.97$ m is scaled with the\n",
    "friction velocity $u_\\tau=\\sqrt{\\tau_w/\\rho}$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x = np.linspace(0.05, 1.95, 96)\n",
    "friction = (\n",
    "    2\n",
    "    * nu\n",
    "    * velocity.evaluate(np.column_stack((x, np.full_like(x, 2e-7))))[:, 0]\n",
    "    / 2e-7\n",
    "    / stream**2\n",
    ")\n",
    "reynolds = stream * x / nu\n",
    "white = lambda r: 0.455 / np.log(0.06 * r) ** 2\n",
    "schlichting = lambda r: 0.0592 * r**-0.2\n",
    "print(\n",
    "    \"  x [m]    Re_x      c_f·10³   Schlichting   White    deviation (Schlichting, White)\"\n",
    ")\n",
    "for position in (0.25, 0.5, 0.97, 1.5, 1.9):\n",
    "    value = np.interp(position, x, friction)\n",
    "    r = stream * position / nu\n",
    "    print(\n",
    "        f\"{position:6.2f} {r:10.3g} {1e3 * value:9.3f} {1e3 * schlichting(r):10.3f} {1e3 * white(r):9.3f}\"\n",
    "        f\"    {100 * (value / schlichting(r) - 1):+5.1f} %, {100 * (value / white(r) - 1):+5.1f} %\"\n",
    "    )\n",
    "print(\n",
    "    f\"x = 0.97 m: c_f = {np.interp(0.97, x, friction):.5f}, SST reference (TMR, CFL3D) 0.00268, deviation {100 * (np.interp(0.97, x, friction) / 0.00268 - 1):+.1f} %\"\n",
    ")\n",
    "\n",
    "station = 0.97\n",
    "heights = np.geomspace(2e-7, 0.05, 300)\n",
    "profile = velocity.evaluate(np.column_stack((np.full_like(heights, station), heights)))[\n",
    "    :, 0\n",
    "]\n",
    "u_tau = np.sqrt(np.interp(station, x, friction) / 2) * stream\n",
    "y_plus, u_plus = heights * u_tau / nu, profile / u_tau\n",
    "spalding = lambda up: up + np.exp(-0.41 * 5.0) * (\n",
    "    np.exp(0.41 * up) - 1 - 0.41 * up - (0.41 * up) ** 2 / 2 - (0.41 * up) ** 3 / 6\n",
    ")\n",
    "law = np.array([brentq(lambda up: spalding(up) - yp, 0.0, 60.0) for yp in y_plus])\n",
    "print(\n",
    "    f\"\\nx = {station} m: u_tau = {u_tau:.4f} m/s; u+ at y+ = 1, 10, 30, 100, 300:\",\n",
    "    \", \".join(\n",
    "        f\"{np.interp(v, y_plus, u_plus):.2f} ({np.interp(v, y_plus, law):.2f})\"\n",
    "        for v in (1, 10, 30, 100, 300)\n",
    "    ),\n",
    "    \"(Spalding in brackets)\",\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Skin friction along the plate with the two correlations; the velocity profile in wall units with\n",
    "the law of the wall; the eddy viscosity in the boundary layer."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(layout=[[\"friction\", \"profile\"], [\"eddy\", \"eddy\"]], size=(15, 10))\n",
    "plots.line(\n",
    "    y={\"SST, wall resolved\": (reynolds, 1e3 * friction)},\n",
    "    reference={\n",
    "        \"Schlichting 0.0592 Re^-1/5\": (reynolds, 1e3 * schlichting(reynolds)),\n",
    "        \"White (2006)\": (reynolds, 1e3 * white(reynolds)),\n",
    "    },\n",
    "    xlabel=\"Re_x\",\n",
    "    ylabel=\"c_f · 10³\",\n",
    "    ylimits=(2.0, 5.0),\n",
    "    xlimits=(5e5, 1e7),\n",
    "    scale=\"logx\",\n",
    "    title=\"Skin friction along the plate\",\n",
    "    ax=fig[\"friction\"],\n",
    ")\n",
    "plots.line(\n",
    "    y={\"SST at x = 0.97 m\": (y_plus, u_plus)},\n",
    "    reference={\"Spalding law of the wall\": (y_plus, law)},\n",
    "    xlabel=\"y+\",\n",
    "    ylabel=\"u+\",\n",
    "    scale=\"logx\",\n",
    "    xlimits=(0.1, 3e4),\n",
    "    title=\"Velocity profile in wall units\",\n",
    "    ax=fig[\"profile\"],\n",
    ")\n",
    "plots.surface(\n",
    "    eddy,\n",
    "    component=lambda value, position: value / nu,\n",
    "    xlimits=(0.0, 2.0),\n",
    "    ylimits=(0.0, 0.06),\n",
    "    aspect=8,\n",
    "    label=\"μ_t / μ\",\n",
    "    title=\"Eddy viscosity in the boundary layer along the plate\",\n",
    "    ax=fig[\"eddy\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "`turbulence=SpalartAllmaras(...)` solves the same plate with the one-equation model;\n",
    "`KOmegaSST(wall_treatment=WallFunctions(y_plus=30))` bridges the viscous sublayer with the\n",
    "logarithmic law, so that the first cell can be thirty times higher. A heated plate needs the\n",
    "eddy diffusivity $\\mu_t/(\\rho\\,Pr_t)$ in the energy equation, available from `model.eddy_viscosity`."
   ]
  }
 ]
}
