{
 "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": [
    "# Magnetic force by virtual work and by the Maxwell stress tensor\n",
    "\n",
    "Two NdFeB ring magnets (inner radius 10 mm, outer radius 20 mm, 10 mm high, remanence\n",
    "$B_r=1.2$ T) face each other with like poles across a gap of 4 mm and repel. The magnets are\n",
    "rigid, $\\mathbf B=\\mu_0(\\mathbf H+\\mathbf M)$, and the vector potential solves\n",
    "$\\nabla\\times(\\mu_0^{-1}\\nabla\\times\\mathbf A)=\\nabla\\times\\mathbf M$. The force on the upper\n",
    "magnet is computed twice:\n",
    "\n",
    "* **Virtual work.** The magnetic energy of rigid magnets is $W=\\frac{\\mu_0}{2}\\int H^2\\,dV$ over\n",
    "  all space; moving the upper magnet by $\\pm\\delta$ ($\\delta=0.5$ mm) gives\n",
    "  $F_z=-\\bigl(W(g+\\delta)-W(g-\\delta)\\bigr)/(2\\delta)$.\n",
    "* **Maxwell stress.** The stress tensor $T_{ij}=(B_iB_j-\\tfrac12\\delta_{ij}B^2)/\\mu_0$ integrated\n",
    "  over a plane in the gap gives $F_z=\\int(B_x^2+B_y^2-B_z^2)/(2\\mu_0)\\,dA$.\n",
    "\n",
    "Both moved positions are solved on the same mesh: the space of the upper magnet is cut into three\n",
    "slices, and the magnet fills the lower two or the upper two. One quarter of the air, a quarter\n",
    "ball of 100 mm radius, comes from the CAD file `magnet_force_virtual_work_maxwell.step` (face\n",
    "groups `planes`, `outer`), the lower magnet from `..._lower.step` and the slices from\n",
    "`..._slice_bottom.step`, `..._slice_middle.step` and `..._slice_top.step`. The script\n",
    "`magnet_force_virtual_work_maxwell_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.** Each ring is equivalent to two cylindrical current sheets $\\pm M$ on its outer and\n",
    "inner surface; the exact force follows from Maxwell's mutual inductance of coaxial loops,\n",
    "integrated over the sheets (Furlani, *Permanent Magnet and Electromechanical Devices*, Ch. 3).\n",
    "The central difference of the virtual work estimates the force at the gap $g$; the mean of the\n",
    "two Maxwell-stress forces is compared with the mean of the exact forces at $g\\pm\\delta$."
   ]
  },
  {
   "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 SparseDirect\n",
    "from onesim.physics.magnetostatics import (\n",
    "    CoulombGauge,\n",
    "    MagneticInsulation,\n",
    "    MagneticVectorPotential,\n",
    "    MagnetizationContribution,\n",
    "    Magnetostatics,\n",
    "    SampledMagnetizationLoads,\n",
    "    curl_magnetization_load,\n",
    "    curl_space_magnetization_patches,\n",
    ")\n",
    "from onesim.results.integration import integrate_plane, mean_value, measure\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",
    "The lower magnet and the three slices are embedded in the mesh of the air, so that the surfaces\n",
    "of the upper magnet in both positions are cell faces."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "air, lower = load(\"magnet_force_virtual_work_maxwell.step\"), load(\n",
    "    \"magnet_force_virtual_work_maxwell_lower.step\"\n",
    ")\n",
    "slices = [\n",
    "    load(f\"magnet_force_virtual_work_maxwell_slice_{name}.step\")\n",
    "    for name in (\"bottom\", \"middle\", \"top\")\n",
    "]\n",
    "faces = air.boundaries\n",
    "outer, height = lower.size[0], lower.size[2]\n",
    "inner = min(np.hypot(*vertex.position[:2]) for vertex in lower.vertices)\n",
    "shift = slices[0].size[2] / 2\n",
    "gap = slices[0].bounding_box[0][2] + shift\n",
    "mesh = TetrahedralMesher(\n",
    "    target_size=0.02,\n",
    "    embedded_regions=(lower, *slices),\n",
    "    refinements=tuple(\n",
    "        LocalRefinement(region=region, target_size=0.0025)\n",
    "        for region in (lower, *slices)\n",
    "    ),\n",
    "    size_field=lambda points: np.clip(\n",
    "        0.0025\n",
    "        + 0.6\n",
    "        * np.maximum(\n",
    "            np.hypot(\n",
    "                np.hypot(points[:, 0], points[:, 1]) - 0.015, points[:, 2] - gap / 2\n",
    "            )\n",
    "            - 0.012,\n",
    "            0,\n",
    "        ),\n",
    "        0.0025,\n",
    "        0.025,\n",
    "    ),\n",
    ").generate(air)\n",
    "\n",
    "view = plots.Camera(elevation=25, azimuth=-55)\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    [\n",
    "        lower.named(\"lower magnet\"),\n",
    "        *(\n",
    "            piece.named(f\"{name} slice\")\n",
    "            for piece, name in zip(slices, (\"bottom\", \"middle\", \"top\"))\n",
    "        ),\n",
    "    ],\n",
    "    camera=view,\n",
    "    title=\"Lower magnet and the three slices of the upper one\",\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": [
    "## Model\n",
    "\n",
    "The magnetisation is $+M\\hat{\\mathbf z}$ in the lower ring and $-M\\hat{\\mathbf z}$ in the upper\n",
    "ring, which starts at $g-\\delta$ or at $g+\\delta$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mu0 = float(VacuumPermeability().evaluate())\n",
    "magnetisation = 1.2 / mu0\n",
    "ring = (\n",
    "    lambda points, bottom: (\n",
    "        (np.hypot(points[:, 0], points[:, 1]) - inner)\n",
    "        * (np.hypot(points[:, 0], points[:, 1]) - outer)\n",
    "        < 0\n",
    "    )\n",
    "    & (points[:, 2] > bottom)\n",
    "    & (points[:, 2] < bottom + height)\n",
    ")\n",
    "positions = (gap - shift, gap + shift)\n",
    "models = {\n",
    "    g: Magnetostatics(\n",
    "        domain=air.volume,\n",
    "        permeability=VacuumPermeability(),\n",
    "        formulation=MagneticVectorPotential(gauge=CoulombGauge()),\n",
    "        magnetization_provider=MagnetizationContribution(\n",
    "            (\n",
    "                lambda g: lambda points, time: magnetisation\n",
    "                * np.column_stack(\n",
    "                    (0 * points[:, :2], ring(points, -height) * 1.0 - ring(points, g))\n",
    "                )\n",
    "            )(g),\n",
    "            SampledMagnetizationLoads(\n",
    "                curl_space_magnetization_patches,\n",
    "                lambda points, data, field_offset, context: field_offset(\n",
    "                    points, context.time\n",
    "                ),\n",
    "                curl_magnetization_load,\n",
    "            ),\n",
    "        ),\n",
    "    )\n",
    "    for g in positions\n",
    "}\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Nedelec(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "results = {\n",
    "    g: Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Magnet pair\",\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",
    "    ).solve_stationary()\n",
    "    for g, model in models.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The energy $\\frac{\\mu_0}{2}\\int H^2dV$ from `mean_value` and `measure`, the Maxwell stress on the\n",
    "plane halfway across the narrower gap from `integrate_plane`, four times the quarter each."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "strength = {g: results[g].field(models[g].magnetic_field_strength) for g in positions}\n",
    "induction = {g: results[g].field(models[g].magnetic_flux_density) for g in positions}\n",
    "energy = {\n",
    "    g: 4\n",
    "    * mu0\n",
    "    / 2\n",
    "    * mean_value(H, component=lambda H, position: (H**2).sum(axis=1))\n",
    "    * measure(H)\n",
    "    for g, H in strength.items()\n",
    "}\n",
    "stress = lambda B, position: (B[:, 0] ** 2 + B[:, 1] ** 2 - B[:, 2] ** 2) / (2 * mu0)\n",
    "maxwell = {\n",
    "    g: 4\n",
    "    * integrate_plane(\n",
    "        B, Plane(origin=(0, 0, positions[0] / 2), normal=(0, 0, 1)), component=stress\n",
    "    ).value\n",
    "    for g, B in induction.items()\n",
    "}\n",
    "virtual = -(energy[positions[1]] - energy[positions[0]]) / (2 * shift)\n",
    "nodes, weights = np.polynomial.legendre.leggauss(48)\n",
    "pair = np.outer(weights, weights) * (height / 2) ** 2\n",
    "mutual = lambda a, b, z: (\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 + z**2)))\n",
    "separation = (\n",
    "    lambda g: (g + height / 2 + height / 2 * nodes)[None, :]\n",
    "    - (-height / 2 + height / 2 * nodes)[:, None]\n",
    ")\n",
    "exact = lambda g: sum(\n",
    "    s1\n",
    "    * s2\n",
    "    * magnetisation**2\n",
    "    * np.sum(\n",
    "        pair\n",
    "        * (mutual(a, b, separation(g) + 1e-8) - mutual(a, b, separation(g) - 1e-8))\n",
    "        / 2e-8\n",
    "    )\n",
    "    for a, s1 in ((outer, 1), (inner, -1))\n",
    "    for b, s2 in ((outer, -1), (inner, 1))\n",
    ")\n",
    "mean_exact = (exact(positions[0]) + exact(positions[1])) / 2\n",
    "print(\n",
    "    f\"magnetic energy: {energy[positions[0]]:.6f} J at g - delta, {energy[positions[1]]:.6f} J at g + delta\"\n",
    ")\n",
    "print(\n",
    "    f\"virtual work, force at g = {1e3 * gap:.0f} mm:      {virtual:9.4f} N   exact {exact(gap):9.4f} N  ({100 * (virtual / exact(gap) - 1):+.2f} %)\"\n",
    ")\n",
    "for g in positions:\n",
    "    print(\n",
    "        f\"Maxwell stress at g = {1e3 * g:.1f} mm:        {maxwell[g]:9.4f} N   exact {exact(g):9.4f} N  ({100 * (maxwell[g] / exact(g) - 1):+.2f} %)\"\n",
    "    )\n",
    "print(\n",
    "    f\"mean of the two Maxwell forces:      {np.mean(list(maxwell.values())):9.4f} N   mean exact {mean_exact:9.4f} N\"\n",
    ")\n",
    "print(\n",
    "    f\"virtual work against the mean Maxwell force: {100 * (virtual / np.mean(list(maxwell.values())) - 1):+.2f} %; \"\n",
    "    f\"exact force at g against the exact mean: {100 * (exact(gap) / mean_exact - 1):+.3f} %\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The Maxwell stress on the plane in the gap and the field strength through the axis."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.section(\n",
    "    induction[positions[0]],\n",
    "    plane=Plane(origin=(0, 0, positions[0] / 2), normal=(0, 0, 1)),\n",
    "    component=lambda B, position: stress(B, position) / 1e3,\n",
    "    contours=10,\n",
    "    subdivisions=2,\n",
    "    symmetry={\"planes\": [((1, 0, 0), (0, 0, 0)), ((0, 1, 0), (0, 0, 0))]},\n",
    "    label=\"Maxwell stress [kPa]\",\n",
    "    xlimits=(-0.03, 0.03),\n",
    "    ylimits=(-0.03, 0.03),\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    title=\"Stress pushing the magnets apart\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.section(\n",
    "    strength[positions[0]],\n",
    "    plane=Plane(origin=(0, 1e-6, 0), normal=(0, 1, 0)),\n",
    "    component=lambda H, position: np.linalg.norm(H, axis=1) / 1e3,\n",
    "    limits=(0, 700),\n",
    "    contours=8,\n",
    "    subdivisions=2,\n",
    "    symmetry={\"planes\": [((1, 0, 0), (0, 0, 0))]},\n",
    "    label=\"|H| [kA/m]\",\n",
    "    xlimits=(-0.04, 0.04),\n",
    "    ylimits=(-0.025, 0.03),\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    title=\"Field strength, whose energy is W\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Halve the shift in `magnet_force_virtual_work_maxwell_geometry.py` and the central difference\n",
    "approaches the force at the gap itself; move the stress plane away from the middle of the gap to\n",
    "see that the Maxwell force does not depend on where the plane lies; or tilt the upper magnet and\n",
    "compute a torque."
   ]
  }
 ]
}
