{
 "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": [
    "# Magnetic prospecting of an iron ore body\n",
    "\n",
    "Magnetic prospecting finds ore bodies rich in magnetite by the small changes, the anomalies, they\n",
    "cause in the magnetic field of the Earth. A magnetometer on the surface records the total-field\n",
    "anomaly\n",
    "\n",
    "$$\\Delta T=|\\mathbf B|-|\\mathbf B_0|\\approx(\\mathbf B-\\mathbf B_0)\\cdot\\hat{\\mathbf B}_0 ,$$\n",
    "\n",
    "the change of the field strength along the direction of the undisturbed field $\\mathbf B_0$.\n",
    "\n",
    "Here the Earth's field has a strength of 50 µT and an inclination of 60° (a mid-latitude of the\n",
    "northern hemisphere), pointing north ($+x$) and downwards. The ore body is a sphere of radius\n",
    "$a=50$ m with its centre 100 m below the surface and a magnetic susceptibility $\\chi=0.5$\n",
    "($\\mu_r=1.5$, a magnetite-rich ore). Rock and air are non-magnetic. Without currents,\n",
    "$\\nabla\\times\\mathbf H=0$, $\\nabla\\cdot\\mathbf B=0$; OneSimulation solves for the vector potential\n",
    "with second-order Nédélec elements and a Coulomb gauge.\n",
    "\n",
    "The field is symmetric about the magnetic meridian plane through the body, so half of the\n",
    "surroundings is modelled: a half ball of 800 m radius about the centre of the body, from\n",
    "`magnetic_prospecting_ore_body.step` with the face groups `meridian` and `outer`; the half ore\n",
    "body is in `magnetic_prospecting_ore_body_ore.step`. The script\n",
    "`magnetic_prospecting_ore_body_geometry.py` builds both with the CAD objects of OneSimulation.\n",
    "\n",
    "| faces | condition |\n",
    "|---|---|\n",
    "| `meridian` (the plane $y=0$) | field tangential, $\\mathbf n\\times\\mathbf A=0$ |\n",
    "| `outer`, 800 m from the body | undisturbed Earth field, $\\mathbf A=\\tfrac12\\mathbf B_0\\times\\mathbf r$ |\n",
    "\n",
    "**Reference.** A permeable sphere in a uniform field is magnetized uniformly; outside, it acts as\n",
    "a dipole at its centre (Telford, Geldart and Sheriff, *Applied Geophysics*, 2nd ed., 1990,\n",
    "Sec. 3.7; Blakely, *Potential Theory in Gravity and Magnetic Applications*, 1995, Ch. 4):\n",
    "\n",
    "$$\\mathbf B=\\mathbf B_0+K\\,\\frac{a^3}{r^3}\\big[3(\\mathbf B_0\\cdot\\hat{\\mathbf r})\\hat{\\mathbf r}-\\mathbf B_0\\big],\n",
    "  \\qquad K=\\frac{\\mu_r-1}{\\mu_r+2}.$$\n",
    "\n",
    "The outer boundary sees the undisturbed field only; the dipole field it misses there is about\n",
    "1 nT, a thousandth of the anomaly."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\n",
    "from onesim.cad.d3 import Box\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import VacuumPermeability\n",
    "from onesim.meshing import LocalRefinement, TetrahedralMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Nedelec\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.magnetostatics import (\n",
    "    CoulombGauge,\n",
    "    MagneticInsulation,\n",
    "    MagneticPotentialBoundary,\n",
    "    MagneticVectorPotential,\n",
    "    Magnetostatics,\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",
    "`load` returns the half ball with its named faces and the half ore body. The mesher embeds the\n",
    "body and refines a layer around the surface where the magnetometer measures; elsewhere the cells\n",
    "grow with the distance from the body. Two meshes differ in their cell sizes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "region, ore = load(\"magnetic_prospecting_ore_body.step\"), load(\n",
    "    \"magnetic_prospecting_ore_body_ore.step\"\n",
    ")\n",
    "faces = region.boundaries\n",
    "radius, depth = ore.size[0] / 2, 100.0\n",
    "sizes = (0.36 * radius, 0.25 * radius)\n",
    "meshes = [\n",
    "    TetrahedralMesher(\n",
    "        target_size=150.0,\n",
    "        embedded_regions=(ore,),\n",
    "        refinements=(\n",
    "            LocalRefinement(region=ore, target_size=size),\n",
    "            LocalRefinement(\n",
    "                region=Box(\n",
    "                    length=800.0,\n",
    "                    width=400.0,\n",
    "                    height=60.0,\n",
    "                    origin=(-400.0, 0.0, depth - 30.0),\n",
    "                ),\n",
    "                target_size=2.5 * size,\n",
    "            ),\n",
    "        ),\n",
    "        size_field=lambda points, size=size: np.clip(\n",
    "            size * (np.linalg.norm(points, axis=1) / radius) ** 1.5, size, 150.0\n",
    "        ),\n",
    "    ).generate(region)\n",
    "    for size in sizes\n",
    "]\n",
    "\n",
    "view = plots.Camera(elevation=20, azimuth=-120)\n",
    "fig = plots.figure(1, 2, size=(14, 6.5))\n",
    "plots.geometry(\n",
    "    [region.named(\"ground and air\"), ore.named(\"ore body\")],\n",
    "    camera=view,\n",
    "    title=\"Half of the surroundings of the ore body\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Coarsest mesh: {meshes[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 ore body its permeability; the Earth's field enters through the vector\n",
    "potential on the outer face."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "earth, inclination, mu_r = 50e-6, np.radians(60.0), 1.5\n",
    "B0 = earth * np.array((np.cos(inclination), 0.0, -np.sin(inclination)))\n",
    "mu0 = float(VacuumPermeability().evaluate())\n",
    "model = Magnetostatics(\n",
    "    domain=region.volume,\n",
    "    formulation=MagneticVectorPotential(gauge=CoulombGauge()),\n",
    "    permeability=regionwise(\n",
    "        ((lambda points: np.linalg.norm(points, axis=1) < radius, mu0 * mu_r),),\n",
    "        default=mu0,\n",
    "        unit=\"H/m\",\n",
    "    ),\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Magnetic prospecting\",\n",
    "    geometry=region,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        MagneticPotentialBoundary(\n",
    "            boundary=faces.outer,\n",
    "            physics=model,\n",
    "            value=lambda x, y, z: 0.5 * np.cross(B0, np.stack((x, y, z), axis=-1)),\n",
    "        ),\n",
    "        MagneticInsulation(boundary=faces.meridian, physics=model),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Nedelec(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "fields = [\n",
    "    Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "    .solve_stationary()\n",
    "    .field(model.magnetic_flux_density)\n",
    "    for mesh in meshes\n",
    "]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The anomaly along the north-south profile over the body on the surface, against the dipole field\n",
    "of the sphere."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "K = (mu_r - 1) / (mu_r + 2)\n",
    "\n",
    "\n",
    "def sphere_field(points):\n",
    "    \"\"\"Exact field outside a permeable sphere in the uniform field B0.\"\"\"\n",
    "    r = np.linalg.norm(points, axis=1, keepdims=True)\n",
    "    return B0 + K * (radius / r) ** 3 * (\n",
    "        3 * (points @ B0)[:, None] * points / r**2 - B0\n",
    "    )\n",
    "\n",
    "\n",
    "anomaly = lambda B, position: 1e9 * (B @ B0) / earth - 1e9 * earth\n",
    "x = np.linspace(-400.0, 400.0, 321)\n",
    "profile = np.column_stack((x, np.full_like(x, 1e-3), np.full_like(x, depth)))\n",
    "exact = anomaly(sphere_field(profile), None)\n",
    "computed = [anomaly(field.evaluate(profile), None) for field in fields]\n",
    "peaks = [values.max() for values in computed]\n",
    "print(\n",
    "    f\"exact: largest anomaly {exact.max():.1f} nT at x = {x[np.argmax(exact)]:+.1f} m, smallest {exact.min():.1f} nT at x = {x[np.argmin(exact)]:+.1f} m\"\n",
    ")\n",
    "print(\n",
    "    \"cell size in the body [m]   tetrahedra   largest anomaly [nT]   deviation   largest deviation on the profile\"\n",
    ")\n",
    "for size, mesh, values in zip(sizes, meshes, computed):\n",
    "    print(\n",
    "        f\"{size:25.1f} {mesh.cell_count:12d} {values.max():20.1f} {100 * (values.max() / exact.max() - 1):+10.2f} % \"\n",
    "        f\"{np.max(np.abs(values - exact)):12.1f} nT ({100 * np.max(np.abs(values - exact)) / exact.max():.2f} % of the peak)\"\n",
    "    )\n",
    "print(\n",
    "    f\"field inside the body: {1e6 * np.linalg.norm(fields[-1].evaluate(np.array([[5.0, 5.0, 0.0]]))):.3f} µT, \"\n",
    "    f\"exact {1e6 * 3 * mu_r / (mu_r + 2) * earth:.3f} µT\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The anomaly map on the surface (the half mirrored about the meridian), and the north-south\n",
    "profile over the body."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(15, 6.5))\n",
    "plots.section(\n",
    "    fields[-1],\n",
    "    plane=Plane(origin=(0.0, 0.0, depth), normal=(0.0, 0.0, 1.0)),\n",
    "    component=anomaly,\n",
    "    symmetry={\"planes\": [((0, 1, 0), (0, 0, 0))]},\n",
    "    limits=(-800, 2000),\n",
    "    contours=15,\n",
    "    subdivisions=2,\n",
    "    label=\"ΔT [nT]\",\n",
    "    title=\"Total-field anomaly on the surface\",\n",
    "    xlimits=(-400, 400),\n",
    "    ylimits=(-400, 400),\n",
    "    xlabel=\"north x [m]\",\n",
    "    ylabel=\"east y [m]\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"simulation\": (x[::8], computed[-1][::8])},\n",
    "    reference={\"permeable sphere, exact\": (x, exact)},\n",
    "    hlines=0.0,\n",
    "    xlabel=\"north x [m]\",\n",
    "    ylabel=\"ΔT [nT]\",\n",
    "    title=\"North-south profile over the body\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Replace the sphere in `magnetic_prospecting_ore_body_geometry.py` by a dipping slab or an\n",
    "irregular body and write the STEP files again; the exact sphere then serves as a first estimate.\n",
    "Add a remanent magnetization (`magnetization_provider`) to see how it shifts and turns the anomaly,\n",
    "or move the body to the magnetic equator (inclination 0°), where the anomaly over it is negative."
   ]
  }
 ]
}
