{
 "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": [
    "# Microchannel H-cell: separation by diffusion\n",
    "\n",
    "The H-cell, the microfluidic \"H-filter\" (J. P. Brody and P. Yager, *Sensors and Actuators A*\n",
    "58, 13, 1997), brings two laminar streams into contact for a controlled time. Stream A enters\n",
    "with a solute at $c_0=1$ mol/m³, stream B with pure water. At a Reynolds number of $10^{-3}$ the\n",
    "streams do not mix by convection; the solute crosses the interface only by diffusion. A small\n",
    "molecule (large diffusivity $D$) leaves through both outlets almost equally, a large molecule\n",
    "stays in stream A: the cell separates by molecular size.\n",
    "\n",
    "Every arm is 10 µm wide and 40 µm long and joins the contact zone, 20 µm wide and 100 µm long,\n",
    "through a quarter bend; the channel is 20 µm deep. Each inlet carries 20 pl/s of water (mean\n",
    "velocity 0.1 mm/s). The diffusivities are $D=10^{-10}$, $5\\cdot10^{-11}$ and $10^{-11}$ m²/s. The\n",
    "steady flow and the steady convection-diffusion of the dilute solute in that flow obey\n",
    "\n",
    "$$\\rho(\\mathbf u\\cdot\\nabla)\\mathbf u=-\\nabla p+\\mu\\nabla^2\\mathbf u,\\quad\\nabla\\cdot\\mathbf u=0,\n",
    "  \\qquad \\mathbf u\\cdot\\nabla c=D\\nabla^2 c .$$\n",
    "\n",
    "The lower half of the channel comes from the CAD file `microchannel_h_cell_diffusion.step`,\n",
    "written by `microchannel_h_cell_diffusion_geometry.py` with the CAD objects of OneSimulation. The\n",
    "mid-depth plane is a plane of symmetry. The file names the faces:\n",
    "\n",
    "| face | flow | solute |\n",
    "|---|---|---|\n",
    "| `inlet_a` | fully developed duct profile, 20 pl/s | $c=c_0$ |\n",
    "| `inlet_b` | fully developed duct profile, 20 pl/s | $c=0$ |\n",
    "| `outlet_a`, `outlet_b` | traction free | no diffusive flux |\n",
    "| `mid_plane` | symmetry: impermeable, shear free | no flux |\n",
    "| `walls` (side walls and bottom) | no slip | no flux |\n",
    "\n",
    "**Reference.** A Graetz-type exchange estimate. Two streams of width $W=10$ µm side by side in a\n",
    "channel of width $2W$ exchange solute by diffusion across $y$; after the contact time $\\tau$ the\n",
    "fraction of the solute found in stream B is (J. Crank, *The Mathematics of Diffusion*, 2nd ed.,\n",
    "Oxford 1975, Sec. 4.3)\n",
    "\n",
    "$$f_B=\\frac12-\\sum_{n\\ \\mathrm{odd}}\\frac{4}{n^2\\pi^2}\\exp\\!\\Big(-\\frac{n^2\\pi^2D\\tau}{4W^2}\\Big),$$\n",
    "\n",
    "and the outlet-B concentration is $c_B=f_B\\,c_0$. For plug flow the contact time is\n",
    "$\\tau=L/\\bar u$. In the real channel the interface moves fast at mid-depth and slowly near the\n",
    "bottom, and the slow fluid has more time to exchange (A. E. Kamholz et al., *Anal. Chem.* 71,\n",
    "5340, 1999; R. F. Ismagilov et al., *Appl. Phys. Lett.* 76, 2376, 2000). Averaging the\n",
    "short-contact flux $c_0\\sqrt{D\\,u_i(z)\\,L/\\pi}$ over a parabolic interface velocity $u_i(z)$ with\n",
    "the duct peak $u_\\max=2.096\\,\\bar u$ of a square section (R. K. Shah and A. L. London, *Laminar\n",
    "Flow Forced Convection in Ducts*, Academic Press 1978, Ch. VII) gives the effective contact time\n",
    "$\\tau_\\mathrm{eff}=(\\pi/4)^2\\,(u_\\max/\\bar u)\\,L/\\bar u$. The estimate neglects the merging and\n",
    "parting of the streams and axial diffusion, so agreement to a few per cent is expected."
   ]
  },
  {
   "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 Geometric, SweepMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, GalerkinAdvection, Lagrange, TaylorHood\n",
    "from onesim.numerics.field_transfer import FieldInterpolation\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.comparisons import convergence\n",
    "from onesim.results.derived import derived_field\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.field_connections import FieldCoupling\n",
    "from onesim.simulation.initial_conditions import InitialValue\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",
    "`load` returns the half channel with its named faces. `SweepMesher` covers the bottom of the\n",
    "channel with quadrilaterals and sweeps them up to the mid-depth plane into hexahedra, with thinner\n",
    "layers at the bottom wall. Three cell sizes (with two, three and four layers) serve the mesh\n",
    "study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "um = 1e-6\n",
    "channel = load(\"microchannel_h_cell_diffusion.step\")\n",
    "faces = channel.boundaries\n",
    "bottom = channel.select(\n",
    "    faces=lambda face: face.kind == \"plane\" and abs(face.center[2]) < 1e-12\n",
    ")\n",
    "sizes = [5.0 * um, 4.0 * um, 3.0 * um]\n",
    "meshes = [\n",
    "    SweepMesher(\n",
    "        source=bottom, target_size=size, layers=Geometric(layers, ratio=2.0)\n",
    "    ).generate(channel)\n",
    "    for size, layers in zip(sizes, (2, 3, 4))\n",
    "]\n",
    "\n",
    "view = plots.Camera(elevation=55, azimuth=-70)\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.geometry(\n",
    "    channel,\n",
    "    selection={\n",
    "        \"inlet A\": faces.inlet_a,\n",
    "        \"inlet B\": faces.inlet_b,\n",
    "        \"outlets\": faces.outlet_a | faces.outlet_b,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Lower half of the H-cell with its named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[-1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Finest mesh: {meshes[-1].cell_count} swept hexahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "One problem holds the flow and three solute transports. The flow is `IncompressibleNavierStokes`\n",
    "with Taylor-Hood elements. A dilute solute obeys the same convection-diffusion equation as\n",
    "temperature, so each solute is a `ConvectiveHeatTransfer` model with unit heat capacity and the\n",
    "diffusivity in place of the conductivity; a `FieldCoupling` hands it the computed velocity. The\n",
    "solutes use quadratic elements on the same mesh as the flow. The problem is solved on the three\n",
    "meshes, each with its own fully developed inflow profiles."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "W, L, mean_speed, c0 = 10 * um, 100 * um, 1.0e-4, 1.0\n",
    "diffusivities = [1e-10, 5e-11, 1e-11]\n",
    "flow = IncompressibleNavierStokes(\n",
    "    domain=channel.volume,\n",
    "    material=NewtonianFluid(density=1000.0, dynamic_viscosity=1.0e-3),\n",
    ")\n",
    "solutes = [\n",
    "    ConvectiveHeatTransfer(\n",
    "        domain=channel.volume,\n",
    "        velocity=None,\n",
    "        material=IsotropicSolid(\n",
    "            density=1.0,\n",
    "            specific_heat_capacity=1.0,\n",
    "            thermal_conductivity=D,\n",
    "            youngs_modulus=1.0,\n",
    "            poisson_ratio=0.3,\n",
    "            thermal_expansion_coefficient=0.0,\n",
    "        ),\n",
    "    )\n",
    "    for D in diffusivities\n",
    "]\n",
    "transport = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2), convection=GalerkinAdvection()),\n",
    "    linear_solver=SparseDirect(),\n",
    ")\n",
    "numerics = {\n",
    "    flow: 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-15,\n",
    "            relative_tolerance=1e-10,\n",
    "            maximum_iterations=10,\n",
    "        ),\n",
    "    ),\n",
    "    **{solute: transport for solute in solutes},\n",
    "}\n",
    "results = [\n",
    "    Simulation(\n",
    "        mesh=dict.fromkeys((flow, *solutes), mesh),\n",
    "        numerics=numerics,\n",
    "        problem=Problem(\n",
    "            name=\"Microchannel H-cell\",\n",
    "            geometry=channel,\n",
    "            physics=(flow, *solutes),\n",
    "            boundary_conditions=(\n",
    "                FixedVelocity(\n",
    "                    boundary=faces.inlet_a,\n",
    "                    physics=flow,\n",
    "                    value=fully_developed_inflow(\n",
    "                        mesh,\n",
    "                        faces.inlet_a,\n",
    "                        mean_velocity=mean_speed,\n",
    "                        no_slip=faces.walls,\n",
    "                    ),\n",
    "                ),\n",
    "                FixedVelocity(\n",
    "                    boundary=faces.inlet_b,\n",
    "                    physics=flow,\n",
    "                    value=fully_developed_inflow(\n",
    "                        mesh,\n",
    "                        faces.inlet_b,\n",
    "                        mean_velocity=mean_speed,\n",
    "                        no_slip=faces.walls,\n",
    "                    ),\n",
    "                ),\n",
    "                FlowTraction(\n",
    "                    boundary=faces.outlet_a | faces.outlet_b,\n",
    "                    physics=flow,\n",
    "                    value=lambda x, y, z: np.zeros((len(x), 3)),\n",
    "                ),\n",
    "                NoSlipWall(boundary=faces.walls, physics=flow),\n",
    "                WallShear(boundary=faces.mid_plane, physics=flow, law=FreeSlipLaw()),\n",
    "                *[\n",
    "                    condition\n",
    "                    for solute in solutes\n",
    "                    for condition in (\n",
    "                        FixedTemperature(\n",
    "                            physics=solute, boundary=faces.inlet_a, value=c0\n",
    "                        ),\n",
    "                        FixedTemperature(\n",
    "                            physics=solute, boundary=faces.inlet_b, value=0.0\n",
    "                        ),\n",
    "                        HeatFlux(\n",
    "                            physics=solute,\n",
    "                            boundary=faces.all - faces.inlet_a - faces.inlet_b,\n",
    "                            value=0.0,\n",
    "                        ),\n",
    "                    )\n",
    "                ],\n",
    "            ),\n",
    "            initial_conditions=(InitialValue(flow.velocity, (0.0, 0.0, 0.0)),),\n",
    "            couplings=tuple(\n",
    "                FieldCoupling(\n",
    "                    source=flow.velocity,\n",
    "                    target=solute.advecting_velocity,\n",
    "                    transfer=FieldInterpolation(),\n",
    "                )\n",
    "                for solute in solutes\n",
    "            ),\n",
    "        ),\n",
    "    ).solve_stationary()\n",
    "    for mesh in meshes\n",
    "]\n",
    "velocity = results[-1].field(flow.velocity)\n",
    "concentrations = [results[-1].field(solute.temperature) for solute in solutes]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Balances and outlet concentrations\n",
    "\n",
    "The water flow through a face is the integral of the normal velocity, the solute flow the\n",
    "integral of the normal component of $c\\,\\mathbf u$. Both are doubled for the full depth. The\n",
    "outlet-B concentration is the solute flow divided by the water flow through that face (mixing-cup\n",
    "average)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "ports = (\"inlet_a\", \"inlet_b\", \"outlet_a\", \"outlet_b\")\n",
    "water = {\n",
    "    port: 2\n",
    "    * velocity.integrate(boundary=getattr(faces, port), normal_component=True).value\n",
    "    for port in ports\n",
    "}\n",
    "carried = [\n",
    "    derived_field(\n",
    "        velocity,\n",
    "        lambda u, points, c=c: u * np.ravel(c.evaluate(points))[:, None],\n",
    "        name=\"solute_flux\",\n",
    "        unit=\"mol/m^2/s\",\n",
    "        components=(\"x\", \"y\", \"z\"),\n",
    "    )\n",
    "    for c in concentrations\n",
    "]\n",
    "solute = [\n",
    "    {\n",
    "        port: 2\n",
    "        * flux.integrate(boundary=getattr(faces, port), normal_component=True).value\n",
    "        for port in ports\n",
    "    }\n",
    "    for flux in carried\n",
    "]\n",
    "print(\n",
    "    f\"water [pl/s]: in A {-1e15 * water['inlet_a']:.4f}, in B {-1e15 * water['inlet_b']:.4f}, out A {1e15 * water['outlet_a']:.4f}, \"\n",
    "    f\"out B {1e15 * water['outlet_b']:.4f}; out/in - 1 = {-sum(water.values()) / (water['inlet_a'] + water['inlet_b']):+.1e}\"\n",
    ")\n",
    "for D, flows in zip(diffusivities, solute):\n",
    "    print(\n",
    "        f\"solute D = {D:.0e} m²/s [fmol/s]: in {-1e15 * (flows['inlet_a'] + flows['inlet_b']):.4f}, out A {1e15 * flows['outlet_a']:.4f}, \"\n",
    "        f\"out B {1e15 * flows['outlet_b']:.4f}; out/in - 1 = {-sum(flows.values()) / (flows['inlet_a'] + flows['inlet_b']):+.1e}\"\n",
    "    )\n",
    "\n",
    "tau = L / mean_speed\n",
    "tau_eff = (np.pi / 4) ** 2 * 2.096 * tau\n",
    "exchange = lambda D, time, n=np.arange(1, 2001, 2): 0.5 - np.sum(\n",
    "    4 / (n * np.pi) ** 2 * np.exp(-((n * np.pi) ** 2) * D * time / (4 * W**2))\n",
    ")\n",
    "c_b = [flows[\"outlet_b\"] / water[\"outlet_b\"] for flows in solute]\n",
    "print(\n",
    "    \"D [m²/s]   c_B simulation [mol/m³]   Graetz-type estimate   deviation   plug-flow estimate   c range in the channel\"\n",
    ")\n",
    "for D, value, c in zip(diffusivities, c_b, concentrations):\n",
    "    nodal = np.ravel(c.evaluate(meshes[-1].coordinates))\n",
    "    print(\n",
    "        f\"{D:8.0e} {value:25.4f} {c0 * exchange(D, tau_eff):22.4f} {100 * (value / (c0 * exchange(D, tau_eff)) - 1):+10.1f} % \"\n",
    "        f\"{c0 * exchange(D, tau):20.4f}     {nodal.min():+.3f} to {nodal.max():.3f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Mesh study\n",
    "\n",
    "The outlet-B concentration of the large molecule ($D=10^{-11}$ m²/s, the steepest fronts) and\n",
    "the pressure drop from inlet A to the outlets on the three meshes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "c_low = [\n",
    "    derived_field(\n",
    "        result.field(flow.velocity),\n",
    "        lambda u, points, c=result.field(solutes[-1].temperature): u\n",
    "        * np.ravel(c.evaluate(points))[:, None],\n",
    "        name=\"solute_flux\",\n",
    "        unit=\"mol/m^2/s\",\n",
    "        components=(\"x\", \"y\", \"z\"),\n",
    "    )\n",
    "    .integrate(boundary=faces.outlet_b, normal_component=True)\n",
    "    .value\n",
    "    / result.field(flow.velocity)\n",
    "    .integrate(boundary=faces.outlet_b, normal_component=True)\n",
    "    .value\n",
    "    for result in results\n",
    "]\n",
    "inlet_point = [[5 * um, -60 * um + 1e-9, 10 * um - 1e-12]]\n",
    "drop = [\n",
    "    float(result.field(flow.pressure).evaluate(inlet_point)[0]) for result in results\n",
    "]\n",
    "study_c, study_p = convergence(c_low, sizes), convergence(drop, sizes)\n",
    "print(\"cell size [µm]   hexahedra   c_B for D = 1e-11 [mol/m³]   inlet pressure [Pa]\")\n",
    "for size, mesh, value, p in zip(sizes, meshes, c_low, drop):\n",
    "    print(f\"{size / um:14.1f} {mesh.cell_count:11d} {value:28.4f} {p:21.4f}\")\n",
    "print(\n",
    "    f\"change between the two finest meshes: c_B {100 * study_c.change:+.2f} %, inlet pressure {100 * study_p.change:+.2f} %\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The concentration of the large and the small molecule on the mid-depth plane, two cross-sections\n",
    "of the contact zone for the large molecule (full depth, mirrored at the symmetry plane), the\n",
    "outlet-B concentration against the diffusivity with both estimates, and the mesh study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "D_line = np.geomspace(3e-12, 3e-10, 80)\n",
    "fig = plots.figure(\n",
    "    layout=[\n",
    "        [\"slow\"] * 3 + [\"fast\"] * 3,\n",
    "        [\"cut 70\"] * 3 + [\"cut 110\"] * 3,\n",
    "        [\"outlet\"] * 3 + [\"mesh\"] * 3,\n",
    "    ],\n",
    "    size=(16, 15),\n",
    ")\n",
    "for panel, index in ((\"slow\", 2), (\"fast\", 0)):\n",
    "    plots.surface(\n",
    "        concentrations[index],\n",
    "        boundary=faces.mid_plane,\n",
    "        limits=(0.0, c0),\n",
    "        contours=9,\n",
    "        subdivisions=3,\n",
    "        aspect=1.0,\n",
    "        label=\"c [mol/m³]\",\n",
    "        title=f\"D = {diffusivities[index]:.0e} m²/s on the mid-depth plane: c_B = {c_b[index]:.3f} mol/m³\",\n",
    "        ax=fig[panel],\n",
    "    )\n",
    "for x_cut in (70, 110):\n",
    "    plots.section(\n",
    "        concentrations[2],\n",
    "        plane=Plane(origin=(x_cut * um, 0.0, 0.0), normal=(1.0, 0.0, 0.0)),\n",
    "        symmetry={\"planes\": [((0, 0, 1), (0, 0, 10 * um))]},\n",
    "        limits=(0.0, c0),\n",
    "        contours=9,\n",
    "        subdivisions=3,\n",
    "        label=\"c [mol/m³]\",\n",
    "        title=f\"D = 1e-11 m²/s, x = {x_cut} µm\",\n",
    "        xlimits=(-W, W),\n",
    "        ylimits=(0.0, 2 * W),\n",
    "        ax=fig[f\"cut {x_cut}\"],\n",
    "    )\n",
    "plots.line(\n",
    "    D_line,\n",
    "    {\"Graetz-type estimate\": [c0 * exchange(D, tau_eff) for D in D_line]},\n",
    "    reference={\"plug-flow estimate\": (D_line, [c0 * exchange(D, tau) for D in D_line])},\n",
    "    points={\"3D simulation\": (diffusivities, c_b)},\n",
    "    hlines={\"complete mixing\": 0.5 * c0},\n",
    "    scale=\"logx\",\n",
    "    ylimits=(0.0, 0.55),\n",
    "    xlabel=\"diffusivity D [m²/s]\",\n",
    "    ylabel=\"concentration at outlet B [mol/m³]\",\n",
    "    title=\"Separation by molecular size\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[\"outlet\"],\n",
    ")\n",
    "plots.line(\n",
    "    [size / um for size in sizes],\n",
    "    {\"3D simulation, D = 1e-11 m²/s\": c_low},\n",
    "    markers=True,\n",
    "    hlines={\"Graetz-type estimate\": c0 * exchange(1e-11, tau_eff)},\n",
    "    xlabel=\"cell size [µm]\",\n",
    "    ylabel=\"concentration at outlet B [mol/m³]\",\n",
    "    title=\"Mesh study\",\n",
    "    ax=fig[\"mesh\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Lengthen the contact zone in `microchannel_h_cell_diffusion_geometry.py` and write the STEP file\n",
    "again, or lower the inlet flow: the contact time grows and the large molecule reaches outlet B in\n",
    "larger amounts. Feed outlet B of one cell into the next to enrich the small molecule further, or\n",
    "make the viscosity depend on the concentration to see the interface shift towards the more\n",
    "viscous stream."
   ]
  }
 ]
}
