{
 "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": [
    "# Lid-driven cavity at Re = 100\n",
    "\n",
    "An incompressible Newtonian fluid fills a square cavity of side $L$. The top lid\n",
    "slides in its own plane at constant speed $U$ while the three remaining walls are\n",
    "fixed (no-slip). The Reynolds number is $Re=\\rho U L/\\mu = 100$. This recirculating\n",
    "flow has no closed-form solution and is a classic verification case for\n",
    "incompressible Navier-Stokes solvers.\n",
    "\n",
    "The cavity comes from the CAD file `lid_driven_cavity.step`, a thin slab whose face `y_max` is\n",
    "the lid. The script `lid_driven_cavity_geometry.py` builds it with the CAD objects of\n",
    "OneSimulation. The model is its cross-section: OneSimulation solves the two-dimensional\n",
    "stationary Navier-Stokes system $\\rho(u\\cdot\\nabla)u=-\\nabla p+\\mu\\nabla^2 u$,\n",
    "$\\nabla\\cdot u=0$ with Taylor-Hood finite elements (quadratic velocity, linear pressure) on\n",
    "triangles and a Newton solver.\n",
    "\n",
    "| side | condition |\n",
    "|---|---|\n",
    "| `y_max` (lid) | $u=(U,0)$ |\n",
    "| `x_min`, `x_max`, `y_min` | no slip |\n",
    "| pressure level | mean pressure zero |\n",
    "\n",
    "**Reference.** The horizontal velocity $u_x$ along the vertical centre line $x=L/2$ in the\n",
    "benchmark of Ghia, Ghia & Shin (1982), \"High-Re solutions for incompressible flow using the\n",
    "Navier-Stokes equations and a multigrid method\", J. Comput. Phys. 48, 387-411, Table I, Re = 100."
   ]
  },
  {
   "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",
    "    NoSlipWall,\n",
    "    PlanarIncompressibleNavierStokes,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.field_constraints import MeanValue\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 cross-section keeps the names of the faces it was\n",
    "cut from. The triangles are 1/32 of the side wide and half as wide along the lid, where the\n",
    "velocity changes fastest."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "part = load(\"lid_driven_cavity.step\")\n",
    "cavity = part.section((0, 0, 1), origin=(0, 0, part.size[2] / 2))\n",
    "faces = cavity.boundaries\n",
    "side = cavity.size[0]\n",
    "cells = 32\n",
    "mesh = TriangularMesher(\n",
    "    target_size=side / cells,\n",
    "    size_field=lambda p: side\n",
    "    / cells\n",
    "    * (0.5 + 0.5 * np.minimum(1.0, 4 * (side - p[:, 1]) / side)),\n",
    ").generate(cavity)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 6.5))\n",
    "plots.geometry(\n",
    "    part,\n",
    "    selection={\n",
    "        \"lid\": part.boundaries.y_max,\n",
    "        \"fixed walls\": part.boundaries.x_min\n",
    "        | part.boundaries.x_max\n",
    "        | part.boundaries.y_min,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=62, azimuth=-90),\n",
    "    title=\"Cavity with its lid and fixed walls\",\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\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Density and viscosity give $Re=100$. The lid speed is uniform except for a linear ramp to zero\n",
    "over the last 1/32 of the side at each end, so the velocity is single-valued where the lid meets\n",
    "the fixed walls."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "lid_speed = 1.0\n",
    "fluid = NewtonianFluid(density=1.0, dynamic_viscosity=0.01)\n",
    "model = PlanarIncompressibleNavierStokes(domain=cavity.domain(), material=fluid)\n",
    "problem = Problem(\n",
    "    name=\"Lid-driven cavity\",\n",
    "    geometry=cavity,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        NoSlipWall(boundary=faces.x_min | faces.x_max | faces.y_min, physics=model),\n",
    "        FixedVelocity(\n",
    "            boundary=faces.y_max,\n",
    "            physics=model,\n",
    "            value=lambda x: np.column_stack(\n",
    "                (\n",
    "                    lid_speed\n",
    "                    * np.clip(np.minimum(x, side - x) * cells / side, 0.0, 1.0),\n",
    "                    0 * x,\n",
    "                )\n",
    "            ),\n",
    "        ),\n",
    "    ),\n",
    "    constraints=(MeanValue(model.pressure, 0.0),),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=TaylorHood()),\n",
    "    initial_guess={model.velocity: (0.0, 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": [
    "## Comparison with the Ghia-Ghia-Shin benchmark\n",
    "\n",
    "The horizontal velocity on the vertical centre line at the heights of the benchmark table."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "benchmark_y = np.array(\n",
    "    [\n",
    "        0.0000,\n",
    "        0.0547,\n",
    "        0.0625,\n",
    "        0.0703,\n",
    "        0.1016,\n",
    "        0.1719,\n",
    "        0.2813,\n",
    "        0.4531,\n",
    "        0.5000,\n",
    "        0.6172,\n",
    "        0.7344,\n",
    "        0.8516,\n",
    "        0.9531,\n",
    "        0.9609,\n",
    "        0.9688,\n",
    "        0.9766,\n",
    "        1.0000,\n",
    "    ]\n",
    ")\n",
    "benchmark_u = np.array(\n",
    "    [\n",
    "        0.00000,\n",
    "        -0.03717,\n",
    "        -0.04192,\n",
    "        -0.04775,\n",
    "        -0.06434,\n",
    "        -0.10150,\n",
    "        -0.15662,\n",
    "        -0.21090,\n",
    "        -0.20581,\n",
    "        -0.13641,\n",
    "        0.00332,\n",
    "        0.23151,\n",
    "        0.68717,\n",
    "        0.73722,\n",
    "        0.78871,\n",
    "        0.84123,\n",
    "        1.00000,\n",
    "    ]\n",
    ")\n",
    "u = (\n",
    "    velocity.evaluate(\n",
    "        np.column_stack((np.full_like(benchmark_y, side / 2), benchmark_y * side))\n",
    "    )[:, 0]\n",
    "    / lid_speed\n",
    ")\n",
    "\n",
    "print(\n",
    "    f\"Reynolds number: {fluid.density * lid_speed * side / fluid.dynamic_viscosity:.0f}\"\n",
    ")\n",
    "print(\"   y / L    benchmark   simulation\")\n",
    "for height, reference, value in zip(benchmark_y, benchmark_u, u):\n",
    "    print(f\"{height:8.4f} {reference:+12.5f} {value:+12.5f}\")\n",
    "print(\n",
    "    f\"largest deviation from the benchmark: {np.abs(u - benchmark_u).max():.4f} of the lid speed\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The speed in the cavity with the streamlines of the primary vortex, and the horizontal velocity\n",
    "on the vertical centre line against the benchmark."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "height = np.linspace(0.0, 1.0, 201)\n",
    "profile = (\n",
    "    velocity.evaluate(np.column_stack((np.full_like(height, side / 2), height * side)))[\n",
    "        :, 0\n",
    "    ]\n",
    "    / lid_speed\n",
    ")\n",
    "grid = np.linspace(0.0, side, 81)\n",
    "samples = velocity.evaluate(np.array([[a, b] for a in grid for b in grid])).reshape(\n",
    "    len(grid), len(grid), 2\n",
    ")\n",
    "fig = plots.figure(1, 2, size=(14, 6.2))\n",
    "plots.streamlines(\n",
    "    grid,\n",
    "    grid,\n",
    "    samples[..., 0],\n",
    "    samples[..., 1],\n",
    "    density=1.6,\n",
    "    label=\"speed [m/s]\",\n",
    "    title=\"Streamlines of the primary vortex, Re = 100\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\"simulation\": (profile, height)},\n",
    "    points={\"Ghia et al. (1982), Re = 100\": (benchmark_u, benchmark_y)},\n",
    "    vlines=0.0,\n",
    "    xlabel=\"horizontal velocity u_x / U\",\n",
    "    ylabel=\"vertical position y / L\",\n",
    "    title=\"Velocity on the vertical centre line\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the Reynolds number toward 400 or 1000 and refine the mesh; the primary vortex\n",
    "strengthens, its centre drifts, and secondary corner vortices grow, all of which the same\n",
    "benchmark tables document. The cubic cavity in three dimensions is the example\n",
    "`lid_driven_cube_3d`."
   ]
  }
 ]
}
