{
 "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": [
    "# Self and mutual inductance of two coplanar loops\n",
    "\n",
    "A primary loop of mean radius $R_1=50$ mm and a secondary loop of $R_2=100$ mm, both of copper with\n",
    "a square cross-section of $c=4$ mm, lie concentrically in the plane $z=0$ in air. The\n",
    "magnetostatic field of a current $I$ in a loop gives its self-inductance $L=2W/I^2$; with currents\n",
    "in both loops the flux linked with the secondary gives the mutual inductance $M$.\n",
    "\n",
    "The arrangement is symmetric about the planes $x=0$, $y=0$ and $z=0$, so one eighth of a ball of\n",
    "air of 0.6 m radius is modelled. The loop currents flow around the $z$ axis: on the planes $x=0$\n",
    "and $y=0$ the field lies in the plane ($\\mathbf n\\times\\mathbf A=0$), on $z=0$ it is normal to it\n",
    "(magnetic symmetry); on the outer sphere $\\mathbf n\\times\\mathbf A=0$ as well. The inductances of\n",
    "the whole loops follow with `copies=8`.\n",
    "\n",
    "With these inductances a short-circuited secondary carries, for an alternating primary current\n",
    "$I_1$ of angular frequency $\\omega$, $I_2=-j\\omega M I_1/(R_2+j\\omega L_2)$ with\n",
    "$R_2=2\\pi R_2/(\\sigma c^2)$, as long as the skin depth exceeds the wire size.\n",
    "\n",
    "The air region and the loops come from the CAD files `coplanar_loops_mutual_inductance*.step`;\n",
    "the script `coplanar_loops_mutual_inductance_geometry.py` builds them with the CAD objects of\n",
    "OneSimulation.\n",
    "\n",
    "**Reference.** Maxwell's formula for two coaxial circular filaments (Grover, *Inductance\n",
    "Calculations*, 1946), $M=\\mu_0\\sqrt{ab}\\,[(2/k-k)K(k)-2E(k)/k]$ with $k^2=4ab/((a+b)^2+d^2)$,\n",
    "integrated over both square cross-sections with Gauss points. For the self-inductance of a ring\n",
    "of square cross-section the geometric mean distance $g=0.44705\\,c$ gives\n",
    "$L=\\mu_0R\\,[\\ln(8R/g)-2]$ (Rosa and Grover, valid for $c\\ll R$). In the plane of a circular\n",
    "filament of radius $a$ the field is $B_z(\\rho)=\\frac{\\mu_0 I}{2\\pi}\\,\\frac{1}{a+\\rho}\\big[K(k)+\\frac{a^2-\\rho^2}{(a-\\rho)^2}E(k)\\big]$,\n",
    "$k^2=4a\\rho/(a+\\rho)^2$ (Smythe, *Static and Dynamic Electricity*, 1950)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\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 GMRES, AuxiliarySpaceMaxwell\n",
    "from onesim.physics.magnetostatics import (\n",
    "    CoulombGauge,\n",
    "    MagneticInsulation,\n",
    "    MagneticSymmetry,\n",
    "    MagneticVectorPotential,\n",
    "    Magnetostatics,\n",
    "    RegionCurrent,\n",
    "    flux_linkage,\n",
    "    inductance,\n",
    "    magnetic_energy,\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 the eighth of the air ball with its named faces and the two loops, which the mesher\n",
    "embeds and clips at the symmetry planes. Tetrahedra of 2 mm in and around the loops grow to 10 cm\n",
    "at the outer sphere, six secondary radii away."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "name = \"coplanar_loops_mutual_inductance\"\n",
    "air = load(f\"{name}.step\")\n",
    "faces = air.boundaries\n",
    "loops = [load(f\"{name}_{part}.step\").named(part) for part in (\"primary\", \"secondary\")]\n",
    "radii, side, h = (0.05, 0.1), 0.004, 0.002\n",
    "distance = lambda p: np.min(\n",
    "    [np.hypot(np.hypot(p[:, 0], p[:, 1]) - r, p[:, 2]) for r in radii], axis=0\n",
    ")\n",
    "mesh = TetrahedralMesher(\n",
    "    target_size=0.1,\n",
    "    embedded_regions=tuple(loops),\n",
    "    clip_regions=True,\n",
    "    refinements=tuple(LocalRefinement(region=loop, target_size=h) for loop in loops),\n",
    "    size_field=lambda p: np.clip(h + 0.3 * np.maximum(distance(p) - side, 0), h, 0.1),\n",
    ").generate(air)\n",
    "\n",
    "view = plots.Camera(elevation=35, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    [air.named(\"air, one eighth\")] + loops,\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"The two loops in the air region\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{mesh.cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Magnetostatic fields\n",
    "\n",
    "`RegionCurrent.coil` drives 1 A around each loop. Second-order Nédélec elements with the\n",
    "auxiliary-space preconditioner; three fields: primary alone, secondary alone and both."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mu0 = float(VacuumPermeability().evaluate())\n",
    "source = lambda index: RegionCurrent.coil(\n",
    "    loops[index], turns=1, current=1.0, cross_section=side**2\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Nedelec(order=2)),\n",
    "    linear_solver=GMRES(\n",
    "        preconditioner=AuxiliarySpaceMaxwell(),\n",
    "        relative_tolerance=1e-9,\n",
    "        maximum_iterations=50,\n",
    "    ),\n",
    ")\n",
    "conditions = lambda model: (\n",
    "    MagneticInsulation(boundary=faces.planes | faces.outer, physics=model),\n",
    "    MagneticSymmetry(boundary=faces.midplane, physics=model),\n",
    ")\n",
    "static = {}\n",
    "for case, indices in ((\"primary\", (0,)), (\"secondary\", (1,)), (\"both\", (0, 1))):\n",
    "    sources = tuple(source(i) for i in indices)\n",
    "    model = Magnetostatics(\n",
    "        domain=air.volume,\n",
    "        permeability=VacuumPermeability(),\n",
    "        formulation=MagneticVectorPotential(gauge=CoulombGauge()),\n",
    "        current_sources=sources,\n",
    "    )\n",
    "    result = Simulation(\n",
    "        problem=Problem(\n",
    "            name=f\"Loops, {case}\",\n",
    "            geometry=air,\n",
    "            physics=(model,),\n",
    "            boundary_conditions=conditions(model),\n",
    "        ),\n",
    "        mesh=mesh,\n",
    "        numerics=numerics,\n",
    "    ).solve_stationary()\n",
    "    static[case] = (result, model, sources)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Inductances\n",
    "\n",
    "The self-inductances from the flux linkage of each loop alone; the mutual inductance from the\n",
    "flux linked with the secondary when both carry 1 A, and from the field energy as a second way."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "L1 = inductance(\n",
    "    static[\"primary\"][0], static[\"primary\"][1], static[\"primary\"][2][0], copies=8\n",
    ")\n",
    "L2 = inductance(\n",
    "    static[\"secondary\"][0], static[\"secondary\"][1], static[\"secondary\"][2][0], copies=8\n",
    ")\n",
    "M = (\n",
    "    flux_linkage(static[\"both\"][0], static[\"both\"][1], static[\"both\"][2][1], copies=8)\n",
    "    - L2\n",
    ")\n",
    "M_energy = (\n",
    "    magnetic_energy(static[\"both\"][0], static[\"both\"][1], copies=8) - (L1 + L2) / 2\n",
    ")\n",
    "nodes, weights = np.polynomial.legendre.leggauss(6)\n",
    "r, z = np.meshgrid(side / 2 * nodes, side / 2 * nodes, indexing=\"ij\")\n",
    "w = (np.outer(weights, weights) / 4).ravel()\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",
    "exact_M = np.sum(\n",
    "    w[:, None]\n",
    "    * w[None, :]\n",
    "    * filament(\n",
    "        radii[0] + r.ravel()[:, None],\n",
    "        radii[1] + r.ravel()[None, :],\n",
    "        z.ravel()[:, None] - z.ravel()[None, :],\n",
    "    )\n",
    ")\n",
    "ring = lambda R: mu0 * R * (np.log(8 * R / (0.44705 * side)) - 2)\n",
    "print(f\"{mesh.cell_count} tetrahedra\")\n",
    "print(\"quantity                     simulation [nH]   reference [nH]   deviation\")\n",
    "for label, value, reference in (\n",
    "    (\"L1, primary\", L1, ring(radii[0])),\n",
    "    (\"L2, secondary\", L2, ring(radii[1])),\n",
    "    (\"M from the flux linkage\", M, exact_M),\n",
    "    (\"M from the field energy\", M_energy, exact_M),\n",
    "):\n",
    "    print(\n",
    "        f\"{label:28s} {1e9 * value:16.3f} {1e9 * reference:16.3f} {100 * (value / reference - 1):+10.3f} %\"\n",
    "    )\n",
    "print(f\"coupling coefficient k = M / sqrt(L1 L2) = {M / np.sqrt(L1 * L2):.4f}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Induced current and figure\n",
    "\n",
    "The current induced in a short-circuited copper secondary ($\\sigma=5.8\\cdot10^7$ S/m) per ampere\n",
    "in the primary, from the computed inductances; the flux density of the primary alone on the plane\n",
    "$y=0$; and its axial component along the $x$ axis in the plane of the loops against the circular\n",
    "filament."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "sigma = 5.8e7\n",
    "resistance = 2 * np.pi * radii[1] / (sigma * side**2)\n",
    "f = np.logspace(0.5, 3.3, 80)\n",
    "induced = 2 * np.pi * f * M / np.abs(resistance + 2j * np.pi * f * L2)\n",
    "print(\n",
    "    f\"secondary resistance {1e3 * resistance:.4f} mOhm; corner frequency R2 / (2 pi L2) = {resistance / (2 * np.pi * L2):.1f} Hz; \"\n",
    "    f\"induced current at 50 Hz {induced[np.argmin(np.abs(f - 50))]:.4f} A, at high frequency M / L2 = {M / L2:.4f} A per ampere\"\n",
    ")\n",
    "rho = np.concatenate(\n",
    "    (\n",
    "        np.linspace(0.002, 0.044, 60),\n",
    "        np.linspace(0.056, 0.094, 50),\n",
    "        np.linspace(0.106, 0.28, 80),\n",
    "    )\n",
    ")\n",
    "field = static[\"primary\"][0].field(static[\"primary\"][1].magnetic_flux_density)\n",
    "loop = lambda a, r: (\n",
    "    lambda k2: mu0\n",
    "    / (2 * np.pi)\n",
    "    / (a + r)\n",
    "    * (ellipk(k2) + (a**2 - r**2) / (a - r) ** 2 * ellipe(k2))\n",
    ")(4 * a * r / (a + r) ** 2)\n",
    "axis = np.column_stack((rho, np.full_like(rho, 1e-6), np.full_like(rho, 1e-6)))\n",
    "fig = plots.figure(1, 3, size=(21, 6))\n",
    "plots.section(\n",
    "    field,\n",
    "    plane=Plane(origin=(0, 1e-6, 0), normal=(0, 1, 0)),\n",
    "    component=lambda B, position: 1e6 * np.linalg.norm(B, axis=1),\n",
    "    limits=(0, 40),\n",
    "    contours=11,\n",
    "    subdivisions=2,\n",
    "    xlimits=(0, 0.13),\n",
    "    ylimits=(0, 0.05),\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    label=\"|B| [µT]\",\n",
    "    title=\"Flux density of 1 A in the primary\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"simulation\": (1e3 * rho[::3], 1e6 * field.evaluate(axis[::3])[:, 2])},\n",
    "    reference={\"circular filament\": (1e3 * rho, 1e6 * loop(radii[0], rho))},\n",
    "    vlines=[50.0],\n",
    "    ylimits=(-15, 40),\n",
    "    xlabel=\"x [mm]\",\n",
    "    ylabel=\"B_z [µT]\",\n",
    "    title=\"Axial field in the plane of the loops\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    x=f,\n",
    "    y={\"short-circuited secondary\": induced},\n",
    "    hlines={\"M / L2\": M / L2},\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"frequency [Hz]\",\n",
    "    ylabel=\"|I2| per ampere in the primary\",\n",
    "    title=\"Induced current from the inductances\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Move the secondary out of the plane in `coplanar_loops_mutual_inductance_geometry.py` (a coaxial\n",
    "pair) and compare $M$ with Maxwell's formula at that distance, or wind the secondary with more\n",
    "turns (`RegionCurrent.coil(..., turns=20)`) and watch $M$ grow in proportion."
   ]
  }
 ]
}
