{
 "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": [
    "# Laminar flat-plate boundary layer (Blasius)\n",
    "\n",
    "A uniform stream of speed $U$ flows along a thin flat plate. Viscosity brings the fluid to rest\n",
    "on the plate, and a thin boundary layer grows along it. Blasius (1908) found the similarity\n",
    "solution of the boundary-layer equations: with $\\eta = y\\sqrt{U/(\\nu x)}$,\n",
    "\n",
    "$$f''' + \\tfrac{1}{2}\\,f\\,f'' = 0,\\qquad f(0)=f'(0)=0,\\qquad f'(\\infty)=1,\\qquad \\frac{u}{U}=f'(\\eta) .$$\n",
    "\n",
    "The slab of air above the plate comes from the CAD file `blasius_flat_plate.step`: the plate is\n",
    "the face `y_min`, the inflow `x_min`, the outflow `x_max` and the far field `y_max`. The script\n",
    "`blasius_flat_plate_geometry.py` builds it with the CAD objects of OneSimulation; the model is\n",
    "its cross-section.\n",
    "\n",
    "| side | condition |\n",
    "|---|---|\n",
    "| `x_min` (inflow) | Blasius profile $(u, v)$ at 0.2 m from the leading edge |\n",
    "| `y_min` (plate) | no slip |\n",
    "| `x_max`, `y_max` (outflow, far field) | traction free |\n",
    "\n",
    "**Reference.** From the Blasius solution (Schlichting and Gersten, *Boundary-Layer Theory*):\n",
    "\n",
    "$$\\delta_{99}=5.0\\,\\frac{x}{\\sqrt{Re_x}},\\qquad c_f=\\frac{0.664}{\\sqrt{Re_x}},\\qquad Re_x=\\frac{Ux}{\\nu}.$$\n",
    "\n",
    "The simulation solves the full Navier-Stokes equations, without the boundary-layer\n",
    "approximation. Its domain starts 0.2 m behind the leading edge, where the Blasius profile is\n",
    "the inflow, and follows the layer for 1 m."
   ]
  },
  {
   "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 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",
    "    NoSlipWall,\n",
    "    PlanarIncompressibleNavierStokes,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.integrate import solve_ivp\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; the cross-section keeps the names of the faces. The\n",
    "triangles are 2 mm high on the plate and grow with the distance from it up to 2 cm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "slab = load(\"blasius_flat_plate.step\")\n",
    "section = slab.section((0, 0, 1), origin=(0, 0, slab.size[2] / 2))\n",
    "faces = section.boundaries\n",
    "plate_length, height = section.size[:2]\n",
    "mesh = TriangularMesher(\n",
    "    target_size=0.02, size_field=lambda p: np.minimum(0.02, 0.002 + 0.1 * p[:, 1])\n",
    ").generate(section)\n",
    "\n",
    "fig = plots.figure(2, 1, size=(15, 8))\n",
    "plots.geometry(\n",
    "    slab,\n",
    "    selection={\"plate\": slab.boundaries.y_min, \"inflow\": slab.boundaries.x_min},\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=62, azimuth=-90),\n",
    "    title=\"Slab of air above the plate\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Cross-section: {mesh.cell_count} triangles, graded towards the plate\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The plate is a no-slip wall, the inflow carries the Blasius profile, and the top and the outflow\n",
    "are open. Taylor-Hood elements (quadratic velocity, linear pressure) with a Newton solver."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "start, stream = 0.2, 1.0\n",
    "air = NewtonianFluid(density=1.0, dynamic_viscosity=1.0e-4)\n",
    "viscosity = air.dynamic_viscosity / air.density\n",
    "similarity = solve_ivp(\n",
    "    lambda eta, f: (f[1], f[2], -0.5 * f[0] * f[2]),\n",
    "    (0, 10),\n",
    "    (0, 0, 0.332057),\n",
    "    dense_output=True,\n",
    "    rtol=1e-10,\n",
    "    atol=1e-12,\n",
    ").sol\n",
    "\n",
    "\n",
    "def blasius(x, y):\n",
    "    \"\"\"Velocity components u and v of the Blasius solution at the distance x from the leading edge.\"\"\"\n",
    "    eta = np.minimum(y * np.sqrt(stream / (viscosity * x)), 10.0)\n",
    "    f, slope, _ = similarity(eta)\n",
    "    return stream * slope, 0.5 * np.sqrt(viscosity * stream / x) * (eta * slope - f)\n",
    "\n",
    "\n",
    "model = PlanarIncompressibleNavierStokes(domain=section.domain(), material=air)\n",
    "problem = Problem(\n",
    "    name=\"Blasius boundary layer\",\n",
    "    geometry=section,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        NoSlipWall(boundary=faces.y_min, physics=model),\n",
    "        FixedVelocity(\n",
    "            boundary=faces.x_min,\n",
    "            physics=model,\n",
    "            value=lambda y: np.column_stack(blasius(start, y)),\n",
    "        ),\n",
    "        FlowTraction(\n",
    "            boundary=faces.x_max | faces.y_max, physics=model, value=(0.0, 0.0)\n",
    "        ),\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(),\n",
    "        absolute_tolerance=1e-9,\n",
    "        relative_tolerance=1e-10,\n",
    "        maximum_iterations=40,\n",
    "    ),\n",
    ")\n",
    "velocity = (\n",
    "    Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "    .solve_stationary()\n",
    "    .field(model.velocity)\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The velocity is sampled on a grid of stations along the plate. The thickness $\\delta_{99}$ is\n",
    "where $u$ reaches 99 % of the stream; the skin friction follows from the slope of $u$ at the wall."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x = start + np.linspace(0.1, 0.9, 17) * plate_length\n",
    "y = np.linspace(0, 0.1, 201)\n",
    "grid = np.array([[position - start, level] for position in x for level in y])\n",
    "u = velocity.evaluate(grid)[:, 0].reshape(len(x), len(y))\n",
    "reynolds = stream * x / viscosity\n",
    "thickness = np.array([np.interp(0.99 * stream, profile, y) for profile in u])\n",
    "friction = (\n",
    "    2\n",
    "    * air.dynamic_viscosity\n",
    "    * (4 * u[:, 5] - u[:, 10])\n",
    "    / (2 * y[5])\n",
    "    / (air.density * stream**2)\n",
    ")\n",
    "\n",
    "print(\" x [m]    δ99 [mm]   Blasius    c_f·10³   Blasius\")\n",
    "for index in range(0, 17, 4):\n",
    "    print(\n",
    "        f\"{x[index]:6.2f} {1e3 * thickness[index]:10.2f} {5e3 * x[index] / np.sqrt(reynolds[index]):9.2f}\"\n",
    "        f\" {1e3 * friction[index]:10.3f} {664 / np.sqrt(reynolds[index]):9.3f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Velocity profiles at three stations in the similarity variable, the boundary-layer thickness\n",
    "and the skin friction along the plate."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "eta = np.linspace(0, 8, 200)\n",
    "profiles = {\n",
    "    f\"x = {x[i]:.2f} m\": (\n",
    "        u[i, ::4] / stream,\n",
    "        y[::4] * np.sqrt(stream / (viscosity * x[i])),\n",
    "    )\n",
    "    for i in (4, 8, 12)\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 3, size=(16, 5))\n",
    "plots.line(\n",
    "    points=profiles,\n",
    "    reference={\"Blasius f'(η)\": (similarity(eta)[1], eta)},\n",
    "    ylimits=(0, 8),\n",
    "    xlabel=\"u / U\",\n",
    "    ylabel=\"η = y √(U / ν x)\",\n",
    "    title=\"Velocity profiles collapse onto one curve\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    x,\n",
    "    points={\"simulation\": 1e3 * thickness},\n",
    "    reference={\"5.0 x / √Re\": 5e3 * x / np.sqrt(reynolds)},\n",
    "    xlabel=\"distance from the leading edge [m]\",\n",
    "    ylabel=\"δ99 [mm]\",\n",
    "    title=\"Boundary-layer thickness\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    x,\n",
    "    points={\"simulation\": 1e3 * friction},\n",
    "    reference={\"0.664 / √Re\": 664 / np.sqrt(reynolds)},\n",
    "    xlabel=\"distance from the leading edge [m]\",\n",
    "    ylabel=\"c_f × 10³\",\n",
    "    title=\"Skin friction\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the slab longer in `blasius_flat_plate_geometry.py` and write the STEP file again to follow\n",
    "the layer to higher Reynolds numbers. Add a pressure gradient through the outer boundary to\n",
    "obtain the Falkner-Skan wedge flows, or heat the plate and compare the thermal boundary layer\n",
    "with the Pohlhausen solution."
   ]
  }
 ]
}
