{
 "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 field of a Helmholtz coil\n",
    "\n",
    "Two circular coils of radius $R=0.4$ m with 10 turns each sit at $z=\\pm R/2$ and carry the same\n",
    "current of 0.25 mA. At this spacing the first three derivatives of the axial field vanish at the\n",
    "centre, so the field between the coils is very uniform.\n",
    "\n",
    "The model solves $\\nabla\\times(\\mu_0^{-1}\\nabla\\times\\mathbf A)=\\mathbf J$ with second-order\n",
    "Nédélec edge elements and a Coulomb gauge. The windings have a square cross-section of 5 cm and\n",
    "a uniform current density. The air is a sphere of radius $a=2$ m with magnetic insulation.\n",
    "\n",
    "The air sphere comes from the CAD file `helmholtz_coil_field.step`; the script\n",
    "`helmholtz_coil_field_geometry.py` builds it with the CAD objects of OneSimulation. The windings\n",
    "are current sources of the model, which the mesher places inside the air.\n",
    "\n",
    "**Reference.** On the axis the field of the two loops is\n",
    "\n",
    "$$B_z(z)=\\frac{\\mu_0NIR^2}{2}\\left[\\big(R^2+(z-\\tfrac R2)^2\\big)^{-3/2}+\\big(R^2+(z+\\tfrac R2)^2\\big)^{-3/2}\\right]\n",
    "  -\\frac{\\mu_0NIR^2}{a^3} ,$$\n",
    "\n",
    "with the centre value $(4/5)^{3/2}\\mu_0NI/R$. The last term is the image field of the insulated\n",
    "sphere, which sees the coil pair as a dipole; it lowers the field by 1.1 %."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\n",
    "from onesim.cad.d3 import AnnularCylinder\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import VacuumPermeability\n",
    "from onesim.meshing import LocalRefinement, TetrahedralMesher\n",
    "from onesim.meshing.quality import quality\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",
    "    MagneticVectorPotential,\n",
    "    Magnetostatics,\n",
    "    SolenoidCurrent,\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 air sphere. The two windings are embedded regions of the mesh, which is fine\n",
    "around them and in the region between the coils."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "air = load(\"helmholtz_coil_field.step\")\n",
    "radius, width, turns, current, air_radius = 0.4, 0.05, 10, 0.25e-3, air.size[0] / 2\n",
    "coils = tuple(\n",
    "    SolenoidCurrent(\n",
    "        inner_radius=radius - width / 2,\n",
    "        outer_radius=radius + width / 2,\n",
    "        length=width,\n",
    "        turns=turns,\n",
    "        current=current,\n",
    "        center=(0.0, 0.0, offset),\n",
    "        support_factory=AnnularCylinder,\n",
    "    )\n",
    "    for offset in (-radius / 2, radius / 2)\n",
    ")\n",
    "windings = tuple(coil.support for coil in coils)\n",
    "mesh = TetrahedralMesher(\n",
    "    target_size=0.6,\n",
    "    embedded_regions=windings,\n",
    "    refinements=tuple(\n",
    "        LocalRefinement(region=winding, target_size=0.05) for winding in windings\n",
    "    ),\n",
    "    size_field=lambda points: np.where(\n",
    "        np.linalg.norm(points, axis=1) < 0.55, 0.14, 0.6\n",
    "    ),\n",
    ").generate(air)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    [\n",
    "        winding.named(name)\n",
    "        for winding, name in zip(windings, (\"lower coil\", \"upper coil\"))\n",
    "    ],\n",
    "    title=\"The two windings inside the air sphere\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    cell_values=np.cbrt(quality(mesh)[\"size\"]),\n",
    "    plane=((0, 0, 0), (0, -1, 0)),\n",
    "    label=\"cell size [m]\",\n",
    "    camera=plots.Camera(elevation=5, azimuth=-90),\n",
    "    title=f\"{mesh.cell_count} tetrahedra, cut through the axis\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mu0 = float(VacuumPermeability().evaluate())\n",
    "model = Magnetostatics(\n",
    "    domain=air.volume,\n",
    "    permeability=VacuumPermeability(),\n",
    "    formulation=MagneticVectorPotential(gauge=CoulombGauge()),\n",
    "    current_sources=coils,\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Helmholtz coil\",\n",
    "    geometry=air,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        MagneticInsulation(boundary=air.boundaries.all, physics=model),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Nedelec(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "flux_density = (\n",
    "    Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "    .solve_stationary()\n",
    "    .field(model.magnetic_flux_density)\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The field on the axis against the closed form, and the size of the region in which the field\n",
    "stays within 0.1 % of its centre value."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "centre_field = 0.8**1.5 * mu0 * turns * current / radius\n",
    "\n",
    "\n",
    "def axis_field(z):\n",
    "    \"\"\"Axial field of the two loops inside the insulated air sphere.\"\"\"\n",
    "    loops = sum(\n",
    "        (radius**2 + (z - offset) ** 2) ** -1.5 for offset in (-radius / 2, radius / 2)\n",
    "    )\n",
    "    return mu0 * turns * current * radius**2 * (loops / 2 - 1 / air_radius**3)\n",
    "\n",
    "\n",
    "z = np.linspace(0.0, 0.9, 46)\n",
    "on_axis = flux_density.evaluate(\n",
    "    np.column_stack((np.zeros_like(z), np.zeros_like(z), z))\n",
    ")[:, 2]\n",
    "uniform = z[np.argmax(np.abs(on_axis / on_axis[0] - 1) > 1e-3)]\n",
    "print(\n",
    "    f\"field at the centre: simulation {1e9 * on_axis[0]:.4f} nT, closed form {1e9 * axis_field(0.0):.4f} nT \"\n",
    "    f\"({100 * (on_axis[0] / axis_field(0.0) - 1):+.2f} %); thin loops in free space {1e9 * centre_field:.4f} nT\"\n",
    ")\n",
    "print(\n",
    "    f\"largest deviation on the axis up to z = 0.9 m: {100 * np.abs(on_axis - axis_field(z)).max() / centre_field:.2f} % of the centre field\"\n",
    ")\n",
    "print(\n",
    "    f\"the axial field stays within 0.1 % of its centre value up to z = {uniform:.2f} m\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The field strength in a plane through the axis, and the axial field against the closed form."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "strength = lambda B, position: np.linalg.norm(B, axis=1) / centre_field\n",
    "fine = np.linspace(0.0, 0.9, 200)\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.section(\n",
    "    flux_density,\n",
    "    plane=Plane(origin=(0, 0, 0), normal=(0, 1, 0)),\n",
    "    component=strength,\n",
    "    limits=(0, 2.2),\n",
    "    contours=11,\n",
    "    subdivisions=2,\n",
    "    label=\"|B| / centre field of the thin loops\",\n",
    "    title=\"Field strength\",\n",
    "    xlimits=(-0.9, 0.9),\n",
    "    ylimits=(-0.75, 0.75),\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"simulation\": (z, on_axis / centre_field)},\n",
    "    reference={\"closed form\": (fine, axis_field(fine) / centre_field)},\n",
    "    vlines={\"coil plane\": radius / 2},\n",
    "    xlabel=\"z on the axis [m]\",\n",
    "    ylabel=\"B_z / centre field of the thin loops\",\n",
    "    title=\"Axial field\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Move the coils further apart or closer together and the plateau of the axial field turns into a\n",
    "dip or a peak. A third coil pair (Maxwell coil) widens the uniform region further, and opposite\n",
    "currents give the linear gradient field of an anti-Helmholtz pair."
   ]
  }
 ]
}
