{
 "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 cubic cavity in three dimensions\n",
    "\n",
    "A cube of side $L$ is filled with an incompressible fluid. Its top face (the lid, $y=L$) slides\n",
    "in the $x$-direction with the speed $U$; the other five faces are fixed walls. The Reynolds\n",
    "number is $Re=\\rho UL/\\mu$. Unlike in the two-dimensional cavity, the end walls $z=0$ and $z=L$\n",
    "brake the vortex, and fluid spirals along the vortex axis.\n",
    "\n",
    "The flow is mirror-symmetric about the mid-plane $z=L/2$, so the half cube is computed with a\n",
    "free-slip condition on that plane. It comes from the CAD file `lid_driven_cube_3d.step`: the lid\n",
    "is the face `y_max`, the mid-plane `z_max`. The script `lid_driven_cube_3d_geometry.py` builds it\n",
    "with the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference.** Oueslati, Ben Beya and Lili (*Comptes Rendus Mécanique* 339, 2011) report the\n",
    "extreme velocities on the two centre lines of the mid-plane: the minimum of $u$ along the\n",
    "vertical line and the minimum of $v$ along the horizontal line, with their positions."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import NewtonianFluid\n",
    "from onesim.meshing import StructuredHexahedralMesher, Tanh\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",
    "    FreeSlipLaw,\n",
    "    IncompressibleNavierStokes,\n",
    "    NoSlipWall,\n",
    "    WallShear,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.field_constraints import MeanValue\n",
    "from onesim.simulation.initial_conditions import InitialValue\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 mesh is graded towards all walls, not towards the mid-plane."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "half_cube = load(\"lid_driven_cube_3d.step\")\n",
    "faces = half_cube.boundaries\n",
    "side, _, half = half_cube.size\n",
    "cells = 14\n",
    "mesh = StructuredHexahedralMesher(\n",
    "    cells=(cells, cells, cells // 2),\n",
    "    grading=(Tanh(cells, 1.2), Tanh(cells, 1.2), Tanh(cells // 2, 1.2, toward=\"start\")),\n",
    ").generate(half_cube)\n",
    "\n",
    "view = plots.Camera(elevation=24, azimuth=-58, up=\"y\")\n",
    "fig = plots.figure(1, 2, size=(13, 6))\n",
    "plots.geometry(\n",
    "    half_cube,\n",
    "    selection={\"lid\": faces.y_max, \"mid-plane\": faces.z_max},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Half cube with its lid and mid-plane\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{mesh.cell_count} hexahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The lid speed falls to zero over the last 36 mm before the walls it meets, so the velocity stays\n",
    "continuous in the corners. Newton's method solves the stationary Navier-Stokes equations; the\n",
    "run at $Re=400$ starts from the solution at $Re=100$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "published = {\n",
    "    100: {\"u_min\": -0.21361, \"y\": 0.47702, \"v_min\": -0.24971, \"x\": 0.81026},\n",
    "    400: {\"u_min\": -0.22979, \"y\": 0.22433, \"v_min\": -0.37685, \"x\": 0.87127},\n",
    "}\n",
    "flows, start = {}, (0.0, 0.0, 0.0)\n",
    "for reynolds in published:\n",
    "    model = IncompressibleNavierStokes(\n",
    "        domain=half_cube.volume,\n",
    "        material=NewtonianFluid(density=1.0, dynamic_viscosity=side / reynolds),\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"Lid-driven cube\",\n",
    "        geometry=half_cube,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            FixedVelocity(\n",
    "                boundary=faces.y_max,\n",
    "                physics=model,\n",
    "                value=lambda x, y, z: np.column_stack(\n",
    "                    (\n",
    "                        np.clip(np.minimum.reduce([x, side - x, z]) / 0.036, 0.0, 1.0),\n",
    "                        0 * x,\n",
    "                        0 * x,\n",
    "                    )\n",
    "                ),\n",
    "            ),\n",
    "            NoSlipWall(\n",
    "                boundary=faces.x_min | faces.x_max | faces.y_min | faces.z_min,\n",
    "                physics=model,\n",
    "            ),\n",
    "            WallShear(boundary=faces.z_max, physics=model, law=FreeSlipLaw()),\n",
    "        ),\n",
    "        constraints=(MeanValue(model.pressure, 0.0),),\n",
    "        initial_conditions=(InitialValue(model.velocity, (0.0, 0.0, 0.0)),),\n",
    "    )\n",
    "    numerics = Numerics(\n",
    "        spatial=FiniteElement(element=TaylorHood()),\n",
    "        initial_guess={model.velocity: start},\n",
    "        nonlinear_solver=Newton(\n",
    "            linear_solver=SparseDirect(),\n",
    "            absolute_tolerance=1e-9,\n",
    "            relative_tolerance=1e-9,\n",
    "            maximum_iterations=30,\n",
    "        ),\n",
    "    )\n",
    "    flows[reynolds] = previous = (\n",
    "        Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "        .solve_stationary()\n",
    "        .field(model.velocity)\n",
    "    )\n",
    "    start = lambda x, y, z: previous.evaluate(np.column_stack((x, y, z)))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The velocity on the two centre lines of the mid-plane and its extreme values."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "s = np.linspace(0, side, 401)\n",
    "middle = np.full_like(s, half)\n",
    "u = {\n",
    "    re: flow.evaluate(np.column_stack((middle, s, middle)))[:, 0]\n",
    "    for re, flow in flows.items()\n",
    "}\n",
    "v = {\n",
    "    re: flow.evaluate(np.column_stack((s, middle, middle)))[:, 1]\n",
    "    for re, flow in flows.items()\n",
    "}\n",
    "print(\" Re   quantity      simulation   published\")\n",
    "for re, reference in published.items():\n",
    "    values = {\n",
    "        \"u_min\": u[re].min(),\n",
    "        \"y\": s[u[re].argmin()],\n",
    "        \"v_min\": v[re].min(),\n",
    "        \"x\": s[v[re].argmin()],\n",
    "    }\n",
    "    for name, value in values.items():\n",
    "        print(f\"{re:4d}   {name:10s} {value:12.4f} {reference[name]:11.4f}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The speed on the mid-plane for both Reynolds numbers, and the centre-line profiles with the\n",
    "published extreme values."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "speed = lambda velocity, position: np.linalg.norm(velocity, axis=1)\n",
    "fig = plots.figure(1, 3, size=(17, 5.2))\n",
    "for panel, (re, flow) in zip((fig[0], fig[1]), flows.items()):\n",
    "    plots.section(\n",
    "        flow,\n",
    "        plane=Plane(origin=(0, 0, 0.9998 * half), normal=(0, 0, 1)),\n",
    "        component=speed,\n",
    "        limits=(0, 1),\n",
    "        contours=10,\n",
    "        subdivisions=3,\n",
    "        label=\"speed / lid speed\",\n",
    "        title=f\"Mid-plane, Re = {re}\",\n",
    "        ax=panel,\n",
    "    )\n",
    "plots.line(\n",
    "    y={f\"u along the vertical line, Re = {re}\": (u[re], s) for re in flows},\n",
    "    points={\n",
    "        \"published minima\": (\n",
    "            [published[re][\"u_min\"] for re in flows],\n",
    "            [published[re][\"y\"] for re in flows],\n",
    "        )\n",
    "    },\n",
    "    xlabel=\"u / lid speed\",\n",
    "    ylabel=\"y / L\",\n",
    "    title=\"Vertical centre line\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the Reynolds number in steps to 1000, each run starting from the previous one, and the\n",
    "corner vortices grow. Refine the mesh with `cells`, or make the box longer in $z$ in\n",
    "`lid_driven_cube_3d_geometry.py` and write the STEP file again to approach the two-dimensional\n",
    "cavity."
   ]
  }
 ]
}
