{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1dc9e213",
   "metadata": {},
   "source": [
    "# Inductance from the magnetic field energy\n",
    "\n",
    "A circuit designer does not want the field of a coil but the one number it implies: its\n",
    "inductance. It follows from the stored magnetic energy,\n",
    "\n",
    "$$W=\\frac12\\int \\mathbf B\\cdot\\mathbf H\\,\\mathrm dV,\\qquad L=\\frac{2W}{I^2}.$$\n",
    "\n",
    "The coil is a solenoid with 240 turns, inner radius 10 mm, outer radius 20 mm and length 120 mm,\n",
    "carrying 1 A. The winding is a uniform azimuthal current density. The model solves\n",
    "$\\nabla\\times(\\mu_0^{-1}\\nabla\\times\\mathbf A)=\\mathbf J$ with Nédélec edge elements and a Coulomb\n",
    "gauge in an air cylinder with magnetic insulation on its surface.\n",
    "\n",
    "The air cylinder comes from the CAD file `solenoid_inductance_from_energy.step`; the script\n",
    "`solenoid_inductance_from_energy_geometry.py` builds it with the CAD objects of OneSimulation.\n",
    "The winding is declared as a current source, and the mesher embeds its volume in the air.\n",
    "\n",
    "**Reference.** The long-solenoid formula for a winding of finite thickness, multiplied by\n",
    "Nagaoka's end-correction factor $K$:\n",
    "\n",
    "$$L_\\mathrm{ref}=K\\,\\mu_0\\,n^2\\,\\ell\\,A_\\mathrm{eff},\\qquad n=\\frac{N}{\\ell},\\qquad\n",
    "  A_\\mathrm{eff}=\\pi\\Bigl[R_i^2+\\frac{(R_o-R_i)(R_o+3R_i)}{6}\\Bigr].$$\n",
    "\n",
    "$A_\\mathrm{eff}$ accounts for the field falling linearly across the winding. The combination is\n",
    "accurate to about 2 % for this coil."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6c108c0f",
   "metadata": {},
   "outputs": [],
   "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.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.results.integration import mean_value, measure\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.special import ellipe, ellipk\n",
    "\n",
    "theme.set()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3a557fea",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "The winding is an embedded region of the air cylinder, meshed finely enough to resolve the field\n",
    "across its thickness."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e849f92b",
   "metadata": {},
   "outputs": [],
   "source": [
    "air = load(\"solenoid_inductance_from_energy.step\")\n",
    "centre = air.size[2] / 2\n",
    "inner_radius, outer_radius, coil_length, turns, current = 0.010, 0.020, 0.12, 240, 1.0\n",
    "coil = SolenoidCurrent(\n",
    "    inner_radius=inner_radius,\n",
    "    outer_radius=outer_radius,\n",
    "    length=coil_length,\n",
    "    turns=turns,\n",
    "    current=current,\n",
    "    center=(0, 0, centre),\n",
    "    support_factory=AnnularCylinder,\n",
    ")\n",
    "mesh = TetrahedralMesher(\n",
    "    target_size=0.04,\n",
    "    embedded_regions=(coil.support,),\n",
    "    refinements=(LocalRefinement(region=coil.support, target_size=0.007),),\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": "2727638a",
   "metadata": {},
   "source": [
    "## Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3692df13",
   "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=\"Solenoid inductance\",\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",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21196337",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The energy integral runs over the whole air cylinder. The reference is the long-solenoid formula\n",
    "with the effective winding area and Nagaoka's factor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f9bfc956",
   "metadata": {},
   "outputs": [],
   "source": [
    "mu0 = VacuumPermeability().evaluate()\n",
    "squared = lambda B, position: (B**2).sum(axis=1)\n",
    "inductance = (\n",
    "    mean_value(flux_density, component=squared)\n",
    "    * measure(flux_density)\n",
    "    / (mu0 * current**2)\n",
    ")\n",
    "area = np.pi * (\n",
    "    inner_radius**2\n",
    "    + (outer_radius - inner_radius) * (outer_radius + 3 * inner_radius) / 6\n",
    ")\n",
    "k2 = (inner_radius + outer_radius) ** 2 / (\n",
    "    (inner_radius + outer_radius) ** 2 + coil_length**2\n",
    ")\n",
    "nagaoka = (\n",
    "    4\n",
    "    / (3 * np.pi * np.sqrt(1 - k2))\n",
    "    * ((1 - k2) / k2 * (ellipk(k2) - ellipe(k2)) + ellipe(k2) - np.sqrt(k2))\n",
    ")\n",
    "reference = nagaoka * mu0 * (turns / coil_length) ** 2 * coil_length * area\n",
    "centre_field = flux_density.evaluate([[0, 0, centre]])[0, 2]\n",
    "\n",
    "print(f\"inductance from the field energy   {1e6 * inductance:7.1f} µH\")\n",
    "print(\n",
    "    f\"closed form with end correction    {1e6 * reference:7.1f} µH   (difference {100 * (inductance / reference - 1):+.1f} %)\"\n",
    ")\n",
    "print(\n",
    "    f\"field at the coil centre           {1e3 * centre_field:7.3f} mT   ({centre_field / (mu0 * turns / coil_length * current):.3f} of the infinite solenoid)\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6ee50a49",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The field strength in a section through the axis, and the axial field across the mid-plane\n",
    "against the infinite solenoid, whose field falls linearly through the winding."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d5ee965b",
   "metadata": {},
   "outputs": [],
   "source": [
    "axial = lambda B, position: 1e3 * B[:, 2]\n",
    "r = np.linspace(0, 1.5 * outer_radius, 61)\n",
    "profile = axial(\n",
    "    flux_density.evaluate(\n",
    "        np.column_stack((r, np.zeros_like(r), np.full_like(r, centre)))\n",
    "    ),\n",
    "    None,\n",
    ")\n",
    "ideal = (\n",
    "    1e3\n",
    "    * mu0\n",
    "    * turns\n",
    "    / coil_length\n",
    "    * current\n",
    "    * np.clip((outer_radius - r) / (outer_radius - inner_radius), 0, 1)\n",
    ")\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 5))\n",
    "plots.section(\n",
    "    flux_density,\n",
    "    plane=Plane(origin=(0, 0, 0), normal=(0, 1, 0)),\n",
    "    component=axial,\n",
    "    colormap=\"diverging\",\n",
    "    contours=14,\n",
    "    subdivisions=2,\n",
    "    label=\"B_z [mT]\",\n",
    "    title=\"Axial field in a section through the axis\",\n",
    "    xlimits=(-0.06, 0.06),\n",
    "    ylimits=(0.08, 0.28),\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    1e3 * r,\n",
    "    {\"simulation\": profile},\n",
    "    reference={\"infinite solenoid\": ideal},\n",
    "    vlines={\"winding\": 1e3 * inner_radius, \"\": 1e3 * outer_radius},\n",
    "    xlabel=\"radius [mm]\",\n",
    "    ylabel=\"axial flux density [mT]\",\n",
    "    title=\"Mid-plane profile\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "50a66c80",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Shorten the coil and watch the end correction grow, or enlarge the air cylinder in\n",
    "`solenoid_inductance_from_energy_geometry.py` and write the STEP file again: the insulated\n",
    "surface confines the return flux and lowers the inductance slightly. The same recipe with\n",
    "$\\tfrac12\\int\\varepsilon|\\mathbf E|^2\\,\\mathrm dV$ gives capacitances from electrostatic fields."
   ]
  }
 ],
 "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
}
