{
 "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": [
    "# Laminar static mixer with twisted blades\n",
    "\n",
    "Static (motionless) mixers are pipe inserts that mix viscous liquids in laminar flow. The Kenics\n",
    "design uses short blades twisted by 180°, alternately to the right and to the left, each turned by\n",
    "90° against the previous one. Every blade splits the stream in two and turns each half, and the\n",
    "next one splits it again: the number of layers doubles with each element, and diffusion across\n",
    "the thinner and thinner layers completes the mixing. The price is a higher pressure drop than in\n",
    "the empty pipe.\n",
    "\n",
    "The mixer comes from the CAD file `kenics_static_mixer.step`, a pipe of diameter $D=4$ mm and\n",
    "length 20 mm with two elements 6 mm long and 0.4 mm thick; `kenics_static_mixer_empty.step` is the\n",
    "same pipe without blades. Both are written by `kenics_static_mixer_geometry.py`. A liquid of the\n",
    "viscosity of water flows at the mean speed $\\bar U=0.5$ mm/s ($Re=2$); half of the inflow carries\n",
    "a tracer. The tracer diffusivity is chosen for the Péclet number $Pe=\\bar UD/\\mathcal D=100$.\n",
    "\n",
    "$$-\\nabla p+\\mu\\nabla^2\\mathbf u=0,\\quad\\nabla\\cdot\\mathbf u=0,\\qquad\\mathbf u\\cdot\\nabla c=\\mathcal D\\nabla^2c$$\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 sections before the elements the pressure falls as in Hagen-Poiseuille\n",
    "flow, $dp/dz=-8\\mu\\bar U/R^2$. The tracer and the liquid that enter must leave. The pressure drop\n",
    "of the elements relative to an empty pipe of the same length is of order 5 to 7 for Kenics\n",
    "elements in creeping flow (A. Thakur, C. Vial, K. D. P. Nigam, E. B. Nauman, G. Djelveh, \"Static\n",
    "mixers in the process industries - a review\", *Chem. Eng. Res. Des.* 81, 787-826, 2003)."
   ]
  },
  {
   "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\n",
    "\n",
    "Tetrahedra of 0.6 mm in the mixer and the empty pipe; the mesh study adds 0.45 mm in the mixer."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mm = 1e-3\n",
    "parts = {\n",
    "    \"mixer\": load(\"kenics_static_mixer.step\"),\n",
    "    \"empty pipe\": load(\"kenics_static_mixer_empty.step\"),\n",
    "}\n",
    "mixer = parts[\"mixer\"]\n",
    "radius, length = mixer.size[0] / 2, mixer.size[2]\n",
    "cases = [(\"mixer\", 0.6), (\"mixer\", 0.45), (\"empty pipe\", 0.6)]\n",
    "meshes = {\n",
    "    (name, size): TetrahedralMesher(target_size=size * mm).generate(parts[name])\n",
    "    for name, size in cases\n",
    "}\n",
    "\n",
    "view = plots.Camera(elevation=20, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.geometry(\n",
    "    mixer,\n",
    "    selection={\n",
    "        \"blades\": mixer.boundaries.all\n",
    "        - mixer.boundaries.inlet\n",
    "        - mixer.boundaries.outlet\n",
    "        - mixer.boundaries.outer_wall,\n",
    "        \"inlet\": mixer.boundaries.inlet,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Pipe with two twisted blades\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"mixer\", 0.6],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{meshes['mixer', 0.6].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Flow\n",
    "\n",
    "One flow problem per mesh; the Poiseuille inflow comes from `fully_developed_inflow`."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "water, speed = NewtonianFluid(density=1000.0, dynamic_viscosity=1.0e-3), 0.5e-3\n",
    "flows = {}\n",
    "for name, size in cases:\n",
    "    part, mesh = parts[name], meshes[name, size]\n",
    "    faces = part.boundaries\n",
    "    walls = faces.all - faces.inlet - faces.outlet\n",
    "    model = IncompressibleNavierStokes(domain=part.volume, material=water)\n",
    "    problem = Problem(\n",
    "        name=f\"Static mixer: flow, {name}\",\n",
    "        geometry=part,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            FixedVelocity(\n",
    "                boundary=faces.inlet,\n",
    "                physics=model,\n",
    "                value=fully_developed_inflow(\n",
    "                    mesh, faces.inlet, mean_velocity=speed, no_slip=walls\n",
    "                ),\n",
    "            ),\n",
    "            FlowTraction(boundary=faces.outlet, physics=model, value=(0.0, 0.0, 0.0)),\n",
    "            NoSlipWall(boundary=walls, physics=model),\n",
    "        ),\n",
    "    )\n",
    "    numerics = Numerics(\n",
    "        spatial=FiniteElement(element=TaylorHood()),\n",
    "        initial_guess={model.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",
    "    flows[name, size] = solved.field(model.velocity), solved.field(model.pressure)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Tracer\n",
    "\n",
    "The tracer follows the same convection-diffusion equation as temperature, in the computed flow."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "diffusivity = speed * 2 * radius / 100\n",
    "tracer = 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",
    "tracers = {}\n",
    "for name, size in cases:\n",
    "    part = parts[name]\n",
    "    transport = ConvectiveHeatTransfer(\n",
    "        domain=part.volume,\n",
    "        material=tracer,\n",
    "        velocity=field_function(flows[name, size][0]),\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=f\"Static mixer: tracer, {name}\",\n",
    "        geometry=part,\n",
    "        physics=(transport,),\n",
    "        boundary_conditions=(\n",
    "            FixedTemperature(\n",
    "                physics=transport,\n",
    "                boundary=part.boundaries.inlet,\n",
    "                value=lambda x: 0.5 * (1 + np.tanh(x / (0.2 * mm))),\n",
    "            ),\n",
    "            HeatFlux(\n",
    "                physics=transport,\n",
    "                boundary=part.boundaries.all - part.boundaries.inlet,\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",
    "    tracers[name, size] = (\n",
    "        Simulation(problem=problem, mesh=meshes[name, size], 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\n",
    "of variation $\\sigma/\\bar c$ of the tracer on cross-sections along the pipe, sampled at the points\n",
    "of each section that lie in the liquid at least 0.15 mm from a blade (`contains`)."
   ]
  },
  {
   "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",
    "area_weight = r.ravel()\n",
    "section = lambda z: np.column_stack((disc, np.full(len(disc), z)))\n",
    "mean_pressure = lambda key, z: np.average(\n",
    "    np.ravel(flows[key][1].evaluate(section(z))), weights=area_weight\n",
    ")\n",
    "poiseuille = 8 * water.dynamic_viscosity * speed / radius**2\n",
    "stations = np.linspace(0.2, 19.8, 50) * mm\n",
    "margin = 0.15 * mm * np.array([[0, 0, 0], [1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0]])\n",
    "variation = {}\n",
    "for key, c in tracers.items():\n",
    "    inside = [\n",
    "        np.all([parts[key[0]].contains(section(z) + shift) for shift in margin], axis=0)\n",
    "        for z in stations\n",
    "    ]\n",
    "    w = [\n",
    "        flows[key][0].evaluate(section(z)[keep])[:, 2] * area_weight[keep]\n",
    "        for z, keep in zip(stations, inside)\n",
    "    ]\n",
    "    v = [np.ravel(c.evaluate(section(z)[keep])) for z, keep in zip(stations, inside)]\n",
    "    variation[key] = 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",
    "flux = (\n",
    "    lambda key, face, field: derived_field(\n",
    "        flows[key][0],\n",
    "        lambda u, points, c=field: 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\"Reynolds number {water.density * speed * 2 * radius / water.dynamic_viscosity:.1f}, Péclet number {speed * 2 * radius / diffusivity:.0f}\"\n",
    ")\n",
    "for key in cases:\n",
    "    faces = parts[key[0]].boundaries\n",
    "    gradient = (mean_pressure(key, 1 * mm) - mean_pressure(key, 3 * mm)) / (2 * mm)\n",
    "    drop = mean_pressure(key, 3 * mm) - mean_pressure(key, 17 * mm)\n",
    "    water_in, water_out = (\n",
    "        flows[key][0].integrate(boundary=faces.inlet, normal_component=True).value,\n",
    "        flows[key][0].integrate(boundary=faces.outlet, normal_component=True).value,\n",
    "    )\n",
    "    tracer_balance = (\n",
    "        flux(key, faces.outlet, tracers[key]) / flux(key, faces.inlet, tracers[key]) - 1\n",
    "    )\n",
    "    print(\n",
    "        f\"{key[0]:10s} {meshes[key].cell_count:6d} tetrahedra: inlet gradient / Poiseuille {gradient / poiseuille:.4f}, \"\n",
    "        f\"pressure drop 3-17 mm {drop:.4e} Pa, water balance {(water_out + water_in) / water_out:+.1e}, tracer balance {tracer_balance:+.1e}, \"\n",
    "        f\"outlet variation {variation[key][-1]:.4f}\"\n",
    "    )\n",
    "elements = {\n",
    "    size: (\n",
    "        mean_pressure((\"mixer\", size), 3 * mm)\n",
    "        - mean_pressure((\"mixer\", size), 17 * mm)\n",
    "        - poiseuille * 2 * mm\n",
    "    )\n",
    "    / (poiseuille * 12 * mm)\n",
    "    for size in (0.6, 0.45)\n",
    "}\n",
    "print(\n",
    "    \"pressure drop of the two elements over an empty pipe of 12 mm: \"\n",
    "    + \", \".join(f\"{z:.2f} (mesh {size} mm)\" for size, z in elements.items())\n",
    "    + \"; published range for Kenics elements about 5 to 7\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The tracer on cross-sections behind each element, and the coefficient of variation along the pipe\n",
    "with and without blades."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(\n",
    "    layout=[\n",
    "        [\"start\", \"first\", \"second\", \"end\"],\n",
    "        [\"mixing\", \"mixing\", \"mixing\", \"mixing\"],\n",
    "    ],\n",
    "    size=(18, 10),\n",
    ")\n",
    "for panel, z, title in (\n",
    "    (\"start\", 2.0, \"before the elements\"),\n",
    "    (\"first\", 10.0, \"after the first element\"),\n",
    "    (\"second\", 16.0, \"after the second element\"),\n",
    "    (\"end\", 19.8, \"at the outlet\"),\n",
    "):\n",
    "    plots.section(\n",
    "        tracers[\"mixer\", 0.6],\n",
    "        plane=Plane(origin=(0, 0, z * mm), normal=(0, 0, 1)),\n",
    "        aspect=1.0,\n",
    "        limits=(0.0, 1.0),\n",
    "        subdivisions=2,\n",
    "        label=\"tracer c\",\n",
    "        title=f\"z = {z:.1f} mm, {title}\",\n",
    "        ax=fig[panel],\n",
    "    )\n",
    "plots.line(\n",
    "    stations / mm,\n",
    "    {\"mixer\": variation[\"mixer\", 0.6], \"empty pipe\": variation[\"empty pipe\", 0.6]},\n",
    "    points={\"mixer, finer mesh\": (stations[::4] / mm, variation[\"mixer\", 0.45][::4])},\n",
    "    vlines={\"first element\": 4.0, \"second element\": 10.0, \"end of the elements\": 16.0},\n",
    "    ylimits=(0.0, 1.05),\n",
    "    xlabel=\"distance along the pipe z [mm]\",\n",
    "    ylabel=\"coefficient of variation σ / c̄\",\n",
    "    title=\"Mixing along the pipe, Pe = 100\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[\"mixing\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add elements in `kenics_static_mixer_geometry.py` and write the STEP file again: each element\n",
    "halves the layer thickness, and at higher Péclet numbers - more viscous liquids, larger molecules\n",
    "- more elements are needed. Raising the flow rate past $Re\\approx100$ adds secondary vortices that\n",
    "change both the mixing and the pressure drop."
   ]
  }
 ]
}
