{
 "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": [
    "# Boundary layer meshing\n",
    "\n",
    "Near a wall the velocity of a flow rises from zero to the free-stream value within a thin\n",
    "boundary layer, and the temperature does the same in a thermal layer. Cells that are thin across\n",
    "the wall and wide along it resolve those gradients at a fraction of the cost of small isotropic\n",
    "cells. `BoundaryLayers(walls=..., ...)` inserts such layers into a tetrahedral mesh: every\n",
    "triangle of the wall is extruded into a stack of prisms, each split into three tetrahedra, and the\n",
    "mesh behind is pushed back.\n",
    "\n",
    "| stated by | keywords | layer heights |\n",
    "|---|---|---|\n",
    "| count, first height, growth | `count, first_height, growth` | $h_k = h_1 q^{k-1}$ |\n",
    "| count, total thickness, growth | `count, thickness, growth` | $h_1 = H (q-1)/(q^n-1)$ |\n",
    "| first height, growth, last height | `first_height, growth, last_height` | as many as fit below $h_\\text{last}$ |\n",
    "| count, first height, transition | `count, first_height, transition` | last layer a share of the cells behind |\n",
    "| explicit heights | `heights` | as given |\n",
    "\n",
    "Where the layers of two walls would collide in a narrow gap, `on_collision=\"compress\"` lowers\n",
    "all layers there and `\"step\"` leaves out the outer ones.\n",
    "\n",
    "**Reference.** The geometric series of the stated layers, and the first height for a wall\n",
    "distance $y^+$ from the skin friction of a turbulent flat plate,\n",
    "$c_f = 0.0592\\,Re_L^{-1/5}$, $u_\\tau = U\\sqrt{c_f/2}$, $h_1 = 2\\,y^+\\nu/u_\\tau$ (the first cell\n",
    "centre at $y^+$; H. Schlichting, K. Gersten, *Boundary-Layer Theory*, 9th ed., Springer 2017,\n",
    "ch. 18)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d3 import Box, Cylinder\n",
    "from onesim.meshing import BoundaryLayers, TetrahedralMesher, first_layer_height\n",
    "from onesim.meshing.quality import quality\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The flow domain\n",
    "\n",
    "A duct of 200 x 80 x 40 mm with a cylinder of 20 mm diameter across it, 60 mm from the inlet.\n",
    "Its wall is `obstacle.outer_wall`; the duct walls are `y_min`, `y_max`."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "length, width, depth, radius = 0.2, 0.08, 0.04, 0.01\n",
    "fluid = Box(length=length, width=width, height=depth) - Cylinder(\n",
    "    radius=radius, length=depth, origin=(0.06, width / 2, 0.0)\n",
    ").named(\"obstacle\")\n",
    "walls = (\n",
    "    fluid.boundaries[\"obstacle.outer_wall\"]\n",
    "    | fluid.boundaries.y_min\n",
    "    | fluid.boundaries.y_max\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Five ways to state the layers\n",
    "\n",
    "All five below describe the same four layers of 1, 1.5, 2.25 and 3.375 mm, thick enough to be\n",
    "seen in the figures, or come as close as their keywords allow."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "stated = {\n",
    "    \"count, first height, growth\": BoundaryLayers(\n",
    "        walls=walls, count=4, first_height=1e-3, growth=1.5\n",
    "    ),\n",
    "    \"count, thickness, growth\": BoundaryLayers(\n",
    "        walls=walls, count=4, thickness=8.125e-3, growth=1.5\n",
    "    ),\n",
    "    \"first height, growth, last height\": BoundaryLayers(\n",
    "        walls=walls, first_height=1e-3, growth=1.5, last_height=3.5e-3\n",
    "    ),\n",
    "    \"count, first height, thickness\": BoundaryLayers(\n",
    "        walls=walls, count=4, first_height=1e-3, thickness=8.125e-3\n",
    "    ),\n",
    "    \"explicit heights\": BoundaryLayers(\n",
    "        walls=walls, heights=(1e-3, 1.5e-3, 2.25e-3, 3.375e-3)\n",
    "    ),\n",
    "}\n",
    "series = 1e-3 * 1.5 ** np.arange(4)\n",
    "for name, layers in stated.items():\n",
    "    print(\n",
    "        f\"{name:34s} {', '.join(f'{1e3 * h:.4f}' for h in layers.layer_heights())} mm\"\n",
    "    )\n",
    "print(\n",
    "    f\"{'geometric series h1 q^(k-1)':34s} {', '.join(f'{1e3 * h:.4f}' for h in series)} mm\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## First height from y+\n",
    "\n",
    "Air at 10 m/s along a wall of 0.2 m, $y^+ = 1$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "viscosity, speed = 1.5e-5, 10.0\n",
    "friction = lambda U, L: U * np.sqrt(0.0592 * (U * L / viscosity) ** -0.2 / 2)\n",
    "print(\n",
    "    f\"first height for y+ = 1: library {first_layer_height(1.0, kinematic_viscosity=viscosity, velocity=speed, length=length) * 1e6:.3f} um, \"\n",
    "    f\"flat-plate formula {2 * viscosity / friction(speed, length) * 1e6:.3f} um\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The layered mesh\n",
    "\n",
    "The first statement on all three walls; the mesh behind has cells of 5 mm. Away from corners every\n",
    "layer has its stated height; where the cylinder meets the floor and the lid, and where the duct\n",
    "walls meet them, the columns of the layers lean and are shortened, which lowers the mean."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "layers = stated[\"count, first height, growth\"]\n",
    "plain = TetrahedralMesher(target_size=0.005).generate(fluid)\n",
    "mesh = TetrahedralMesher(target_size=0.005, boundary_layers=(layers,)).generate(fluid)\n",
    "report = mesh.layer_report\n",
    "wall_triangles = sum(\n",
    "    len(plain.facets(fluid.boundaries[name]))\n",
    "    for name in (\"obstacle.outer_wall\", \"y_min\", \"y_max\")\n",
    ")\n",
    "print(\n",
    "    f\"cells: {plain.cell_count} without layers, {mesh.cell_count} with; cells per layer \"\n",
    "    f\"{np.bincount(mesh.cell_layers)[1:].tolist()} (3 x {wall_triangles} wall triangles = {3 * wall_triangles})\"\n",
    ")\n",
    "print(\"layer   stated [mm]   measured largest [mm]   mean [mm]\")\n",
    "for index, (height, item) in enumerate(\n",
    "    zip(layers.layer_heights(), report[\"layer_heights\"]), start=1\n",
    "):\n",
    "    print(\n",
    "        f\"{index:5d} {1e3 * height:12.4f} {1e3 * item['maximum']:20.4f} {1e3 * item['mean']:11.4f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"volume: plain mesh {quality(plain)['size'].sum() * 1e6:.4f} cm3, layered mesh {quality(mesh)['size'].sum() * 1e6:.4f} cm3, \"\n",
    "    f\"CAD {fluid.measure * 1e6:.4f} cm3\"\n",
    ")\n",
    "\n",
    "view = plots.Camera(elevation=30, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(17, 6))\n",
    "plots.geometry(\n",
    "    fluid,\n",
    "    selection={\"walls with layers\": walls},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Duct with a cylinder\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    cell_values=mesh.cell_layers,\n",
    "    limits=(0, 4),\n",
    "    plane=((0.06, width / 2, depth / 2), (0.0, 0.0, 1.0)),\n",
    "    label=\"layer (0 = core)\",\n",
    "    camera=plots.Camera(elevation=70, azimuth=-90),\n",
    "    title=f\"Four layers on three walls: {mesh.cell_count} cells\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Narrow gaps\n",
    "\n",
    "Moved to 3 mm from the wall `y_min`, the cylinder leaves too little room for five layers of\n",
    "0.6 mm growing by 1.3 (5.4 mm in all). Compressed, every layer in the gap becomes thinner;\n",
    "stepped, the outer layers end and the first height stays."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "near = Box(length=length, width=width, height=depth) - Cylinder(\n",
    "    radius=radius, length=depth, origin=(0.06, radius + 0.003, 0.0)\n",
    ").named(\"obstacle\")\n",
    "near_walls = near.boundaries[\"obstacle.outer_wall\"] | near.boundaries.y_min\n",
    "gaps = {\n",
    "    mode: TetrahedralMesher(\n",
    "        target_size=0.005,\n",
    "        boundary_layers=(\n",
    "            BoundaryLayers(\n",
    "                walls=near_walls,\n",
    "                count=5,\n",
    "                first_height=6e-4,\n",
    "                growth=1.3,\n",
    "                on_collision=mode,\n",
    "            ),\n",
    "        ),\n",
    "    ).generate(near)\n",
    "    for mode in (\"compress\", \"step\")\n",
    "}\n",
    "for mode, gap_mesh in gaps.items():\n",
    "    gap_report = gap_mesh.layer_report\n",
    "    print(\n",
    "        f\"{mode:8s}: {gap_mesh.cell_count} cells, compressed points {gap_report['compressed_point_count']}, \"\n",
    "        f\"first layer mean {1e3 * gap_report['layer_heights'][0]['mean']:.4f} mm, smallest shape {quality(gap_mesh)['shape'].min():.3f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The gap between cylinder and wall cut at mid-depth, with the layers compressed and stepped down."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "close = plots.Camera(elevation=80, azimuth=-90)\n",
    "fig = plots.figure(1, 2, size=(17, 6))\n",
    "for index, (mode, gap_mesh) in enumerate(gaps.items()):\n",
    "    plots.mesh(\n",
    "        gap_mesh,\n",
    "        cell_values=gap_mesh.cell_layers,\n",
    "        limits=(0, 5),\n",
    "        plane=((0.06, 0.006, depth / 2), (0.0, 0.0, 1.0)),\n",
    "        label=\"layer (0 = core)\",\n",
    "        camera=close,\n",
    "        title=f\"on_collision='{mode}'\",\n",
    "        ax=fig[index],\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Size the layers for a turbulent wall with `wall_layers(walls, velocity=..., length=...,\n",
    "kinematic_viscosity=...)`, put layers on a planar mesh (`TriangularMesher(boundary_layers=...)`),\n",
    "or solve the flow round the cylinder on `mesh` with `onesim.physics.hydrodynamics`."
   ]
  }
 ]
}
