{
 "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": [
    "# Induction currents from a circular coil in a copper ring\n",
    "\n",
    "A circular coil of 100 turns (winding section 10 mm × 10 mm, mean radius 45 mm) sits 20 mm above a\n",
    "coaxial copper ring of square section $s=6$ mm (mean radius $R=43$ mm, $\\sigma=5.8\\cdot10^7$ S/m)\n",
    "whose ends are short-circuited. A changing coil current induces a voltage in the ring, and the\n",
    "ring current flows so as to oppose the change of flux (Lenz's rule).\n",
    "\n",
    "OneSimulation solves the eddy-current equation for the azimuthal vector potential on the\n",
    "meridian half-plane with quadratic elements (`EddyCurrents` with the revolved space):\n",
    "\n",
    "$$\\nabla\\times\\big(\\mu_0^{-1}\\nabla\\times\\mathbf A\\big)+\\sigma\\,\\partial_t\\mathbf A=\\mathbf J_s .$$\n",
    "\n",
    "The coil is a stranded winding with a prescribed current; the ring is a massive conductor with\n",
    "zero terminal voltage, so its current and its distribution over the section follow from the field\n",
    "(`Coil(..., voltage=0.0, conductor=\"massive\")`). Two analyses are made: time-harmonic at 10 Hz to\n",
    "10 kHz, and transient after the coil current is switched on to 1 A.\n",
    "\n",
    "The domain is the meridian section of `induction_currents_coil_and_ring.step`, a cylinder of air of\n",
    "0.3 m radius; coil and ring are the sections of `_coil.step` and `_ring.step`, which the mesh\n",
    "follows. The script `induction_currents_coil_and_ring_geometry.py` builds them with the CAD\n",
    "objects of OneSimulation. The far boundary carries $A_\\varphi=0$.\n",
    "\n",
    "**Reference.** Coil and ring as two coupled loops (Grover, *Inductance Calculations*, 1946): the\n",
    "mutual inductance of coaxial circles of radii $r_1$, $r_2$ at the distance $d$ is\n",
    "$M=\\mu_0\\sqrt{r_1r_2}\\,[(2/m-m)K(m)-(2/m)E(m)]$ with $m^2=4r_1r_2/((r_1+r_2)^2+d^2)$; the ring has\n",
    "$L_2=\\mu_0R[\\ln(8R/g)-2]$ with the geometric mean distance $g=0.447s$ of its square section, and\n",
    "$R_2=2\\pi R/(\\sigma s^2)$. Then\n",
    "\n",
    "$$I_2=-\\frac{\\mathrm j\\omega MNI_1}{R_2+\\mathrm j\\omega L_2}\\quad\\text{(harmonic)},\\qquad\n",
    "  i_2(t)=-\\frac{MNI_1}{L_2}\\,e^{-t/\\tau},\\ \\tau=\\frac{L_2}{R_2}\\quad\\text{(switch-on)}.$$\n",
    "\n",
    "The circuit model assumes a uniform current over the ring section; once the skin depth falls\n",
    "below the section size the field computation departs from it."
   ]
  },
  {
   "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, SparseDirect\n",
    "from onesim.numerics.time import BDF\n",
    "from onesim.physics.magnetostatics import (\n",
    "    Coil,\n",
    "    EddyCurrents,\n",
    "    MagneticInsulation,\n",
    "    coil_current,\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",
    "`section` cuts the parts in the plane $y=0$; the section coordinates are $(r, z)$. The mesh follows\n",
    "coil and ring, is fine in the ring and grows towards the far boundary."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "meridian = lambda name: load(f\"induction_currents_coil_and_ring{name}.step\").section(\n",
    "    (0, 1, 0)\n",
    ")\n",
    "domain, winding, ring = meridian(\"\"), meridian(\"_coil\"), meridian(\"_ring\")\n",
    "axis = domain.select(\n",
    "    edges=lambda edge: all(abs(point[0]) < 1e-12 for point in edge.points)\n",
    ")\n",
    "mesh = TriangularMesher(\n",
    "    target_size=0.03,\n",
    "    grading=0.25,\n",
    "    embedded_regions=(winding.named(\"coil\"), ring.named(\"ring\")),\n",
    "    region_sizes=((\"coil\", 0.002), (\"ring\", 0.0003)),\n",
    ").generate(domain)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    [\n",
    "        load(f\"induction_currents_coil_and_ring{name}.step\").named(label)\n",
    "        for name, label in ((\"_coil\", \"coil\"), (\"_ring\", \"copper ring\"))\n",
    "    ],\n",
    "    camera=plots.Camera(elevation=25, azimuth=-60),\n",
    "    title=\"Coil and ring (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": [
    "## Time-harmonic analysis\n",
    "\n",
    "Coil current 1 A (peak) with 100 turns; one solve per frequency."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "sigma, turns, current = 5.8e7, 100, 1.0\n",
    "mu0 = float(VacuumPermeability().evaluate())\n",
    "conductivity = regionwise({\"ring\": sigma}, default=0.0, unit=\"S/m\")\n",
    "revolved = FiniteElement(\n",
    "    element=Lagrange(order=2), quadrature_order=4, provider=RevolvedH1SpaceFactory()\n",
    ")\n",
    "frequencies = (10.0, 100.0, 1000.0, 10000.0)\n",
    "rings = {f: Coil(ring, voltage=0.0, conductor=\"massive\") for f in frequencies}\n",
    "harmonic = {\n",
    "    f: EddyCurrents(\n",
    "        domain=domain.domain(),\n",
    "        permeability=VacuumPermeability(),\n",
    "        conductivity=conductivity,\n",
    "        frequency=f,\n",
    "        coils=(Coil(winding, turns=turns, current=current), rings[f]),\n",
    "    )\n",
    "    for f in frequencies\n",
    "}\n",
    "ring_current = {\n",
    "    f: coil_current(\n",
    "        Simulation(\n",
    "            problem=Problem(\n",
    "                name=\"Coil and ring\",\n",
    "                geometry=domain,\n",
    "                physics=(model,),\n",
    "                boundary_conditions=(\n",
    "                    MagneticInsulation(\n",
    "                        boundary=domain.boundaries.all - axis, physics=model\n",
    "                    ),\n",
    "                ),\n",
    "            ),\n",
    "            mesh=mesh,\n",
    "            numerics=Numerics(spatial=revolved, linear_solver=ComplexSparseDirect()),\n",
    "        ).solve_stationary(),\n",
    "        model,\n",
    "        rings[f],\n",
    "    )\n",
    "    for f, model in harmonic.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Transient analysis\n",
    "\n",
    "The coil current is switched on to 1 A at $t=0$; second-order BDF steps of $\\tau/20$ up to $4\\tau$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "r1, r2, s, d = 0.045, 0.043, 0.006, 0.020\n",
    "m2 = 4 * r1 * r2 / ((r1 + r2) ** 2 + d**2)\n",
    "M = (\n",
    "    mu0\n",
    "    * np.sqrt(r1 * r2)\n",
    "    * ((2 / np.sqrt(m2) - np.sqrt(m2)) * ellipk(m2) - 2 / np.sqrt(m2) * ellipe(m2))\n",
    ")\n",
    "L2 = mu0 * r2 * (np.log(8 * r2 / (0.447 * s)) - 2)\n",
    "R2 = 2 * np.pi * r2 / (sigma * s**2)\n",
    "tau = L2 / R2\n",
    "switched_ring = Coil(ring, voltage=0.0, conductor=\"massive\")\n",
    "transient = EddyCurrents(\n",
    "    domain=domain.domain(),\n",
    "    permeability=VacuumPermeability(),\n",
    "    conductivity=conductivity,\n",
    "    coils=(Coil(winding, turns=turns, current=current), switched_ring),\n",
    ")\n",
    "history = Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"Coil switch-on\",\n",
    "        geometry=domain,\n",
    "        physics=(transient,),\n",
    "        boundary_conditions=(\n",
    "            MagneticInsulation(\n",
    "                boundary=domain.boundaries.all - axis, physics=transient\n",
    "            ),\n",
    "        ),\n",
    "    ),\n",
    "    mesh=mesh,\n",
    "    numerics=Numerics(\n",
    "        spatial=revolved, linear_solver=SparseDirect(), time_integrator=BDF(order=2)\n",
    "    ),\n",
    ").run(start_time=0.0, end_time=4 * tau, time_step=tau / 20)\n",
    "times = np.array(history.times)\n",
    "induced = np.array(\n",
    "    [coil_current(history, transient, switched_ring, time=t) for t in times]\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "circuit = (\n",
    "    lambda f: -1j * 2 * np.pi * f * M * turns * current / (R2 + 1j * 2 * np.pi * f * L2)\n",
    ")\n",
    "print(\n",
    "    f\"circuit model: M = {1e9 * M:.2f} nH, L2 = {1e9 * L2:.2f} nH, R2 = {1e6 * R2:.2f} µOhm, tau = {1e3 * tau:.3f} ms\"\n",
    ")\n",
    "print(\n",
    "    \"f [Hz]   skin depth [mm]   |I2| simulation [A]   circuit [A]   deviation   phase simulation / circuit [deg]\"\n",
    ")\n",
    "for f in frequencies:\n",
    "    print(\n",
    "        f\"{f:7.0f} {1e3 * np.sqrt(2 / (2 * np.pi * f * mu0 * sigma)):15.2f} {abs(ring_current[f]):20.4f} {abs(circuit(f)):13.4f} \"\n",
    "        f\"{100 * (abs(ring_current[f]) / abs(circuit(f)) - 1):+10.2f} % {np.degrees(np.angle(ring_current[f])):12.1f} / {np.degrees(np.angle(circuit(f))):.1f}\"\n",
    "    )\n",
    "late = times > 0.5 * tau\n",
    "fitted = -np.polyfit(times[late], np.log(np.abs(induced[late])), 1)[0] ** -1\n",
    "print(\n",
    "    f\"transient: ring current after the first step {induced[1]:.4f} A (circuit {-M * turns * current / L2:.4f} A); \"\n",
    "    f\"decay time {1e3 * fitted:.3f} ms, circuit {1e3 * tau:.3f} ms ({100 * (fitted / tau - 1):+.1f} %)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The induced ring current over frequency against the circuit model, and its decay after the\n",
    "switch-on."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = np.logspace(0.5, 4.5, 200)\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.line(\n",
    "    points={\n",
    "        \"simulation\": (\n",
    "            np.array(frequencies),\n",
    "            np.array([abs(ring_current[f]) for f in frequencies]),\n",
    "        )\n",
    "    },\n",
    "    reference={\"coupled loops\": (fine, np.abs(circuit(fine)))},\n",
    "    scale=\"loglog\",\n",
    "    xlabel=\"frequency [Hz]\",\n",
    "    ylabel=\"|ring current| [A]\",\n",
    "    title=\"Induced ring current (coil 1 A, 100 turns)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"simulation\": (1e3 * times[1:], -induced[1:])},\n",
    "    reference={\n",
    "        \"coupled loops\": (1e3 * times, M * turns * current / L2 * np.exp(-times / tau))\n",
    "    },\n",
    "    xlabel=\"time [ms]\",\n",
    "    ylabel=\"-ring current [A]\",\n",
    "    title=\"After switching on the coil\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Feed the coil by a voltage instead of a current to see the reaction of the ring on the coil\n",
    "current, replace the ring by a solid disc, or make it of steel to add the magnetic pull of the\n",
    "ring towards the coil."
   ]
  }
 ]
}
