{
 "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 rings\n",
    "\n",
    "A primary ring of radius $R_1=100$ mm and a secondary ring of $R_2=10$ mm, both of copper wire with a\n",
    "radius of $r_0=1$ mm, lie concentrically in the plane $z=0$. A current $I_1$ in the primary links a\n",
    "flux with the secondary; its loop voltage $V_2=j\\omega M I_1$ gives the mutual inductance $M$, the\n",
    "primary's own voltage its self-inductance. Everything is rotationally symmetric, so the meridian\n",
    "half-plane is solved for the azimuthal vector potential $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",
    "Three cases are solved at $f=1$ kHz:\n",
    "\n",
    "| case | primary | secondary |\n",
    "|---|---|---|\n",
    "| inductances | 1 A, uniform current density (stranded, no eddy currents) | open, uniform current density |\n",
    "| open circuit | 1 A, solid copper | solid copper, no net current |\n",
    "| short circuit | 1 A, solid copper | solid copper, short-circuited ring |\n",
    "\n",
    "At 1 kHz the skin depth in copper is 2.1 mm, twice the wire radius: the current density in the\n",
    "wires is no longer quite uniform.\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 air and the rings come from the CAD files `coplanar_rings_inductance_axisymmetric*.step`; the\n",
    "script `coplanar_rings_inductance_axisymmetric_geometry.py` builds them with the CAD objects of\n",
    "OneSimulation. Each part is cut to $x>0$, and its section with the plane $y=0$ is the meridian.\n",
    "\n",
    "**Reference.** Maxwell's formula for two coaxial circular filaments (Grover, *Inductance\n",
    "Calculations*, 1946), $M=\\mu_0\\sqrt{R_1R_2}\\,[(2/k-k)K(k)-2E(k)/k]$ with $k^2=4R_1R_2/(R_1+R_2)^2$,\n",
    "which tends to $\\pi\\mu_0R_2^2/(2R_1)$ for $R_2\\ll R_1$; the self-inductance of a ring of round wire\n",
    "with uniform current, $L=\\mu_0R\\,[\\ln(8R/r_0)-7/4]$. A short-circuited secondary carries\n",
    "$I_2=-Z_{21}I_1/Z_{22}$ with the transfer impedance $Z_{21}=V_2/I_1$ of the open circuit and its own\n",
    "impedance $Z_{22}$ (circuit theory of two coupled loops)."
   ]
  },
  {
   "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 wires are embedded as regions with\n",
    "triangles of 0.25 mm; the air grows to 10 cm at the outer boundary."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "name = \"coplanar_rings_inductance_axisymmetric\"\n",
    "meridian = lambda part: load(f\"{name}{part}.step\").section((0, 1, 0))\n",
    "air, primary, secondary = (\n",
    "    meridian(\"\"),\n",
    "    meridian(\"_primary\").named(\"primary\"),\n",
    "    meridian(\"_secondary\").named(\"secondary\"),\n",
    ")\n",
    "axis = air.select(\n",
    "    edges=lambda edge: all(abs(point[0]) < 1e-12 for point in edge.points)\n",
    ")\n",
    "R1, R2, wire = 0.1, 0.01, 0.001\n",
    "distance = lambda p: np.minimum(\n",
    "    np.hypot(p[:, 0] - R1, p[:, 1]), np.hypot(p[:, 0] - R2, p[:, 1])\n",
    ")\n",
    "mesh = TriangularMesher(\n",
    "    target_size=0.1,\n",
    "    embedded_regions=(primary, secondary),\n",
    "    region_sizes={\"primary\": 0.00025, \"secondary\": 0.00025},\n",
    "    size_field=lambda p: np.clip(\n",
    "        0.0004 + 0.5 * np.maximum(distance(p) - wire, 0.0), 0.0004, 0.1\n",
    "    ),\n",
    ").generate(air)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    [\n",
    "        load(f\"{name}_{part}.step\").named(f\"{part} ring\")\n",
    "        for part in (\"primary\", \"secondary\")\n",
    "    ],\n",
    "    camera=plots.Camera(elevation=50, azimuth=-60),\n",
    "    title=\"The two rings (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": [
    "## Three eddy-current fields\n",
    "\n",
    "`EddyCurrents` at 1 kHz with second-order elements on the revolved space. `Coil` feeds each ring:\n",
    "stranded coils have a uniform current density, massive ones carry copper whose current\n",
    "distribution follows from the field; a coil fed with the current 0 is an open ring, one fed with the\n",
    "voltage 0 a short-circuited ring."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "frequency, sigma, mu0 = 1000.0, 5.8e7, float(VacuumPermeability().evaluate())\n",
    "omega = 2 * np.pi * frequency\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",
    "    \"inductances\": (Coil(primary, current=1.0), Coil(secondary, current=0.0), 0.0),\n",
    "    \"inductance of the secondary\": (\n",
    "        Coil(primary, current=0.0),\n",
    "        Coil(secondary, current=1.0),\n",
    "        0.0,\n",
    "    ),\n",
    "    \"open circuit\": (\n",
    "        Coil(primary, current=1.0, conductor=\"massive\"),\n",
    "        Coil(secondary, current=0.0, conductor=\"massive\"),\n",
    "        sigma,\n",
    "    ),\n",
    "    \"secondary alone\": (\n",
    "        Coil(primary, current=0.0, conductor=\"massive\"),\n",
    "        Coil(secondary, current=1.0, conductor=\"massive\"),\n",
    "        sigma,\n",
    "    ),\n",
    "    \"short circuit\": (\n",
    "        Coil(primary, current=1.0, conductor=\"massive\"),\n",
    "        Coil(secondary, voltage=0.0, conductor=\"massive\"),\n",
    "        sigma,\n",
    "    ),\n",
    "}\n",
    "solved = {}\n",
    "for case, (first, second, copper) in cases.items():\n",
    "    model = EddyCurrents(\n",
    "        domain=air.domain(),\n",
    "        permeability=VacuumPermeability(),\n",
    "        frequency=frequency,\n",
    "        coils=(first, second),\n",
    "        conductivity=regionwise(\n",
    "            {\"primary\": copper, \"secondary\": copper}, default=0.0, unit=\"S/m\"\n",
    "        ),\n",
    "    )\n",
    "    result = Simulation(\n",
    "        problem=Problem(\n",
    "            name=f\"Two rings, {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, first, second)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Inductances\n",
    "\n",
    "$L_1=\\operatorname{Im}Z_{11}/\\omega$, $M=V_2/(j\\omega I_1)$ and $L_2$ with uniform current density,\n",
    "against the formulas."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "result, model, first, second = solved[\"inductances\"]\n",
    "L1 = coil_impedance(result, model, first).imag / omega\n",
    "M = (coil_voltage(result, model, second) / (1j * omega)).real\n",
    "result, model, first, second = solved[\"inductance of the secondary\"]\n",
    "L2 = coil_impedance(result, model, second).imag / omega\n",
    "k = np.sqrt(4 * R1 * R2 / (R1 + R2) ** 2)\n",
    "maxwell = mu0 * np.sqrt(R1 * R2) * ((2 / k - k) * ellipk(k**2) - 2 / k * ellipe(k**2))\n",
    "ring = lambda R: mu0 * R * (np.log(8 * R / wire) - 1.75)\n",
    "print(\n",
    "    f\"{mesh.cell_count} triangles; limit pi mu0 R2^2 / (2 R1) = {1e9 * np.pi * mu0 * R2**2 / (2 * R1):.4f} nH\"\n",
    ")\n",
    "print(\"quantity          simulation [nH]   reference [nH]   deviation\")\n",
    "for label, value, reference in (\n",
    "    (\"L1, primary\", L1, ring(R1)),\n",
    "    (\"L2, secondary\", L2, ring(R2)),\n",
    "    (\"M, Maxwell\", M, maxwell),\n",
    "):\n",
    "    print(\n",
    "        f\"{label:16s} {1e9 * value:16.4f} {1e9 * reference:16.4f} {100 * (value / reference - 1):+10.3f} %\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Solid copper at 1 kHz\n",
    "\n",
    "The transfer impedance of the open circuit gives the mutual inductance with the eddy currents in\n",
    "the wires; the short-circuited secondary carries the current that the two impedances predict."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "result, model, first, second = solved[\"open circuit\"]\n",
    "Z21 = coil_voltage(result, model, second) / coil_current(result, model, first)\n",
    "result, model, first, second = solved[\"secondary alone\"]\n",
    "Z22 = coil_impedance(result, model, second)\n",
    "result, model, first, second = solved[\"short circuit\"]\n",
    "I2 = coil_current(result, model, second)\n",
    "print(\n",
    "    f\"open circuit: M = Z21 / (j w) = {1e9 * (Z21 / (1j * omega)).real:.4f} {1e9 * (Z21 / (1j * omega)).imag:+.4f}j nH\"\n",
    ")\n",
    "print(\n",
    "    f\"secondary: R2 = {1e3 * Z22.real:.4f} mOhm (direct current {1e3 * 2 * R2 / (sigma * wire**2):.4f} mOhm), \"\n",
    "    f\"L2 = {1e9 * Z22.imag / omega:.4f} nH\"\n",
    ")\n",
    "print(\n",
    "    f\"short circuit: I2 = {1e3 * I2.real:.4f} {1e3 * I2.imag:+.4f}j mA; circuit -Z21 I1 / Z22 = \"\n",
    "    f\"{1e3 * (-Z21 / Z22).real:.4f} {1e3 * (-Z21 / Z22).imag:+.4f}j mA; deviation {100 * abs(I2 + Z21 / Z22) / abs(Z21 / Z22):.3f} %\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The static inductances follow the formulas, the mutual inductance with copper differs from the\n",
    "static one only in a small imaginary part, the loss of the eddy currents, and the induced current\n",
    "is that of the two coupled loops.\n",
    "\n",
    "## Figure\n",
    "\n",
    "The current density in the cross-section of the short-circuited secondary, and the axial flux\n",
    "density of the primary along the radius in the plane of the rings."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "result, model, first, second = solved[\"short circuit\"]\n",
    "rho = np.concatenate((np.linspace(0.0005, 0.0985, 120), np.linspace(0.1015, 0.2, 60)))\n",
    "plane = np.column_stack((rho, np.zeros_like(rho)))\n",
    "field = solved[\"inductances\"][0].field(solved[\"inductances\"][1].magnetic_flux_density)\n",
    "loop = lambda r: (\n",
    "    lambda m: mu0\n",
    "    / (2 * np.pi)\n",
    "    / (R1 + r)\n",
    "    * (ellipk(m) + (R1**2 - r**2) / (R1 - r) ** 2 * ellipe(m))\n",
    ")(4 * R1 * r / (R1 + r) ** 2)\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.surface(\n",
    "    result.field(model.current_density),\n",
    "    component=lambda J, position: 1e-3 * np.abs(J[:, 1]),\n",
    "    limits=(8, 12),\n",
    "    contours=9,\n",
    "    subdivisions=3,\n",
    "    xlimits=(R2 - 1.2 * wire, R2 + 1.2 * wire),\n",
    "    ylimits=(-1.2 * wire, 1.2 * wire),\n",
    "    xlabel=\"r [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    label=\"|J| [kA/m²]\",\n",
    "    title=\"Induced current density in the short-circuited secondary\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"simulation\": (1e3 * rho[::4], 1e6 * np.abs(field.evaluate(plane[::4])[:, 2]))\n",
    "    },\n",
    "    reference={\"circular filament\": (1e3 * rho, 1e6 * np.abs(loop(rho)))},\n",
    "    scale=\"logy\",\n",
    "    vlines=[1e3 * R2, 1e3 * R1],\n",
    "    xlabel=\"r [mm]\",\n",
    "    ylabel=\"|B_z| per ampere [µT]\",\n",
    "    title=\"Axial flux density of the primary in the plane z = 0\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the frequency until the skin depth is a fraction of the wire radius and watch the\n",
    "resistance of the secondary grow, or move the secondary along the axis in\n",
    "`coplanar_rings_inductance_axisymmetric_geometry.py` and compare $M$ with Maxwell's formula at that\n",
    "distance."
   ]
  }
 ]
}
