{
 "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": [
    "# Interior field of a long solenoid\n",
    "\n",
    "A single homogenised solenoid (mean radius $\\approx 12.5$ mm, length $200$ mm, so\n",
    "length $\\gg$ radius) carries $1\\,\\mathrm{A}$ through $400$ turns. Its current is\n",
    "modelled as an azimuthal volume current density on one explicitly meshed winding\n",
    "region. OneSimulation solves\n",
    "$\\nabla\\times(\\mu^{-1}\\nabla\\times\\mathbf A)=\\mathbf J$ with a weak Coulomb gauge\n",
    "and reconstructs $\\mathbf B=\\nabla\\times\\mathbf A$.\n",
    "\n",
    "The air cylinder comes from the CAD file `long_solenoid_interior_field.step`; the script\n",
    "`long_solenoid_interior_field_geometry.py` builds it with the CAD objects of OneSimulation. The\n",
    "winding is declared as a current source, and the mesher embeds its volume in the air.\n",
    "\n",
    "**Reference.** Deep inside an infinitely long solenoid the field is axial and uniform,\n",
    "\n",
    "$$B=\\mu_0\\,n\\,I,\\qquad n=\\frac{\\text{turns}}{\\text{length}}.$$\n",
    "\n",
    "The coil here is long but finite, so the formula is approached from below (the ends\n",
    "let a little flux escape)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "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()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "The winding sits in the middle of the air cylinder and is meshed more finely than the air."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "air = load(\"long_solenoid_interior_field.step\")\n",
    "centre = air.size[2] / 2\n",
    "coil_length, turns, current = 0.20, 400, 1.0\n",
    "coil = SolenoidCurrent(\n",
    "    inner_radius=0.010,\n",
    "    outer_radius=0.015,\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.02,\n",
    "    embedded_regions=(coil.support,),\n",
    "    refinements=(LocalRefinement(region=coil.support, target_size=0.006),),\n",
    ").generate(air)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(11, 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()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "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=\"Long solenoid interior field\",\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",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Centre field and axial uniformity\n",
    "\n",
    "The axial field is sampled along the axis over the central half of the coil, where an infinite\n",
    "solenoid would be perfectly uniform."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "ideal = VacuumPermeability().evaluate() * turns / coil_length * current\n",
    "z = np.linspace(centre - coil_length / 4, centre + coil_length / 4, 21)\n",
    "axial = flux_density.evaluate(np.column_stack((np.zeros_like(z), np.zeros_like(z), z)))[\n",
    "    :, 2\n",
    "]\n",
    "\n",
    "print(\n",
    "    f\"centre axial field: simulation {1e3 * axial[10]:.4f} mT, ideal mu0 n I {1e3 * ideal:.4f} mT, \"\n",
    "    f\"deviation {100 * (axial[10] / ideal - 1):+.2f} % (finite length lowers the field)\"\n",
    ")\n",
    "print(\n",
    "    f\"axial non-uniformity over the central half: {100 * (axial.max() - axial.min()) / axial.mean():.2f} %\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plots.line(\n",
    "    1e3 * (z - centre),\n",
    "    {\"simulation\": 1e3 * axial},\n",
    "    hlines={\"ideal mu_0 n I\": 1e3 * ideal},\n",
    "    markers=True,\n",
    "    xlabel=\"axial position from centre z [mm]\",\n",
    "    ylabel=\"axial flux density B_z [mT]\",\n",
    "    title=\"Long solenoid: interior axial field\",\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Lengthen the coil and watch the centre field climb towards $\\mu_0 n I$ as the end effects fade.\n",
    "Enlarge the air cylinder in `long_solenoid_interior_field_geometry.py` and write the STEP file\n",
    "again: the magnetic insulation then sits farther from the winding, with the same effect."
   ]
  }
 ]
}
