{
 "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": [
    "# Waterflood with two horizontal wells\n",
    "\n",
    "Horizontal wells drain a thin oil reservoir along their whole length. In a waterflood a second\n",
    "horizontal well near the base injects water, which pushes the oil up towards the producer; the\n",
    "heavier water stays below the oil, so the displacement is stabilised by gravity. Until water\n",
    "reaches the producer the oil rate equals the injection rate; after breakthrough the well\n",
    "produces more and more water.\n",
    "\n",
    "The model is incompressible immiscible two-phase flow in the 3D rock,\n",
    "\n",
    "$$\\phi\\,\\frac{\\partial S_\\alpha}{\\partial t}+\\nabla\\cdot\\mathbf u_\\alpha=q_\\alpha,\\qquad\n",
    "  \\mathbf u_\\alpha=-\\frac{k\\,k_{r\\alpha}(S_w)}{\\mu_\\alpha}\\big(\\nabla p-\\rho_\\alpha\\mathbf g\\big),\\qquad\\alpha=w,o ,$$\n",
    "\n",
    "with Corey relative permeabilities $k_{rw}=S_w^2$, $k_{ro}=(1-S_w)^2$. Each well is connected to\n",
    "the grid cells it passes through by the well index of Peaceman (Soc. Petrol. Eng. J. 23, 1983,\n",
    "531-543), $\\mathrm{WI}=2\\pi k\\,\\Delta x/\\ln(r_e/r_w)$, with the equivalent radius $r_e$ of the cell.\n",
    "\n",
    "**Setup.** A reservoir 600 m × 300 m × 30 m, porosity 0.25, permeability 100 mD, water\n",
    "viscosity 0.5 mPa s and density 1000 kg/m³, oil viscosity 2 mPa s and density 850 kg/m³,\n",
    "initially full of oil. Both wells run 400 m along the middle of the reservoir, radius 0.1 m;\n",
    "the injector 4.5 m above the base injects 500 m³ of water per day, the producer 4.5 m below the cap\n",
    "rock is held at a bottom-hole pressure of 20 MPa. The reservoir comes from the CAD file\n",
    "`horizontal_wells_waterflood.step`, written by `horizontal_wells_waterflood_geometry.py` with the\n",
    "CAD objects of OneSimulation; all its faces are sealed.\n",
    "\n",
    "**Checks.** For incompressible fluids the volumes must balance exactly: injected water equals\n",
    "produced fluid, and the oil produced equals the oil that left the pores; before breakthrough the\n",
    "oil rate equals the injection rate. The breakthrough time and the recovery are compared on two\n",
    "grids."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import CadHexahedralMesher\n",
    "from onesim.physics.geotechnics import (\n",
    "    ImmiscibleReservoir,\n",
    "    ReservoirPerforation,\n",
    "    ReservoirWell,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` returns the reservoir block; it is meshed with mapped hexahedra, 30 m × 33 m × 5 m and,\n",
    "for the comparison, 50 m × 60 m × 7.5 m."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "reservoir = load(\"horizontal_wells_waterflood.step\")\n",
    "length, width, thickness = reservoir.size\n",
    "grids = {\"fine\": (20, 9, 6), \"coarse\": (12, 5, 4)}\n",
    "meshes = {\n",
    "    name: CadHexahedralMesher(cells=cells).generate(reservoir)\n",
    "    for name, cells in grids.items()\n",
    "}\n",
    "\n",
    "view = plots.Camera(elevation=28, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(15, 5.5))\n",
    "plots.geometry(\n",
    "    reservoir,\n",
    "    selection={\n",
    "        \"base\": reservoir.boundaries.z_min,\n",
    "        \"cap rock\": reservoir.boundaries.z_max,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Reservoir block\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"fine\"],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{meshes['fine'].cell_count} hexahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Wells\n",
    "\n",
    "A well perforates every cell whose centre lies on its trajectory, within half a cell; the\n",
    "Peaceman index of each perforation uses the cell size across the well."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "day, year = 86400.0, 365.25 * 86400.0\n",
    "rock = ImmiscibleReservoir(\n",
    "    porosity=0.25,\n",
    "    permeability=1e-13,\n",
    "    water_viscosity=0.5e-3,\n",
    "    oil_viscosity=2e-3,\n",
    "    water_density=1000.0,\n",
    "    oil_density=850.0,\n",
    ")\n",
    "wells = {}\n",
    "for name, (nx, ny, nz) in grids.items():\n",
    "    size = np.array([length / nx, width / ny, thickness / nz])\n",
    "    centres = np.asarray(meshes[name].coordinates)[np.asarray(meshes[name].cells)].mean(\n",
    "        axis=1\n",
    "    )\n",
    "    along = lambda height: np.flatnonzero(\n",
    "        (np.abs(centres[:, 0] - length / 2) < 200.0)\n",
    "        & (np.abs(centres[:, 1] - width / 2) < size[1] / 2)\n",
    "        & (np.abs(centres[:, 2] - height) < size[2] / 2)\n",
    "    )\n",
    "    perforate = lambda cells: tuple(\n",
    "        ReservoirPerforation.peaceman(\n",
    "            cell=int(cell),\n",
    "            transverse_lengths=(size[1], size[2]),\n",
    "            transverse_permeabilities=(1e-13, 1e-13),\n",
    "            completion_length=size[0],\n",
    "            radius=0.1,\n",
    "        )\n",
    "        for cell in cells\n",
    "    )\n",
    "    wells[name] = (\n",
    "        ReservoirWell(\n",
    "            name=\"injector\",\n",
    "            perforations=perforate(along(4.5)),\n",
    "            rate=500.0 / day,\n",
    "            pressure_limit=40e6,\n",
    "        ),\n",
    "        ReservoirWell(\n",
    "            name=\"producer\",\n",
    "            perforations=perforate(along(thickness - 4.5)),\n",
    "            pressure=20e6,\n",
    "        ),\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Ten years with output every two months; gravity points down."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "months = np.linspace(0.0, 10 * year, 61)\n",
    "results = {\n",
    "    name: rock.solve(\n",
    "        mesh=meshes[name],\n",
    "        water_saturation=0.0,\n",
    "        times=months,\n",
    "        max_step=10 * day,\n",
    "        wells=wells[name],\n",
    "        gravity=(0.0, 0.0, -9.81),\n",
    "    )\n",
    "    for name in grids\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Cumulative volumes from the well records (positive into the reservoir), the volume balance, the\n",
    "rates from the cumulative volumes, breakthrough (water cut above 1 %) and recovery."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "print(\n",
    "    f\"{'grid':7s} {'cells':>6s} {'perforations':>13s} {'water balance [m³]':>19s} {'oil balance [m³]':>17s}\"\n",
    "    f\" {'oil rate before bt / injection':>31s} {'breakthrough [years]':>21s} {'recovery after 10 years [%]':>28s}\"\n",
    ")\n",
    "rates = {}\n",
    "for name, result in results.items():\n",
    "    pore_volume = result.pore_volume.sum()\n",
    "    in_place = result.water_saturation @ result.pore_volume\n",
    "    injected, produced_water, produced_oil = (\n",
    "        result.well_phase_volume[:, 0, 0],\n",
    "        -result.well_phase_volume[:, 1, 0],\n",
    "        -result.well_phase_volume[:, 1, 1],\n",
    "    )\n",
    "    oil_rate, water_rate = np.diff(produced_oil) / np.diff(months), np.diff(\n",
    "        produced_water\n",
    "    ) / np.diff(months)\n",
    "    cut = water_rate / (water_rate + oil_rate)\n",
    "    rates[name] = (oil_rate, cut)\n",
    "    breakthrough = months[1:][np.argmax(cut > 0.01)] / year\n",
    "    print(\n",
    "        f\"{name:7s} {meshes[name].cell_count:6d} {len(wells[name][0].perforations):6d} + {len(wells[name][1].perforations):<4d}\"\n",
    "        f\" {np.abs(injected - produced_water - in_place).max():19.2e} {np.abs(produced_oil - in_place).max():17.2e}\"\n",
    "        f\" {oil_rate[0] * day / 500.0:31.6f} {breakthrough:21.2f} {100 * produced_oil[-1] / pore_volume:28.2f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The water saturation in the vertical section through the wells after two and six years, and the\n",
    "oil rate and water cut at the producer on both grids."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = results[\"fine\"]\n",
    "section = np.abs(fine.cell_centers[:, 1] - width / 2) < width / 30\n",
    "x, z = fine.cell_centers[section, 0], fine.cell_centers[section, 2]\n",
    "order = np.lexsort((x, z))\n",
    "shape = (grids[\"fine\"][2], grids[\"fine\"][0])\n",
    "mid_months = (months[1:] + months[:-1]) / 2 / year\n",
    "fig = plots.figure(2, 2, size=(16, 9))\n",
    "for panel, years in ((fig[0], 2), (fig[1], 6)):\n",
    "    plots.heatmap(\n",
    "        np.unique(x),\n",
    "        np.unique(z),\n",
    "        fine.water_saturation[6 * years, section][order].reshape(shape).T,\n",
    "        limits=(0, 1),\n",
    "        aspect=5.0,\n",
    "        label=\"water saturation\",\n",
    "        xlabel=\"x [m]\",\n",
    "        ylabel=\"z [m]\",\n",
    "        title=f\"Section through the wells after {years} years\",\n",
    "        ax=panel,\n",
    "    )\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"{name} grid\": (mid_months, oil_rate * day)\n",
    "        for name, (oil_rate, cut) in rates.items()\n",
    "    },\n",
    "    hlines={\"injection rate\": 500.0},\n",
    "    ylimits=(0, 550),\n",
    "    xlabel=\"time [years]\",\n",
    "    ylabel=\"oil rate [m³/day]\",\n",
    "    title=\"Oil production\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"{name} grid\": (mid_months, 100 * cut)\n",
    "        for name, (oil_rate, cut) in rates.items()\n",
    "    },\n",
    "    ylimits=(0, 100),\n",
    "    xlabel=\"time [years]\",\n",
    "    ylabel=\"water cut [%]\",\n",
    "    title=\"Water cut at the producer\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Lengthen the wells, place them side by side instead of one above the other, or lower the\n",
    "vertical permeability with a permeability tensor: the breakthrough moves and the recovery at\n",
    "breakthrough changes. Switch off gravity to see the water slump less favourably."
   ]
  }
 ]
}
