{
 "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": [
    "# Thermal breakthrough of a geothermal doublet\n",
    "\n",
    "A geothermal doublet circulates water through a hot aquifer: a production well pumps it up, a\n",
    "heat exchanger cools it, an injection well returns it. The cold water spreads from the injector\n",
    "and, after some years, reaches the producer: the **thermal breakthrough**, after which the\n",
    "production temperature falls. Its timing sets the well spacing.\n",
    "\n",
    "Darcy flow and heat transport in the aquifer:\n",
    "\n",
    "$$\\nabla\\cdot\\mathbf q=0,\\quad \\mathbf q=-\\frac{k}{\\mu}\\nabla p,\\qquad\n",
    "  (\\rho c)_a\\frac{\\partial T}{\\partial t}+(\\rho c)_w\\,\\mathbf q\\cdot\\nabla T=\\nabla\\cdot(\\lambda\\nabla T),$$\n",
    "\n",
    "with the heat capacity $(\\rho c)_a$ of the saturated rock and $(\\rho c)_w$ of the water. The cold\n",
    "front therefore moves with $\\mathbf q\\,(\\rho c)_w/(\\rho c)_a$, slower than the water.\n",
    "\n",
    "**Setup.** A confined aquifer 50 m thick, permeability 1 darcy ($10^{-12}$ m²), water viscosity\n",
    "1 mPa s, $(\\rho c)_a=2.6$ MJ/(m³ K), $(\\rho c)_w=4.18$ MJ/(m³ K), thermal conductivity\n",
    "10 W/(m K) (rock conduction plus thermal dispersion). Wells of 0.5 m radius (screen with gravel pack), 600 m apart,\n",
    "circulating $Q=72$ m³/h. Temperatures are the cooling relative to the injection temperature\n",
    "difference, 0 in the untouched aquifer and 1 for injected water. One half of the aquifer (the\n",
    "vertical plane through both wells is a symmetry plane) comes from `geothermal_doublet.step`,\n",
    "written by `geothermal_doublet_geometry.py` with the CAD objects of OneSimulation.\n",
    "\n",
    "| face | flow | heat |\n",
    "|---|---|---|\n",
    "| `injector.outer_wall` | inflow $Q/2$ over the half well | injected water, $\\Delta T=1$ |\n",
    "| `producer.outer_wall` | pressure 0 | outflow |\n",
    "| `y_min` (symmetry), outer faces, top and base | no flow | insulated |\n",
    "\n",
    "**References.** For fully penetrating wells in a large aquifer the potential flow of a source\n",
    "and a sink gives the pressure difference $\\Delta p=Q\\mu\\ln(D/r_w)/(\\pi kH)$ (doublet form of the\n",
    "Thiem equation, e.g. J. Bear, *Hydraulics of Groundwater*, McGraw-Hill 1979). The streamlines are\n",
    "circles through both wells; the one leaving the injector at the angle $\\theta$ to the line between\n",
    "the wells arrives after\n",
    "\n",
    "$$t(\\theta)=\\frac{\\pi H D^2}{Q}\\,\\frac{(\\rho c)_a}{(\\rho c)_w}\\;\\frac{1-\\theta\\cot\\theta}{\\sin^2\\theta},$$\n",
    "\n",
    "which gives the first breakthrough $t_B=\\frac{\\pi}{3}\\frac{(\\rho c)_a}{(\\rho c)_w}\\frac{HD^2}{Q}$\n",
    "(A.C. Gringarten, J.P. Sauty, J. Geophys. Res. 80, 1975, 4956-4962). As the injected water spreads\n",
    "evenly over the angles, the cooled fraction of the production is $\\theta/\\pi$ at the time $t(\\theta)$,\n",
    "without conduction."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import ThermalFluid\n",
    "from onesim.meshing import DistanceRefinement, TetrahedralMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.coupled_systems import QuasiStationaryCoupling\n",
    "from onesim.numerics.fem import FiniteElement, GalerkinAdvection, Lagrange\n",
    "from onesim.numerics.field_transfer import FieldInterpolation\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import FixedPoint, Newton\n",
    "from onesim.numerics.time import BackwardEuler\n",
    "from onesim.physics.heat_transfer import (\n",
    "    ConvectiveHeatTransfer,\n",
    "    FixedTemperature,\n",
    "    HeatFlux,\n",
    ")\n",
    "from onesim.physics.hydrodynamics import (\n",
    "    DarcyFlow,\n",
    "    DarcyFluxBoundary,\n",
    "    DarcyPressureBoundary,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.field_connections import FieldCoupling\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": [
    "## Geometry and mesh\n",
    "\n",
    "`load` returns the half aquifer with its named faces. Tetrahedra of 1.5 m at the well walls,\n",
    "40 m in the band between the wells where the cold front travels, and up to 150 m far away."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "aquifer = load(\"geothermal_doublet.step\")\n",
    "faces = aquifer.boundaries\n",
    "thickness, spacing, radius = 50.0, 600.0, 0.5\n",
    "line = np.column_stack(\n",
    "    (\n",
    "        np.linspace(-spacing / 2, spacing / 2, 61),\n",
    "        np.zeros(61),\n",
    "        np.full(61, thickness / 2),\n",
    "    )\n",
    ")\n",
    "mesh = TetrahedralMesher(\n",
    "    target_size=150.0,\n",
    "    refinements=(\n",
    "        DistanceRefinement(\n",
    "            source=faces[\"injector.outer_wall\"] | faces[\"producer.outer_wall\"],\n",
    "            target_size=1.5,\n",
    "            far=60.0,\n",
    "            far_size=40.0,\n",
    "        ),\n",
    "        DistanceRefinement(source=line, target_size=40.0, near=150.0, far=500.0),\n",
    "    ),\n",
    ").generate(aquifer)\n",
    "\n",
    "view = plots.Camera(elevation=35, azimuth=-70)\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.geometry(\n",
    "    aquifer,\n",
    "    selection={\n",
    "        \"injector\": faces[\"injector.outer_wall\"],\n",
    "        \"producer\": faces[\"producer.outer_wall\"],\n",
    "        \"symmetry plane\": faces.y_min,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Half of the aquifer with the two wells\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{mesh.cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The Darcy flow is stationary; the heat equation is transient. Dividing it by the capacity ratio\n",
    "turns it into a heat equation with the water's capacity in the scaled time\n",
    "$\\tau=t\\,(\\rho c)_w/(\\rho c)_a$, which the model runs; physical times are $\\tau$ times the ratio.\n",
    "The model uses linear tetrahedra with second-order quadrature and implicit time steps of one year.\n",
    "Each time step passes the Darcy velocity to the heat equation; the flow does not depend on\n",
    "temperature here, so the second sweep of the fixed-point iteration only confirms convergence."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "permeability, viscosity, rate, rock, water_capacity = (\n",
    "    1e-12,\n",
    "    1e-3,\n",
    "    72.0 / 3600.0,\n",
    "    2.6e6,\n",
    "    4.18e6,\n",
    ")\n",
    "ratio, year = rock / water_capacity, 365.25 * 86400.0\n",
    "water = ThermalFluid(\n",
    "    density=1000.0,\n",
    "    dynamic_viscosity=viscosity,\n",
    "    thermal_conductivity=10.0,\n",
    "    specific_heat_capacity=water_capacity / 1000.0,\n",
    ")\n",
    "darcy = DarcyFlow(domain=aquifer.volume, permeability=permeability, material=water)\n",
    "heat = ConvectiveHeatTransfer(domain=aquifer.volume, material=water, velocity=None)\n",
    "others = faces.all - faces[\"injector.outer_wall\"] - faces[\"producer.outer_wall\"]\n",
    "problem = Problem(\n",
    "    name=\"geothermal doublet\",\n",
    "    geometry=aquifer,\n",
    "    physics=(darcy, heat),\n",
    "    boundary_conditions=(\n",
    "        DarcyFluxBoundary(\n",
    "            physics=darcy,\n",
    "            boundary=faces[\"injector.outer_wall\"],\n",
    "            flux=-rate / (2 * np.pi * radius * thickness),\n",
    "        ),\n",
    "        DarcyPressureBoundary(\n",
    "            physics=darcy, boundary=faces[\"producer.outer_wall\"], value=0.0\n",
    "        ),\n",
    "        DarcyFluxBoundary(physics=darcy, boundary=others, flux=0.0),\n",
    "        FixedTemperature(\n",
    "            physics=heat, boundary=faces[\"injector.outer_wall\"], value=1.0\n",
    "        ),\n",
    "        HeatFlux(\n",
    "            physics=heat, boundary=others | faces[\"producer.outer_wall\"], value=0.0\n",
    "        ),\n",
    "    ),\n",
    "    initial_conditions=(InitialValue(heat.temperature, 0.0),),\n",
    "    couplings=(\n",
    "        FieldCoupling(\n",
    "            source=darcy.darcy_velocity,\n",
    "            target=heat.advecting_velocity,\n",
    "            transfer=FieldInterpolation(),\n",
    "        ),\n",
    "    ),\n",
    ")\n",
    "result = Simulation(\n",
    "    problem=problem,\n",
    "    mesh={darcy: mesh, heat: mesh},\n",
    "    numerics={\n",
    "        darcy: Numerics(\n",
    "            spatial=FiniteElement(element=Lagrange(order=1), quadrature_order=2),\n",
    "            linear_solver=SparseDirect(),\n",
    "        ),\n",
    "        heat: Numerics(\n",
    "            spatial=FiniteElement(\n",
    "                element=Lagrange(order=1),\n",
    "                quadrature_order=2,\n",
    "                convection=GalerkinAdvection(),\n",
    "            ),\n",
    "            time_integrator=BackwardEuler(),\n",
    "            nonlinear_solver=Newton(\n",
    "                linear_solver=SparseDirect(),\n",
    "                absolute_tolerance=1e-9,\n",
    "                relative_tolerance=1e-9,\n",
    "            ),\n",
    "        ),\n",
    "    },\n",
    "    coupling_solver=QuasiStationaryCoupling(\n",
    "        transient_systems=(heat,),\n",
    "        stationary_systems=(darcy,),\n",
    "        iteration=FixedPoint(\n",
    "            relative_tolerance=1e-8, absolute_tolerance=1e-12, maximum_iterations=3\n",
    "        ),\n",
    "    ),\n",
    ").run(start_time=0.0, end_time=60 * year / ratio, time_step=1.0 * year / ratio)\n",
    "pressure, temperature = result.field(darcy.pressure), result.field(heat.temperature)\n",
    "times = np.asarray(temperature.times) * ratio / year"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the references\n",
    "\n",
    "The pressure at the injector wall against the doublet formula; the production temperature is\n",
    "the mean over a ring of points around the producer at mid-depth."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "ring = np.column_stack(\n",
    "    (\n",
    "        spacing / 2 + 1.0 * np.cos(np.linspace(0.05, np.pi - 0.05, 12)),\n",
    "        1.0 * np.sin(np.linspace(0.05, np.pi - 0.05, 12)),\n",
    "        np.full(12, thickness / 2),\n",
    "    )\n",
    ")\n",
    "production = np.array(\n",
    "    [temperature.evaluate(ring, time=t).mean() for t in temperature.times]\n",
    ")\n",
    "theta = np.linspace(1e-3, np.pi - 1e-3, 2000)\n",
    "arrival = (\n",
    "    np.pi\n",
    "    * thickness\n",
    "    * spacing**2\n",
    "    / rate\n",
    "    * ratio\n",
    "    * (1 - theta / np.tan(theta))\n",
    "    / np.sin(theta) ** 2\n",
    "    / year\n",
    ")\n",
    "injector_pressure = pressure.evaluate(\n",
    "    [[-spacing / 2 - radius - 1e-3, 1e-3, thickness / 2]], time=temperature.times[-1]\n",
    ")[0]\n",
    "print(\n",
    "    f\"pressure difference between the wells: simulation {injector_pressure / 1e5:.2f} bar, \"\n",
    "    f\"doublet formula {rate * viscosity * np.log(spacing / radius) / (np.pi * permeability * thickness) / 1e5:.2f} bar\"\n",
    ")\n",
    "print(f\"first breakthrough without conduction: t_B = {arrival.min():.1f} years\")\n",
    "print(\n",
    "    f\"{'cooled fraction':>16s} {'time, simulation [a]':>21s} {'streamline solution [a]':>24s}\"\n",
    ")\n",
    "for fraction in (0.05, 0.1, 0.25, 0.5):\n",
    "    print(\n",
    "        f\"{fraction:16.2f} {np.interp(fraction, production, times):21.1f} {np.interp(fraction, theta / np.pi, arrival):24.1f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The cooling in the mid-plane of the aquifer after 10 and 30 years, and the production\n",
    "temperature over time against the streamline solution."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(20, 5.5))\n",
    "for k, years in enumerate((10, 30)):\n",
    "    plots.section(\n",
    "        temperature,\n",
    "        time=temperature.times[years],\n",
    "        plane=Plane(origin=(0, 0, thickness / 2), normal=(0, 0, 1)),\n",
    "        limits=(0, 1),\n",
    "        contours=5,\n",
    "        xlimits=(-700, 700),\n",
    "        ylimits=(0, 600),\n",
    "        label=\"cooling ΔT / ΔT_inj\",\n",
    "        title=f\"Mid-plane after {years} years\",\n",
    "        ax=fig[k],\n",
    "    )\n",
    "plots.line(\n",
    "    y={\"simulation\": (times, production)},\n",
    "    reference={\"streamline solution, no conduction\": (arrival, theta / np.pi)},\n",
    "    xlimits=(0, 60),\n",
    "    ylimits=(0, 1),\n",
    "    xlabel=\"time [years]\",\n",
    "    ylabel=\"cooling of the production ΔT / ΔT_inj\",\n",
    "    title=\"Thermal breakthrough at the producer\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Increase the spacing in `geothermal_doublet_geometry.py` and write the STEP file again: the\n",
    "breakthrough time grows with the square of the spacing. Add confining layers above and below the\n",
    "aquifer as further parts: the heat they conduct delays the cooling."
   ]
  }
 ]
}
