{
 "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": [
    "# Helical static mixer: mixing element by element\n",
    "\n",
    "A helical static mixer is a row of short blades twisted by 180°, alternately right- and\n",
    "left-handed and each turned by 90° against the previous one. Each element divides every layer of\n",
    "the stream into two and restacks them, so after $n$ elements the stream consists of about $2^n$\n",
    "layers, and the distance that diffusion must bridge halves with every element. How many elements\n",
    "a duty needs depends on the Péclet number $Pe=\\bar UD/\\mathcal D$: the slower the diffusion, the\n",
    "more layers are needed before it completes the mixing.\n",
    "\n",
    "The mixer comes from the CAD file `helical_static_mixer_elements.step`, written by\n",
    "`helical_static_mixer_elements_geometry.py`: a pipe of diameter $D=4$ mm with six elements 6 mm long\n",
    "and 0.4 mm thick between 4 mm of empty pipe at each end. A liquid of the viscosity of water flows\n",
    "at $\\bar U=0.5$ mm/s ($Re=2$); half of the inflow carries a tracer, at $Pe=50$ and $Pe=200$.\n",
    "\n",
    "| face | flow | tracer |\n",
    "|---|---|---|\n",
    "| `inlet` | Poiseuille profile, mean speed $\\bar U$ | $c=\\tfrac12\\left(1+\\tanh(x/0.2\\,\\text{mm})\\right)$ |\n",
    "| `outlet` | traction free | no diffusive flux |\n",
    "| pipe wall and blades | no slip | no flux |\n",
    "\n",
    "**Reference.** In the empty inlet section the pressure falls as in Hagen-Poiseuille flow,\n",
    "$dp/dz=-8\\mu\\bar U/R^2$; the pressure drop of the elements relative to an empty pipe of the same\n",
    "length is of order 5 to 7 for this element type in creeping flow (A. Thakur, C. Vial, K. D. P.\n",
    "Nigam, E. B. Nauman, G. Djelveh, *Chem. Eng. Res. Des.* 81, 787-826, 2003); the tracer that enters\n",
    "must leave."
   ]
  },
  {
   "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"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mm = 1e-3\n",
    "mixer = load(\"helical_static_mixer_elements.step\")\n",
    "faces = mixer.boundaries\n",
    "walls = faces.all - faces.inlet - faces.outlet\n",
    "radius, length = mixer.size[0] / 2, mixer.size[2]\n",
    "mesh = TetrahedralMesher(target_size=0.6 * mm).generate(mixer)\n",
    "\n",
    "view = plots.Camera(elevation=20, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(16, 5.5))\n",
    "plots.geometry(\n",
    "    mixer,\n",
    "    selection={\"blades\": walls - faces.outer_wall, \"inlet\": faces.inlet},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Pipe with six helical elements\",\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": [
    "## Flow and tracer\n",
    "\n",
    "The creeping flow first, then the tracer in it for both Péclet numbers."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "water, speed = NewtonianFluid(density=1000.0, dynamic_viscosity=1.0e-3), 0.5e-3\n",
    "flow = IncompressibleNavierStokes(domain=mixer.volume, material=water)\n",
    "problem = Problem(\n",
    "    name=\"Helical 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(), absolute_tolerance=1e-20, relative_tolerance=1e-9\n",
    "    ),\n",
    ")\n",
    "solved = Simulation(problem=problem, mesh=mesh, numerics=numerics).solve_stationary()\n",
    "velocity, pressure = solved.field(flow.velocity), solved.field(flow.pressure)\n",
    "\n",
    "tracers = {}\n",
    "for peclet in (50, 200):\n",
    "    tracer = IsotropicSolid(\n",
    "        density=1.0,\n",
    "        specific_heat_capacity=1.0,\n",
    "        thermal_conductivity=speed * 2 * radius / peclet,\n",
    "        youngs_modulus=1.0,\n",
    "        poisson_ratio=0.3,\n",
    "        thermal_expansion_coefficient=0.0,\n",
    "    )\n",
    "    transport = ConvectiveHeatTransfer(\n",
    "        domain=mixer.volume, material=tracer, velocity=field_function(velocity)\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"Helical mixer: tracer\",\n",
    "        geometry=mixer,\n",
    "        physics=(transport,),\n",
    "        boundary_conditions=(\n",
    "            FixedTemperature(\n",
    "                physics=transport,\n",
    "                boundary=faces.inlet,\n",
    "                value=lambda x: 0.5 * (1 + np.tanh(x / (0.2 * 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",
    "    tracers[peclet] = (\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 are averaged over cross-sections. The mixing quality is the flow-weighted coefficient of\n",
    "variation $\\sigma/\\bar c$ at the end of each element, sampled at the points of the section that\n",
    "lie in the liquid at least 0.15 mm from a blade."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "r, angle = np.meshgrid(\n",
    "    np.linspace(0.05, 0.95, 12) * radius, np.linspace(0, 2 * np.pi, 36, endpoint=False)\n",
    ")\n",
    "disc = np.column_stack(((r * np.cos(angle)).ravel(), (r * np.sin(angle)).ravel()))\n",
    "weight = r.ravel()\n",
    "section = lambda z: np.column_stack((disc, np.full(len(disc), z)))\n",
    "margin = 0.15 * mm * np.array([[0, 0, 0], [1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0]])\n",
    "ends = (3.8 + 6 * np.arange(7)) * mm\n",
    "inside = [\n",
    "    np.all([mixer.contains(section(z) + shift) for shift in margin], axis=0)\n",
    "    for z in ends\n",
    "]\n",
    "variation = {}\n",
    "for peclet, c in tracers.items():\n",
    "    w = [\n",
    "        velocity.evaluate(section(z)[keep])[:, 2] * weight[keep]\n",
    "        for z, keep in zip(ends, inside)\n",
    "    ]\n",
    "    v = [np.ravel(c.evaluate(section(z)[keep])) for z, keep in zip(ends, inside)]\n",
    "    variation[peclet] = np.array(\n",
    "        [\n",
    "            np.sqrt(np.average((a - np.average(a, weights=b)) ** 2, weights=b))\n",
    "            / np.average(a, weights=b)\n",
    "            for a, b in zip(v, w)\n",
    "        ]\n",
    "    )\n",
    "mean_pressure = lambda z: np.average(\n",
    "    np.ravel(pressure.evaluate(section(z))), weights=weight\n",
    ")\n",
    "poiseuille = 8 * water.dynamic_viscosity * speed / radius**2\n",
    "elements = (\n",
    "    mean_pressure(3 * mm) - mean_pressure(length - 3 * mm) - poiseuille * 2 * mm\n",
    ") / (poiseuille * 36 * mm)\n",
    "flux = (\n",
    "    lambda c, face: derived_field(\n",
    "        velocity,\n",
    "        lambda u, points: np.ravel(c.evaluate(points)) * u[:, 2],\n",
    "        name=\"tracer_flux\",\n",
    "        unit=\"1\",\n",
    "    )\n",
    "    .integrate(boundary=face)\n",
    "    .value\n",
    ")\n",
    "\n",
    "print(\n",
    "    f\"{mesh.cell_count} tetrahedra; inlet pressure gradient / Hagen-Poiseuille {(mean_pressure(1 * mm) - mean_pressure(3 * mm)) / (2 * mm) / poiseuille:.4f}\"\n",
    ")\n",
    "print(\n",
    "    f\"pressure drop of the six elements over an empty pipe of the same length: {elements:.2f} (published about 5 to 7)\"\n",
    ")\n",
    "print(\n",
    "    \"coefficient of variation at the end of element   0      1      2      3      4      5      6\"\n",
    ")\n",
    "for peclet in tracers:\n",
    "    print(\n",
    "        f\"Pe = {peclet:3d} {'':34s}\"\n",
    "        + \" \".join(f\"{value:6.3f}\" for value in variation[peclet])\n",
    "        + f\"   tracer balance {flux(tracers[peclet], faces.outlet) / flux(tracers[peclet], faces.inlet) - 1:+.1e}\"\n",
    "    )\n",
    "print(\n",
    "    \"reduction per element (geometric mean of elements 2 to 6): \"\n",
    "    + \", \".join(\n",
    "        f\"Pe = {peclet}: {(variation[peclet][6] / variation[peclet][1]) ** 0.2:.3f}\"\n",
    "        for peclet in tracers\n",
    "    )\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The tracer at the end of every second element at $Pe=200$, and the coefficient of variation\n",
    "element by element."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(\n",
    "    layout=[[\"e0\", \"e2\", \"e4\", \"e6\"], [\"mixing\", \"mixing\", \"mixing\", \"mixing\"]],\n",
    "    size=(18, 10),\n",
    ")\n",
    "for panel, index in ((\"e0\", 0), (\"e2\", 2), (\"e4\", 4), (\"e6\", 6)):\n",
    "    plots.section(\n",
    "        tracers[200],\n",
    "        plane=Plane(origin=(0, 0, ends[index]), normal=(0, 0, 1)),\n",
    "        aspect=1.0,\n",
    "        limits=(0.0, 1.0),\n",
    "        subdivisions=2,\n",
    "        label=\"tracer c\",\n",
    "        title=f\"after {index} elements\",\n",
    "        ax=fig[panel],\n",
    "    )\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"Pe = {peclet}\": (list(range(7)), variation[peclet]) for peclet in tracers\n",
    "    },\n",
    "    scale=\"logy\",\n",
    "    markers=True,\n",
    "    xlabel=\"number of elements passed\",\n",
    "    ylabel=\"coefficient of variation σ / c̄\",\n",
    "    title=\"Mixing element by element\",\n",
    "    ax=fig[\"mixing\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the twist of the blades or their length in `helical_static_mixer_elements_geometry.py` and\n",
    "write the STEP file again: shorter, more strongly twisted blades mix more per element at a higher\n",
    "pressure drop. The coefficient of variation needed by a process then fixes the number of elements."
   ]
  }
 ]
}
