{
 "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 flow over a backward-facing step\n",
    "\n",
    "A channel suddenly doubles its height. The flow cannot follow the sharp corner of the step: it\n",
    "separates, and a recirculation zone forms behind the step until the stream reattaches to the\n",
    "lower wall at the distance $x_r$. Armaly, Durst, Pereira and Schönung (1983) measured how $x_r$\n",
    "grows with the Reynolds number for an expansion ratio of almost two; above $Re\\approx400$ a\n",
    "second recirculation zone opens on the upper wall. The flow is a standard test for\n",
    "incompressible flow solvers because the reattachment length is sensitive to the resolution of\n",
    "the free shear layer behind the step.\n",
    "\n",
    "The channel behind the step comes from the CAD file `backward_facing_step_flow.step`, written by\n",
    "`backward_facing_step_flow_geometry.py`: 30 channel heights long, height $H=1$ m, step height\n",
    "$S=H/2$, with the step corner at the origin. The model is its cross-section. The fluid enters\n",
    "through the upper half of the face `x_min` with the parabolic profile of the channel upstream;\n",
    "the lower half of that face is the vertical face of the step. With the mean inflow speed\n",
    "$\\bar U=1$ m/s the Reynolds number is $Re=\\bar U\\,H/\\nu$, which equals the definition of Armaly\n",
    "et al. with the hydraulic diameter $2(H-S)$ of the upstream channel.\n",
    "\n",
    "$$\\rho(\\mathbf u\\cdot\\nabla)\\mathbf u=-\\nabla p+\\mu\\nabla^2\\mathbf u,\\qquad\\nabla\\cdot\\mathbf u=0$$\n",
    "\n",
    "| side | condition |\n",
    "|---|---|\n",
    "| `x_min`, $0<y<H/2$ (inflow) | $u=24\\,\\bar U\\,y\\,(H/2-y)/H^2$, $v=0$ |\n",
    "| `x_min`, $-H/2<y<0$ (step face) | no slip |\n",
    "| `y_min`, `y_max` (lower and upper wall) | no slip |\n",
    "| `x_max` (outflow) | traction free |\n",
    "\n",
    "**Reference.** D. K. Gartling, \"A test problem for outflow boundary conditions - flow over a\n",
    "backward-facing step\", *Int. J. Numer. Methods Fluids* 11, 953-967 (1990): at $Re=800$ the lower\n",
    "eddy reattaches at $x=6.10\\,H$, the upper eddy extends from $x=4.85\\,H$ to $x=10.48\\,H$. B. F.\n",
    "Armaly, F. Durst, J. C. F. Pereira, B. Schönung, *J. Fluid Mech.* 127, 473-496 (1983) for the\n",
    "growth of $x_r$ with the Reynolds number."
   ]
  },
  {
   "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",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`section` cuts the slab at half thickness. The triangles are 3 cm wide at the step and grow\n",
    "downstream, where the flow becomes parallel again; the mesh study scales all sizes by 1.4 and\n",
    "by 0.8."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "part = load(\"backward_facing_step_flow.step\")\n",
    "channel = part.section((0, 0, 1), origin=(0, 0, 0.05))\n",
    "faces = channel.boundaries\n",
    "length, height = channel.size[:2]\n",
    "step = height / 2\n",
    "meshes = {\n",
    "    scale: TriangularMesher(\n",
    "        target_size=0.1 * scale,\n",
    "        size_field=lambda p, s=scale: s * np.minimum(0.03 + 0.004 * p[:, 0], 0.1),\n",
    "    ).generate(channel)\n",
    "    for scale in (1.4, 1.0, 0.8)\n",
    "}\n",
    "mesh = meshes[1.0]\n",
    "\n",
    "fig = plots.figure(layout=[[\"geometry\"], [\"mesh\"]], size=(16, 7))\n",
    "plots.geometry(\n",
    "    part,\n",
    "    selection={\n",
    "        \"inflow and step face\": part.boundaries.x_min,\n",
    "        \"outflow\": part.boundaries.x_max,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=30, azimuth=-75),\n",
    "    title=\"Channel behind the step\",\n",
    "    ax=fig[\"geometry\"],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"{mesh.cell_count} triangles, graded towards the step\",\n",
    "    ax=fig[\"mesh\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The steady flow at high Reynolds numbers is reached by continuation: each Newton solve starts\n",
    "from the solution at the previous Reynolds number."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "inflow = lambda y: np.column_stack(\n",
    "    (np.maximum(24 * y * (step - y) / height**2, 0.0), 0 * y)\n",
    ")\n",
    "reynolds_numbers = (100, 200, 300, 400, 500, 550, 600, 650, 700, 750, 800)\n",
    "flows, guess = {}, (0.0, 0.0)\n",
    "for reynolds in reynolds_numbers:\n",
    "    model = PlanarIncompressibleNavierStokes(\n",
    "        domain=channel.domain(),\n",
    "        material=NewtonianFluid(density=1.0, dynamic_viscosity=height / reynolds),\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"Backward-facing step\",\n",
    "        geometry=channel,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            FixedVelocity(boundary=faces.x_min, physics=model, value=inflow),\n",
    "            NoSlipWall(boundary=faces.y_min | faces.y_max, physics=model),\n",
    "            FlowTraction(boundary=faces.x_max, physics=model, value=(0.0, 0.0)),\n",
    "        ),\n",
    "    )\n",
    "    numerics = Numerics(\n",
    "        spatial=FiniteElement(element=TaylorHood()),\n",
    "        initial_guess={model.velocity: guess},\n",
    "        nonlinear_solver=Newton(\n",
    "            linear_solver=SparseDirect(),\n",
    "            absolute_tolerance=1e-6,\n",
    "            relative_tolerance=1e-7,\n",
    "            maximum_iterations=25,\n",
    "        ),\n",
    "    )\n",
    "    flows[reynolds] = (\n",
    "        Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "        .solve_stationary()\n",
    "        .field(model.velocity)\n",
    "    )\n",
    "    previous = flows[reynolds]\n",
    "    guess = lambda x, y: previous.evaluate(np.column_stack((x, y)))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same problem at $Re=800$ on the coarser and the finer mesh, each started from the solution\n",
    "above."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "study = {\n",
    "    scale: Simulation(problem=problem, mesh=meshes[scale], numerics=numerics)\n",
    "    .solve_stationary()\n",
    "    .field(model.velocity)\n",
    "    for scale in (1.4, 0.8)\n",
    "}\n",
    "study[1.0] = flows[800]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The wall shear changes sign where an eddy begins or ends. It is read from the velocity 1 mm\n",
    "from the wall on a fine line: the lower eddy ends where $u$ turns from backward to forward,\n",
    "the upper eddy lies between the first change from forward to backward and the next change back."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x = np.linspace(0.01, 20.0, 4000)\n",
    "near = lambda u, y: u.evaluate(np.column_stack((x, np.full_like(x, y))))[:, 0]\n",
    "turns = lambda ux, sign: x[np.flatnonzero((sign * ux[:-1] < 0) & (sign * ux[1:] >= 0))]\n",
    "lower = {\n",
    "    reynolds: turns(near(u, -step + 1e-3), 1)[0] / height\n",
    "    for reynolds, u in flows.items()\n",
    "}\n",
    "upper = {\n",
    "    scale: turns(near(u, step - 1e-3), -1)[:1].tolist()\n",
    "    + turns(near(u, step - 1e-3), 1)[:1].tolist()\n",
    "    for scale, u in study.items()\n",
    "}\n",
    "reattachment = {\n",
    "    scale: turns(near(u, -step + 1e-3), 1)[0] / height for scale, u in study.items()\n",
    "}\n",
    "\n",
    "print(\" Re   lower reattachment x_r / H   x_r / S\")\n",
    "for reynolds, value in lower.items():\n",
    "    print(f\"{reynolds:4d} {value:22.3f} {value * height / step:13.2f}\")\n",
    "print(\n",
    "    \"\\nRe = 800                  coarse    medium    fine    Gartling (1990)   deviation (fine)\"\n",
    ")\n",
    "for name, values, published in (\n",
    "    (\"lower reattachment x/H\", [reattachment[s] for s in (1.4, 1.0, 0.8)], 6.10),\n",
    "    (\"upper separation x/H\", [upper[s][0] / height for s in (1.4, 1.0, 0.8)], 4.85),\n",
    "    (\"upper reattachment x/H\", [upper[s][1] / height for s in (1.4, 1.0, 0.8)], 10.48),\n",
    "):\n",
    "    print(\n",
    "        f\"{name:24s} \"\n",
    "        + \"  \".join(f\"{v:8.3f}\" for v in values)\n",
    "        + f\"   {published:10.2f}   {100 * (values[-1] / published - 1):+12.1f} %\"\n",
    "    )\n",
    "print(\"triangles: \" + \", \".join(f\"{meshes[s].cell_count}\" for s in (1.4, 1.0, 0.8)))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Streamlines and speed behind the step at $Re=800$ with the two eddies, and the recirculation\n",
    "length over the Reynolds number."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "grid_x, grid_y = np.linspace(0.0, 15.0, 301), np.linspace(-step, step, 41)\n",
    "samples = (\n",
    "    flows[800]\n",
    "    .evaluate(np.array([[a, b] for a in grid_x for b in grid_y]))\n",
    "    .reshape(len(grid_x), len(grid_y), 2)\n",
    ")\n",
    "fig = plots.figure(layout=[[\"speed\"], [\"streamlines\"], [\"length\"]], size=(15, 13))\n",
    "plots.surface(\n",
    "    flows[800],\n",
    "    component=lambda u, position: np.linalg.norm(u, axis=1),\n",
    "    limits=(0.0, 1.5),\n",
    "    contours=6,\n",
    "    subdivisions=2,\n",
    "    xlimits=(0.0, 15.0),\n",
    "    label=\"speed [m/s]\",\n",
    "    title=\"Speed behind the step, Re = 800\",\n",
    "    ax=fig[\"speed\"],\n",
    ")\n",
    "plots.streamlines(\n",
    "    grid_x,\n",
    "    grid_y,\n",
    "    samples[..., 0],\n",
    "    samples[..., 1],\n",
    "    density=2.5,\n",
    "    label=\"speed [m/s]\",\n",
    "    title=\"Streamlines: lower eddy behind the step, upper eddy on the opposite wall\",\n",
    "    ax=fig[\"streamlines\"],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        \"lower eddy: reattachment\": (list(lower), list(lower.values())),\n",
    "        \"upper eddy: separation and reattachment\": (\n",
    "            [800, 800],\n",
    "            [value / height for value in upper[1.0]],\n",
    "        ),\n",
    "    },\n",
    "    points={\"Gartling (1990), Re = 800\": ([800, 800, 800], [6.10, 4.85, 10.48])},\n",
    "    markers=True,\n",
    "    xlabel=\"Reynolds number Re = U H / ν\",\n",
    "    ylabel=\"distance from the step x / H\",\n",
    "    title=\"Recirculation lengths grow with the Reynolds number\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[\"length\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Lengthen the channel in `backward_facing_step_flow_geometry.py` and write the STEP file again to\n",
    "check that the outflow boundary does not disturb the eddies; Gartling's paper discusses exactly\n",
    "this. Above $Re\\approx1000$ the steady solution becomes unstable; a transient run with\n",
    "`Simulation.run` shows the shear layer rolling up into travelling vortices."
   ]
  }
 ]
}
