{
 "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": [
    "# Separation in a liquid chromatography column\n",
    "\n",
    "In high-performance liquid chromatography a short pulse of a mixture is injected into a column\n",
    "packed with porous particles. Every solute partitions between the moving liquid and the\n",
    "stationary surface; the more strongly it adsorbs, the later it leaves the column. In the mobile\n",
    "phase the solutes $i=\\mathrm A,\\mathrm B$ are carried with the interstitial velocity $u$ and\n",
    "dispersed axially,\n",
    "\n",
    "$$\\frac{\\partial c_i}{\\partial t}+u\\frac{\\partial c_i}{\\partial x}=D_\\mathrm{ax}\\frac{\\partial^2c_i}{\\partial x^2}-r_i,\n",
    "  \\qquad r_i=k_{a,i}\\,c_i\\,s-k_{d,i}\\,q_i ,$$\n",
    "\n",
    "while the adsorbed amounts $q_i$ and the free sites $s$ (both per volume of mobile phase) do not\n",
    "move: $\\partial q_i/\\partial t=r_i$, $\\partial s/\\partial t=-r_\\mathrm A-r_\\mathrm B$, with the\n",
    "site capacity $s_0=s+q_\\mathrm A+q_\\mathrm B$. At equilibrium this is the competitive Langmuir\n",
    "isotherm $q_i=s_0K_ic_i/(1+K_\\mathrm Ac_\\mathrm A+K_\\mathrm Bc_\\mathrm B)$, $K_i=k_{a,i}/k_{d,i}$.\n",
    "\n",
    "| boundary | mobile solutes | adsorbed amounts, sites |\n",
    "|---|---|---|\n",
    "| inlet $x=0$ | Danckwerts feed with the injection pulse $c_\\mathrm{in}(t)$ | – |\n",
    "| outlet $x=L$ | convective outflow | – |\n",
    "\n",
    "**Setup.** Column 25 cm long, $u=1$ mm/s, $D_\\mathrm{ax}=2\\cdot10^{-7}$ m²/s (Péclet number\n",
    "1250), $s_0=100$ mol/m³, $K_\\mathrm A=0.02$ and $K_\\mathrm B=0.03$ m³/mol, desorption rate\n",
    "$k_d=2$ 1/s for both. The injection is a Gaussian pulse of 5 s standard deviation centred at 20 s.\n",
    "\n",
    "**Reference.** For a dilute injection the isotherm is linear with the retention factors\n",
    "$k'_i=s_0K_i$ (2 and 3), and the moments of the elution peak are exact (E. Kučera,\n",
    "*J. Chromatogr.* 19 (1965) 237; G. Guiochon et al., *Fundamentals of Preparative and Nonlinear\n",
    "Chromatography*, 2nd ed., 2006, ch. 6):\n",
    "\n",
    "$$\\mu_1=t_0+\\frac Lu(1+k'),\\qquad \\sigma^2=s_\\mathrm{in}^2+\\frac{2D_\\mathrm{ax}L}{u^3}(1+k')^2+\\frac{2Lk'}{u\\,k_d},$$\n",
    "\n",
    "equivalent to the plate height $H=2D_\\mathrm{ax}/u+2k'u/\\big(k_d(1+k')^2\\big)$."
   ]
  },
  {
   "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 (\n",
    "    DanckwertsInflow,\n",
    "    ReactionIR,\n",
    "    SpeciesOutflow,\n",
    "    SpeciesTransport,\n",
    "    TransportSpecies,\n",
    ")\n",
    "from onesim.simulation import 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": [
    "## Column and adsorption kinetics\n",
    "\n",
    "The adsorption steps are mass-action reactions between a mobile solute and the immobile free\n",
    "sites; `TransportSpecies(..., mobile=False)` keeps the adsorbed amounts and the sites out of\n",
    "the convection."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "length, velocity, dispersion = 0.25, 1.0e-3, 2.0e-7\n",
    "capacity, desorption = 100.0, 2.0\n",
    "equilibrium = {\"A\": 0.02, \"B\": 0.03}\n",
    "centre, spread = 20.0, 5.0\n",
    "retention = {name: capacity * K for name, K in equilibrium.items()}\n",
    "reactions = tuple(\n",
    "    item\n",
    "    for name, K in equilibrium.items()\n",
    "    for item in (\n",
    "        ReactionIR(\n",
    "            f\"{name} adsorbs\",\n",
    "            {name: 1, \"s\": 1},\n",
    "            {\"q\" + name: 1},\n",
    "            {\"kind\": \"constant\", \"unit\": \"m^3/mol/s\", \"value\": K * desorption},\n",
    "        ),\n",
    "        ReactionIR(\n",
    "            f\"{name} desorbs\",\n",
    "            {\"q\" + name: 1},\n",
    "            {name: 1, \"s\": 1},\n",
    "            {\"kind\": \"constant\", \"unit\": \"1/s\", \"value\": desorption},\n",
    "        ),\n",
    "    )\n",
    ")\n",
    "print(\n",
    "    f\"hold-up time L/u = {length / velocity:.0f} s, Péclet number u L / D = {velocity * length / dispersion:.0f}, \"\n",
    "    + \", \".join(f\"k'_{name} = {k:.1f}\" for name, k in retention.items())\n",
    ")\n",
    "\n",
    "line = Line(start=(0.0, 0.0, 0.0), end=(length, 0.0, 0.0))\n",
    "mesh = StructuredLineMesher(cells=625).generate(line)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Dilute and overloaded injection\n",
    "\n",
    "The same column is run with a dilute injection (0.1 mol/m³ of each solute, $K_ic\\le0.003$) and\n",
    "an overloaded one (20 mol/m³, $K_ic$ up to 0.6). Quadratic elements of 0.4 mm (cell Péclet\n",
    "number 2) and the second-order BDF method with 1 s steps."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "elution = {}\n",
    "for label, injected in ((\"dilute\", 0.1), (\"overloaded\", 20.0)):\n",
    "    model = SpeciesTransport(\n",
    "        domain=line.line,\n",
    "        velocity=(velocity, 0.0, 0.0),\n",
    "        reactions=reactions,\n",
    "        species=(\n",
    "            TransportSpecies(\"A\", diffusivity=dispersion),\n",
    "            TransportSpecies(\"B\", diffusivity=dispersion),\n",
    "            TransportSpecies(\"qA\", diffusivity=0.0, mobile=False),\n",
    "            TransportSpecies(\"qB\", diffusivity=0.0, mobile=False),\n",
    "            TransportSpecies(\"s\", diffusivity=0.0, mobile=False),\n",
    "        ),\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"Chromatography column\",\n",
    "        geometry=line,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            DanckwertsInflow(\n",
    "                physics=model,\n",
    "                boundary=line.boundaries.start,\n",
    "                concentration={\n",
    "                    name: (\n",
    "                        lambda t: injected * np.exp(-0.5 * ((t - centre) / spread) ** 2)\n",
    "                    )\n",
    "                    for name in equilibrium\n",
    "                },\n",
    "            ),\n",
    "            SpeciesOutflow(physics=model, boundary=line.boundaries.end),\n",
    "        ),\n",
    "        initial_conditions=tuple(\n",
    "            InitialValue(model.field(name), capacity if name == \"s\" else 0.0)\n",
    "            for name in (\"A\", \"B\", \"qA\", \"qB\", \"s\")\n",
    "        ),\n",
    "    )\n",
    "    result = Simulation(\n",
    "        problem=problem,\n",
    "        mesh=mesh,\n",
    "        numerics=Numerics(\n",
    "            spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "            nonlinear_solver=Newton(\n",
    "                linear_solver=SparseDirect(),\n",
    "                absolute_tolerance=1e-12,\n",
    "                relative_tolerance=1e-10,\n",
    "            ),\n",
    "            time_integrator=BDF(order=2, startup=BackwardEuler()),\n",
    "        ),\n",
    "    ).run(start_time=0.0, end_time=1600.0, time_step=1.0)\n",
    "    outlet = np.array([[length, 0.0, 0.0]])\n",
    "    elution[label] = {\n",
    "        name: result.field(model.field(name)).time_series(outlet)\n",
    "        for name in equilibrium\n",
    "    }\n",
    "    elution[label][\"profiles\"] = {\n",
    "        name: result.field(model.field(name)) for name in (\"A\", \"qA\")\n",
    "    }"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the moment theory\n",
    "\n",
    "Zeroth, first and second moments of the dilute elution peaks against the exact values, and the\n",
    "resolution $R_s=(\\mu_{1,\\mathrm B}-\\mu_{1,\\mathrm A})/\\big(2(\\sigma_\\mathrm A+\\sigma_\\mathrm B)\\big)$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "injected_amount = 0.1 * spread * np.sqrt(2 * np.pi)\n",
    "theory = {\n",
    "    name: (\n",
    "        centre + length / velocity * (1 + k),\n",
    "        np.sqrt(\n",
    "            spread**2\n",
    "            + 2 * dispersion * length / velocity**3 * (1 + k) ** 2\n",
    "            + 2 * length * k / (velocity * desorption)\n",
    "        ),\n",
    "        length\n",
    "        / (2 * dispersion / velocity + 2 * k * velocity / (desorption * (1 + k) ** 2)),\n",
    "    )\n",
    "    for name, k in retention.items()\n",
    "}\n",
    "print(\n",
    "    f\"{'solute':>6s} {'recovered':>10s} {'mu1 [s]':>9s} {'theory':>9s} {'sigma [s]':>10s} {'theory':>9s} {'plates N':>9s} {'theory':>9s}\"\n",
    ")\n",
    "moments = {}\n",
    "for name in retention:\n",
    "    t, c = elution[\"dilute\"][name]\n",
    "    zeroth = np.trapezoid(c, t)\n",
    "    first = np.trapezoid(t * c, t) / zeroth\n",
    "    sigma = np.sqrt(np.trapezoid((t - first) ** 2 * c, t) / zeroth)\n",
    "    moments[name] = (first, sigma)\n",
    "    print(\n",
    "        f\"{name:>6s} {zeroth / injected_amount:10.5f} {first:9.2f} {theory[name][0]:9.2f} {sigma:10.3f} {theory[name][1]:9.3f} \"\n",
    "        f\"{(first - centre) ** 2 / (sigma**2 - spread**2):9.1f} {theory[name][2]:9.1f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"resolution R_s = {(moments['B'][0] - moments['A'][0]) / (2 * (moments['A'][1] + moments['B'][1])):.3f} \"\n",
    "    f\"(theory {(theory['B'][0] - theory['A'][0]) / (2 * (theory['A'][1] + theory['B'][1])):.3f})\"\n",
    ")\n",
    "for name in equilibrium:\n",
    "    t, c = elution[\"overloaded\"][name]\n",
    "    print(\n",
    "        f\"overloaded {name}: peak at {t[np.argmax(c)]:.0f} s (dilute {elution['dilute'][name][0][np.argmax(elution['dilute'][name][1])]:.0f} s), \"\n",
    "        f\"recovered {np.trapezoid(c, t) / (200 * injected_amount):.4f} of the injection\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Elution profiles of the dilute injection (normalised to the injected amount) with the Gaussian\n",
    "of the moment theory, the overloaded injection with its sharp fronts and tails, and the mobile\n",
    "and adsorbed amount of A along the column during the overloaded run."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "t = elution[\"dilute\"][\"A\"][0]\n",
    "fig = plots.figure(1, 3, size=(19, 5.5))\n",
    "plots.line(\n",
    "    points={\n",
    "        name: (t[::12], elution[\"dilute\"][name][1][::12] / 0.1) for name in equilibrium\n",
    "    },\n",
    "    reference={\n",
    "        f\"{name}, moment theory\": (\n",
    "            t,\n",
    "            spread\n",
    "            / theory[name][1]\n",
    "            * np.exp(-0.5 * ((t - theory[name][0]) / theory[name][1]) ** 2),\n",
    "        )\n",
    "        for name in equilibrium\n",
    "    },\n",
    "    xlimits=(400, 1500),\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"c_out / c_inj\",\n",
    "    title=\"Dilute injection\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        name: (elution[\"overloaded\"][name][0], elution[\"overloaded\"][name][1])\n",
    "        for name in equilibrium\n",
    "    },\n",
    "    xlimits=(200, 1500),\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"outlet concentration [mol/m³]\",\n",
    "    title=\"Overloaded injection\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "x = np.linspace(0.0, length, 801)\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"{name} at {time:.0f} s\": (\n",
    "            x * 100,\n",
    "            elution[\"overloaded\"][\"profiles\"][name].evaluate(\n",
    "                np.column_stack((x, 0 * x, 0 * x)), time=time\n",
    "            ),\n",
    "        )\n",
    "        for time in (200.0, 500.0)\n",
    "        for name in (\"A\", \"qA\")\n",
    "    },\n",
    "    xlabel=\"position x [cm]\",\n",
    "    ylabel=\"concentration [mol/m³]\",\n",
    "    title=\"Mobile and adsorbed A (overloaded)\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the desorption rate: the kinetic share of the plate height vanishes and the peaks approach\n",
    "the dispersion limit. A gradient of the mobile-phase strength enters through a time-dependent\n",
    "adsorption coefficient; a third solute is one more pair of reactions."
   ]
  }
 ]
}
