{
 "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": [
    "# Mutual inductance of a ring and a coil of 20 resolved turns\n",
    "\n",
    "A primary ring of radius $R_1=100$ mm (copper wire of 1 mm radius) carries 1 A at 1 kHz. At its\n",
    "centre, coplanar and concentric, sits a secondary coil of $N=20$ turns of the same wire: two layers\n",
    "of ten turns, turn centres at radii 8.5 mm and 11.5 mm and every 3 mm along the axis. Every turn is\n",
    "resolved: each wire is a solid conductor whose current distribution follows from the field (skin\n",
    "and proximity effects between the turns included), all 20 carry the coil current and their loop\n",
    "voltages add up. At direct current the coil has the resistance of 20 turns of wire in series,\n",
    "$R_2=\\sum_k 2\\pi r_k/(\\sigma\\pi r_0^2)$. The meridian half-plane is solved for $A_\\varphi$:\n",
    "\n",
    "$$\\nabla\\times\\big(\\mu_0^{-1}\\nabla\\times A_\\varphi\\mathbf e_\\varphi\\big)+j\\omega\\sigma A_\\varphi\\mathbf e_\\varphi=\\mathbf J_s .$$\n",
    "\n",
    "| case | primary ring (solid copper) | secondary coil (20 solid turns in series) |\n",
    "|---|---|---|\n",
    "| open circuit | 1 A | no current: voltage $V_2=j\\omega M I_1$ |\n",
    "| coil alone | no current | 1 A: impedance $Z_{22}=R_2+j\\omega L_2$ |\n",
    "| short circuit | 1 A | voltage 0 |\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| outer boundary of the air cylinder (1 m radius, 2 m high) | $A_\\varphi=0$ |\n",
    "| axis $r=0$ | symmetry |\n",
    "\n",
    "The parts come from the CAD files `explicit_turns_coil_mutual_inductance*.step`; the script\n",
    "`explicit_turns_coil_mutual_inductance_geometry.py` builds them with the CAD objects of OneSimulation.\n",
    "Each part is cut to $x>0$, and its section with the plane $y=0$ is the meridian.\n",
    "\n",
    "**Reference.** For $R_1\\gg R_2$ the primary field is uniform over the coil and\n",
    "$M=N\\pi\\mu_0R_2^2/(2R_1)=39.478$ nH with $R_2=10$ mm. More precisely, Maxwell's formula for\n",
    "coaxial filaments (Grover, *Inductance Calculations*, 1946),\n",
    "$m(a,b,d)=\\mu_0\\sqrt{ab}\\,[(2/k-k)K(k)-2E(k)/k]$ with $k^2=4ab/((a+b)^2+d^2)$, summed over the\n",
    "20 turn positions. The short-circuited coil carries $I_2=-j\\omega M I_1/Z_{22}$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import VacuumPermeability, regionwise\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange, RevolvedH1SpaceFactory\n",
    "from onesim.numerics.linear import ComplexSparseDirect\n",
    "from onesim.physics.magnetostatics import (\n",
    "    Coil,\n",
    "    EddyCurrents,\n",
    "    MagneticInsulation,\n",
    "    coil_current,\n",
    "    coil_impedance,\n",
    "    coil_voltage,\n",
    ")\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()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` returns each part, `section` its meridian; the 20 turns are one body of separate pieces, and\n",
    "`sections` returns one region per turn. Ring and turns are embedded regions with triangles of\n",
    "0.25 mm; the air grows to 10 cm at the outer boundary."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "name = \"explicit_turns_coil_mutual_inductance\"\n",
    "meridian = lambda part: load(f\"{name}{part}.step\").section((0, 1, 0))\n",
    "air, ring = meridian(\"\"), meridian(\"_ring\").named(\"ring\")\n",
    "wires = [\n",
    "    piece.named(f\"turn{index}\")\n",
    "    for index, piece in enumerate(load(f\"{name}_turns.step\").sections((0, 1, 0)))\n",
    "]\n",
    "axis = air.select(\n",
    "    edges=lambda edge: all(abs(point[0]) < 1e-12 for point in edge.points)\n",
    ")\n",
    "R1, wire, turns = 0.1, 0.001, 20\n",
    "mesh = TriangularMesher(\n",
    "    target_size=0.1,\n",
    "    embedded_regions=(ring, *wires),\n",
    "    region_sizes={\"ring\": 0.00025, **{f\"turn{i}\": 0.00025 for i in range(turns)}},\n",
    "    grading=0.25,\n",
    ").generate(air)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    [\n",
    "        load(f\"{name}_{part}.step\").named(label)\n",
    "        for part, label in ((\"ring\", \"primary ring\"), (\"turns\", \"20 turns of the coil\"))\n",
    "    ],\n",
    "    camera=plots.Camera(elevation=50, azimuth=-60),\n",
    "    title=\"Ring and coil (x > 0)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Meridian section: {mesh.cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`Coil(..., conductor=\"massive\")` is the solid copper ring; `Coil(wires[0], series=wires[1:],\n",
    "conductor=\"massive\")` the coil of 20 solid turns in series, fed by the current 0 (open), by 1 A\n",
    "(alone) or by the voltage 0 (short circuit)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "frequency, sigma, mu0 = 1000.0, 5.8e7, float(VacuumPermeability().evaluate())\n",
    "omega = 2 * np.pi * frequency\n",
    "radii = np.repeat([0.0085, 0.0115], 10)\n",
    "heights = np.tile(np.linspace(-0.0135, 0.0135, 10), 2)\n",
    "resistance = np.sum(2 * np.pi * radii / (sigma * np.pi * wire**2))\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(\n",
    "        element=Lagrange(order=2), quadrature_order=4, provider=RevolvedH1SpaceFactory()\n",
    "    ),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "cases = {\n",
    "    \"open circuit\": (\n",
    "        Coil(ring, current=1.0, conductor=\"massive\"),\n",
    "        Coil(wires[0], series=wires[1:], current=0.0, conductor=\"massive\"),\n",
    "    ),\n",
    "    \"coil alone\": (\n",
    "        Coil(ring, current=0.0, conductor=\"massive\"),\n",
    "        Coil(wires[0], series=wires[1:], current=1.0, conductor=\"massive\"),\n",
    "    ),\n",
    "    \"short circuit\": (\n",
    "        Coil(ring, current=1.0, conductor=\"massive\"),\n",
    "        Coil(wires[0], series=wires[1:], voltage=0.0, conductor=\"massive\"),\n",
    "    ),\n",
    "}\n",
    "solved = {}\n",
    "for case, (primary, secondary) in cases.items():\n",
    "    model = EddyCurrents(\n",
    "        domain=air.domain(),\n",
    "        permeability=VacuumPermeability(),\n",
    "        frequency=frequency,\n",
    "        coils=(primary, secondary),\n",
    "        conductivity=regionwise(\n",
    "            {\"ring\": sigma, **{f\"turn{i}\": sigma for i in range(turns)}},\n",
    "            default=0.0,\n",
    "            unit=\"S/m\",\n",
    "        ),\n",
    "    )\n",
    "    result = Simulation(\n",
    "        problem=Problem(\n",
    "            name=f\"Ring and coil, {case}\",\n",
    "            geometry=air,\n",
    "            physics=(model,),\n",
    "            boundary_conditions=(\n",
    "                MagneticInsulation(boundary=air.boundaries.all - axis, physics=model),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=mesh,\n",
    "        numerics=numerics,\n",
    "    ).solve_stationary()\n",
    "    solved[case] = (result, model, primary, secondary)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The mutual inductance from the open-circuit voltage against both references, the impedance of the\n",
    "coil, and the short-circuit current against the coupled-loop circuit."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "result, model, primary, secondary = solved[\"open circuit\"]\n",
    "M = coil_voltage(result, model, secondary) / (\n",
    "    1j * omega * coil_current(result, model, primary)\n",
    ")\n",
    "filament = lambda a, b, d: (\n",
    "    lambda k: mu0\n",
    "    * np.sqrt(a * b)\n",
    "    * ((2 / k - k) * ellipk(k * k) - 2 / k * ellipe(k * k))\n",
    ")(np.sqrt(4 * a * b / ((a + b) ** 2 + d**2)))\n",
    "maxwell = np.sum(filament(R1, radii, heights))\n",
    "uniform = turns * np.pi * mu0 * 0.01**2 / (2 * R1)\n",
    "print(f\"{mesh.cell_count} triangles\")\n",
    "print(f\"M from the open-circuit voltage: {1e9 * M.real:.3f} {1e9 * M.imag:+.3f}j nH\")\n",
    "print(\n",
    "    f\"Maxwell's formula over the 20 turns: {1e9 * maxwell:.3f} nH ({100 * (M.real / maxwell - 1):+.3f} %); \"\n",
    "    f\"uniform-field limit {1e9 * uniform:.3f} nH ({100 * (M.real / uniform - 1):+.2f} %)\"\n",
    ")\n",
    "result, model, primary, secondary = solved[\"coil alone\"]\n",
    "Z22 = coil_impedance(result, model, secondary)\n",
    "print(\n",
    "    f\"coil: R2 = {1e3 * Z22.real:.3f} mOhm (20 turns of wire at direct current {1e3 * resistance:.3f} mOhm; \"\n",
    "    f\"skin and proximity effect {100 * (Z22.real / resistance - 1):+.1f} %), L2 = {1e6 * Z22.imag / omega:.4f} µH\"\n",
    ")\n",
    "result, model, primary, secondary = solved[\"short circuit\"]\n",
    "I2 = coil_current(result, model, secondary)\n",
    "circuit = -1j * omega * M / Z22\n",
    "print(\n",
    "    f\"short circuit: I2 = {1e3 * I2.real:.3f} {1e3 * I2.imag:+.3f}j mA; circuit -j w M I1 / Z22 = \"\n",
    "    f\"{1e3 * circuit.real:.3f} {1e3 * circuit.imag:+.3f}j mA; deviation {100 * abs(I2 - circuit) / abs(circuit):.3f} %\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The magnitude of the flux density with the short-circuited coil, near the centre, and the flux\n",
    "density on the axis with the coil open and short-circuited: the induced current pushes the field\n",
    "of the ring out of the coil."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "z = np.linspace(-0.05, 0.05, 201)\n",
    "line = np.column_stack((np.full_like(z, 1e-5), z))\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.surface(\n",
    "    solved[\"short circuit\"][0].field(solved[\"short circuit\"][1].magnetic_flux_density),\n",
    "    component=lambda B, position: 1e6 * np.hypot(np.abs(B[:, 0]), np.abs(B[:, 2])),\n",
    "    limits=(0, 8),\n",
    "    contours=9,\n",
    "    subdivisions=2,\n",
    "    xlimits=(0, 0.04),\n",
    "    ylimits=(-0.04, 0.04),\n",
    "    xlabel=\"r [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    label=\"|B| [µT]\",\n",
    "    title=\"Flux density with the short-circuited coil\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    x=1e3 * z,\n",
    "    y={\n",
    "        case: 1e6\n",
    "        * np.abs(\n",
    "            solved[case][0]\n",
    "            .field(solved[case][1].magnetic_flux_density)\n",
    "            .evaluate(line)[:, 2]\n",
    "        )\n",
    "        for case in (\"open circuit\", \"short circuit\")\n",
    "    },\n",
    "    hlines={\"field of the ring alone, mu0 I / (2 R1)\": 1e6 * mu0 / (2 * R1)},\n",
    "    xlabel=\"z [mm]\",\n",
    "    ylabel=\"|B_z| on the axis [µT]\",\n",
    "    title=\"Axial flux density on the axis\",\n",
    "    legend=\"lower center\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Replace the 20 solid turns by a homogenized winding (`Coil(..., turns=20)` over the winding space)\n",
    "and compare the resistance, which then lacks the proximity effect, or raise the frequency and watch\n",
    "the current crowd to the outer turns."
   ]
  }
 ]
}
