{
 "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": [
    "# Danckwerts benchmark: tubular reactor with axial dispersion\n",
    "\n",
    "In a real tube the fluid is neither perfectly mixed nor in ideal plug flow. The dispersion model\n",
    "superposes an axial dispersion coefficient $D$ on the mean velocity $u$. For a first-order\n",
    "reaction $A\\to B$ the steady concentration along the tube of length $L$ obeys\n",
    "\n",
    "$$u\\,\\frac{dc}{dx} = D\\,\\frac{d^2c}{dx^2} - k\\,c,\\qquad 0<x<L .$$\n",
    "\n",
    "Danckwerts (1953) argued that the dispersion stops at the ends of the vessel. All reactant that\n",
    "enters must cross the inlet plane, and nothing flows back through the outlet:\n",
    "\n",
    "| boundary | condition | as total outward flux $\\;-(u\\,c - D\\,c')\\cdot n$ |\n",
    "|---|---|---|\n",
    "| inlet $x=0$ | $u\\,c_0 = u\\,c - D\\,c'$ | prescribed: $-u\\,c_0$ |\n",
    "| outlet $x=L$ | $c' = 0$ | advective only: $u\\,c$ |\n",
    "\n",
    "The inlet condition makes the concentration jump at the entrance; that jump is the signature of\n",
    "the benchmark. Two numbers govern the result, the Peclet number $\\mathrm{Pe}=uL/D$ and the\n",
    "Damköhler number $\\mathrm{Da}=kL/u$.\n",
    "\n",
    "**Reference.** P. V. Danckwerts, *Continuous flow systems*, Chem. Eng. Sci. 2 (1953) 1;\n",
    "J. F. Wehner & R. H. Wilhelm, Chem. Eng. Sci. 6 (1956) 89. With $a=\\sqrt{1+4\\,\\mathrm{Da}/\\mathrm{Pe}}$\n",
    "and $z=x/L$ the exact profile is\n",
    "\n",
    "$$\\frac{c(z)}{c_0}=\\frac{2\\,e^{\\mathrm{Pe}\\,z/2}\\Big[(1+a)\\,e^{a\\mathrm{Pe}(1-z)/2}-(1-a)\\,e^{-a\\mathrm{Pe}(1-z)/2}\\Big]}\n",
    "  {(1+a)^2e^{a\\mathrm{Pe}/2}-(1-a)^2e^{-a\\mathrm{Pe}/2}},$$\n",
    "\n",
    "which tends to the stirred tank, $1/(1+\\mathrm{Da})$, for $\\mathrm{Pe}\\to0$ and to plug flow,\n",
    "$e^{-\\mathrm{Da}}$, for $\\mathrm{Pe}\\to\\infty$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d1 import Line\n",
    "from onesim.meshing import StructuredLineMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import Newton\n",
    "from onesim.numerics.time import BDF, BackwardEuler\n",
    "from onesim.physics.chemistry import SpeciesTransport, TransportSpecies\n",
    "from onesim.results.comparisons import convergence\n",
    "from onesim.simulation import OutwardFluxBoundary, 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": [
    "## Tube, mesh and numerics\n",
    "\n",
    "A 1 m tube with $u = 1$ m/s and $\\mathrm{Da}=2$. The tube starts empty and is run for fifteen\n",
    "residence times with the second-order BDF method until the profile is steady; space is\n",
    "discretised with quadratic Lagrange elements."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "length, velocity, rate, inlet = 1.0, 1.0, 2.0, 1.0\n",
    "tube = Line(start=(0.0, 0.0, 0.0), end=(length, 0.0, 0.0))\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(2), quadrature_order=5),\n",
    "    linear_solver=SparseDirect(),\n",
    "    nonlinear_solver=Newton(\n",
    "        linear_solver=SparseDirect(),\n",
    "        jacobian=\"analytic\",\n",
    "        absolute_tolerance=1e-12,\n",
    "        relative_tolerance=1e-11,\n",
    "    ),\n",
    "    time_integrator=BDF(order=2, startup=BackwardEuler()),\n",
    ")\n",
    "a = lambda Pe: np.sqrt(1 + 4 * rate * length / velocity / Pe)\n",
    "exact = lambda Pe, z: (\n",
    "    2\n",
    "    * np.exp(Pe * z / 2)\n",
    "    * (\n",
    "        (1 + a(Pe)) * np.exp(a(Pe) * Pe * (1 - z) / 2)\n",
    "        - (1 - a(Pe)) * np.exp(-a(Pe) * Pe * (1 - z) / 2)\n",
    "    )\n",
    "    / (\n",
    "        (1 + a(Pe)) ** 2 * np.exp(a(Pe) * Pe / 2)\n",
    "        - (1 - a(Pe)) ** 2 * np.exp(-a(Pe) * Pe / 2)\n",
    "    )\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model and Peclet sweep\n",
    "\n",
    "The same reactor for eight Peclet numbers on 80 elements. The Danckwerts conditions enter as\n",
    "total outward fluxes: a fixed feed flux at the inlet, the advective flux of the interior state at\n",
    "the outlet."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "peclets = (0.1, 0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 50.0)\n",
    "models = {\n",
    "    Pe: SpeciesTransport(\n",
    "        domain=tube.line,\n",
    "        velocity=velocity,\n",
    "        species=(\n",
    "            TransportSpecies(\"A\", diffusivity=velocity * length / Pe, decay_rate=rate),\n",
    "        ),\n",
    "    )\n",
    "    for Pe in peclets\n",
    "}\n",
    "problems = {\n",
    "    Pe: Problem(\n",
    "        name=\"Danckwerts tubular reactor\",\n",
    "        geometry=tube,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            OutwardFluxBoundary(\n",
    "                physics=model,\n",
    "                boundary=tube.boundaries.start,\n",
    "                flux=lambda **kw: np.array([-velocity * inlet]),\n",
    "                jacobian=lambda **kw: np.zeros((1, 1)),\n",
    "            ),\n",
    "            OutwardFluxBoundary(\n",
    "                physics=model,\n",
    "                boundary=tube.boundaries.end,\n",
    "                flux=lambda interior, **kw: velocity * interior,\n",
    "                jacobian=lambda **kw: np.array([[velocity]]),\n",
    "                wave_speed=velocity,\n",
    "            ),\n",
    "        ),\n",
    "        initial_conditions=(InitialValue(model.concentration(\"A\"), 0.0),),\n",
    "    )\n",
    "    for Pe, model in models.items()\n",
    "}\n",
    "fields = {\n",
    "    Pe: Simulation(\n",
    "        problem=problems[Pe],\n",
    "        mesh=StructuredLineMesher(cells=80).generate(tube),\n",
    "        numerics=numerics,\n",
    "    )\n",
    "    .run(start_time=0.0, end_time=15 * length / velocity, time_step=0.05)\n",
    "    .field(model.concentration(\"A\"))\n",
    "    for Pe, model in models.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Outlet and inlet concentration of every run against the closed form, and the largest deviation\n",
    "along the tube."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "z = np.linspace(0.0, 1.0, 401)\n",
    "line_points = np.column_stack([z * length, 0 * z, 0 * z])\n",
    "profiles = {Pe: np.ravel(field.evaluate(line_points)) for Pe, field in fields.items()}\n",
    "for Pe, c in profiles.items():\n",
    "    print(\n",
    "        f\"Pe = {Pe:5.1f}: outlet c/c0 {c[-1]:.6f} (exact {exact(Pe, 1.0):.6f}), inlet c/c0 {c[0]:.6f} (exact {exact(Pe, 0.0):.6f}), \"\n",
    "        f\"largest deviation along the tube {np.max(np.abs(c - exact(Pe, z))):.1e}\"\n",
    "    )\n",
    "print(\n",
    "    f\"limits: stirred tank 1/(1+Da) = {1 / (1 + rate * length / velocity):.4f}, plug flow exp(-Da) = {np.exp(-rate * length / velocity):.4f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Mesh study\n",
    "\n",
    "The outlet concentration at $\\mathrm{Pe}=20$ on four meshes. At the element nodes quadratic\n",
    "elements are superconvergent, so the error falls with the fourth power of the element size."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "cells = (5, 10, 20, 40)\n",
    "outlet = [\n",
    "    float(\n",
    "        np.ravel(\n",
    "            Simulation(\n",
    "                problem=problems[20.0],\n",
    "                mesh=StructuredLineMesher(cells=n).generate(tube),\n",
    "                numerics=numerics,\n",
    "            )\n",
    "            .run(start_time=0.0, end_time=15 * length / velocity, time_step=0.05)\n",
    "            .field(models[20.0].concentration(\"A\"))\n",
    "            .evaluate(np.array([[length, 0.0, 0.0]]))\n",
    "        )[0]\n",
    "    )\n",
    "    for n in cells\n",
    "]\n",
    "study = convergence(outlet, [length / n for n in cells])\n",
    "for n, value in zip(cells, outlet):\n",
    "    print(\n",
    "        f\"{n:3d} elements: outlet c/c0 {value:.9f}, error {abs(value - exact(20.0, 1.0)):.2e}\"\n",
    "    )\n",
    "print(\n",
    "    f\"observed order of convergence {study.order:.2f}, Richardson extrapolation {study.extrapolated:.9f} (exact {exact(20.0, 1.0):.9f})\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Concentration profiles along the tube with the jump at the inlet, the outlet conversion between\n",
    "the stirred-tank and the plug-flow limits, and the mesh study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "Pe_line = np.geomspace(0.05, 100, 200)\n",
    "fig = plots.figure(1, 3, size=(18, 5))\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"Pe = {Pe:g}\": (z[::20], profiles[Pe][::20]) for Pe in (0.1, 1.0, 5.0, 50.0)\n",
    "    },\n",
    "    reference={f\"Pe = {Pe:g}\": (z, exact(Pe, z)) for Pe in (0.1, 1.0, 5.0, 50.0)},\n",
    "    hlines={\"feed\": inlet},\n",
    "    ylimits=(0, 1.05),\n",
    "    xlabel=\"position x / L\",\n",
    "    ylabel=\"c / c0\",\n",
    "    title=\"Profiles, dashed: exact\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"OneSimulation\": (peclets, [1 - profiles[Pe][-1] for Pe in peclets])},\n",
    "    reference={\"Danckwerts\": (Pe_line, 1 - exact(Pe_line, 1.0))},\n",
    "    hlines={\n",
    "        \"stirred tank\": 1 - 1 / (1 + rate * length / velocity),\n",
    "        \"plug flow\": 1 - np.exp(-rate * length / velocity),\n",
    "    },\n",
    "    scale=\"logx\",\n",
    "    ylimits=(0.65, 0.88),\n",
    "    xlabel=\"Peclet number uL/D\",\n",
    "    ylabel=\"conversion at the outlet\",\n",
    "    title=\"Between mixed and plug flow (Da = 2)\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        \"outlet error\": (\n",
    "            [length / n for n in cells],\n",
    "            [abs(value - exact(20.0, 1.0)) for value in outlet],\n",
    "        )\n",
    "    },\n",
    "    markers=True,\n",
    "    scale=\"loglog\",\n",
    "    slope=4,\n",
    "    xlabel=\"element size [m]\",\n",
    "    ylabel=\"error of c/c0 at the outlet\",\n",
    "    title=\"Mesh study at Pe = 20\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the Damköhler number and watch the inlet jump grow. Swap the quadratic elements for a\n",
    "finite-volume scheme with upwinding to reach Peclet numbers of several thousand, or replace the\n",
    "first-order decay by a reaction network to model a non-linear rate law in the same tube."
   ]
  }
 ]
}
