{
 "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": [
    "# Buckley-Leverett waterflood\n",
    "\n",
    "When water displaces oil in a reservoir rock, both phases flow at once, each through the part\n",
    "of the pores it occupies. With the water saturation $S$, the porosity $\\phi$ and the total\n",
    "Darcy velocity $u$, mass conservation of the water in one dimension reads\n",
    "\n",
    "$$\\phi\\,\\frac{\\partial S}{\\partial t}+u\\,\\frac{\\partial f(S)}{\\partial x}=0,\\qquad\n",
    "  f(S)=\\frac{k_{rw}(S)/\\mu_w}{k_{rw}(S)/\\mu_w+k_{ro}(S)/\\mu_o} ,$$\n",
    "\n",
    "where the fractional flow $f$ follows from the relative permeabilities, here the Corey laws\n",
    "$k_{rw}=S^2$, $k_{ro}=(1-S)^2$. Capillary pressure and gravity are neglected.\n",
    "\n",
    "**Setup.** A column of length $L=100$ m, porosity 0.2, permeability 100 mD, water viscosity\n",
    "1 mPa s, oil viscosity 5 mPa s, initially full of oil. Water is injected at $x=0$ with the\n",
    "Darcy velocity $u=10^{-6}$ m/s (8.6 cm per day); the outlet produces whatever arrives.\n",
    "\n",
    "| end | condition |\n",
    "|---|---|\n",
    "| $x=0$ (inlet) | total inflow $u$, pure water |\n",
    "| $x=L$ (outlet) | pressure 0, outflow of both phases |\n",
    "\n",
    "**Reference.** S.E. Buckley and M.C. Leverett, Trans. AIME 146, 1942, 107-116: each saturation\n",
    "moves with the speed $u f'(S)/\\phi$, and the multivalued part is replaced by a shock at the\n",
    "saturation $S_f$ where the tangent from the initial state touches $f$ (H.J. Welge, Trans. AIME\n",
    "195, 1952, 91-98):\n",
    "\n",
    "$$f'(S_f)=\\frac{f(S_f)}{S_f},\\qquad\n",
    "  t_\\mathrm{bt}=\\frac{\\phi L}{u\\,f'(S_f)},\\qquad\n",
    "  \\bar S=S_2+\\big(1-f(S_2)\\big)\\,Q\\quad\\text{with}\\quad f'(S_2)=\\frac1Q ,$$\n",
    "\n",
    "with $Q$ the injected pore volumes and $\\bar S$ the mean water saturation, equal to the oil\n",
    "recovered per pore volume."
   ]
  },
  {
   "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.physics.geotechnics import (\n",
    "    ImmiscibleReservoir,\n",
    "    ReservoirFiniteVolume,\n",
    "    ReservoirFluxBoundary,\n",
    "    ReservoirGeometryFactory,\n",
    "    ReservoirPressureBoundary,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The column is a line of finite volumes with a cross-section of 1 m²; the outlet is held at zero\n",
    "pressure. Three grids of 50, 100 and 200 cells; the results are written every 0.05 injected\n",
    "pore volumes up to 2."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "length, porosity, velocity = 100.0, 0.2, 1e-6\n",
    "rock = ImmiscibleReservoir(\n",
    "    porosity=porosity,\n",
    "    permeability=1e-13,\n",
    "    water_viscosity=1e-3,\n",
    "    oil_viscosity=5e-3,\n",
    "    water_density=1000.0,\n",
    "    oil_density=850.0,\n",
    "    corey_exponent=2.0,\n",
    "    cross_section=1.0,\n",
    ")\n",
    "pore_volume_time = porosity * length / velocity\n",
    "injected = np.linspace(0.0, 2.0, 41)\n",
    "columns = [50, 100, 200]\n",
    "column = Line(start=(0.0, 0.0, 0.0), end=(length, 0.0, 0.0))\n",
    "meshes = {n: StructuredLineMesher(cells=n).generate(column) for n in columns}\n",
    "results = {\n",
    "    n: rock.solve(\n",
    "        mesh=mesh,\n",
    "        water_saturation=0.0,\n",
    "        times=injected * pore_volume_time,\n",
    "        max_step=pore_volume_time / n,\n",
    "        spatial=ReservoirFiniteVolume(geometry_factory=ReservoirGeometryFactory()),\n",
    "        flux_boundaries=(\n",
    "            ReservoirFluxBoundary(\n",
    "                boundary=column.boundaries.start, flux=-velocity, water_saturation=1.0\n",
    "            ),\n",
    "        ),\n",
    "        pressure_boundaries=(\n",
    "            ReservoirPressureBoundary(boundary=column.boundaries.end, pressure=0.0),\n",
    "        ),\n",
    "    )\n",
    "    for n, mesh in meshes.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reference: Buckley-Leverett and Welge\n",
    "\n",
    "The fractional flow on a fine saturation grid, the front saturation where the chord $f(S)/S$ from\n",
    "the initial state is steepest (the tangent condition),\n",
    "the saturation profile $x(S)=u t f'(S)/\\phi$ behind the front, and the outlet saturation, water\n",
    "cut and recovery after breakthrough."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fraction = lambda s: s**2 / (s**2 + (1 - s) ** 2 / 5)\n",
    "s = np.linspace(0.0, 1.0, 200001)\n",
    "slope = np.gradient(fraction(s), s)\n",
    "front = s[1:][np.argmax(fraction(s[1:]) / s[1:])]\n",
    "behind = s >= front\n",
    "breakthrough = 1 / np.interp(front, s, slope)\n",
    "profile = lambda q, x: np.interp(\n",
    "    x / length / q, slope[behind][::-1], s[behind][::-1], right=0.0\n",
    ")\n",
    "outlet = lambda q: np.interp(1 / q, slope[behind][::-1], s[behind][::-1], left=1.0)\n",
    "recovery = lambda q: np.where(\n",
    "    q < breakthrough, q, outlet(q) + (1 - fraction(outlet(q))) * q\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "The mean saturation in the column is the oil recovered; the breakthrough is the first output\n",
    "with water at the outlet cell; the profile error is the pore-volume weighted mean deviation at\n",
    "0.4 injected pore volumes. Last, the mass balance of both phases: the change of the mass in the\n",
    "column against what entered and left through the ends."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "print(\n",
    "    f\"front saturation S_f = {front:.4f}, breakthrough after {breakthrough:.4f} pore volumes = {breakthrough * pore_volume_time / 86400:.0f} days\"\n",
    ")\n",
    "print(\n",
    "    f\"{'cells':>6s} {'profile error at Q = 0.4':>25s} {'breakthrough [PV]':>18s} {'recovery at Q = 1':>18s} {'Welge':>7s} {'recovery at Q = 2':>18s} {'Welge':>7s}\"\n",
    ")\n",
    "errors = []\n",
    "for n, result in results.items():\n",
    "    x = (meshes[n].faces[:-1] + meshes[n].faces[1:]) / 2\n",
    "    mean = result.water_saturation @ result.pore_volume / result.pore_volume.sum()\n",
    "    errors.append(\n",
    "        result.pore_volume\n",
    "        @ np.abs(result.water_saturation[8] - profile(0.4, x))\n",
    "        / result.pore_volume.sum()\n",
    "    )\n",
    "    first = injected[np.argmax(result.water_saturation[:, -1] > 0.05)]\n",
    "    print(\n",
    "        f\"{n:6d} {errors[-1]:25.4f} {first:18.2f} {mean[20]:18.4f} {recovery(1.0):7.4f} {mean[40]:18.4f} {recovery(2.0):7.4f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"profile error ratio per halving of the cells: {errors[0] / errors[1]:.2f}, {errors[1] / errors[2]:.2f}\"\n",
    ")\n",
    "print(\n",
    "    \"largest mass-balance error of the phases over the run [kg]: \"\n",
    "    + \", \".join(\n",
    "        f\"{np.abs(result.phase_mass - result.phase_mass[0] - (result.well_phase_volume.sum(axis=1) - result.boundary_phase_volume) * (1000.0, 850.0)).max():.1e} ({n} cells)\"\n",
    "        for n, result in results.items()\n",
    "    )\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Saturation profiles at three times before breakthrough, the oil recovery and the water cut at\n",
    "the outlet over the injected pore volumes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x = np.linspace(0.0, length, 2001)\n",
    "fine = results[200]\n",
    "centres = (meshes[200].faces[:-1] + meshes[200].faces[1:]) / 2\n",
    "order = np.argsort(centres)\n",
    "fig = plots.figure(1, 3, size=(18, 5.5))\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"Q = {q}\": (centres[order], fine.water_saturation[k, order])\n",
    "        for q, k in ((0.2, 4), (0.4, 8), (0.6, 12))\n",
    "    },\n",
    "    reference={f\"Q = {q}\": (x, profile(q, x)) for q in (0.2, 0.4, 0.6)},\n",
    "    ylimits=(0, 1),\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"water saturation S\",\n",
    "    title=\"Saturation profiles, 200 cells\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"{n} cells\": (\n",
    "            injected,\n",
    "            result.water_saturation @ result.pore_volume / result.pore_volume.sum(),\n",
    "        )\n",
    "        for n, result in results.items()\n",
    "    },\n",
    "    reference={\n",
    "        \"Welge\": (np.linspace(0.01, 2, 400), recovery(np.linspace(0.01, 2, 400)))\n",
    "    },\n",
    "    vlines={\"breakthrough\": breakthrough},\n",
    "    xlabel=\"injected pore volumes Q\",\n",
    "    ylabel=\"oil recovered [pore volumes]\",\n",
    "    title=\"Oil recovery\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"{n} cells\": (injected, fraction(result.water_saturation[:, -1]))\n",
    "        for n, result in results.items()\n",
    "    },\n",
    "    reference={\n",
    "        \"Welge\": (\n",
    "            np.linspace(0.01, 2, 400),\n",
    "            np.where(\n",
    "                np.linspace(0.01, 2, 400) < breakthrough,\n",
    "                0.0,\n",
    "                fraction(outlet(np.linspace(0.01, 2, 400))),\n",
    "            ),\n",
    "        )\n",
    "    },\n",
    "    xlabel=\"injected pore volumes Q\",\n",
    "    ylabel=\"water cut f at the outlet\",\n",
    "    title=\"Water cut\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the oil viscosity: the front saturation drops and water breaks through early, the\n",
    "classical argument for polymer flooding. Add `capillary_pressure_scale` to smear the front, or\n",
    "turn the column upright and add gravity."
   ]
  }
 ]
}
