{
 "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": [
    "# Split-and-recombine mixer benchmark: layers, numerical and physical mixing\n",
    "\n",
    "Split-and-recombine (SAR) mixers are a standard test for the transport of a tracer at high Péclet\n",
    "numbers: each element doubles the number of layers, so after three elements two inlet streams have\n",
    "become sixteen layers an eighth of the original thickness, with steep gradients between them. A\n",
    "simulation then mixes the layers twice - physically by diffusion, and numerically by the\n",
    "discretization. The benchmark asks how much of the computed mixing is real.\n",
    "\n",
    "The mixer comes from the CAD file `split_recombine_mixer_benchmark.step`, written by\n",
    "`split_recombine_mixer_benchmark_geometry.py`: square channels of side $w=1$ mm with three elements\n",
    "4 mm long, walls 0.2 mm thick between the branches, 1 mm of inlet and 4 mm of outlet channel. Water\n",
    "flows at $\\bar U=1$ mm/s ($Re=1$). The tracer enters in the left half of the inlet.\n",
    "\n",
    "The finite-element advection used here is the plain Galerkin form, without streamline-upwind\n",
    "stabilization, so the cell Péclet number $Pe_h=\\bar Uh/D$ must stay moderate to avoid\n",
    "oscillations. The tracer diffusivity is therefore chosen for $Pe=\\bar Uw/D=100$, which gives\n",
    "$Pe_h\\approx30$ and 22 on the two meshes ($h=0.3$ and 0.22 mm). This is far from the nearly\n",
    "diffusion-free tracer of the original benchmark: at this Péclet number diffusion already blurs the\n",
    "layers of the second and third element, which are only 0.12 and 0.06 mm thick. A faithful\n",
    "near-zero-diffusion run needs a stabilized (streamline-upwind) or finite-volume tracer transport.\n",
    "\n",
    "| face | flow | tracer |\n",
    "|---|---|---|\n",
    "| `inlet` | fully developed duct profile, mean speed $\\bar U$ | $c=\\tfrac12\\left(1+\\tanh((w/2-y)/0.05\\,\\text{mm})\\right)$ |\n",
    "| `outlet` | traction free | no diffusive flux |\n",
    "| all walls | no slip | no flux |\n",
    "\n",
    "**Reference.** The layer count doubles in every element, $2^{n+1}$ after $n$ elements (V. Hessel,\n",
    "H. Löwe, F. Schönfeld, *Chem. Eng. Sci.* 60, 2479-2501, 2005), as long as diffusion does not blur\n",
    "them. The tracer that enters must leave. The difference between the meshes bounds the error of\n",
    "the discretization in the mixing index."
   ]
  },
  {
   "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 IsotropicSolid, NewtonianFluid\n",
    "from onesim.meshing import TetrahedralMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, GalerkinAdvection, Lagrange, TaylorHood\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import Newton\n",
    "from onesim.physics.heat_transfer import (\n",
    "    ConvectiveHeatTransfer,\n",
    "    FixedTemperature,\n",
    "    HeatFlux,\n",
    ")\n",
    "from onesim.physics.hydrodynamics import (\n",
    "    FixedVelocity,\n",
    "    FlowTraction,\n",
    "    IncompressibleNavierStokes,\n",
    "    NoSlipWall,\n",
    "    fully_developed_inflow,\n",
    ")\n",
    "from onesim.results.derived import derived_field\n",
    "from onesim.results.sampling import field_function\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",
    "Tetrahedra of 0.3 mm and 0.22 mm; `split_boundary_cells` divides the cells whose corners all lie\n",
    "on walls."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mm = 1e-3\n",
    "mixer = load(\"split_recombine_mixer_benchmark.step\")\n",
    "faces = mixer.boundaries\n",
    "walls = faces.all - faces.inlet - faces.outlet\n",
    "side, length = mixer.size[1], mixer.size[0]\n",
    "meshes = {\n",
    "    size: TetrahedralMesher(target_size=size * mm, split_boundary_cells=True).generate(\n",
    "        mixer\n",
    "    )\n",
    "    for size in (0.3, 0.22)\n",
    "}\n",
    "\n",
    "view = plots.Camera(elevation=30, azimuth=-55)\n",
    "fig = plots.figure(1, 2, size=(16, 5.5))\n",
    "plots.geometry(\n",
    "    mixer,\n",
    "    selection={\"inlet\": faces.inlet, \"outlet\": faces.outlet},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Three split-and-recombine elements\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0.22],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{meshes[0.22].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Flow and tracer"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "water, speed = NewtonianFluid(density=1000.0, dynamic_viscosity=1.0e-3), 1e-3\n",
    "tracer = IsotropicSolid(\n",
    "    density=1.0,\n",
    "    specific_heat_capacity=1.0,\n",
    "    thermal_conductivity=speed * side / 100,\n",
    "    youngs_modulus=1.0,\n",
    "    poisson_ratio=0.3,\n",
    "    thermal_expansion_coefficient=0.0,\n",
    ")\n",
    "flows, tracers = {}, {}\n",
    "for size, mesh in meshes.items():\n",
    "    flow = IncompressibleNavierStokes(domain=mixer.volume, material=water)\n",
    "    problem = Problem(\n",
    "        name=\"SAR benchmark: flow\",\n",
    "        geometry=mixer,\n",
    "        physics=(flow,),\n",
    "        boundary_conditions=(\n",
    "            FixedVelocity(\n",
    "                boundary=faces.inlet,\n",
    "                physics=flow,\n",
    "                value=fully_developed_inflow(\n",
    "                    mesh, faces.inlet, mean_velocity=speed, no_slip=walls\n",
    "                ),\n",
    "            ),\n",
    "            FlowTraction(boundary=faces.outlet, physics=flow, value=(0.0, 0.0, 0.0)),\n",
    "            NoSlipWall(boundary=walls, physics=flow),\n",
    "        ),\n",
    "    )\n",
    "    numerics = Numerics(\n",
    "        spatial=FiniteElement(element=TaylorHood()),\n",
    "        initial_guess={flow.velocity: (0.0, 0.0, 0.0)},\n",
    "        nonlinear_solver=Newton(\n",
    "            linear_solver=SparseDirect(),\n",
    "            absolute_tolerance=1e-20,\n",
    "            relative_tolerance=1e-9,\n",
    "        ),\n",
    "    )\n",
    "    flows[size] = (\n",
    "        Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "        .solve_stationary()\n",
    "        .field(flow.velocity)\n",
    "    )\n",
    "    transport = ConvectiveHeatTransfer(\n",
    "        domain=mixer.volume, material=tracer, velocity=field_function(flows[size])\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"SAR benchmark: tracer\",\n",
    "        geometry=mixer,\n",
    "        physics=(transport,),\n",
    "        boundary_conditions=(\n",
    "            FixedTemperature(\n",
    "                physics=transport,\n",
    "                boundary=faces.inlet,\n",
    "                value=lambda y: 0.5 * (1 + np.tanh((side / 2 - y) / (0.05 * mm))),\n",
    "            ),\n",
    "            HeatFlux(physics=transport, boundary=faces.all - faces.inlet, value=0.0),\n",
    "        ),\n",
    "    )\n",
    "    numerics = Numerics(\n",
    "        spatial=FiniteElement(\n",
    "            element=Lagrange(order=2), convection=GalerkinAdvection()\n",
    "        ),\n",
    "        linear_solver=SparseDirect(),\n",
    "    )\n",
    "    tracers[size] = (\n",
    "        Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "        .solve_stationary()\n",
    "        .field(transport.temperature)\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Behind each element the tracer is sampled across the channel at mid-height; the layers are the\n",
    "sign changes of $c-\\bar c$. The mixing index $1-\\sigma/\\sigma_0$ uses the flow-weighted standard\n",
    "deviation on full cross-sections of the joined channel."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "across = np.column_stack(\n",
    "    (np.zeros(401), np.linspace(0.02, 0.98, 401) * side, np.full(401, side / 2))\n",
    ")\n",
    "behind = {0: 0.5 * mm, 1: 4.6 * mm, 2: 8.6 * mm, 3: 12.6 * mm}\n",
    "profiles = {\n",
    "    (size, n): np.ravel(c.evaluate(across + (x, 0, 0)))\n",
    "    for size, c in tracers.items()\n",
    "    for n, x in behind.items()\n",
    "}\n",
    "layers = {\n",
    "    key: int(np.count_nonzero(np.diff(np.sign(profile - profile.mean())))) + 1\n",
    "    for key, profile in profiles.items()\n",
    "}\n",
    "grid_y, grid_z = np.meshgrid(\n",
    "    np.linspace(0.04, 0.96, 24) * side, np.linspace(0.04, 0.96, 24) * side\n",
    ")\n",
    "section = lambda x: np.column_stack(\n",
    "    (np.full(grid_y.size, x), grid_y.ravel(), grid_z.ravel())\n",
    ")\n",
    "sample = lambda size, x: (\n",
    "    np.ravel(tracers[size].evaluate(section(x))),\n",
    "    flows[size].evaluate(section(x))[:, 0],\n",
    ")\n",
    "deviation = lambda values, weights: np.sqrt(\n",
    "    np.average((values - np.average(values, weights=weights)) ** 2, weights=weights)\n",
    ")\n",
    "mixing = {\n",
    "    (size, n): 1 - deviation(*sample(size, x)) / deviation(*sample(size, behind[0]))\n",
    "    for size in meshes\n",
    "    for n, x in behind.items()\n",
    "}\n",
    "flux = (\n",
    "    lambda size, face: derived_field(\n",
    "        flows[size],\n",
    "        lambda u, points, c=tracers[size]: np.ravel(c.evaluate(points)) * u[:, 0],\n",
    "        name=\"tracer_flux\",\n",
    "        unit=\"1\",\n",
    "    )\n",
    "    .integrate(boundary=face)\n",
    "    .value\n",
    ")\n",
    "\n",
    "print(\"elements passed            0      1      2      3\")\n",
    "print(\"layers, doubling law  \" + \" \".join(f\"{2 ** (n + 1):6d}\" for n in behind))\n",
    "for size in meshes:\n",
    "    print(\n",
    "        f\"layers, h = {size} mm  \" + \" \".join(f\"{layers[size, n]:6d}\" for n in behind)\n",
    "    )\n",
    "for size in meshes:\n",
    "    print(\n",
    "        f\"mixing index, h = {size} mm \"\n",
    "        + \" \".join(f\"{mixing[size, n]:6.3f}\" for n in behind)\n",
    "        + f\"   tracer balance {flux(size, faces.outlet) / flux(size, faces.inlet) - 1:+.1e}, cell Péclet {100 * size * mm / side:.0f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"mixing index after three elements: difference between the meshes {mixing[0.22, 3] - mixing[0.3, 3]:+.3f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The tracer on cross-sections behind each element, and the profiles across the channel at\n",
    "mid-height on both meshes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(\n",
    "    layout=[[\"e0\", \"e1\", \"e2\", \"e3\"], [\"profiles\", \"profiles\", \"profiles\", \"profiles\"]],\n",
    "    size=(18, 10),\n",
    ")\n",
    "for n, x in behind.items():\n",
    "    plots.section(\n",
    "        tracers[0.22],\n",
    "        plane=Plane(origin=(x, 0, 0), normal=(1, 0, 0)),\n",
    "        aspect=1.0,\n",
    "        limits=(0.0, 1.0),\n",
    "        subdivisions=2,\n",
    "        label=\"tracer c\",\n",
    "        title=f\"after {n} elements: {layers[0.22, n]} layers\",\n",
    "        ax=fig[f\"e{n}\"],\n",
    "    )\n",
    "plots.line(\n",
    "    across[:, 1] / mm,\n",
    "    {f\"after {n} elements, h = 0.22 mm\": profiles[0.22, n] for n in (1, 2, 3)},\n",
    "    points={\n",
    "        f\"after 3 elements, h = 0.3 mm\": (across[::8, 1] / mm, profiles[0.3, 3][::8])\n",
    "    },\n",
    "    ylimits=(-0.05, 1.05),\n",
    "    xlabel=\"y across the channel [mm]\",\n",
    "    ylabel=\"tracer c at mid-height\",\n",
    "    title=\"Layers across the channel\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[\"profiles\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the Péclet number together with a finer mesh in `split_recombine_mixer_benchmark.py`, keeping\n",
    "the cell Péclet number moderate: the layers then stay sharp longer, and the numerical share of the\n",
    "mixing shrinks with the cell size."
   ]
  }
 ]
}
