{
 "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": [
    "# Stresses around a multilateral well junction\n",
    "\n",
    "A multilateral well taps several reservoir zones from one main bore through branching legs. Where\n",
    "a leg leaves the main bore, the rock between the two openings carries the stress that the removed\n",
    "rock carried before, from two directions at once. This junction is the weak spot of the well: if\n",
    "the stress concentration there exceeds the shear strength of the rock, the wall breaks out.\n",
    "\n",
    "**Setup.** A rock block of 2 m × 2 m × 2 m; by the symmetry of the well about the vertical plane\n",
    "$y=0$ only the half $y\\ge0$ is modelled. A vertical main bore of 100 mm diameter runs through the\n",
    "block; at mid height a lateral leg of 80 mm diameter branches off downwards at 45° in the plane\n",
    "$y=0$ and ends 0.8 m from the axis. Rock with $E=20$ GPa and $\\nu=0.25$; in-situ stresses\n",
    "(compression) $\\sigma_H=30$ MPa along $x$, $\\sigma_h=20$ MPa along $y$, $\\sigma_v=40$ MPa vertical;\n",
    "mud pressure $p_w=12$ MPa in both bores. The block comes from the CAD file\n",
    "`multilateral_well_stability.step`, written by `multilateral_well_stability_geometry.py` with the\n",
    "CAD objects of OneSimulation.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `x_high`, `y_high`, `z_high` | traction $-\\sigma_H$, $-\\sigma_h$, $-\\sigma_v$ normal to the face |\n",
    "| `x_low`, `z_low` | normal displacement 0 |\n",
    "| `symmetry` | $u_y=0$ |\n",
    "| `main_bore`, `lateral_bore` | mud pressure $p_w$ |\n",
    "\n",
    "**Reference.** Far from the junction and from the block faces the main bore is a hole in a plate\n",
    "under plane strain. With $\\theta$ measured from the $x$ axis, the wall stresses (compression\n",
    "positive) are (Kirsch 1898; Fjaer et al., *Petroleum Related Rock Mechanics*, 2nd ed., Ch. 4)\n",
    "\n",
    "$$\\sigma_\\theta=\\sigma_H+\\sigma_h-2(\\sigma_H-\\sigma_h)\\cos2\\theta-p_w,\\qquad \\sigma_r=p_w,\\qquad\n",
    "  \\sigma_z=\\sigma_v-2\\nu(\\sigma_H-\\sigma_h)\\cos2\\theta .$$\n",
    "\n",
    "The Mohr-Coulomb failure index $F=\\tfrac12(\\sigma_1-\\sigma_3)/\\big(c\\cos\\varphi+\\tfrac12(\\sigma_1+\\sigma_3)\\sin\\varphi\\big)$,\n",
    "with cohesion $c=10$ MPa and friction angle $\\varphi=30°$, reaches 1 where the rock fails in shear."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import LocalRefinement, 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.solid_mechanics import (\n",
    "    FixedDisplacementComponents,\n",
    "    LinearElasticity,\n",
    "    Pressure,\n",
    "    Traction,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\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 block with its named faces; quadratic tetrahedra of 0.15 m, refined to\n",
    "15 mm on both bore walls and bound to their curved surfaces."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "rock = load(\"multilateral_well_stability.step\")\n",
    "faces = rock.boundaries\n",
    "radius = 0.05\n",
    "mesh = TetrahedralMesher(\n",
    "    target_size=0.15,\n",
    "    geometry_order=2,\n",
    "    refinements=(\n",
    "        LocalRefinement(region=faces.main_bore | faces.lateral_bore, target_size=0.015),\n",
    "    ),\n",
    ").generate(rock)\n",
    "\n",
    "view = plots.Camera(elevation=20, azimuth=-110)\n",
    "fig = plots.figure(1, 2, size=(15, 6.5))\n",
    "plots.geometry(\n",
    "    rock,\n",
    "    selection={\n",
    "        \"main bore\": faces.main_bore,\n",
    "        \"lateral leg\": faces.lateral_bore,\n",
    "        \"symmetry plane\": faces.symmetry,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Half rock block around the well\",\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} curved tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`LinearElasticity` with the in-situ stresses as tractions on the far faces and the mud pressure as\n",
    "`Pressure` on the bore walls, solved with a sparse direct solver."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "stone = IsotropicSolid(\n",
    "    density=2500.0,\n",
    "    specific_heat_capacity=900.0,\n",
    "    thermal_conductivity=2.5,\n",
    "    youngs_modulus=20e9,\n",
    "    poisson_ratio=0.25,\n",
    "    thermal_expansion_coefficient=8e-6,\n",
    ")\n",
    "model = LinearElasticity(domain=rock.volume, material=stone)\n",
    "major, minor, vertical, mud, poisson = 30e6, 20e6, 40e6, 12e6, 0.25\n",
    "problem = Problem(\n",
    "    name=\"Multilateral junction\",\n",
    "    geometry=rock,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        FixedDisplacementComponents(\n",
    "            boundary=faces.x_low, physics=model, components=(\"x\",)\n",
    "        ),\n",
    "        FixedDisplacementComponents(\n",
    "            boundary=faces.symmetry, physics=model, components=(\"y\",)\n",
    "        ),\n",
    "        FixedDisplacementComponents(\n",
    "            boundary=faces.z_low, physics=model, components=(\"z\",)\n",
    "        ),\n",
    "        Traction(boundary=faces.x_high, physics=model, value=(-major, 0.0, 0.0)),\n",
    "        Traction(boundary=faces.y_high, physics=model, value=(0.0, -minor, 0.0)),\n",
    "        Traction(boundary=faces.z_high, physics=model, value=(0.0, 0.0, -vertical)),\n",
    "        Pressure(\n",
    "            boundary=faces.main_bore | faces.lateral_bore, physics=model, value=mud\n",
    "        ),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "result = Simulation(problem=problem, mesh=mesh, numerics=numerics).solve_stationary()\n",
    "stress = result.field(model.stress)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the Kirsch solution\n",
    "\n",
    "The wall stresses of the main bore half-way between the junction and the top face, 0.5 m above\n",
    "the junction, for $0\\le\\theta\\le180°$, against the Kirsch solution; then the failure index there and\n",
    "at the junction."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "theta = np.linspace(0.0, np.pi, 37)\n",
    "wall = np.column_stack(\n",
    "    (\n",
    "        radius * (1 + 2e-4) * np.cos(theta),\n",
    "        radius * (1 + 2e-4) * np.sin(theta),\n",
    "        np.full_like(theta, 0.5),\n",
    "    )\n",
    ")\n",
    "tensors = lambda s: np.stack(\n",
    "    [\n",
    "        [s[:, 0], s[:, 3], s[:, 5]],\n",
    "        [s[:, 3], s[:, 1], s[:, 4]],\n",
    "        [s[:, 5], s[:, 4], s[:, 2]],\n",
    "    ]\n",
    ").transpose(2, 0, 1)\n",
    "local = tensors(np.asarray(stress.evaluate(wall)))\n",
    "hoop = -np.einsum(\n",
    "    \"ni,nij,nj->n\",\n",
    "    np.column_stack((-np.sin(theta), np.cos(theta), 0 * theta)),\n",
    "    local,\n",
    "    np.column_stack((-np.sin(theta), np.cos(theta), 0 * theta)),\n",
    ")\n",
    "radial = -np.einsum(\n",
    "    \"ni,nij,nj->n\",\n",
    "    np.column_stack((np.cos(theta), np.sin(theta), 0 * theta)),\n",
    "    local,\n",
    "    np.column_stack((np.cos(theta), np.sin(theta), 0 * theta)),\n",
    ")\n",
    "axial = -local[:, 2, 2]\n",
    "kirsch = {\n",
    "    \"hoop\": major + minor - 2 * (major - minor) * np.cos(2 * theta) - mud,\n",
    "    \"radial\": mud + 0 * theta,\n",
    "    \"axial\": vertical - 2 * poisson * (major - minor) * np.cos(2 * theta),\n",
    "}\n",
    "cohesion, friction = 10e6, np.radians(30.0)\n",
    "failure = lambda s, position: (\n",
    "    lambda e: 0.5\n",
    "    * (e[:, 2] - e[:, 0])\n",
    "    / (cohesion * np.cos(friction) + 0.5 * (e[:, 2] + e[:, 0]) * np.sin(friction))\n",
    ")(np.linalg.eigvalsh(-tensors(np.asarray(s))))\n",
    "for name, values in ((\"hoop\", hoop), (\"radial\", radial), (\"axial\", axial)):\n",
    "    print(\n",
    "        f\"{name:6s} stress: largest deviation from Kirsch {np.abs(values - kirsch[name]).max() / 1e6:.2f} MPa \"\n",
    "        f\"({100 * np.abs(values - kirsch[name]).max() / kirsch['hoop'].max():.2f} % of the peak hoop stress)\"\n",
    "    )\n",
    "print(\n",
    "    f\"hoop stress at θ = 0: {hoop[0] / 1e6:.2f} MPa (Kirsch {kirsch['hoop'][0] / 1e6:.2f}); at θ = 90°: {hoop[18] / 1e6:.2f} MPa (Kirsch {kirsch['hoop'][18] / 1e6:.2f})\"\n",
    ")\n",
    "along_main = failure(np.asarray(stress.evaluate(wall)), None)\n",
    "far_field = failure(\n",
    "    np.stack(\n",
    "        [\n",
    "            -kirsch[\"radial\"],\n",
    "            -kirsch[\"hoop\"],\n",
    "            -kirsch[\"axial\"],\n",
    "            0 * theta,\n",
    "            0 * theta,\n",
    "            0 * theta,\n",
    "        ],\n",
    "        axis=1,\n",
    "    ),\n",
    "    None,\n",
    ")\n",
    "walls = stress.sample(along=faces.main_bore | faces.lateral_bore, subdivisions=2)\n",
    "near = np.linalg.norm(walls.positions, axis=1) < 5 * radius\n",
    "index = failure(walls.values[near], walls.positions[near])\n",
    "worst = walls.positions[near][int(np.argmax(index))]\n",
    "print(\n",
    "    f\"failure index on the main bore 0.5 m above the junction: {along_main.max():.3f} at θ = {np.degrees(theta[np.argmax(along_main)]):.0f}° \"\n",
    "    f\"(Kirsch: {far_field.max():.3f})\"\n",
    ")\n",
    "print(\n",
    "    f\"within 5 bore radii of the junction centre: largest failure index {index.max():.3f} at ({worst[0]:.3f}, {worst[1]:.3f}, {worst[2]:.3f}) m; \"\n",
    "    f\"{100 * np.mean(index > 1):.1f} % of the wall samples there exceed 1\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left the wall stresses of the main bore against the Kirsch solution; right the failure index on the\n",
    "walls of both bores. Away from the junction the main bore stays at the plane-strain value of about\n",
    "0.88; the highest values, above 1, sit on the flank of the lateral leg just below the junction,\n",
    "where the leg cuts into the most loaded side of the main bore. The flat closed end of the lateral\n",
    "leg, an idealisation with a sharp edge, is left out of the junction statistics."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(17, 6.5))\n",
    "plots.line(\n",
    "    points={\n",
    "        name: (np.degrees(theta), values / 1e6)\n",
    "        for name, values in ((\"hoop\", hoop), (\"radial\", radial), (\"axial\", axial))\n",
    "    },\n",
    "    reference={\n",
    "        f\"{name}, Kirsch\": (np.degrees(theta), values / 1e6)\n",
    "        for name, values in kirsch.items()\n",
    "    },\n",
    "    xlabel=\"θ from the x axis [°]\",\n",
    "    ylabel=\"stress, compression positive [MPa]\",\n",
    "    title=\"Main bore wall 0.5 m above the junction\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.surface(\n",
    "    stress,\n",
    "    boundary=faces.main_bore | faces.lateral_bore,\n",
    "    component=failure,\n",
    "    subdivisions=3,\n",
    "    limits=(0.5, 1.25),\n",
    "    camera=plots.Camera(elevation=15, azimuth=55),\n",
    "    label=\"Mohr-Coulomb failure index\",\n",
    "    title=\"Failure index on the bore walls\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the mud weight until the failure index stays below 1 everywhere, turn the lateral towards\n",
    "the direction of the smaller horizontal stress, or replace the elastic rock by a Mohr-Coulomb\n",
    "plastic material to follow the breakout itself."
   ]
  }
 ]
}
