{
 "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 at five flow rates\n",
    "\n",
    "A micromixer is designed for a range of flow rates, not for one, and the design study runs the\n",
    "same model as a batch over that range. In a split-and-recombine mixer the layers that leave the\n",
    "last element have a thickness $s$ set by the geometry; the faster the flow, the less time diffusion\n",
    "has to bridge them. With the residence time $t\\propto 1/\\bar U$ the unmixed fraction decays as\n",
    "$e^{-\\pi^2Dt/s^2}$, so its logarithm falls linearly with $1/\\bar U$, that is with the inverse\n",
    "Péclet number $1/Pe=D/(\\bar Uw)$ (lamination law; V. Hessel, H. Löwe, F. Schönfeld, *Chem. Eng.\n",
    "Sci.* 60, 2479-2501, 2005). In creeping flow the pressure drop grows in proportion to the flow\n",
    "rate.\n",
    "\n",
    "The mixer comes from the CAD file `split_recombine_micromixer_flow_rates.step`, written by\n",
    "`split_recombine_micromixer_flow_rates_geometry.py`: square channels of side $w=1$ mm with two\n",
    "split-and-recombine elements and a straight outlet section of 4 mm. Water with a solute of\n",
    "diffusivity $D=10^{-8}$ m²/s enters at mean speeds from 0.15 to 2 mm/s ($Re$ from 0.15 to 2,\n",
    "$Pe$ from 15 to 200).\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.** Creeping flow: $\\Delta p\\propto\\bar U$. Lamination law: in the outlet section\n",
    "$\\ln(1-M)$, with the mixing index $M$, falls linearly with $1/Pe$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\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.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; `split_boundary_cells` divides the cells whose corners all lie on walls."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mm = 1e-3\n",
    "mixer = load(\"split_recombine_micromixer_flow_rates.step\")\n",
    "faces = mixer.boundaries\n",
    "walls = faces.all - faces.inlet - faces.outlet\n",
    "side = mixer.size[1]\n",
    "mesh = TetrahedralMesher(target_size=0.25 * mm, split_boundary_cells=True).generate(\n",
    "    mixer\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=\"Split-and-recombine micromixer\",\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} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The batch of flow rates\n",
    "\n",
    "For each mean speed one flow problem and one solute problem in its flow."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "water, diffusivity = NewtonianFluid(density=1000.0, dynamic_viscosity=1.0e-3), 1e-8\n",
    "solute = IsotropicSolid(\n",
    "    density=1.0,\n",
    "    specific_heat_capacity=1.0,\n",
    "    thermal_conductivity=diffusivity,\n",
    "    youngs_modulus=1.0,\n",
    "    poisson_ratio=0.3,\n",
    "    thermal_expansion_coefficient=0.0,\n",
    ")\n",
    "speeds = (0.15e-3, 0.3e-3, 0.6e-3, 1.2e-3, 2e-3)\n",
    "runs = {}\n",
    "for speed in speeds:\n",
    "    flow = IncompressibleNavierStokes(domain=mixer.volume, material=water)\n",
    "    problem = Problem(\n",
    "        name=\"SAR mixer batch: 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",
    "    velocity = solved.field(flow.velocity)\n",
    "    transport = ConvectiveHeatTransfer(\n",
    "        domain=mixer.volume, material=solute, velocity=field_function(velocity)\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"SAR mixer batch: 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",
    "    runs[speed] = (\n",
    "        velocity,\n",
    "        solved.field(flow.pressure),\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",
    "Pressures and the flow-weighted mixing index $M=1-\\sigma/\\sigma_0$ on cross-sections of the\n",
    "straight inlet and outlet sections."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "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 run, x: (\n",
    "    np.ravel(run[2].evaluate(section(x))),\n",
    "    run[0].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",
    "stations = (9.2 * mm, 11 * mm, 12.8 * mm)\n",
    "mixing = {\n",
    "    speed: np.array(\n",
    "        [\n",
    "            1 - deviation(*sample(run, x)) / deviation(*sample(run, 0.5 * mm))\n",
    "            for x in stations\n",
    "        ]\n",
    "    )\n",
    "    for speed, run in runs.items()\n",
    "}\n",
    "drops = {\n",
    "    speed: np.mean(run[1].evaluate(section(0.5 * mm)))\n",
    "    - np.mean(run[1].evaluate(section(12.8 * mm)))\n",
    "    for speed, run in runs.items()\n",
    "}\n",
    "peclet = {speed: speed * side / diffusivity for speed in speeds}\n",
    "slope, offset = np.polyfit(\n",
    "    [1 / peclet[s] for s in speeds], [np.log(1 - mixing[s][-1]) for s in speeds], 1\n",
    ")\n",
    "fitted = {s: 1 - np.exp(offset + slope / peclet[s]) for s in speeds}\n",
    "\n",
    "print(\n",
    "    \" U [mm/s]   Re     Pe    Δp [Pa]   (Δp/U) / (Δp/U at the lowest speed)   mixing index at x = 9.2, 11, 12.8 mm   lamination law\"\n",
    ")\n",
    "for speed in speeds:\n",
    "    print(\n",
    "        f\"{1e3 * speed:8.2f} {water.density * speed * side / water.dynamic_viscosity:5.2f} {peclet[speed]:6.0f} {drops[speed]:9.4f}\"\n",
    "        f\" {drops[speed] / speed / (drops[speeds[0]] / speeds[0]):22.4f}            \"\n",
    "        + \"  \".join(f\"{m:.4f}\" for m in mixing[speed])\n",
    "        + f\" {fitted[speed]:14.4f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"\\nlamination law fitted to all five runs: ln(1 - M) = {offset:.3f} {slope:+.2f} / Pe\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Outlet mixing and pressure drop over the Péclet number, and the lamination-law plot."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "inverse = np.linspace(0.0, 1.1 / peclet[speeds[0]], 50)\n",
    "fig = plots.figure(1, 2, size=(15, 5.5))\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"x = {x / mm:.1f} mm\": (\n",
    "            [peclet[s] for s in speeds],\n",
    "            [mixing[s][index] for s in speeds],\n",
    "        )\n",
    "        for index, x in enumerate(stations)\n",
    "    },\n",
    "    right={\"pressure drop\": ([peclet[s] for s in speeds], [drops[s] for s in speeds])},\n",
    "    right_label=\"pressure drop [Pa]\",\n",
    "    scale=\"logx\",\n",
    "    markers=True,\n",
    "    ylimits=(0.0, 1.02),\n",
    "    xlabel=\"Péclet number Pe = U w / D\",\n",
    "    ylabel=\"mixing index M\",\n",
    "    title=\"The batch of flow rates\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"simulation, outlet\": (\n",
    "            [1 / peclet[s] for s in speeds],\n",
    "            [np.log(1 - mixing[s][-1]) for s in speeds],\n",
    "        )\n",
    "    },\n",
    "    reference={\"lamination law, fitted\": (inverse, offset + slope * inverse)},\n",
    "    xlabel=\"1 / Pe\",\n",
    "    ylabel=\"ln(1 - M)\",\n",
    "    title=\"Lamination law: straight line in 1/Pe\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add a third element in `split_recombine_micromixer_flow_rates_geometry.py`: the layer thickness\n",
    "halves and the slope of the lamination law grows about fourfold, so the same mixing is reached at\n",
    "four times the flow rate."
   ]
  }
 ]
}
