{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Reactive transport in a 1D reactor\n",
    "\n",
    "A dissolved species flows through a thin tubular reactor at a constant speed\n",
    "$u$, spreads by diffusion with coefficient $D$, and is consumed by a\n",
    "first-order reaction of rate $k$. At the inlet ($x=0$) its concentration is\n",
    "held at $C_0$; at the outlet ($x=L$) it is held at $C_L$.\n",
    "\n",
    "The steady advection-diffusion-reaction balance is\n",
    "\n",
    "$$u\\,\\frac{dC}{dx}=D\\,\\frac{d^2C}{dx^2}-k\\,C .$$\n",
    "\n",
    "OneSimulation integrates the transient transport in time on a real 1D line mesh\n",
    "with continuous finite elements until only the steady profile remains.\n",
    "\n",
    "**Reference.** The steady equation is a linear, constant-coefficient ODE. With\n",
    "$C=e^{m x}$ the characteristic equation $D m^2-u m-k=0$ gives the two roots\n",
    "\n",
    "$$m_\\pm=\\frac{u\\pm\\sqrt{u^2+4Dk}}{2D},$$\n",
    "\n",
    "so the exact solution is $C(x)=A\\,e^{m_+x}+B\\,e^{m_-x}$, with $A$ and $B$ fixed\n",
    "by $C(0)=C_0$ and $C(L)=C_L$. The dimensionless **Damkoehler number**\n",
    "$\\mathrm{Da}=kL/u$ measures reaction against advection, and the **Peclet\n",
    "number** $\\mathrm{Pe}=uL/D$ advection against diffusion. We compare the\n",
    "computed steady profile with this closed form."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "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, Nitsche\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.simulation import PrescribedValueBoundary, Problem, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Parameters\n",
    "\n",
    "The values are freely adjustable and in SI units. They give a moderately\n",
    "reaction- and advection-dominated reactor."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "L = 1.0\n",
    "cells = 200\n",
    "u = 0.2\n",
    "D = 0.01\n",
    "k = 1.0\n",
    "C0 = 1.0\n",
    "CL = 0.0\n",
    "\n",
    "Da = k * L / u\n",
    "Pe = u * L / D\n",
    "print(f\"Damkoehler Da = {Da:.2f},  Peclet Pe = {Pe:.2f}\")\n",
    "\n",
    "disc = np.sqrt(u * u + 4.0 * D * k)\n",
    "m_plus = (u + disc) / (2.0 * D)\n",
    "m_minus = (u - disc) / (2.0 * D)\n",
    "coeffs = np.linalg.solve(\n",
    "    np.array([[1.0, 1.0], [np.exp(m_plus * L), np.exp(m_minus * L)]]),\n",
    "    np.array([C0, CL]),\n",
    ")\n",
    "\n",
    "\n",
    "def reference(x):\n",
    "    return coeffs[0] * np.exp(m_plus * x) + coeffs[1] * np.exp(m_minus * x)\n",
    "\n",
    "\n",
    "line = Line(start=(0.0, 0.0, 0.0), end=(L, 0.0, 0.0))\n",
    "mesh = StructuredLineMesher(cells=cells).generate(line)\n",
    "\n",
    "species = (TransportSpecies(\"reactive\", diffusivity=D, decay_rate=k),)\n",
    "model = SpeciesTransport(domain=line.line, velocity=u, species=species)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Both ends carry an explicit boundary condition: the concentration is prescribed\n",
    "at the inlet and at the outlet."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "boundary_conditions = (\n",
    "    PrescribedValueBoundary(\n",
    "        physics=model,\n",
    "        boundary=line.boundaries.start,\n",
    "        value=lambda time, coordinate: {\"reactive\": C0},\n",
    "    ),\n",
    "    PrescribedValueBoundary(\n",
    "        physics=model,\n",
    "        boundary=line.boundaries.end,\n",
    "        value=lambda time, coordinate: {\"reactive\": CL},\n",
    "    ),\n",
    ")\n",
    "\n",
    "problem = Problem(\n",
    "    name=\"steady reactive transport in a 1D reactor\",\n",
    "    geometry=line,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=boundary_conditions,\n",
    "    initial_conditions=(InitialValue(model.concentration(\"reactive\"), 0.0),),\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The reaction fixes the slowest transient time scale to ~1/k, so a few reaction\n",
    "times are enough to reach steady state."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "end_time = 15.0 / k\n",
    "time_step = end_time / 300.0\n",
    "print(f\"settling run: end time = {end_time:.1f} s,  time step = {time_step:.3f} s\")\n",
    "\n",
    "result = Simulation(\n",
    "    problem=problem,\n",
    "    mesh=mesh,\n",
    "    numerics=Numerics(\n",
    "        spatial=FiniteElement(\n",
    "            element=Lagrange(2), quadrature_order=5, boundary_enforcement=Nitsche()\n",
    "        ),\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",
    ").run(start_time=0.0, end_time=end_time, time_step=time_step)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the closed-form steady profile\n",
    "\n",
    "The last stored time is deep in the steady regime. We compare the computed\n",
    "concentration with the exact two-exponential solution."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "field = result.field(model.concentration(\"reactive\"))\n",
    "points = np.asarray(field.space.dof_coordinates)\n",
    "x = points[:, 0]\n",
    "order = np.argsort(x)\n",
    "x = x[order]\n",
    "c_num = np.asarray(field.evaluate(points, time=float(result.times[-1]))).reshape(-1)[\n",
    "    order\n",
    "]\n",
    "\n",
    "c_ref = reference(x)\n",
    "max_abs_error = float(np.max(np.abs(c_num - c_ref)))\n",
    "rel_error = max_abs_error / C0\n",
    "print(\n",
    "    f\"maximum deviation from the closed form: {max_abs_error:.3e} mol/m^3  ({100*rel_error:.3f} % of C0)\"\n",
    ")\n",
    "\n",
    "previous = np.asarray(field.evaluate(points, time=float(result.times[-2]))).reshape(-1)[\n",
    "    order\n",
    "]\n",
    "drift = float(np.max(np.abs(c_num - previous)))\n",
    "print(f\"change over the last stored interval: {drift:.3e} mol/m^3\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "xs = np.linspace(0.0, L, 400)\n",
    "plots.line(\n",
    "    points={\"OneSimulation\": (x[::5], c_num[::5])},\n",
    "    reference={\"closed form\": (xs, reference(xs))},\n",
    "    xlabel=\"position x [m]\",\n",
    "    ylabel=\"concentration [mol/m^3]\",\n",
    "    title=f\"Steady reactive transport (Da = {Da:.1f}, Pe = {Pe:.0f})\",\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the reaction rate $k$ (larger Damkoehler number) and the species is\n",
    "consumed closer to the inlet. Shrink the diffusivity $D$ (larger Peclet number)\n",
    "and the profile sharpens into a nearly pure advection-reaction exponential\n",
    "$C(x)\\approx C_0\\,e^{-kx/u}$ over the interior."
   ]
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 }
}
