{
 "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": [
    "# Controlled diffusion separator: separation by molecular size in an H-cell\n",
    "\n",
    "The H-cell (formulated by A. Witarsa and B. A. Finlayson, University of Washington, as a test\n",
    "case for evaluating microfluidic patents; the \"H-filter\" of J. P. Brody and P. Yager, *Sensors\n",
    "and Actuators A* 58, 13, 1997) brings two laminar streams into contact for a controlled time.\n",
    "Stream A enters with a solute at $c_0=1$ mol/m³, stream B with pure water. Both flow side by\n",
    "side through a straight contact zone and are split again. At a Reynolds number of order\n",
    "$10^{-3}$ the streams do not mix by convection; the solute crosses the interface only by\n",
    "diffusion. A small molecule (large diffusivity $D$) leaves through both outlets almost equally,\n",
    "a large molecule stays in stream A.\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 15 pl/s of water. The flow\n",
    "is creeping, followed by the steady convection-diffusion of the dilute solute in that flow:\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 `controlled_diffusion_separator.step`,\n",
    "written by `controlled_diffusion_separator_geometry.py` with the CAD objects of OneSimulation.\n",
    "The file names the faces:\n",
    "\n",
    "| face | flow | solute |\n",
    "|---|---|---|\n",
    "| `inlet_a` | fully developed duct profile, 15 pl/s | $c=c_0$ |\n",
    "| `inlet_b` | fully developed duct profile, 15 pl/s | $c=0$ |\n",
    "| `outlet_a`, `outlet_b` | traction free | no diffusive flux |\n",
    "| `mid_plane` (symmetry at mid-depth) | impermeable, shear free | no flux |\n",
    "| all other faces (walls, with `bottom`) | no slip | no flux |\n",
    "\n",
    "**Reference.** The published outlet-B concentrations of this benchmark: 0.492, 0.448 and 0.235\n",
    "mol/m³ for $D=10^{-10}$, $5\\cdot10^{-11}$ and $10^{-11}$ m²/s."
   ]
  },
  {
   "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.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` meshes the bottom with\n",
    "quadrilaterals and sweeps them up to the mid-depth plane, with thinner layers at the bottom."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "um = 1e-6\n",
    "channel = load(\"controlled_diffusion_separator.step\")\n",
    "faces = channel.boundaries\n",
    "walls = (\n",
    "    faces.all\n",
    "    - faces.inlet_a\n",
    "    - faces.inlet_b\n",
    "    - faces.outlet_a\n",
    "    - faces.outlet_b\n",
    "    - faces.mid_plane\n",
    ")\n",
    "meshes = [\n",
    "    SweepMesher(\n",
    "        source=faces.bottom, target_size=size * um, layers=Geometric(layers, ratio=2.0)\n",
    "    ).generate(channel)\n",
    "    for size, layers in ((5.0, 2), (4.0, 3))\n",
    "]\n",
    "\n",
    "view = plots.Camera(elevation=50, azimuth=-70)\n",
    "fig = plots.figure(1, 2, size=(15, 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-channel 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\"Finer mesh: {meshes[-1].cell_count} hexahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Flow\n",
    "\n",
    "`fully_developed_inflow` gives the laminar duct profile on each inlet for the mean velocity of\n",
    "0.075 mm/s. The flow is solved on both meshes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mean_speed, published = 15e-15 / (10 * um * 20 * um), {\n",
    "    1e-10: 0.492,\n",
    "    5e-11: 0.448,\n",
    "    1e-11: 0.235,\n",
    "}\n",
    "flow = IncompressibleNavierStokes(\n",
    "    domain=channel.volume,\n",
    "    material=NewtonianFluid(density=1000.0, dynamic_viscosity=1.0e-3),\n",
    ")\n",
    "fields = []\n",
    "for mesh in meshes:\n",
    "    problem = Problem(\n",
    "        name=\"Controlled diffusion separator: flow\",\n",
    "        geometry=channel,\n",
    "        physics=(flow,),\n",
    "        boundary_conditions=(\n",
    "            FixedVelocity(\n",
    "                boundary=faces.inlet_a,\n",
    "                physics=flow,\n",
    "                value=fully_developed_inflow(\n",
    "                    mesh, faces.inlet_a, mean_velocity=mean_speed, no_slip=walls\n",
    "                ),\n",
    "            ),\n",
    "            FixedVelocity(\n",
    "                boundary=faces.inlet_b,\n",
    "                physics=flow,\n",
    "                value=fully_developed_inflow(\n",
    "                    mesh, faces.inlet_b, mean_velocity=mean_speed, no_slip=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=walls, physics=flow),\n",
    "            WallShear(boundary=faces.mid_plane, physics=flow, law=FreeSlipLaw()),\n",
    "        ),\n",
    "        initial_conditions=(InitialValue(flow.velocity, (0.0, 0.0, 0.0)),),\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-15,\n",
    "            relative_tolerance=1e-10,\n",
    "            maximum_iterations=10,\n",
    "        ),\n",
    "    )\n",
    "    fields.append(\n",
    "        Simulation(problem=problem, mesh=mesh, numerics=numerics).solve_stationary()\n",
    "    )\n",
    "velocities = [result.field(flow.velocity) for result in fields]\n",
    "velocity, pressure = velocities[-1], fields[-1].field(flow.pressure)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Solute\n",
    "\n",
    "The dilute solute obeys the same convection-diffusion equation as temperature, with the\n",
    "diffusivity in place of the thermal diffusivity. The three diffusivities are solved on the finer\n",
    "mesh, the smallest one also on the coarser mesh."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "cases = [(meshes[-1], velocity, D) for D in published] + [\n",
    "    (meshes[0], velocities[0], 1e-11)\n",
    "]\n",
    "concentrations = []\n",
    "for mesh, carrier, D in cases:\n",
    "    solute = 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",
    "    transport = ConvectiveHeatTransfer(\n",
    "        domain=channel.volume, material=solute, velocity=field_function(carrier)\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"Controlled diffusion separator: solute\",\n",
    "        geometry=channel,\n",
    "        physics=(transport,),\n",
    "        boundary_conditions=(\n",
    "            FixedTemperature(physics=transport, boundary=faces.inlet_a, value=1.0),\n",
    "            FixedTemperature(physics=transport, boundary=faces.inlet_b, value=0.0),\n",
    "            HeatFlux(\n",
    "                physics=transport,\n",
    "                boundary=faces.all - faces.inlet_a - faces.inlet_b,\n",
    "                value=0.0,\n",
    "            ),\n",
    "        ),\n",
    "    )\n",
    "    numerics = Numerics(\n",
    "        spatial=FiniteElement(\n",
    "            element=Lagrange(order=2), convection=GalerkinAdvection()\n",
    "        ),\n",
    "        linear_solver=SparseDirect(),\n",
    "    )\n",
    "    concentrations.append(\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": [
    "## Comparison with the published values\n",
    "\n",
    "The concentration at outlet B is the solute flow divided by the water flow through that face\n",
    "(mixing-cup average)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "outlet_b = []\n",
    "for (mesh, carrier, D), concentration in zip(cases, concentrations):\n",
    "    carried = derived_field(\n",
    "        carrier,\n",
    "        lambda u, points, c=concentration: u[:, 1] * np.ravel(c.evaluate(points)),\n",
    "        name=\"solute_flux\",\n",
    "        unit=\"mol/m^2/s\",\n",
    "    )\n",
    "    outlet_b.append(\n",
    "        carried.integrate(boundary=faces.outlet_b).value\n",
    "        / carrier.integrate(boundary=faces.outlet_b, normal_component=True).value\n",
    "    )\n",
    "\n",
    "inlet_pressure = pressure.evaluate([[5 * um, -60 * um + 1e-9, 10 * um - 1e-12]])[0]\n",
    "print(\n",
    "    f\"water through outlet B: {2e15 * velocity.integrate(boundary=faces.outlet_b, normal_component=True).value:.3f} pl/s (inlet 15 pl/s)\"\n",
    ")\n",
    "print(f\"pressure at the inlet: {inlet_pressure:.3f} Pa (published about 2.29 Pa)\")\n",
    "print(\"diffusivity [m²/s]   outlet-B concentration [mol/m³]   published   deviation\")\n",
    "for D, value in zip(published, outlet_b):\n",
    "    print(\n",
    "        f\"{D:18.0e} {value:33.4f} {published[D]:11.3f} {100 * (value / published[D] - 1):+10.1f} %\"\n",
    "    )\n",
    "print(\n",
    "    f\"D = 1e-11 m²/s on the coarser mesh ({meshes[0].cell_count} hexahedra): {outlet_b[-1]:.4f} mol/m³, \"\n",
    "    f\"change to the finer mesh {100 * (outlet_b[2] / outlet_b[-1] - 1):+.1f} %\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The speed and the concentration of the largest and the smallest molecule on the mid-depth plane,\n",
    "and the outlet-B concentration against the diffusivity."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(2, 2, size=(15, 11))\n",
    "plots.surface(\n",
    "    velocity,\n",
    "    boundary=faces.mid_plane,\n",
    "    component=lambda u, position: 1e3 * np.linalg.norm(u, axis=1),\n",
    "    contours=4,\n",
    "    subdivisions=3,\n",
    "    aspect=1.0,\n",
    "    label=\"speed [mm/s]\",\n",
    "    title=\"Speed on the mid-depth plane\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "for panel, index in ((fig[1], 2), (fig[2], 0)):\n",
    "    plots.surface(\n",
    "        concentrations[index],\n",
    "        boundary=faces.mid_plane,\n",
    "        limits=(0.0, 1.0),\n",
    "        contours=4,\n",
    "        subdivisions=3,\n",
    "        aspect=1.0,\n",
    "        label=\"concentration [mol/m³]\",\n",
    "        ax=panel,\n",
    "        title=f\"D = {cases[index][2]:.0e} m²/s: {outlet_b[index]:.3f} mol/m³ at outlet B\",\n",
    "    )\n",
    "plots.line(\n",
    "    points={\"simulation\": (list(published), outlet_b[:3])},\n",
    "    reference={\"published benchmark\": (list(published), list(published.values()))},\n",
    "    hlines={\"complete mixing\": 0.5},\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[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Lengthen the contact zone in `controlled_diffusion_separator_geometry.py` and write the STEP file\n",
    "again: the contact time grows and the large molecule's outlet concentration rises roughly with\n",
    "its square root. Halve the flow rate for the same effect, or feed the B outlet of one separator\n",
    "into the next to enrich the small molecule further."
   ]
  }
 ]
}
