{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "10489975",
   "metadata": {},
   "source": [
    "# Magnetostatics: the on-axis field of a finite solenoid\n",
    "\n",
    "A single short, thin-walled solenoid carries a steady current. OneSimulation\n",
    "solves the full 3-D magnetostatic problem\n",
    "\n",
    "$$\\nabla\\times\\big(\\mu^{-1}\\nabla\\times\\mathbf A\\big)=\\mathbf J,\\qquad\n",
    "  \\mathbf B=\\nabla\\times\\mathbf A,$$\n",
    "\n",
    "with first-order Nedelec (edge) elements and a weak Coulomb gauge, and\n",
    "reconstructs the magnetic flux density $\\mathbf B$ on a tetrahedral mesh.\n",
    "\n",
    "The air cylinder comes from the CAD file `solenoid_on_axis_field.step`; the script\n",
    "`solenoid_on_axis_field_geometry.py` builds it with the CAD objects of OneSimulation. The winding\n",
    "is declared as a current source, and the mesher embeds its volume in the air. The outer surface\n",
    "carries a magnetic-insulation condition; the air cylinder is several coil radii wide and long so\n",
    "that this boundary barely affects the central field.\n",
    "\n",
    "**Reference.** On the axis of a finite solenoid of radius $R$, length $L$, with\n",
    "$N$ turns carrying current $I$, the axial flux density has the closed form\n",
    "\n",
    "$$B_z(z)=\\frac{\\mu_0 N I}{2L}\n",
    "  \\left[\\frac{z-z_a}{\\sqrt{(z-z_a)^2+R^2}}\n",
    "       -\\frac{z-z_b}{\\sqrt{(z-z_b)^2+R^2}}\\right],$$\n",
    "\n",
    "where $z_a,z_b$ are the axial positions of the two coil ends. The winding is thin, so the\n",
    "formula is accurate to well under a percent."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd26dac1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\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.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()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16968377",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "The coil is a thin cylindrical shell at the centre of the air cylinder, meshed more finely than\n",
    "the air."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3446cfdc",
   "metadata": {},
   "outputs": [],
   "source": [
    "air = load(\"solenoid_on_axis_field.step\")\n",
    "centre = air.size[2] / 2\n",
    "inner_radius, outer_radius, coil_length, turns, current = 0.0235, 0.0265, 0.03, 200, 1.0\n",
    "coil = SolenoidCurrent(\n",
    "    inner_radius=inner_radius,\n",
    "    outer_radius=outer_radius,\n",
    "    length=coil_length,\n",
    "    center=(0.0, 0.0, centre),\n",
    "    turns=turns,\n",
    "    current=current,\n",
    "    support_factory=AnnularCylinder,\n",
    ")\n",
    "mesh = TetrahedralMesher(\n",
    "    target_size=0.032,\n",
    "    embedded_regions=(coil.support,),\n",
    "    refinements=(LocalRefinement(region=coil.support, target_size=0.0045),),\n",
    ").generate(air)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 6))\n",
    "plots.geometry([air, coil.support], title=\"Air cylinder with the winding\", ax=fig[0])\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"{mesh.cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "31dc1937",
   "metadata": {},
   "source": [
    "## Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c7c0e3c2",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = Magnetostatics(\n",
    "    domain=air.volume,\n",
    "    permeability=VacuumPermeability(),\n",
    "    formulation=MagneticVectorPotential(gauge=CoulombGauge()),\n",
    "    current_sources=(coil,),\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"On-axis field of a finite solenoid\",\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=1)), 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",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "56c958ed",
   "metadata": {},
   "source": [
    "## Comparison with the finite-solenoid formula\n",
    "\n",
    "First-order edge elements give a flux density that is constant per tetrahedron. To read off the\n",
    "smooth bore field, $B_z$ is averaged at each axial station over the axis point and twelve points\n",
    "on a coaxial circle of radius 6 mm, well inside the bore."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7f422023",
   "metadata": {},
   "outputs": [],
   "source": [
    "z = centre + np.linspace(-0.045, 0.045, 31)\n",
    "angles = np.linspace(0.0, 2 * np.pi, 12, endpoint=False)\n",
    "ring = np.column_stack(\n",
    "    (np.append(0.0, 0.006 * np.cos(angles)), np.append(0.0, 0.006 * np.sin(angles)))\n",
    ")\n",
    "stations = np.column_stack((np.tile(ring, (len(z), 1)), np.repeat(z, len(ring))))\n",
    "axial = flux_density.evaluate(stations)[:, 2].reshape(len(z), len(ring)).mean(axis=1)\n",
    "radius, ends = (inner_radius + outer_radius) / 2, (\n",
    "    centre - coil_length / 2,\n",
    "    centre + coil_length / 2,\n",
    ")\n",
    "formula = (\n",
    "    VacuumPermeability().evaluate()\n",
    "    * turns\n",
    "    * current\n",
    "    / (2 * coil_length)\n",
    "    * (\n",
    "        (z - ends[0]) / np.hypot(z - ends[0], radius)\n",
    "        - (z - ends[1]) / np.hypot(z - ends[1], radius)\n",
    "    )\n",
    ")\n",
    "inside = np.abs(z - centre) <= coil_length / 2 + 1e-12\n",
    "\n",
    "print(\n",
    "    f\"centre B_z: simulation {1e6 * axial[15]:.2f} µT, formula {1e6 * formula[15]:.2f} µT, \"\n",
    "    f\"deviation {100 * (axial[15] / formula[15] - 1):+.2f} %\"\n",
    ")\n",
    "print(\n",
    "    f\"largest deviation along the axis inside the coil: {100 * np.max(np.abs(axial[inside] / formula[inside] - 1)):.2f} %\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "597f7bb0",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "80f0d582",
   "metadata": {},
   "outputs": [],
   "source": [
    "plots.line(\n",
    "    1e3 * (z - centre),\n",
    "    points={\"simulation\": 1e6 * axial},\n",
    "    reference={\"finite-solenoid formula\": 1e6 * formula},\n",
    "    vlines={\"coil ends\": -1e3 * coil_length / 2, \"\": 1e3 * coil_length / 2},\n",
    "    xlabel=\"axial position z from the coil centre [mm]\",\n",
    "    ylabel=\"axial flux density B_z [µT]\",\n",
    "    title=\"Finite solenoid: on-axis field\",\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5802aa99",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Refine the mesh (smaller `target_size`), or widen the air cylinder in\n",
    "`solenoid_on_axis_field_geometry.py` and write the STEP file again: the finite domain and the\n",
    "magnetic insulation set the small residual offset from the free-space formula. Make the coil\n",
    "longer relative to its radius and the bore field flattens towards the ideal $\\mu_0 n I$."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
