{
 "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": [
    "# Film flow down an inclined channel with side walls\n",
    "\n",
    "A liquid film of depth $H$ flows down an open channel of width $W$ that is inclined at the\n",
    "angle $\\beta$. The liquid sticks to the bottom and to both side walls; its flat free surface is\n",
    "free of shear stress. Coordinates: $x$ down the channel, $y\\in[0,W]$ across, $z\\in[0,H]$ from the\n",
    "bottom to the surface.\n",
    "\n",
    "The film comes from CAD files, one for each channel width: `film_flow_side_walls_3d.step`\n",
    "($W=8$ mm, $W/H=4$) and `film_flow_side_walls_3d_1mm.step`, `..._2mm.step`, `..._4mm.step` and\n",
    "`..._16mm.step`. Each holds a short slab of the film with the bottom `z_min`, the free surface\n",
    "`z_max` and the side walls `y_min` and `y_max`. The script `film_flow_side_walls_3d_geometry.py`\n",
    "builds them with the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference.** Far from the inlet the flow obeys $\\mu\\nabla^2u=-\\rho g\\sin\\beta$ on the\n",
    "cross-section. With $\\lambda_n=(2n+1)\\pi/(2H)$ the solution is the series (White, *Viscous Fluid\n",
    "Flow*)\n",
    "\n",
    "$$u(y,z)=\\frac{\\rho g\\sin\\beta}{\\mu}\\left[Hz-\\frac{z^2}{2}-\\sum_{n=0}^{\\infty}\\frac{2}{H\\lambda_n^3}\n",
    "  \\sin(\\lambda_n z)\\,\\frac{\\cosh\\lambda_n(y-W/2)}{\\cosh(\\lambda_n W/2)}\\right],\\qquad\n",
    "  \\frac{Q}{W\\,q_N}=1-\\frac{12H}{W}\\sum_{n=0}^{\\infty}\\frac{\\tanh(\\lambda_n W/2)}{(\\lambda_n H)^5} .$$\n",
    "\n",
    "$q_N=\\rho g\\sin\\beta\\,H^3/(3\\mu)$ is the flow rate per width of the Nusselt film without side\n",
    "walls."
   ]
  },
  {
   "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 (\n",
    "    PeriodicPair,\n",
    "    StructuredHexahedralMesher,\n",
    "    StructuredTetrahedralMesher,\n",
    ")\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fdm import CentralDifference, CentralLaplacian, FiniteDifference\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",
    "    FlowTraction,\n",
    "    IncompressibleNavierStokes,\n",
    "    NoSlipWall,\n",
    ")\n",
    "from onesim.results.integration import mean_value\n",
    "from onesim.simulation import PeriodicBoundary, Problem, Simulation\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 five films, keyed by their aspect ratio $W/H$, and the finite-element mesh of the film with\n",
    "$W/H=4$: one cell along the channel, 16 over the depth."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "film = load(\"film_flow_side_walls_3d.step\")\n",
    "length, width, depth = film.size\n",
    "films = {\n",
    "    0.5: load(\"film_flow_side_walls_3d_1mm.step\"),\n",
    "    1.0: load(\"film_flow_side_walls_3d_2mm.step\"),\n",
    "    2.0: load(\"film_flow_side_walls_3d_4mm.step\"),\n",
    "    4.0: film,\n",
    "    8.0: load(\"film_flow_side_walls_3d_16mm.step\"),\n",
    "}\n",
    "\n",
    "view = plots.Camera(elevation=28, azimuth=-35)\n",
    "fig = plots.figure(1, 2, size=(14, 5))\n",
    "plots.geometry(\n",
    "    film,\n",
    "    selection={\n",
    "        \"bottom and side walls\": film.boundaries.z_min\n",
    "        | film.boundaries.y_min\n",
    "        | film.boundaries.y_max,\n",
    "        \"free surface\": film.boundaries.z_max,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Slab of the film, W/H = 4\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "mesh = StructuredTetrahedralMesher(cells=(1, 64, 16)).generate(film)\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{mesh.cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Both methods solve the full Navier-Stokes equations on the slab, whose upstream and downstream\n",
    "faces are joined by a periodic condition. Gravity acts as a body force."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "tilt = np.deg2rad(10.0)\n",
    "oil = NewtonianFluid(density=1200.0, dynamic_viscosity=0.10)\n",
    "drive = oil.density * 9.81 * np.sin(tilt)\n",
    "nusselt_rate = drive * depth**3 / (3 * oil.dynamic_viscosity)\n",
    "nusselt_speed = drive * depth**2 / (2 * oil.dynamic_viscosity)\n",
    "methods = {\n",
    "    \"Taylor-Hood finite elements\": (\n",
    "        FiniteElement(element=TaylorHood()),\n",
    "        StructuredTetrahedralMesher,\n",
    "        1,\n",
    "    ),\n",
    "    \"staggered finite differences\": (\n",
    "        FiniteDifference(gradient=CentralDifference(), diffusion=CentralLaplacian()),\n",
    "        StructuredHexahedralMesher,\n",
    "        5,\n",
    "    ),\n",
    "}\n",
    "\n",
    "\n",
    "def solve(method, channel, cells):\n",
    "    \"\"\"Velocity field in a channel with `cells` cells over the depth of the film.\"\"\"\n",
    "    spatial, mesher, along = methods[method]\n",
    "    faces = channel.boundaries\n",
    "    model = IncompressibleNavierStokes(\n",
    "        domain=channel.volume,\n",
    "        material=oil,\n",
    "        body_force=lambda x, y, z: np.column_stack(\n",
    "            (\n",
    "                np.full(len(x), drive),\n",
    "                np.zeros(len(x)),\n",
    "                np.full(len(x), -oil.density * 9.81 * np.cos(tilt)),\n",
    "            )\n",
    "        ),\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"Film flow in an inclined channel\",\n",
    "        geometry=channel,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            NoSlipWall(boundary=faces.z_min | faces.y_min | faces.y_max, physics=model),\n",
    "            FlowTraction(boundary=faces.z_max, physics=model, value=(0.0, 0.0, 0.0)),\n",
    "            PeriodicBoundary(\n",
    "                pair=PeriodicPair(first=faces.x_min, second=faces.x_max), physics=model\n",
    "            ),\n",
    "        ),\n",
    "        initial_conditions=(InitialValue(model.velocity, (0.0, 0.0, 0.0)),),\n",
    "    )\n",
    "    numerics = Numerics(\n",
    "        spatial=spatial,\n",
    "        initial_guess={model.velocity: (0.0, 0.0, 0.0)},\n",
    "        nonlinear_solver=Newton(\n",
    "            linear_solver=SparseDirect(),\n",
    "            absolute_tolerance=1e-12,\n",
    "            relative_tolerance=1e-10,\n",
    "        ),\n",
    "    )\n",
    "    mesh = mesher(\n",
    "        cells=(along, round(channel.size[1] / depth * cells), cells)\n",
    "    ).generate(channel)\n",
    "    return (\n",
    "        Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "        .solve_stationary()\n",
    "        .field(model.velocity)\n",
    "    )\n",
    "\n",
    "\n",
    "flows = {\n",
    "    aspect: solve(\"Taylor-Hood finite elements\", channel, 16)\n",
    "    for aspect, channel in films.items()\n",
    "}\n",
    "studies = {\n",
    "    \"Taylor-Hood finite elements\": (4, 8, 16),\n",
    "    \"staggered finite differences\": (8, 16, 32),\n",
    "}\n",
    "surface_speeds = {\n",
    "    method: [\n",
    "        solve(method, film, cells).evaluate([[length / 2, width / 2, depth]])[0, 0]\n",
    "        for cells in levels\n",
    "    ]\n",
    "    for method, levels in studies.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The flow does not change along the channel, so the flow rate is the mean velocity times the\n",
    "cross-section. Relative to the Nusselt film, narrow channels carry far less. The mesh study\n",
    "compares the speed at the middle of the free surface for both methods."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "k = (2 * np.arange(400) + 1) * np.pi / 2\n",
    "exact_rate = lambda aspect: 1 - 12 / aspect * np.sum(np.tanh(k * aspect / 2) / k**5)\n",
    "exact_surface_speed = (\n",
    "    2\n",
    "    * nusselt_speed\n",
    "    * (\n",
    "        0.5\n",
    "        - np.sum(\n",
    "            2 / k[:50] ** 3 * np.sin(k[:50]) / np.cosh(k[:50] * width / (2 * depth))\n",
    "        )\n",
    "    )\n",
    ")\n",
    "rates = {\n",
    "    aspect: mean_value(flow, component=0) * depth / nusselt_rate\n",
    "    for aspect, flow in flows.items()\n",
    "}\n",
    "errors = {\n",
    "    method: np.abs(np.array(speeds) / exact_surface_speed - 1)\n",
    "    for method, speeds in surface_speeds.items()\n",
    "}\n",
    "\n",
    "print(\" W/H   flow rate / (W q_N)   exact series   deviation\")\n",
    "for aspect, rate in rates.items():\n",
    "    print(\n",
    "        f\"{aspect:4.1f} {rate:18.6f} {exact_rate(aspect):14.6f} {rate / exact_rate(aspect) - 1:+11.1e}\"\n",
    "    )\n",
    "for method, levels in studies.items():\n",
    "    print(\n",
    "        f\"{method}, W/H = 4, {levels} cells over the depth: surface-speed error \"\n",
    "        + \", \".join(f\"{e:.1e}\" for e in errors[method])\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The velocity over the cross-section for $W/H=4$, the flow rate against the channel width, and\n",
    "the mesh study of both methods."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "wide = np.geomspace(0.25, 20, 200)\n",
    "fig = plots.figure(layout=[[\"field\", \"field\"], [\"rate\", \"study\"]], size=(13, 9))\n",
    "plots.section(\n",
    "    flows[4.0],\n",
    "    plane=Plane(origin=(length / 2, 0, 0), normal=(1, 0, 0)),\n",
    "    component=lambda u, position: u[:, 0] / nusselt_speed,\n",
    "    limits=(0, 1),\n",
    "    contours=9,\n",
    "    subdivisions=2,\n",
    "    label=\"u / surface speed of the Nusselt film\",\n",
    "    xlabel=\"y across the channel [m]\",\n",
    "    ylabel=\"z above the bottom [m]\",\n",
    "    title=\"Velocity down the channel, W/H = 4\",\n",
    "    ax=fig[\"field\"],\n",
    ")\n",
    "plots.line(\n",
    "    wide,\n",
    "    {\"exact series\": [exact_rate(aspect) for aspect in wide]},\n",
    "    points={\"finite elements\": (list(rates), list(rates.values()))},\n",
    "    scale=\"logx\",\n",
    "    ylimits=(0, 1.02),\n",
    "    xlabel=\"aspect ratio W/H\",\n",
    "    ylabel=\"flow rate / (W q_N)\",\n",
    "    title=\"Side walls reduce the flow rate\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[\"rate\"],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        method: ([1 / cells for cells in levels], errors[method])\n",
    "        for method, levels in studies.items()\n",
    "    },\n",
    "    markers=True,\n",
    "    scale=\"loglog\",\n",
    "    xlabel=\"cell size / depth\",\n",
    "    ylabel=\"relative error of the surface speed\",\n",
    "    title=\"Mesh study, W/H = 4\",\n",
    "    ax=fig[\"study\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add a width to `film_flow_side_walls_3d_geometry.py` and write the STEP files again. Tilt the\n",
    "channel further and the film speeds up with $\\sin\\beta$; a shear stress on the free surface\n",
    "(wind) changes the profile near the surface."
   ]
  }
 ]
}
