{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Mass transfer out of a thin flow channel\n",
    "\n",
    "This benchmark follows one dilute species at a prescribed, uniform velocity.\n",
    "It compares resolved wall exchange with a thickness-averaged sink.\n",
    "\n",
    "A channel of length $L$, width $W$ and small thickness $d$ carries a gas at the mean velocity $u$.\n",
    "A species fed at the concentration $c_0$ leaves through the two permeable walls $z=0$ and $z=d$\n",
    "with the film law $N=k\\,(c-c_\\infty)$, $c_\\infty=0$. When the thickness is small compared with\n",
    "the diffusion length, the concentration is nearly uniform across $d$, and averaging the\n",
    "species balance over the thickness turns the wall flux into a volumetric sink:\n",
    "\n",
    "$$u\\,\\frac{\\partial c}{\\partial x}=D\\,\\nabla^2c-\\frac{2k}{d}\\,c\\qquad\\text{in the mid-plane}.$$\n",
    "\n",
    "OneSimulation solves this two-dimensional problem with the `SpeciesTransport` model: the sink is\n",
    "a decay rate $2k/d$, the inlet a Danckwerts feed, the outlet a convective outflow, with quadratic\n",
    "triangles on the mid-plane section of the STEP channel. As a check of the reduction, the full\n",
    "channel is also computed in 3D with the film law `MassTransferFlux` on the two walls.\n",
    "\n",
    "| Boundary | 2D mid-plane | 3D channel |\n",
    "|---|---|---|\n",
    "| inlet `x_min` | Danckwerts feed $c_0$ | Danckwerts feed $c_0$ |\n",
    "| outlet `x_max` | convective outflow | convective outflow |\n",
    "| side walls `y_min`, `y_max` | no flux | no flux |\n",
    "| permeable walls `z_min`, `z_max` | sink $2k/d$ in the volume | $N=k\\,c$ |\n",
    "\n",
    "**Reference.** P. V. Danckwerts, *Continuous flow systems*, Chem. Eng. Sci. 2, 1-13 (1953);\n",
    "O. Levenspiel, *Chemical Reaction Engineering*, 3rd ed., Wiley 1999, ch. 13. With a uniform\n",
    "velocity the 2D solution does not depend on $y$ and equals the dispersion model with the\n",
    "first-order rate $\\kappa=2k/d$: with $\\mathrm{Pe}=uL/D$, $\\mathrm{Da}=\\kappa L/u$ and\n",
    "$a=\\sqrt{1+4\\mathrm{Da}/\\mathrm{Pe}}$,\n",
    "\n",
    "$$\\frac{c_\\mathrm{out}}{c_0}=\\frac{4a\\,e^{\\mathrm{Pe}/2}}{(1+a)^2e^{a\\mathrm{Pe}/2}-(1-a)^2e^{-a\\mathrm{Pe}/2}}.$$\n",
    "\n",
    "The reduction itself is accurate when the mass-transfer Biot number $\\mathrm{Bi}=kd/(2D)$ is\n",
    "small; the 3D channel measures the remaining difference."
   ],
   "id": "d4db3ca18be5"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import StructuredHexahedralMesher, TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.chemistry import (\n",
    "    DanckwertsInflow,\n",
    "    MassTransferFlux,\n",
    "    SpeciesOutflow,\n",
    "    SpeciesTransport,\n",
    "    TransportSpecies,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "af751b8c188d"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "The channel from the STEP file and its mid-plane, meshed with quadratic triangles of four\n",
    "sizes for a mesh study."
   ],
   "id": "5fe376f01083"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "channel = load(\"thin_channel_wall_mass_transfer.step\")\n",
    "plane = channel.section((0, 0, 1), origin=(0, 0, 0.00025))\n",
    "length, width, thickness = channel.size\n",
    "meshes = {size: TriangularMesher(target_size=size).generate(plane) for size in (2e-3, 1e-3, 5e-4, 3e-4)}\n",
    "fig = plots.figure(1, 2, size=(15, 5))\n",
    "plots.geometry(\n",
    "    channel,\n",
    "    selection={\"inlet\": channel.boundaries.x_min, \"permeable walls\": channel.boundaries.z_max},\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=50, azimuth=-60),\n",
    "    title=\"Thin channel (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[3e-4],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Mid-plane: {meshes[3e-4].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "ba4167cb0127"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Air with a light gas: $D=2\\times10^{-5}$ m²/s, mean velocity 5 cm/s, film coefficient 2 mm/s,\n",
    "feed 1 mol/m³."
   ],
   "id": "61747e7cdbef"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "diffusivity, velocity, film, feed = 2e-5, 0.05, 2e-3, 1.0\n",
    "sink = 2 * film / thickness\n",
    "peclet, damkoehler = velocity * length / diffusivity, sink * length / velocity\n",
    "print(\n",
    "    f\"Pe = {peclet:.0f}, Da = {damkoehler:.2f}, Biot number k d / 2D = {film * thickness / (2 * diffusivity):.4f}\"\n",
    ")\n",
    "planar = SpeciesTransport(\n",
    "    domain=plane.domain(),\n",
    "    species=(TransportSpecies(\"A\", diffusivity=diffusivity, decay_rate=sink),),\n",
    "    velocity=(velocity, 0.0),\n",
    ")\n",
    "fields = {\n",
    "    size: Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Thin channel, mid-plane\",\n",
    "            geometry=plane,\n",
    "            physics=(planar,),\n",
    "            boundary_conditions=(\n",
    "                DanckwertsInflow(\n",
    "                    physics=planar, boundary=plane.boundaries.x_min, concentration=feed\n",
    "                ),\n",
    "                SpeciesOutflow(physics=planar, boundary=plane.boundaries.x_max),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=mesh,\n",
    "        numerics=Numerics(\n",
    "            spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    "        ),\n",
    "    )\n",
    "    .solve_stationary()\n",
    "    .field(planar.field(\"A\"))\n",
    "    for size, mesh in meshes.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "d747fac5b94e"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Three-dimensional check\n",
    "\n",
    "The full channel with the film law on both walls, 128 x 20 x 8 hexahedra. Refinement targets axial transport and the\n",
    "concentration variation normal to the permeable walls."
   ],
   "id": "3faf7cf9cb78"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "solid = SpeciesTransport(\n",
    "    domain=channel.volume,\n",
    "    species=(TransportSpecies(\"A\", diffusivity=diffusivity),),\n",
    "    velocity=(velocity, 0.0, 0.0),\n",
    ")\n",
    "volume_mesh = StructuredHexahedralMesher(cells=(128, 20, 8)).generate(channel)\n",
    "volume = (\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Thin channel, 3D\",\n",
    "            geometry=channel,\n",
    "            physics=(solid,),\n",
    "            boundary_conditions=(\n",
    "                DanckwertsInflow(\n",
    "                    physics=solid, boundary=channel.boundaries.x_min, concentration=feed\n",
    "                ),\n",
    "                SpeciesOutflow(physics=solid, boundary=channel.boundaries.x_max),\n",
    "                MassTransferFlux(\n",
    "                    physics=solid,\n",
    "                    boundary=channel.boundaries.z_min | channel.boundaries.z_max,\n",
    "                    coefficient=film,\n",
    "                ),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=volume_mesh,\n",
    "        numerics=Numerics(\n",
    "            spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    "        ),\n",
    "    )\n",
    "    .solve_stationary()\n",
    "    .field(solid.field(\"A\"))\n",
    ")"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "2fdbe2a0d1f5"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison\n",
    "\n",
    "The outlet concentration (convective outflow divided by the feed), the share of the species that\n",
    "leaves through the walls, and the profile along the channel axis."
   ],
   "id": "3dabebe87ca7"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "root = np.sqrt(1 + 4 * damkoehler / peclet)\n",
    "exit_ratio = (\n",
    "    4\n",
    "    * root\n",
    "    * np.exp(peclet / 2)\n",
    "    / ((1 + root) ** 2 * np.exp(root * peclet / 2) - (1 - root) ** 2 * np.exp(-root * peclet / 2))\n",
    ")\n",
    "print(\"  mesh size   2D c_out / c0   Danckwerts   deviation    feed + outflow + wall loss\")\n",
    "for size, field in fields.items():\n",
    "    print(f\"2D mesh: {meshes[size].cell_count} triangles, {len(field.space.dof_coordinates)} concentration nodes\")\n",
    "    outflow = field.boundary_flux(plane.boundaries.x_max) / (velocity * width * feed)\n",
    "    balance = (\n",
    "        field.boundary_flux(plane.boundaries.x_min)\n",
    "        + field.boundary_flux(plane.boundaries.x_max)\n",
    "        + sink * field.integrate().value\n",
    "    )\n",
    "    print(\n",
    "        f\"{1e3 * size:8.1f} mm {outflow:14.6f} {exit_ratio:12.6f} {100 * (outflow / exit_ratio - 1):+9.3f} % {balance:16.1e}\"\n",
    "    )\n",
    "print(f\"3D mesh: {volume_mesh.cell_count} hexahedra, {len(volume.space.dof_coordinates)} concentration nodes\")\n",
    "three = volume.boundary_flux(channel.boundaries.x_max) / (velocity * width * thickness * feed)\n",
    "walls = volume.boundary_flux(channel.boundaries.z_min | channel.boundaries.z_max) / (\n",
    "    velocity * width * thickness * feed\n",
    ")\n",
    "print(\n",
    "    f\"3D channel: c_out / c0 = {three:.6f} ({100 * (three / exit_ratio - 1):+.2f} % against the reduced model), \"\n",
    "    f\"share through the walls {walls:.4f} (reduced model {1 - exit_ratio:.4f})\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "82064aa8e09c"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The mid-plane model reproduces the exact solution of the reduced problem on every mesh. The\n",
    "full 3D channel passes slightly more species: at the walls the concentration is lower than its\n",
    "thickness average, by a fraction of about Bi/3 = 0.8 %, so the walls transfer a little less;\n",
    "over Da = 3.2 this adds up to the 2.4 % higher outlet concentration.\n",
    "\n",
    "## Figure\n",
    "\n",
    "The concentration in the mid-plane, and the concentration along the channel axis from the 2D\n",
    "model, the 3D channel (mid-plane and wall) and the Danckwerts profile."
   ],
   "id": "79c6c86b4ce7"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x = np.linspace(0.0, length, 201)\n",
    "denominator = (1 - root) / 2 - (1 + root) ** 2 / (2 * (1 - root)) * np.exp(peclet * root)\n",
    "profile = (\n",
    "    feed\n",
    "    / denominator\n",
    "    * (\n",
    "        np.exp(peclet * (1 + root) / 2 * x / length)\n",
    "        - (1 + root)\n",
    "        / (1 - root)\n",
    "        * np.exp(peclet * root)\n",
    "        * np.exp(peclet * (1 - root) / 2 * x / length)\n",
    "    )\n",
    ")\n",
    "fig = plots.figure(1, 2, size=(16, 5))\n",
    "plots.surface(\n",
    "    fields[3e-4],\n",
    "    limits=(0.0, 1.0),\n",
    "    contours=11,\n",
    "    subdivisions=2,\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    label=\"c [mol/m³]\",\n",
    "    title=\"Concentration in the mid-plane\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    1e3 * x,\n",
    "    {\n",
    "        \"2D mid-plane\": np.asarray(\n",
    "            fields[3e-4].evaluate(np.column_stack((x, np.full_like(x, width / 2))))\n",
    "        ).reshape(-1)\n",
    "    },\n",
    "    points={\n",
    "        \"3D channel, mid-plane\": (\n",
    "            1e3 * x[::10],\n",
    "            np.asarray(\n",
    "                volume.evaluate(\n",
    "                    np.column_stack((x[::10], np.full(21, width / 2), np.full(21, thickness / 2)))\n",
    "                )\n",
    "            ).reshape(-1),\n",
    "        ),\n",
    "        \"3D channel, wall\": (\n",
    "            1e3 * x[::10],\n",
    "            np.asarray(\n",
    "                volume.evaluate(np.column_stack((x[::10], np.full(21, width / 2), np.zeros(21))))\n",
    "            ).reshape(-1),\n",
    "        ),\n",
    "    },\n",
    "    reference={\"Danckwerts\": (1e3 * x, profile)},\n",
    "    xlabel=\"x [mm]\",\n",
    "    ylabel=\"c [mol/m³]\",\n",
    "    title=\"Along the channel axis\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "d71149725d34"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the film coefficient tenfold and the Biot number reaches 0.25: the 3D concentration at the\n",
    "walls drops visibly below the mid-plane value and the reduced model overpredicts the transfer.\n",
    "Replace the uniform velocity by the coupled velocity field of a channel with obstacles\n",
    "(`FieldCoupling` from a flow model) and the mid-plane model still applies, while the closed-form\n",
    "check does not."
   ],
   "id": "43c3f12b43a1"
  }
 ]
}
