{
 "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": [
    "# Seawater intrusion in a coastal aquifer\n",
    "\n",
    "Where an aquifer meets the sea, the heavier seawater sinks below the fresh groundwater and\n",
    "intrudes inland as a **salt wedge**; the fresh water flowing to the sea pushes it back. The\n",
    "balance decides how far a coastal well can pump before it draws salt. H.R. Henry's idealised\n",
    "problem of 1964 is the classical test of density-dependent groundwater models:\n",
    "\n",
    "$$\\nabla\\cdot\\mathbf q=0,\\qquad \\mathbf q=-\\frac{k}{\\mu}\\big(\\nabla p-\\rho(c)\\,\\mathbf g\\big),\\qquad\n",
    "  \\mathbf q\\cdot\\nabla c=\\nabla\\cdot(D\\nabla c),\\qquad \\rho=\\rho_0(1+\\varepsilon c) ,$$\n",
    "\n",
    "with the normalised salt concentration $c\\in[0,1]$ and the density contrast\n",
    "$\\varepsilon=0.025$ of seawater. Two numbers characterise it: $a=Q/(K\\varepsilon d)=0.263$, the\n",
    "freshwater inflow against the density-driven flow, and $b=D/Q=0.1$, the dispersion.\n",
    "\n",
    "**Setup.** An aquifer 2 m long and 1 m deep, freshwater inflow $Q=6.6\\cdot10^{-5}$ m²/s per metre\n",
    "of coast; water density 1000 kg/m³, viscosity 1 mPa s. The aquifer comes from the CAD file\n",
    "`seawater_intrusion_henry.step`, written by `seawater_intrusion_henry_geometry.py` with the CAD\n",
    "objects of OneSimulation; the model is its vertical section.\n",
    "\n",
    "| side | flow | salt |\n",
    "|---|---|---|\n",
    "| `x_min` (inland) | inflow $Q/d$ | $c=0$ |\n",
    "| `x_max` (sea) | hydrostatic seawater pressure | $c=1$ |\n",
    "| `y_min`, `y_max` | no flow | no flux |\n",
    "\n",
    "The pressure is the excess over the freshwater hydrostat, so the sea side carries\n",
    "$\\rho_0\\varepsilon g(d-y)$.\n",
    "\n",
    "**Reference.** Henry's semi-analytical Fourier-Galerkin solution (H.R. Henry, U.S. Geol. Surv.\n",
    "Water-Supply Paper 1613-C, 1964), here as the positions of the isochlors 0.25, 0.5 and 0.75 at\n",
    "eleven heights, recomputed with 14 × 14 Fourier modes for the variant with a uniform inland\n",
    "inflow (M.J. Simpson, T.P. Clement, Water Resour. Res. 40, 2004, W01504)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import ThermalFluid\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.coupled_systems import StationaryPartitionedCoupling\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.field_transfer import FieldInterpolation\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import FixedPoint\n",
    "from onesim.physics.chemistry import (\n",
    "    FixedConcentration,\n",
    "    SpeciesFlux,\n",
    "    SpeciesTransport,\n",
    "    TransportSpecies,\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 DensityBuoyancy, 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",
    "`section` cuts the block at half thickness; the cut faces keep their names. Two triangle\n",
    "meshes, 5 cm and 2.5 cm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "block = load(\"seawater_intrusion_henry.step\")\n",
    "aquifer = block.section((0, 0, 1), origin=(0, 0, block.size[2] / 2))\n",
    "side = aquifer.boundaries\n",
    "length, depth = aquifer.size[:2]\n",
    "sizes = [0.05, 0.025]\n",
    "meshes = [TriangularMesher(target_size=size).generate(aquifer) for size in sizes]\n",
    "\n",
    "fig = plots.figure(2, 1, size=(12, 9))\n",
    "plots.geometry(\n",
    "    aquifer,\n",
    "    selection={\n",
    "        \"inland, fresh water\": side.x_min,\n",
    "        \"sea\": side.x_max,\n",
    "        \"no flow\": side.y_min | side.y_max,\n",
    "    },\n",
    "    labels=False,\n",
    "    title=\"Vertical section of the aquifer\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[-1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Finer mesh: {meshes[-1].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Darcy flow and salt transport with quadratic elements. The salt makes the water heavier through\n",
    "`DensityBuoyancy`; the Darcy velocity carries the salt. A relaxed fixed-point iteration couples\n",
    "the two stationary problems."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "a, b, inflow, rho0, viscosity, g, contrast = (\n",
    "    0.263,\n",
    "    0.1,\n",
    "    6.6e-5,\n",
    "    1000.0,\n",
    "    1e-3,\n",
    "    9.81,\n",
    "    0.025,\n",
    ")\n",
    "water = ThermalFluid(\n",
    "    density=rho0,\n",
    "    dynamic_viscosity=viscosity,\n",
    "    thermal_conductivity=0.6,\n",
    "    specific_heat_capacity=4180.0,\n",
    ")\n",
    "results = []\n",
    "for mesh in meshes:\n",
    "    darcy = DarcyFlow(\n",
    "        domain=aquifer.domain(),\n",
    "        permeability=inflow / (a * contrast * depth) * viscosity / (rho0 * g),\n",
    "        material=water,\n",
    "    )\n",
    "    salt = SpeciesTransport(\n",
    "        domain=aquifer.domain(),\n",
    "        species=(TransportSpecies(\"salt\", diffusivity=b * inflow),),\n",
    "        nonnegative=False,\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"Henry problem\",\n",
    "        geometry=aquifer,\n",
    "        physics=(darcy, salt),\n",
    "        boundary_conditions=(\n",
    "            DarcyFluxBoundary(physics=darcy, boundary=side.x_min, flux=-inflow / depth),\n",
    "            DarcyPressureBoundary(\n",
    "                physics=darcy,\n",
    "                boundary=side.x_max,\n",
    "                value=lambda x, y: rho0 * contrast * g * (depth - y),\n",
    "            ),\n",
    "            DarcyFluxBoundary(\n",
    "                physics=darcy, boundary=side.y_min | side.y_max, flux=0.0\n",
    "            ),\n",
    "            FixedConcentration(physics=salt, boundary=side.x_min, value=0.0),\n",
    "            FixedConcentration(physics=salt, boundary=side.x_max, value=1.0),\n",
    "            SpeciesFlux(physics=salt, boundary=side.y_min | side.y_max, value=0.0),\n",
    "        ),\n",
    "        initial_conditions=(InitialValue(salt.field(\"salt\"), lambda x: x / length),),\n",
    "        couplings=(\n",
    "            FieldCoupling(\n",
    "                source=salt.field(\"salt\"),\n",
    "                target=darcy.field(\"body_force\"),\n",
    "                transfer=DensityBuoyancy(gravity=(0, -g), expansion=contrast),\n",
    "            ),\n",
    "            FieldCoupling(\n",
    "                source=darcy.darcy_velocity,\n",
    "                target=salt.advecting_velocity,\n",
    "                transfer=FieldInterpolation(),\n",
    "            ),\n",
    "        ),\n",
    "    )\n",
    "    solved = Simulation(\n",
    "        problem=problem,\n",
    "        mesh={darcy: mesh, salt: mesh},\n",
    "        numerics={\n",
    "            physics: Numerics(\n",
    "                spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "                linear_solver=SparseDirect(),\n",
    "            )\n",
    "            for physics in (darcy, salt)\n",
    "        },\n",
    "        coupling_solver=StationaryPartitionedCoupling(\n",
    "            stationary_systems=(darcy, salt),\n",
    "            iteration=FixedPoint(\n",
    "                relative_tolerance=1e-6,\n",
    "                absolute_tolerance=1e-10,\n",
    "                maximum_iterations=150,\n",
    "                relaxation=0.8,\n",
    "            ),\n",
    "        ),\n",
    "    ).solve_stationary()\n",
    "    results.append(\n",
    "        (solved.field(salt.field(\"salt\")), solved.field(darcy.darcy_velocity))\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "The positions of the three isochlors at eleven heights, from the salinity along horizontal\n",
    "lines, against Henry's solution; the toe of the wedge is the position at the base."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "heights = np.round(np.arange(0.0, 1.0001, 0.1), 1)\n",
    "henry = {\n",
    "    0.25: [\n",
    "        1.1772,\n",
    "        1.1977,\n",
    "        1.2484,\n",
    "        1.3217,\n",
    "        1.4134,\n",
    "        1.5201,\n",
    "        1.6379,\n",
    "        1.761,\n",
    "        1.8538,\n",
    "        1.9519,\n",
    "        1.9673,\n",
    "    ],\n",
    "    0.5: [\n",
    "        1.3738,\n",
    "        1.4007,\n",
    "        1.4649,\n",
    "        1.5508,\n",
    "        1.648,\n",
    "        1.747,\n",
    "        1.8363,\n",
    "        1.9107,\n",
    "        1.9543,\n",
    "        1.9723,\n",
    "        1.9799,\n",
    "    ],\n",
    "    0.75: [\n",
    "        1.5857,\n",
    "        1.6151,\n",
    "        1.6816,\n",
    "        1.7606,\n",
    "        1.8358,\n",
    "        1.8975,\n",
    "        1.9411,\n",
    "        1.9664,\n",
    "        1.9797,\n",
    "        1.9869,\n",
    "        1.9903,\n",
    "    ],\n",
    "}\n",
    "line = np.linspace(0.0, length, 2001)\n",
    "isochlor = lambda salinity, level, z: np.interp(\n",
    "    level, salinity.evaluate(np.column_stack((line, np.full_like(line, z)))), line\n",
    ")\n",
    "print(\n",
    "    f\"{'isochlor':>8s} {'toe, Henry':>11s}\"\n",
    "    + \"\".join(f\" {f'toe, {mesh.cell_count} tri':>15s}\" for mesh in meshes)\n",
    "    + \"   largest deviation over the height [m]\"\n",
    ")\n",
    "for level, positions in henry.items():\n",
    "    simulated = [\n",
    "        [\n",
    "            isochlor(salinity, level, z)\n",
    "            for z, x in zip(heights, positions)\n",
    "            if x is not None\n",
    "        ]\n",
    "        for salinity, _ in results\n",
    "    ]\n",
    "    reference = np.array([x for x in positions if x is not None])\n",
    "    print(\n",
    "        f\"{level:8.2f} {reference[0]:11.3f}\"\n",
    "        + \"\".join(f\" {values[0]:15.3f}\" for values in simulated)\n",
    "        + \"   \"\n",
    "        + \", \".join(\n",
    "            f\"{np.abs(np.array(values) - reference).max():.3f}\" for values in simulated\n",
    "        )\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The salinity with its isochlors and the Darcy velocity on the finer mesh, and the isochlor\n",
    "positions over the height against Henry's solution."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "salinity, velocity = results[-1]\n",
    "fig = plots.figure(1, 2, size=(17, 6))\n",
    "plots.surface(\n",
    "    salinity,\n",
    "    limits=(0, 1),\n",
    "    contours=4,\n",
    "    subdivisions=2,\n",
    "    label=\"normalised salinity c\",\n",
    "    title=\"Salt wedge\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"c = {level}\": (\n",
    "            [\n",
    "                isochlor(salinity, level, z)\n",
    "                for z, x in zip(heights, positions)\n",
    "                if x is not None\n",
    "            ],\n",
    "            [z for z, x in zip(heights, positions) if x is not None],\n",
    "        )\n",
    "        for level, positions in henry.items()\n",
    "    },\n",
    "    points={\n",
    "        f\"c = {level}\": (\n",
    "            [x for x in positions if x is not None],\n",
    "            [z for z, x in zip(heights, positions) if x is not None],\n",
    "        )\n",
    "        for level, positions in henry.items()\n",
    "    },\n",
    "    xlimits=(0, length),\n",
    "    ylimits=(0, depth),\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"height y [m]\",\n",
    "    title=\"Isochlors: simulation (lines), Henry (markers)\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Halve the freshwater inflow (a = 0.1315, the variant of Simpson and Clement): the wedge\n",
    "reaches much further inland. Lower the dispersion b for a sharper interface, or add a pumping\n",
    "well and see when it starts to draw salt."
   ]
  }
 ]
}
