{
 "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": [
    "# Geoelectrical sounding over a layered earth\n",
    "\n",
    "In a vertical electrical sounding four electrodes stand in a line on the ground at equal spacing\n",
    "$a$ (Wenner array): the current $I$ enters at A and leaves at B, the voltage $\\Delta V$ is measured\n",
    "between the inner electrodes M and N. Over a homogeneous ground of resistivity $\\rho$ the reading\n",
    "gives $\\rho=2\\pi a\\,\\Delta V/I$; over any other ground this formula defines the **apparent\n",
    "resistivity** $\\rho_a(a)$. Small spacings see the top layer, large spacings the ground deeper down.\n",
    "\n",
    "Here the ground has a top layer of $\\rho_1=100\\ \\Omega$m and $h=5$ m thickness over a basement of\n",
    "$\\rho_2=20\\ \\Omega$m. The potential obeys $\\nabla\\cdot(\\sigma\\nabla V)=0$ with $\\sigma=1/\\rho$,\n",
    "the equation of electrostatics with the conductivity in place of the permittivity.\n",
    "\n",
    "The array is symmetric about the vertical plane along it and antisymmetric about its mid-plane.\n",
    "One quarter of the ground (a quarter of a half ball of radius 250 m) with the current electrode A\n",
    "(a hemisphere of 25 cm radius) comes from the CAD file `geoelectric_wenner_sounding.step` ($a=8$ m)\n",
    "and from one file per other spacing, `..._2m.step`, `..._4m.step` and `..._16m.step`; the basement is\n",
    "`geoelectric_wenner_sounding_basement.step`. The script `geoelectric_wenner_sounding_geometry.py`\n",
    "builds them with the CAD objects of OneSimulation.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `electrode` (A) | $V=V_A$ |\n",
    "| `midplane` | $V=0$ (antisymmetry, electrode B is the mirror image of A) |\n",
    "| `symmetry`, `surface` | no current |\n",
    "| `outer` | no current (far away) |\n",
    "\n",
    "**Reference.** For a two-layer earth the potential of a point source follows from an infinite\n",
    "series of images in the layer boundary. With the reflection coefficient\n",
    "$k=(\\rho_2-\\rho_1)/(\\rho_2+\\rho_1)$ the Wenner apparent resistivity is (Telford, Geldart and\n",
    "Sheriff, *Applied Geophysics*, 2nd ed., Sec. 8.5)\n",
    "\n",
    "$$\\frac{\\rho_a}{\\rho_1}=1+4\\sum_{n=1}^{\\infty}k^n\\left[\\frac{1}{\\sqrt{1+(2nh/a)^2}}\n",
    "  -\\frac{1}{\\sqrt{4+(2nh/a)^2}}\\right].$$"
   ]
  },
  {
   "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.meshing import TetrahedralMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.electrostatics import (\n",
    "    FixedPotential,\n",
    "    PoissonEquation,\n",
    "    ZeroNormalElectricDisplacement,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation, regionwise\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",
    "The basement is embedded in the mesh, so that the layer boundary consists of cell faces. The cells\n",
    "are about 8 cm at the electrode, a twentieth of the spacing at the potential electrode M, and grow to\n",
    "25 m far away."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "spacings = (2.0, 4.0, 8.0, 16.0)\n",
    "grounds = {\n",
    "    a: load(\n",
    "        \"geoelectric_wenner_sounding.step\"\n",
    "        if a == 8.0\n",
    "        else f\"geoelectric_wenner_sounding_{round(a)}m.step\"\n",
    "    )\n",
    "    for a in spacings\n",
    "}\n",
    "basement = load(\"geoelectric_wenner_sounding_basement.step\")\n",
    "electrode, layer = 0.25, grounds[8.0].size[2] - basement.size[2]\n",
    "meshes = {\n",
    "    a: TetrahedralMesher(\n",
    "        target_size=25.0,\n",
    "        minimum_size=electrode / 4,\n",
    "        geometry_order=2,\n",
    "        embedded_regions=(basement,),\n",
    "        size_field=lambda points, a=a: np.clip(\n",
    "            np.minimum(\n",
    "                electrode / 3\n",
    "                + 0.5 * np.linalg.norm(points - (1.5 * a, 0.0, 0.0), axis=1),\n",
    "                a / 20 + 0.5 * np.linalg.norm(points - (0.5 * a, 0.0, 0.0), axis=1),\n",
    "            ),\n",
    "            electrode / 4,\n",
    "            25.0,\n",
    "        ),\n",
    "    ).generate(grounds[a])\n",
    "    for a in spacings\n",
    "}\n",
    "\n",
    "faces = grounds[8.0].boundaries\n",
    "view = plots.Camera(elevation=30, azimuth=-55)\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    [grounds[8.0].named(\"top layer\"), basement.named(\"basement\")],\n",
    "    camera=view,\n",
    "    title=\"Quarter of the ground below the array (a = 8 m)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[8.0],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{meshes[8.0].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`regionwise` gives the basement its conductivity. Electrode A is held at 1 V; the current it\n",
    "injects is twice the `reaction` on the half electrode in the quarter. The spacing of 8 m is also\n",
    "solved over a homogeneous ground."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "rho1, rho2 = 100.0, 20.0\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "runs = [(a, rho2) for a in spacings] + [(8.0, rho1)]\n",
    "models = [\n",
    "    PoissonEquation(\n",
    "        domain=grounds[a].volume,\n",
    "        permittivity=regionwise(((basement, 1 / lower),), default=1 / rho1, unit=\"S/m\"),\n",
    "        charge_density=0.0,\n",
    "    )\n",
    "    for a, lower in runs\n",
    "]\n",
    "potentials = [\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Wenner sounding\",\n",
    "            geometry=grounds[a],\n",
    "            physics=(model,),\n",
    "            boundary_conditions=(\n",
    "                FixedPotential(\n",
    "                    boundary=grounds[a].boundaries.electrode, physics=model, value=1.0\n",
    "                ),\n",
    "                FixedPotential(\n",
    "                    boundary=grounds[a].boundaries.midplane, physics=model, value=0.0\n",
    "                ),\n",
    "                ZeroNormalElectricDisplacement(\n",
    "                    boundary=grounds[a].boundaries.symmetry\n",
    "                    | grounds[a].boundaries.surface\n",
    "                    | grounds[a].boundaries.outer,\n",
    "                    physics=model,\n",
    "                ),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=meshes[a],\n",
    "        numerics=numerics,\n",
    "    )\n",
    "    .solve_stationary()\n",
    "    .field(model.potential)\n",
    "    for model, (a, _) in zip(models, runs)\n",
    "]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The voltage between M and N is twice the potential at M; the apparent resistivity follows from\n",
    "the Wenner formula."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "reflection = (rho2 - rho1) / (rho2 + rho1)\n",
    "n = np.arange(1, 200)\n",
    "two_layer = lambda a: rho1 * (\n",
    "    1\n",
    "    + 4\n",
    "    * np.sum(\n",
    "        reflection**n\n",
    "        * (\n",
    "            1 / np.sqrt(1 + (2 * n * layer / a) ** 2)\n",
    "            - 1 / np.sqrt(4 + (2 * n * layer / a) ** 2)\n",
    "        )\n",
    "    )\n",
    ")\n",
    "apparent = [\n",
    "    4\n",
    "    * np.pi\n",
    "    * a\n",
    "    * potential.evaluate([(0.5 * a, 0.0, 0.0)])[0]\n",
    "    / (2 * potential.reaction(grounds[a].boundaries.electrode))\n",
    "    for potential, (a, _) in zip(potentials, runs)\n",
    "]\n",
    "print(\n",
    "    f\"homogeneous ground, a = 8 m: apparent resistivity {apparent[-1]:.3f} Ωm, true {rho1:.1f} Ωm ({100 * (apparent[-1] / rho1 - 1):+.3f} %)\"\n",
    ")\n",
    "print(\n",
    "    \"spacing a   tetrahedra   apparent resistivity [Ωm]   two-layer series [Ωm]   deviation\"\n",
    ")\n",
    "for a, mesh, value in zip(spacings, meshes.values(), apparent):\n",
    "    print(\n",
    "        f\"{a:7.0f} m {mesh.cell_count:12d} {value:23.3f} {two_layer(a):23.3f} {100 * (value / two_layer(a) - 1):+11.3f} %\"\n",
    "    )\n",
    "print(\n",
    "    f\"reflection coefficient k = {reflection:.4f}; the curve tends to {rho1:.0f} Ωm for small and {rho2:.0f} Ωm for large spacings\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The potential in the vertical plane along the array for $a=8$ m, where the current bends into the\n",
    "conductive basement, and the sounding curve against the two-layer series."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "wide = np.geomspace(0.5, 200.0, 200)\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.section(\n",
    "    potentials[2],\n",
    "    plane=Plane(origin=(0, 1e-6, 0), normal=(0, 1, 0)),\n",
    "    component=lambda V, position: np.ravel(V),\n",
    "    limits=(0, 0.06),\n",
    "    contours=13,\n",
    "    subdivisions=2,\n",
    "    label=\"potential [V]\",\n",
    "    xlimits=(0, 40),\n",
    "    ylimits=(-20, 0),\n",
    "    xlabel=\"x along the array [m]\",\n",
    "    ylabel=\"depth [m]\",\n",
    "    title=\"Potential below the array, a = 8 m\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    wide,\n",
    "    {\"two-layer image series\": [two_layer(a) for a in wide]},\n",
    "    points={\"simulation\": (list(spacings), apparent[: len(spacings)])},\n",
    "    hlines={\"top layer\": rho1, \"basement\": rho2},\n",
    "    scale=\"loglog\",\n",
    "    xlabel=\"electrode spacing a [m]\",\n",
    "    ylabel=\"apparent resistivity [Ωm]\",\n",
    "    title=\"Wenner sounding curve\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Swap the resistivities to model a resistive basement (positive $k$), add a third layer to the\n",
    "geometry script, or move to a Schlumberger array by changing the electrode positions; a buried\n",
    "conductive body in place of the basement turns the sounding into a resistivity survey."
   ]
  }
 ]
}
