{
 "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": [
    "# Eddy currents in a cylinder inside a long coil\n",
    "\n",
    "A long coil (inner radius 15 mm, outer radius 17 mm, 1000 turns per metre) carries an\n",
    "alternating current of 2 A amplitude. Inside sits a cylinder of radius $a=10$ mm with the\n",
    "conductivity $\\sigma=3.5\\cdot10^7$ S/m (aluminium). The time-harmonic field induces azimuthal\n",
    "eddy currents that oppose the applied field, so the field decays towards the axis within the\n",
    "skin depth $\\delta=\\sqrt{2/(\\omega\\mu_0\\sigma)}$, and the currents heat the cylinder.\n",
    "\n",
    "OneSimulation solves the time-harmonic eddy-current equation for the azimuthal vector potential\n",
    "\n",
    "$$\\nabla\\times\\big(\\mu_0^{-1}\\nabla\\times\\mathbf A\\big)+\\mathrm j\\omega\\sigma\\mathbf A=\\mathbf J_s$$\n",
    "\n",
    "on the meridian half-plane with quadratic elements (`EddyCurrents` with the revolved space). The\n",
    "coil is long, so a 10 mm slice with field-normal conditions on its top and bottom stands for it.\n",
    "The domain is the meridian section of `eddy_currents_cylinder_in_coil.step`; the cylinder and the\n",
    "winding are the sections of `_cylinder.step` and `_winding.step`, which the mesh follows. The\n",
    "script `eddy_currents_cylinder_in_coil_geometry.py` builds them with the CAD objects of\n",
    "OneSimulation.\n",
    "\n",
    "| edge | condition |\n",
    "|---|---|\n",
    "| axis $r=0$ | axis of the revolved space |\n",
    "| top, bottom and $r=20$ mm | field normal, $\\mathbf n\\times\\mathbf H=0$ (`MagneticSymmetry`) |\n",
    "\n",
    "**Reference.** Inside an infinitely long cylinder in the uniform applied field $B_0=\\mu_0nI$ (which\n",
    "falls linearly to zero across the winding) the field and the loss per metre are (Jackson, *Classical Electrodynamics*, 3rd ed., Sec. 5.18;\n",
    "Lammeraner and Štafl, *Eddy Currents*, 1966)\n",
    "\n",
    "$$B_z(r)=B_0\\frac{J_0(kr)}{J_0(ka)},\\qquad\n",
    "  \\frac{P}{\\ell}=\\int_0^a\\frac{|nI\\,k\\,J_1(kr)/J_0(ka)|^2}{2\\sigma}\\,2\\pi r\\,\\mathrm dr,\\qquad k=\\sqrt{-\\mathrm j\\omega\\mu_0\\sigma}.$$"
   ]
  },
  {
   "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",
    "    MagneticSymmetry,\n",
    "    coil_impedance,\n",
    "    joule_losses,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.integrate import quad\n",
    "from scipy.special import jv\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",
    "the surfaces of the cylinder and the winding and is fine enough for the smallest skin depth."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "meridian = lambda name: load(f\"eddy_currents_cylinder_in_coil{name}.step\").section(\n",
    "    (0, 1, 0)\n",
    ")\n",
    "domain, cylinder, winding = meridian(\"\"), meridian(\"_cylinder\"), meridian(\"_winding\")\n",
    "axis = domain.select(\n",
    "    edges=lambda edge: all(abs(point[0]) < 1e-12 for point in edge.points)\n",
    ")\n",
    "height, radius = domain.size[1], cylinder.size[0]\n",
    "inner, outer = winding.bounding_box[0][0], winding.bounding_box[1][0]\n",
    "mesh = TriangularMesher(\n",
    "    target_size=0.0004,\n",
    "    embedded_regions=(cylinder.named(\"cylinder\"), winding.named(\"winding\")),\n",
    ").generate(domain)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    [\n",
    "        load(f\"eddy_currents_cylinder_in_coil{name}.step\").named(label)\n",
    "        for name, label in ((\"_cylinder\", \"cylinder\"), (\"_winding\", \"winding\"))\n",
    "    ],\n",
    "    camera=plots.Camera(elevation=30, azimuth=-60),\n",
    "    title=\"Slice of the cylinder and the 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",
    "The winding is a stranded coil of $n\\,h=10$ turns carrying 2 A; three frequencies put the skin\n",
    "depth above, near and below the radius. A second set of runs feeds the same winding as one massive\n",
    "copper conductor ($5.8\\cdot10^7$ S/m) carrying the same ampere-turns, 20 A."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "sigma, per_metre, current = 3.5e7, 1000, 2.0\n",
    "turns = int(round(per_metre * height))\n",
    "mu0 = float(VacuumPermeability().evaluate())\n",
    "frequencies = (50.0, 500.0, 5000.0)\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",
    "    (f, kind): (\n",
    "        (\n",
    "            Coil(winding, turns=turns, current=current)\n",
    "            if kind == \"stranded\"\n",
    "            else Coil(winding, current=turns * current, conductor=\"massive\")\n",
    "        ),\n",
    "        regionwise(\n",
    "            (\n",
    "                {\"cylinder\": sigma}\n",
    "                if kind == \"stranded\"\n",
    "                else {\"cylinder\": sigma, \"winding\": 5.8e7}\n",
    "            ),\n",
    "            default=0.0,\n",
    "            unit=\"S/m\",\n",
    "        ),\n",
    "    )\n",
    "    for f in frequencies\n",
    "    for kind in (\"stranded\", \"massive\")\n",
    "}\n",
    "models = {\n",
    "    key: EddyCurrents(\n",
    "        domain=domain.domain(),\n",
    "        permeability=VacuumPermeability(),\n",
    "        conductivity=conductivity,\n",
    "        frequency=key[0],\n",
    "        coils=(coil,),\n",
    "    )\n",
    "    for key, (coil, conductivity) in cases.items()\n",
    "}\n",
    "results = {\n",
    "    key: Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Cylinder in a coil\",\n",
    "            geometry=domain,\n",
    "            physics=(model,),\n",
    "            boundary_conditions=(\n",
    "                MagneticSymmetry(boundary=domain.boundaries.all - axis, physics=model),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=mesh,\n",
    "        numerics=numerics,\n",
    "    ).solve_stationary()\n",
    "    for key, model in models.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Field on the mid-height line and loss of the cylinder against the Bessel solution; for the\n",
    "massive coil the loss in the winding and the power balance of its terminals."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "r = np.linspace(0.0005, 0.0195, 39)\n",
    "line = np.column_stack((r, np.full_like(r, height / 2)))\n",
    "k_of = lambda f: np.sqrt(-1j * 2 * np.pi * f * mu0 * sigma)\n",
    "bessel_field = (\n",
    "    lambda f, r: mu0\n",
    "    * per_metre\n",
    "    * current\n",
    "    * np.where(\n",
    "        r < radius,\n",
    "        jv(0, k_of(f) * np.minimum(r, radius)) / jv(0, k_of(f) * radius),\n",
    "        np.clip((outer - r) / (outer - inner), 0.0, 1.0),\n",
    "    )\n",
    ")\n",
    "print(\n",
    "    \"f [Hz]   skin depth [mm]   largest |B| deviation   loss [W/m]   Bessel [W/m]   deviation\"\n",
    ")\n",
    "for f in frequencies:\n",
    "    key = (f, \"stranded\")\n",
    "    computed = np.abs(\n",
    "        results[key].field(models[key].magnetic_flux_density).evaluate(line)[:, 2]\n",
    "    )\n",
    "    exact_loss = quad(\n",
    "        lambda s: abs(\n",
    "            per_metre * current * k_of(f) * jv(1, k_of(f) * s) / jv(0, k_of(f) * radius)\n",
    "        )\n",
    "        ** 2\n",
    "        / (2 * sigma)\n",
    "        * 2\n",
    "        * np.pi\n",
    "        * s,\n",
    "        0,\n",
    "        radius,\n",
    "        limit=200,\n",
    "    )[0]\n",
    "    loss = joule_losses(results[key], models[key], cylinder) / height\n",
    "    print(\n",
    "        f\"{f:6.0f} {1e3 * np.sqrt(2 / (2 * np.pi * f * mu0 * sigma)):17.2f} \"\n",
    "        f\"{100 * np.max(np.abs(computed - np.abs(bessel_field(f, r)))) / (mu0 * per_metre * current):18.3f} % of B0 \"\n",
    "        f\"{loss:12.5f} {exact_loss:14.5f} {100 * (loss / exact_loss - 1):+10.3f} %\"\n",
    "    )\n",
    "print(\n",
    "    \"f [Hz]   massive coil: loss in the winding / in the cylinder [W/m]   1/2 Re(V I*) / total loss\"\n",
    ")\n",
    "for f in frequencies:\n",
    "    key = (f, \"massive\")\n",
    "    coil = cases[key][0]\n",
    "    total = joule_losses(results[key], models[key])\n",
    "    terminal = (\n",
    "        0.5\n",
    "        * (\n",
    "            coil_impedance(results[key], models[key], coil) * abs(turns * current) ** 2\n",
    "        ).real\n",
    "    )\n",
    "    print(\n",
    "        f\"{f:6.0f} {joule_losses(results[key], models[key], winding) / height:24.4f} / {joule_losses(results[key], models[key], cylinder) / height:8.4f}\"\n",
    "        f\" {terminal / total:30.6f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The amplitude of the eddy-current density in the meridian plane at 5 kHz, and the field on the\n",
    "mid-height line for the three frequencies against the Bessel solution."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = np.linspace(0.0, 0.02, 400)\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.surface(\n",
    "    results[5000.0, \"stranded\"].field(models[5000.0, \"stranded\"].current_density),\n",
    "    component=lambda J, position: 1e-6 * np.sqrt(np.sum(np.abs(J) ** 2, axis=1)),\n",
    "    limits=(0, 2.0),\n",
    "    contours=11,\n",
    "    subdivisions=2,\n",
    "    label=\"|J| [A/mm²]\",\n",
    "    title=\"Eddy-current density at 5 kHz\",\n",
    "    xlabel=\"r [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"{f:.0f} Hz\": (\n",
    "            1e3 * r[::2],\n",
    "            1e3\n",
    "            * np.abs(\n",
    "                results[f, \"stranded\"]\n",
    "                .field(models[f, \"stranded\"].magnetic_flux_density)\n",
    "                .evaluate(line[::2])[:, 2]\n",
    "            ),\n",
    "        )\n",
    "        for f in frequencies\n",
    "    },\n",
    "    reference={\n",
    "        f\"Bessel, {f:.0f} Hz\": (1e3 * fine, 1e3 * np.abs(bessel_field(f, fine)))\n",
    "        for f in frequencies\n",
    "    },\n",
    "    vlines=[1e3 * radius],\n",
    "    xlabel=\"r [mm]\",\n",
    "    ylabel=\"|B_z| [mT]\",\n",
    "    title=\"Field amplitude across the cylinder\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the cylinder of steel (a relative permeability in `permeability`) and watch the field\n",
    "concentrate in a much thinner skin, or couple the loss density to heat conduction as in the\n",
    "example *Inductive heating of a copper cylinder*."
   ]
  }
 ]
}
