{
 "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 micromixer\n",
    "\n",
    "Without turbulence, two liquids in a microchannel mix only by diffusion across their interface.\n",
    "Split-and-recombine (SAR) mixers speed this up geometrically: each element cuts the stream into\n",
    "an upper and a lower half, squeezes the upper half into the left and the lower half into the right\n",
    "part of the channel, stretches both back to full height and joins them side by side. The two\n",
    "layers become four after the first element and eight after the second, and the diffusion distance\n",
    "halves each time (multilamination).\n",
    "\n",
    "The mixer comes from the CAD file `split_recombine_micromixer.step`, written by\n",
    "`split_recombine_micromixer_geometry.py`: square channels of side $w=1$ mm, two elements 4 mm long\n",
    "whose branches are separated by walls 0.2 mm thick, an inlet section of 1 mm and an outlet section\n",
    "of 4 mm. Water enters at the mean speed $\\bar U=1$ mm/s ($Re=1$); the left half carries the solute.\n",
    "The diffusivity gives the Péclet number $Pe=\\bar Uw/D=100$.\n",
    "\n",
    "$$-\\nabla p+\\mu\\nabla^2\\mathbf u=0,\\quad\\nabla\\cdot\\mathbf u=0,\\qquad\\mathbf u\\cdot\\nabla c=D\\nabla^2c$$\n",
    "\n",
    "| face | flow | solute |\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.** In the straight outlet section the flow is the fully developed flow in a square\n",
    "duct, whose pressure gradient is exact: $dp/dx=-12\\,\\mu Q/(0.4217\\,w^4)$ (F. M. White, *Viscous\n",
    "Fluid Flow*, section 3-3). Water and solute that enter must leave. The layer count must double in\n",
    "every element (V. Hessel, H. Löwe, F. Schönfeld, \"Micromixers - a review on passive and active\n",
    "mixing principles\", *Chem. Eng. Sci.* 60, 2479-2501, 2005)."
   ]
  },
  {
   "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.25 mm and, for the mesh study, 0.2 mm. `split_boundary_cells` divides the few cells\n",
    "whose four corners all lie on walls, where the quadratic velocity would have no free node."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mm = 1e-3\n",
    "mixer = load(\"split_recombine_micromixer.step\")\n",
    "faces = mixer.boundaries\n",
    "walls = faces.all - faces.inlet - faces.outlet\n",
    "side = mixer.size[1]\n",
    "meshes = {\n",
    "    size: TetrahedralMesher(target_size=size * mm, split_boundary_cells=True).generate(\n",
    "        mixer\n",
    "    )\n",
    "    for size in (0.25, 0.2)\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=\"Two split-and-recombine elements\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0.2],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{meshes[0.2].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Flow and solute\n",
    "\n",
    "The creeping flow on each mesh, then the solute in it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "water, speed = NewtonianFluid(density=1000.0, dynamic_viscosity=1.0e-3), 1e-3\n",
    "solute = 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, concentrations = {}, {}\n",
    "for size, mesh in meshes.items():\n",
    "    flow = IncompressibleNavierStokes(domain=mixer.volume, material=water)\n",
    "    problem = Problem(\n",
    "        name=\"SAR mixer: 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",
    "    solved = Simulation(\n",
    "        problem=problem, mesh=mesh, numerics=numerics\n",
    "    ).solve_stationary()\n",
    "    flows[size] = solved.field(flow.velocity), solved.field(flow.pressure)\n",
    "    transport = ConvectiveHeatTransfer(\n",
    "        domain=mixer.volume, material=solute, velocity=field_function(flows[size][0])\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"SAR mixer: solute\",\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",
    "    concentrations[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",
    "Cross-sections every half millimetre, sampled at the points in the liquid at least 0.08 mm from a\n",
    "wall; the mixing index is $1-\\sigma/\\sigma_0$ with the flow-weighted standard deviation $\\sigma$ and\n",
    "its value $\\sigma_0$ at the inlet. The layers are counted as the sign changes of $c-\\bar c$ across\n",
    "the channel at mid-height."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "grid_y, grid_z = np.meshgrid(\n",
    "    np.linspace(0.02, 0.98, 25) * side, np.linspace(0.02, 0.98, 25) * side\n",
    ")\n",
    "section = lambda x: np.column_stack(\n",
    "    (np.full(grid_y.size, x), grid_y.ravel(), grid_z.ravel())\n",
    ")\n",
    "margin = 0.08 * mm * np.array([[0, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]])\n",
    "stations = np.arange(0.25, 13.0, 0.5) * mm\n",
    "inside = [\n",
    "    np.all([mixer.contains(section(x) + shift) for shift in margin], axis=0)\n",
    "    for x in stations\n",
    "]\n",
    "mixing = {}\n",
    "for size, c in concentrations.items():\n",
    "    w = [\n",
    "        flows[size][0].evaluate(section(x)[keep])[:, 0]\n",
    "        for x, keep in zip(stations, inside)\n",
    "    ]\n",
    "    v = [np.ravel(c.evaluate(section(x)[keep])) for x, keep in zip(stations, inside)]\n",
    "    spread = np.array(\n",
    "        [\n",
    "            np.sqrt(np.average((a - np.average(a, weights=b)) ** 2, weights=b))\n",
    "            for a, b in zip(v, w)\n",
    "        ]\n",
    "    )\n",
    "    mixing[size] = 1 - spread / spread[0]\n",
    "across = np.column_stack(\n",
    "    (np.zeros(201), np.linspace(0.02, 0.98, 201) * side, np.full(201, side / 2))\n",
    ")\n",
    "layers = {\n",
    "    x: np.ravel(concentrations[0.2].evaluate(across + (x, 0, 0)))\n",
    "    for x in (0.5 * mm, 4.5 * mm, 8.5 * mm)\n",
    "}\n",
    "count = {\n",
    "    x: int(np.count_nonzero(np.diff(np.sign(c - c.mean())))) + 1\n",
    "    for x, c in layers.items()\n",
    "}\n",
    "duct = 12 * water.dynamic_viscosity * speed * side**2 / (0.4217 * side**4)\n",
    "\n",
    "for size in meshes:\n",
    "    velocity, pressure = flows[size]\n",
    "    gradient = (\n",
    "        np.mean(pressure.evaluate(section(10 * mm)))\n",
    "        - np.mean(pressure.evaluate(section(12 * mm)))\n",
    "    ) / (2 * mm)\n",
    "    water_in, water_out = (\n",
    "        velocity.integrate(boundary=faces.inlet, normal_component=True).value,\n",
    "        velocity.integrate(boundary=faces.outlet, normal_component=True).value,\n",
    "    )\n",
    "    carried = (\n",
    "        lambda face: derived_field(\n",
    "            velocity,\n",
    "            lambda u, points, c=concentrations[size]: np.ravel(c.evaluate(points))\n",
    "            * u[:, 0],\n",
    "            name=\"solute_flux\",\n",
    "            unit=\"1\",\n",
    "        )\n",
    "        .integrate(boundary=face)\n",
    "        .value\n",
    "    )\n",
    "    print(\n",
    "        f\"mesh {size} mm, {meshes[size].cell_count} tetrahedra: outlet pressure gradient / square duct {gradient / duct:.4f}, \"\n",
    "        f\"water balance {(water_in + water_out) / water_out:+.1e}, solute balance {carried(faces.outlet) / carried(faces.inlet) - 1:+.1e}, \"\n",
    "        f\"mixing index at the outlet {mixing[size][-1]:.3f}\"\n",
    "    )\n",
    "print(\n",
    "    \"layers across the channel at mid-height: \"\n",
    "    + \", \".join(f\"x = {x / mm:.1f} mm: {n}\" for x, n in count.items())\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The solute on cross-sections before, between and behind the elements, and the mixing index along\n",
    "the mixer."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(\n",
    "    layout=[[\"a\", \"b\", \"c\", \"d\"], [\"mixing\", \"mixing\", \"mixing\", \"mixing\"]],\n",
    "    size=(18, 10),\n",
    ")\n",
    "for panel, x, title in (\n",
    "    (\"a\", 0.5, \"inlet\"),\n",
    "    (\"b\", 4.5, \"after one element\"),\n",
    "    (\"c\", 8.5, \"after two elements\"),\n",
    "    (\"d\", 12.5, \"outlet\"),\n",
    "):\n",
    "    plots.section(\n",
    "        concentrations[0.2],\n",
    "        plane=Plane(origin=(x * mm, 0, 0), normal=(1, 0, 0)),\n",
    "        aspect=1.0,\n",
    "        limits=(0.0, 1.0),\n",
    "        subdivisions=2,\n",
    "        label=\"solute c\",\n",
    "        title=f\"x = {x} mm, {title}\",\n",
    "        ax=fig[panel],\n",
    "    )\n",
    "plots.line(\n",
    "    stations / mm,\n",
    "    {\"mesh 0.2 mm\": mixing[0.2]},\n",
    "    points={\"mesh 0.25 mm\": (stations[::2] / mm, mixing[0.25][::2])},\n",
    "    vlines={\"element 1\": 1.0, \"element 2\": 5.0, \"outlet section\": 9.0},\n",
    "    ylimits=(0.0, 1.02),\n",
    "    xlabel=\"distance x [mm]\",\n",
    "    ylabel=\"mixing index 1 - σ/σ0\",\n",
    "    title=\"Mixing along the mixer, Pe = 100\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[\"mixing\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add elements in `split_recombine_micromixer_geometry.py` and write the STEP file again: every\n",
    "element doubles the layer count, so the mixing length falls exponentially with the number of\n",
    "elements. Raising the flow rate raises the Péclet number in proportion."
   ]
  }
 ]
}
