{
 "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": [
    "# Lamella micromixer with hydrodynamic focusing\n",
    "\n",
    "In a microchannel the flow is laminar, and two liquids that enter side by side mix only by\n",
    "molecular diffusion across their interface - slowly, because the diffusion time grows with the\n",
    "square of the layer thickness $s$: $t\\sim s^2/D$. Lamella mixers therefore split the two inlet\n",
    "streams into many thin alternating layers and, in addition, squeeze them in a contraction\n",
    "(hydrodynamic focusing). With $N$ lamellae across a channel of width $w$ the layer thickness is\n",
    "$s=w/N$, and the length needed for mixing at the mean speed $\\bar U$ is\n",
    "\n",
    "$$L_\\text{mix}\\sim\\frac{\\bar U s^2}{\\pi^2D}=\\frac{\\bar U w^2}{\\pi^2 D N^2}$$\n",
    "\n",
    "(W. Ehrfeld, K. Golbig, V. Hessel, H. Löwe, T. Richter, *Ind. Eng. Chem. Res.* 38, 1075-1082,\n",
    "1999; V. Hessel, H. Löwe, F. Schönfeld, *Chem. Eng. Sci.* 60, 2479-2501, 2005). Doubling the\n",
    "number of lamellae shortens the mixer four times.\n",
    "\n",
    "The mixer comes from the CAD file `lamella_mixer_focusing.step`, written by\n",
    "`lamella_mixer_focusing_geometry.py`: an inlet chamber 4 mm wide, a contraction to the mixing\n",
    "channel 1 mm wide and 12 mm long, 0.5 mm deep. The file holds the lower half below the mid-depth\n",
    "plane. The lamellae enter as a smooth concentration pattern $c=\\tfrac12\\left(1+\\cos(N\\pi y'/W)\\right)$\n",
    "across the inlet of width $W=4$ mm. The steady creeping flow and the convection-diffusion of the\n",
    "solute in it are\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 0.1 mm/s | $c=\\tfrac12(1+\\cos(N\\pi y'/W))$ |\n",
    "| `outlet` | traction free | no diffusive flux |\n",
    "| `top` (mid-depth symmetry plane) | impermeable, shear free | no flux |\n",
    "| `wall`, `bottom` | no slip | no flux |\n",
    "\n",
    "**Reference.** The solute that enters must leave (mass balance). The mixing must follow the\n",
    "lamination law: plotted over $N^2\\int dx/W$ the curves for different $N$ collapse, and the\n",
    "depth-averaged plug-flow solution of the diffusion across the lamellae gives the scale."
   ]
  },
  {
   "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 Geometric, SweepMesher\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",
    "    FreeSlipLaw,\n",
    "    IncompressibleNavierStokes,\n",
    "    NoSlipWall,\n",
    "    WallShear,\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",
    "`SweepMesher` meshes the bottom with quadrilaterals and sweeps them up to the mid-depth plane in\n",
    "three layers, thinner at the bottom; the quadrilaterals are 0.14 mm wide. The mesh study uses\n",
    "0.2 mm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mm = 1e-3\n",
    "mixer = load(\"lamella_mixer_focusing.step\")\n",
    "faces = mixer.boundaries\n",
    "meshes = {\n",
    "    size: SweepMesher(\n",
    "        source=faces.bottom, target_size=size * mm, layers=Geometric(3, ratio=1.5)\n",
    "    ).generate(mixer)\n",
    "    for size in (0.20, 0.14)\n",
    "}\n",
    "mesh = meshes[0.14]\n",
    "\n",
    "view = plots.Camera(elevation=50, azimuth=-65)\n",
    "fig = plots.figure(1, 2, size=(16, 5))\n",
    "plots.geometry(\n",
    "    mixer,\n",
    "    selection={\n",
    "        \"inlet\": faces.inlet,\n",
    "        \"outlet\": faces.outlet,\n",
    "        \"mid-depth plane\": faces.top,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Lower half of the lamella mixer\",\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} hexahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Flow\n",
    "\n",
    "Water enters with the laminar duct profile; the Reynolds number in the mixing channel is 0.4."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "water = NewtonianFluid(density=1000.0, dynamic_viscosity=1.0e-3)\n",
    "flow = IncompressibleNavierStokes(domain=mixer.volume, material=water)\n",
    "velocities = {}\n",
    "for size, grid in meshes.items():\n",
    "    problem = Problem(\n",
    "        name=\"Lamella 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",
    "                    grid,\n",
    "                    faces.inlet,\n",
    "                    mean_velocity=1e-4,\n",
    "                    no_slip=faces.wall | faces.bottom,\n",
    "                ),\n",
    "            ),\n",
    "            FlowTraction(boundary=faces.outlet, physics=flow, value=(0.0, 0.0, 0.0)),\n",
    "            NoSlipWall(boundary=faces.wall | faces.bottom, physics=flow),\n",
    "            WallShear(boundary=faces.top, physics=flow, law=FreeSlipLaw()),\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",
    "    velocities[size] = (\n",
    "        Simulation(problem=problem, mesh=grid, numerics=numerics)\n",
    "        .solve_stationary()\n",
    "        .field(flow.velocity)\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Solute\n",
    "\n",
    "A small molecule, $D=2\\cdot10^{-9}$ m²/s, follows the same convection-diffusion equation as\n",
    "temperature. It is solved for 2, 4 and 8 lamellae on the finer mesh and for 4 lamellae on the\n",
    "coarser one."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "diffusivity, inlet_width = 2e-9, 4 * mm\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",
    "patterns = {\n",
    "    2: lambda y: 0.5 * (1 + np.cos(2 * np.pi * (y / inlet_width + 0.5))),\n",
    "    4: lambda y: 0.5 * (1 + np.cos(4 * np.pi * (y / inlet_width + 0.5))),\n",
    "    8: lambda y: 0.5 * (1 + np.cos(8 * np.pi * (y / inlet_width + 0.5))),\n",
    "}\n",
    "cases = [(lamellae, 0.14) for lamellae in patterns] + [(4, 0.20)]\n",
    "concentrations = {}\n",
    "for lamellae, size in cases:\n",
    "    transport = ConvectiveHeatTransfer(\n",
    "        domain=mixer.volume, material=solute, velocity=field_function(velocities[size])\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"Lamella mixer: solute\",\n",
    "        geometry=mixer,\n",
    "        physics=(transport,),\n",
    "        boundary_conditions=(\n",
    "            FixedTemperature(\n",
    "                physics=transport, boundary=faces.inlet, value=patterns[lamellae]\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[lamellae, size] = (\n",
    "        Simulation(problem=problem, mesh=meshes[size], numerics=numerics)\n",
    "        .solve_stationary()\n",
    "        .field(transport.temperature)\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The solute flow through a face is $\\int c\\,u_x\\,dA$. On cross-sections from the inlet to the\n",
    "outlet the flow-weighted standard deviation $\\sigma$ of the concentration gives the mixing index\n",
    "$1-\\sigma/\\sigma_0$, with $\\sigma_0$ its value at the inlet. For comparison, in plug flow through a\n",
    "channel of width $W(x)$ the pattern $\\cos(N\\pi y/W)$ decays by diffusion as\n",
    "$\\exp\\!\\big(-\\pi^2N^2D\\int_0^x dx'/(\\bar U_0W_0\\,W(x'))\\big)$, since the flow rate $\\bar U W$ is\n",
    "the same on every cross-section ($\\bar U_0=0.1$ mm/s and $W_0=4$ mm at the inlet)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "flux = (\n",
    "    lambda key, face: derived_field(\n",
    "        velocities[key[1]],\n",
    "        lambda u, points, c=concentrations[key]: np.ravel(c.evaluate(points)) * u[:, 0],\n",
    "        name=\"solute_flux\",\n",
    "        unit=\"mol/m^2/s\",\n",
    "    )\n",
    "    .integrate(boundary=face)\n",
    "    .value\n",
    ")\n",
    "width_at = lambda x: np.interp(\n",
    "    x, [0.0, 2 * mm, 4 * mm, 16 * mm], [4 * mm, 4 * mm, 1 * mm, 1 * mm]\n",
    ")\n",
    "eta, z = np.meshgrid(np.linspace(-0.49, 0.49, 50), np.linspace(0.005, 0.245, 13) * mm)\n",
    "stations = np.linspace(0.05, 15.95, 80) * mm\n",
    "fine = np.linspace(0.0, 16 * mm, 3201)\n",
    "path = np.interp(\n",
    "    stations,\n",
    "    fine,\n",
    "    np.concatenate(\n",
    "        ([0.0], np.cumsum(np.diff(fine) / width_at(0.5 * (fine[1:] + fine[:-1]))))\n",
    "    ),\n",
    ")\n",
    "plug = {\n",
    "    lamellae: 1\n",
    "    - np.exp(-np.pi**2 * lamellae**2 * diffusivity * path / (1e-4 * inlet_width))\n",
    "    for lamellae in patterns\n",
    "}\n",
    "mixing = {}\n",
    "for key, c in concentrations.items():\n",
    "    points = [\n",
    "        np.column_stack((np.full(eta.size, x), (eta * width_at(x)).ravel(), z.ravel()))\n",
    "        for x in stations\n",
    "    ]\n",
    "    weights = [velocities[key[1]].evaluate(p)[:, 0] for p in points]\n",
    "    spread = np.array(\n",
    "        [\n",
    "            np.sqrt(np.average((v - np.average(v, weights=w)) ** 2, weights=w))\n",
    "            for v, w in ((np.ravel(c.evaluate(p)), w) for p, w in zip(points, weights))\n",
    "        ]\n",
    "    )\n",
    "    mixing[key] = 1 - spread / spread[0]\n",
    "reach = {key: np.interp(0.9, curve, stations) for key, curve in mixing.items()}\n",
    "\n",
    "print(\n",
    "    \" lamellae   mesh [mm]   solute in    solute out   balance    x(90 % mixed) [mm]   plug flow [mm]   mixing at outlet\"\n",
    ")\n",
    "for key in cases:\n",
    "    inflow, outflow = flux(key, faces.inlet), flux(key, faces.outlet)\n",
    "    print(\n",
    "        f\"{key[0]:6d} {key[1]:12.2f} {inflow:12.4e} {outflow:12.4e} {outflow / inflow - 1:+10.1e} {1e3 * reach[key]:15.2f}\"\n",
    "        f\" {1e3 * np.interp(0.9, plug[key[0]], stations):16.2f} {mixing[key][-1]:17.4f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"\\nmesh study, 4 lamellae: 90 % mixed at {1e3 * reach[4, 0.20]:.2f} mm ({meshes[0.20].cell_count} hexahedra) and \"\n",
    "    f\"{1e3 * reach[4, 0.14]:.2f} mm ({meshes[0.14].cell_count} hexahedra)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The concentration on the mid-depth plane for 4 and 8 lamellae, the mixing index along the mixer\n",
    "with the plug-flow estimate, and the same over $N^2\\int dx/W$, where the lamination law makes\n",
    "all curves one."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(\n",
    "    layout=[[\"four\", \"four\"], [\"eight\", \"eight\"], [\"mixing\", \"collapse\"]], size=(15, 13)\n",
    ")\n",
    "for panel, lamellae in ((\"four\", 4), (\"eight\", 8)):\n",
    "    plots.surface(\n",
    "        concentrations[lamellae, 0.14],\n",
    "        boundary=faces.top,\n",
    "        limits=(0.0, 1.0),\n",
    "        contours=6,\n",
    "        subdivisions=2,\n",
    "        aspect=1.0,\n",
    "        label=\"concentration\",\n",
    "        title=f\"{lamellae} lamellae: concentration on the mid-depth plane\",\n",
    "        ax=fig[panel],\n",
    "    )\n",
    "plots.line(\n",
    "    1e3 * stations,\n",
    "    {f\"N = {lamellae}\": mixing[lamellae, 0.14] for lamellae in patterns},\n",
    "    reference={f\"N = {lamellae}\": plug[lamellae] for lamellae in patterns},\n",
    "    points={\"N = 4, coarser mesh\": (1e3 * stations[::5], mixing[4, 0.20][::5])},\n",
    "    vlines={\"end of the contraction\": 4.0},\n",
    "    ylimits=(0.0, 1.02),\n",
    "    xlabel=\"distance from the inlet x [mm]\",\n",
    "    ylabel=\"mixing index 1 - σ/σ0\",\n",
    "    title=\"Mixing along the mixer: simulation (solid), plug flow (dashed)\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[\"mixing\"],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"N = {lamellae}\": (lamellae**2 * path, mixing[lamellae, 0.14])\n",
    "        for lamellae in patterns\n",
    "    },\n",
    "    reference={\"plug flow\": (64 * path, plug[8])},\n",
    "    scale=\"logx\",\n",
    "    ylimits=(0.0, 1.02),\n",
    "    xlabel=\"N² ∫ dx / W\",\n",
    "    ylabel=\"mixing index 1 - σ/σ0\",\n",
    "    title=\"Lamination law: one curve for all N\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[\"collapse\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the contraction stronger in `lamella_mixer_focusing_geometry.py` and write the STEP file\n",
    "again: the focusing ratio enters the mixing length squared. Raise the flow rate and the mixer\n",
    "must grow in proportion; a larger diffusivity (a smaller molecule or a warmer liquid) shortens it."
   ]
  }
 ]
}
