{
 "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": [
    "# Force between two coaxial coils: a verification series\n",
    "\n",
    "Two coaxial coils of mean radius $R=50$ mm with a square winding cross-section of 10 x 10 mm and\n",
    "100 turns each carry 1 A in the same direction and attract each other. The force on a winding is\n",
    "the Lorentz force\n",
    "\n",
    "$$\\mathbf F=\\int_V\\mathbf J\\times\\mathbf B\\,dV,\\qquad F_z=-J\\int_V B_r\\,dV$$\n",
    "\n",
    "for the uniform azimuthal current density $J=NI/A$. The field solves\n",
    "$\\nabla\\times(\\mu_0^{-1}\\nabla\\times\\mathbf A)=\\mathbf J$ with second-order Nédélec elements and a\n",
    "Coulomb gauge; one quarter is computed, and the windings are cut by its two symmetry planes. The\n",
    "coil distance is varied from $R/2$ to $2R$, and the middle distance is also solved on a finer mesh.\n",
    "\n",
    "The air, a quarter of a ball of 0.4 m radius, comes from the CAD file\n",
    "`coil_force_verification.step` (face groups `planes` and `outer`), the quarter of the lower winding\n",
    "from `coil_force_verification_lower.step` and the upper winding for the three distances from\n",
    "`..._upper_25mm.step`, `..._upper_50mm.step` and `..._upper_100mm.step`. The script\n",
    "`coil_force_verification_geometry.py` builds them with the CAD objects of OneSimulation.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `planes` (through the axis), `outer` | $\\mathbf n\\times\\mathbf A=0$ |\n",
    "\n",
    "**Reference.** Two coaxial loops of radii $a$, $b$ at the axial distance $z$ attract with\n",
    "$F_z=I_1I_2\\,\\partial M/\\partial z$, with Maxwell's mutual inductance\n",
    "$M=\\mu_0\\sqrt{ab}\\,[(2/k-k)K(k)-(2/k)E(k)]$, $k^2=4ab/((a+b)^2+z^2)$ (Smythe, *Static and Dynamic\n",
    "Electricity*, 3rd ed., Sec. 7.13). Integrating it over both rectangular cross-sections with\n",
    "Gauss-Legendre points gives the exact force between the windings."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\n",
    "from onesim.cad.d3 import AnnularCylinder\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",
    "    MagneticVectorPotential,\n",
    "    Magnetostatics,\n",
    "    SolenoidCurrent,\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",
    "Each winding is declared whole, as `SolenoidCurrent` with its own annular support; with\n",
    "`clip_regions=True` the mesher keeps the quarter of it that lies inside the air region as an\n",
    "embedded region. The cells are 4 mm (2.8 mm on the finer mesh) in and around the windings and grow\n",
    "towards the outer boundary."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "air = load(\"coil_force_verification.step\")\n",
    "faces = air.boundaries\n",
    "radius, width, turns, current = 0.05, 0.01, 100, 1.0\n",
    "cases = [(0.025, 0.004), (0.05, 0.004), (0.05, 0.0028), (0.10, 0.004)]\n",
    "lower = load(\"coil_force_verification_lower.step\")\n",
    "windings = [\n",
    "    (lower, load(f\"coil_force_verification_upper_{round(1e3 * d)}mm.step\"))\n",
    "    for d, _ in cases\n",
    "]\n",
    "coils = [\n",
    "    tuple(\n",
    "        SolenoidCurrent(\n",
    "            inner_radius=radius - width / 2,\n",
    "            outer_radius=radius + width / 2,\n",
    "            length=width,\n",
    "            turns=turns,\n",
    "            current=current,\n",
    "            center=(0.0, 0.0, z),\n",
    "            support_factory=AnnularCylinder,\n",
    "        )\n",
    "        for z in (0.0, d)\n",
    "    )\n",
    "    for d, _ in cases\n",
    "]\n",
    "meshes = [\n",
    "    TetrahedralMesher(\n",
    "        target_size=0.06,\n",
    "        embedded_regions=tuple(coil.support for coil in pair),\n",
    "        clip_regions=True,\n",
    "        refinements=tuple(\n",
    "            LocalRefinement(region=coil.support, target_size=h) for coil in pair\n",
    "        ),\n",
    "        size_field=lambda points, d=d, h=h: np.clip(\n",
    "            h\n",
    "            + 0.6\n",
    "            * np.maximum(\n",
    "                np.hypot(\n",
    "                    np.hypot(points[:, 0], points[:, 1]) - radius, points[:, 2] - d / 2\n",
    "                )\n",
    "                - d / 2\n",
    "                - width,\n",
    "                0,\n",
    "            ),\n",
    "            h,\n",
    "            0.06,\n",
    "        ),\n",
    "    ).generate(air)\n",
    "    for (d, h), pair in zip(cases, coils)\n",
    "]\n",
    "\n",
    "view = plots.Camera(elevation=20, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    [coil.named(name) for coil, name in zip(windings[1], (\"lower coil\", \"upper coil\"))],\n",
    "    camera=view,\n",
    "    title=\"The two windings, 50 mm apart\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{meshes[1].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Each winding carries $NI=100$ ampere-turns spread uniformly over its cross-section\n",
    "(`SolenoidCurrent`, with the same dimensions as the STEP windings). The linear systems are solved\n",
    "with GMRES and the auxiliary-space preconditioner for edge elements (`AuxiliarySpaceMaxwell`: a\n",
    "discrete gradient and a nodal interpolation with algebraic multigrid on the nodal spaces)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Nedelec(order=2)),\n",
    "    linear_solver=GMRES(preconditioner=AuxiliarySpaceMaxwell()),\n",
    ")\n",
    "models = [\n",
    "    Magnetostatics(\n",
    "        domain=air.volume,\n",
    "        permeability=VacuumPermeability(),\n",
    "        formulation=MagneticVectorPotential(gauge=CoulombGauge()),\n",
    "        current_sources=pair,\n",
    "    )\n",
    "    for pair in coils\n",
    "]\n",
    "fields = [\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Two coils\",\n",
    "            geometry=air,\n",
    "            physics=(model,),\n",
    "            boundary_conditions=(\n",
    "                MagneticInsulation(boundary=faces.planes | faces.outer, physics=model),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=mesh,\n",
    "        numerics=numerics,\n",
    "    )\n",
    "    .solve_stationary()\n",
    "    .field(model.magnetic_flux_density)\n",
    "    for model, mesh in zip(models, meshes)\n",
    "]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The force on each winding, $F_z=-J\\int B_r\\,dV$, integrated over the cells of the winding (its\n",
    "embedded region, `region=coil.support`), four times the quarter, against the exact force."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mu0 = float(VacuumPermeability().evaluate())\n",
    "density = turns * current / width**2\n",
    "radial = lambda B, p: (B[:, 0] * p[:, 0] + B[:, 1] * p[:, 1]) / np.hypot(\n",
    "    p[:, 0], p[:, 1]\n",
    ")\n",
    "forces = [\n",
    "    [\n",
    "        -4 * density * field.integrate(region=coil.support, component=radial).value\n",
    "        for coil in pair\n",
    "    ]\n",
    "    for field, pair in zip(fields, coils)\n",
    "]\n",
    "nodes, weights = np.polynomial.legendre.leggauss(8)\n",
    "r, z = np.meshgrid(radius + width / 2 * nodes, width / 2 * nodes, indexing=\"ij\")\n",
    "w = (np.outer(weights, weights) * (width / 2) ** 2 * density).ravel()\n",
    "mutual = lambda a, b, s: (\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 + s**2)))\n",
    "exact = lambda d: np.sum(\n",
    "    w[:, None]\n",
    "    * w[None, :]\n",
    "    * (\n",
    "        mutual(\n",
    "            r.ravel()[:, None],\n",
    "            r.ravel()[None, :],\n",
    "            d + z.ravel()[None, :] - z.ravel()[:, None] + 1e-9,\n",
    "        )\n",
    "        - mutual(\n",
    "            r.ravel()[:, None],\n",
    "            r.ravel()[None, :],\n",
    "            d + z.ravel()[None, :] - z.ravel()[:, None] - 1e-9,\n",
    "        )\n",
    "    )\n",
    "    / 2e-9\n",
    ")\n",
    "print(\n",
    "    \"distance   cell size   tetrahedra   force on the upper coil [mN]   exact [mN]   deviation   (F_lower + F_upper) / F_upper\"\n",
    ")\n",
    "for (d, h), mesh, (f_lower, f_upper) in zip(cases, meshes, forces):\n",
    "    print(\n",
    "        f\"{1e3 * d:6.0f} mm {1e3 * h:8.1f} mm {mesh.cell_count:12d} {1e3 * f_upper:22.4f} {1e3 * exact(d):17.4f} {100 * (f_upper / exact(d) - 1):+10.3f} %\"\n",
    "        f\" {(f_lower + f_upper) / f_upper:+16.1e}\"\n",
    "    )\n",
    "thin = (\n",
    "    lambda d: current**2\n",
    "    * turns**2\n",
    "    * (mutual(radius, radius, d + 1e-9) - mutual(radius, radius, d - 1e-9))\n",
    "    / 2e-9\n",
    ")\n",
    "print(\n",
    "    \"thin-loop formula for comparison: \"\n",
    "    + \", \".join(\n",
    "        f\"{1e3 * thin(d):.4f} mN at {1e3 * d:.0f} mm\" for d in (0.025, 0.05, 0.10)\n",
    "    )\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The field strength through the axis for the middle distance and the force against the distance."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "wide = np.linspace(0.012, 0.15, 120)\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.section(\n",
    "    fields[1],\n",
    "    plane=Plane(origin=(0, 1e-6, 0), normal=(0, 1, 0)),\n",
    "    component=lambda B, p: 1e3 * np.linalg.norm(B, axis=1),\n",
    "    limits=(0, 3),\n",
    "    contours=13,\n",
    "    subdivisions=2,\n",
    "    symmetry={\"planes\": [((1, 0, 0), (0, 0, 0))]},\n",
    "    label=\"|B| [mT]\",\n",
    "    xlimits=(-0.12, 0.12),\n",
    "    ylimits=(-0.07, 0.12),\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    title=\"Field of the two coils, 50 mm apart\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    1e3 * wide,\n",
    "    {\n",
    "        \"exact, windings\": [-1e3 * exact(d) for d in wide],\n",
    "        \"thin loops\": [-1e3 * thin(d) for d in wide],\n",
    "    },\n",
    "    points={\n",
    "        \"simulation, upper coil\": (\n",
    "            [1e3 * d for d, _ in cases],\n",
    "            [-1e3 * f[1] for f in forces],\n",
    "        ),\n",
    "        \"simulation, lower coil (sign reversed)\": (\n",
    "            [1e3 * d for d, _ in cases],\n",
    "            [1e3 * f[0] for f in forces],\n",
    "        ),\n",
    "    },\n",
    "    scale=\"logy\",\n",
    "    xlabel=\"coil distance [mm]\",\n",
    "    ylabel=\"attractive force [mN]\",\n",
    "    title=\"Force between the coils\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Reverse one current to make the force repulsive, tilt the upper winding in\n",
    "`coil_force_verification_geometry.py` (half model) and compute the torque, or put an iron plate\n",
    "between the coils and watch the force change."
   ]
  }
 ]
}
