{
 "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": [
    "# Static field of a Halbach rotor\n",
    "\n",
    "A four-pole rotor ($p=2$ pole pairs) is a ring of permanent magnet (inner radius $r_i=20$ mm,\n",
    "outer radius $r_o=30$ mm, length $L=40$ mm, remanence $B_r=1.2$ T) magnetised in the Halbach\n",
    "pattern\n",
    "\n",
    "$$\\mathbf M=M\\bigl(\\cos p\\varphi\\,\\hat{\\mathbf r}-\\sin p\\varphi\\,\\hat{\\boldsymbol\\varphi}\\bigr),\\qquad \\mu_0M=B_r ,$$\n",
    "\n",
    "so the direction of magnetisation turns by $(p+1)\\cdot360°$ around the ring. The field of the rigid\n",
    "magnet, $\\mathbf B=\\mu_0(\\mathbf H+\\mathbf M)$, solves\n",
    "$\\nabla\\times(\\mu_0^{-1}\\nabla\\times\\mathbf A)=\\nabla\\times\\mathbf M$. Outside the rotor, where a\n",
    "stator would sit, the field is strong and sinusoidal; inside it almost vanishes.\n",
    "\n",
    "The rotor is symmetric about its mid-plane and about the planes $x=0$ and $y=0$, so one eighth is\n",
    "computed. The air, an eighth of a ball of 150 mm radius, comes from the CAD file\n",
    "`halbach_rotor_field.step` with the face groups `planes`, `midplane` and `outer`, the magnet ring\n",
    "from `halbach_rotor_field_magnet.step`; the script `halbach_rotor_field_geometry.py` builds them\n",
    "with the CAD objects of OneSimulation.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `planes` ($x=0$, $y=0$), `midplane` ($z=0$) | field tangential to the plane, $\\mathbf n\\times\\mathbf A=0$ |\n",
    "| `outer` | $\\mathbf n\\times\\mathbf A=0$ (far away) |\n",
    "\n",
    "**Reference.** For an infinitely long rotor the field follows in closed form (Halbach, *Nucl.\n",
    "Instrum. Methods* 169, 1, 1980; Zhu and Howe, *IEEE Trans. Magn.* 29, 1993): $\\mathbf B=0$ in the\n",
    "bore and outside\n",
    "\n",
    "$$B_r=B_r^\\mathrm{rem}\\,\\frac{p}{p+1}\\Bigl[1-\\Bigl(\\frac{r_i}{r_o}\\Bigr)^{p+1}\\Bigr]\\Bigl(\\frac{r_o}{r}\\Bigr)^{p+1}\\cos p\\varphi,\\qquad\n",
    "  B_\\varphi=\\ldots\\sin p\\varphi .$$\n",
    "\n",
    "In the mid-plane of the finite rotor the field approaches this value; the difference is the end\n",
    "effect of the finite length. Independently of any formula, no flux may be created: the net flux\n",
    "out of any closed surface vanishes ($\\nabla\\cdot\\mathbf B=0$)."
   ]
  },
  {
   "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.meshing.quality import quality\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",
    "    MagnetizationContribution,\n",
    "    Magnetostatics,\n",
    "    SampledMagnetizationLoads,\n",
    "    curl_magnetization_load,\n",
    "    curl_space_magnetization_patches,\n",
    ")\n",
    "from onesim.results.integration import integrate_plane\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "The magnet ring is embedded in the mesh with 2 mm cells. The air gap where the field is read\n",
    "(radii 29 to 35 mm) gets 1.5 mm cells on the first and 1 mm cells on the second mesh; the cells\n",
    "grow towards the outer boundary."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "space, magnet = load(\"halbach_rotor_field.step\"), load(\n",
    "    \"halbach_rotor_field_magnet.step\"\n",
    ")\n",
    "faces = space.boundaries\n",
    "outer, half = magnet.size[0], magnet.size[2]\n",
    "inner = min(np.hypot(*vertex.position[:2]) for vertex in magnet.vertices)\n",
    "sizes = (0.0015, 0.001)\n",
    "meshes = [\n",
    "    TetrahedralMesher(\n",
    "        target_size=0.03,\n",
    "        embedded_regions=(magnet,),\n",
    "        refinements=(LocalRefinement(region=magnet, target_size=0.002),),\n",
    "        size_field=lambda points, h=h: np.clip(\n",
    "            h\n",
    "            + 0.5\n",
    "            * np.hypot(\n",
    "                np.maximum(\n",
    "                    np.abs(np.hypot(points[:, 0], points[:, 1]) - 0.032) - 0.003, 0\n",
    "                ),\n",
    "                np.maximum(points[:, 2] - half - 0.002, 0),\n",
    "            ),\n",
    "            h,\n",
    "            0.03,\n",
    "        ),\n",
    "    ).generate(space)\n",
    "    for h in sizes\n",
    "]\n",
    "\n",
    "view = plots.Camera(elevation=30, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    magnet, labels=False, camera=view, title=\"Eighth of the rotor ring\", ax=fig[0]\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[-1],\n",
    "    cell_values=1e3 * np.cbrt(quality(meshes[-1])[\"size\"]),\n",
    "    plane=((0, 1e-6, 0), (0, -1, 0)),\n",
    "    label=\"cell size [mm]\",\n",
    "    camera=plots.Camera(elevation=5, azimuth=-90),\n",
    "    title=f\"{meshes[-1].cell_count} tetrahedra, cut through the axis\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "In Cartesian components the Halbach magnetisation of the four-pole ring is\n",
    "$\\mathbf M=M(\\cos(p-1)\\varphi,\\,-\\sin(p-1)\\varphi,\\,0)$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mu0, remanence, pairs = float(VacuumPermeability().evaluate()), 1.2, 2\n",
    "in_ring = (\n",
    "    lambda points: (np.hypot(points[:, 0], points[:, 1]) > inner)\n",
    "    & (np.hypot(points[:, 0], points[:, 1]) < outer)\n",
    "    & (points[:, 2] < half)\n",
    ")\n",
    "angle = lambda points: np.arctan2(points[:, 1], points[:, 0])\n",
    "model = Magnetostatics(\n",
    "    domain=space.volume,\n",
    "    permeability=VacuumPermeability(),\n",
    "    formulation=MagneticVectorPotential(gauge=CoulombGauge()),\n",
    "    magnetization_provider=MagnetizationContribution(\n",
    "        lambda points, time: remanence\n",
    "        / mu0\n",
    "        * in_ring(points)[:, None]\n",
    "        * np.column_stack(\n",
    "            (\n",
    "                np.cos((pairs - 1) * angle(points)),\n",
    "                -np.sin((pairs - 1) * angle(points)),\n",
    "                0 * points[:, 0],\n",
    "            )\n",
    "        ),\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",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Nedelec(order=2)),\n",
    "    linear_solver=GMRES(preconditioner=AuxiliarySpaceMaxwell()),\n",
    ")\n",
    "fields = [\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Halbach rotor\",\n",
    "            geometry=space,\n",
    "            physics=(model,),\n",
    "            boundary_conditions=(\n",
    "                MagneticInsulation(\n",
    "                    boundary=faces.planes | faces.midplane | faces.outer, physics=model\n",
    "                ),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=mesh,\n",
    "        numerics=numerics,\n",
    "    )\n",
    "    .solve_stationary()\n",
    "    .field(model.magnetic_flux_density)\n",
    "    for mesh in meshes\n",
    "]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The radial field 2 mm outside the magnet (in the air gap of a machine) in the mid-plane: its\n",
    "$\\cos2\\varphi$ amplitude $\\frac4\\pi\\int_0^{\\pi/2}B_r\\cos2\\varphi\\,d\\varphi$ against the\n",
    "two-dimensional solution and against the finite ring computed independently by Coulomb's law from\n",
    "the magnetic charges of the magnetisation: the volume charge $-\\nabla\\cdot\\mathbf M=(p-1)M\\cos\n",
    "p\\varphi/r$ and the surface charges $\\mathbf M\\cdot\\mathbf n=\\pm M\\cos p\\varphi$ on the outer and\n",
    "inner cylinder (the end faces carry none), integrated over the whole ring by quadrature. A flux\n",
    "balance checks the field independently of any formula: the space below the plane $z=c$ above\n",
    "the rotor is closed by the symmetry planes and the outer boundary, which no flux crosses, so the\n",
    "net flux through it must vanish. The end effect is not a uniform scaling: the short rotor's field\n",
    "falls off faster with the radius than the 2D field, so in the mid-plane the radial component\n",
    "grows while the tangential one shrinks, by about 16 % at 45°, which the same Coulomb integration\n",
    "shows for $B_\\varphi$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "phi = np.linspace(0.0, np.pi / 2, 181)\n",
    "ring_at = lambda r, z: np.column_stack(\n",
    "    (r * np.cos(phi), r * np.sin(phi), np.full_like(phi, z))\n",
    ")\n",
    "radial = lambda B: B[:, 0] * np.cos(phi) + B[:, 1] * np.sin(phi)\n",
    "gap = outer + 0.002\n",
    "peak = (\n",
    "    remanence\n",
    "    * pairs\n",
    "    / (pairs + 1)\n",
    "    * (1 - (inner / outer) ** (pairs + 1))\n",
    "    * (outer / gap) ** (pairs + 1)\n",
    ")\n",
    "amplitudes = [\n",
    "    4\n",
    "    / np.pi\n",
    "    * np.trapezoid(\n",
    "        radial(field.evaluate(ring_at(gap, 1e-6))) * np.cos(pairs * phi), phi\n",
    "    )\n",
    "    for field in fields\n",
    "]\n",
    "zq, wq = np.polynomial.legendre.leggauss(200)\n",
    "psi, zeta = np.meshgrid((np.arange(1440) + 0.5) * np.pi / 720, half * zq, indexing=\"ij\")\n",
    "sources = np.concatenate(\n",
    "    (\n",
    "        [outer, inner],\n",
    "        (outer + inner) / 2\n",
    "        + (outer - inner) / 2 * np.polynomial.legendre.leggauss(16)[0],\n",
    "    )\n",
    ")\n",
    "charges = np.concatenate(\n",
    "    ([outer, -inner], (outer - inner) / 2 * np.polynomial.legendre.leggauss(16)[1])\n",
    ")\n",
    "coulomb = (\n",
    "    lambda r0: remanence\n",
    "    / (4 * np.pi)\n",
    "    * np.pi\n",
    "    / 720\n",
    "    * np.einsum(\n",
    "        \"k,kij,j->\",\n",
    "        charges,\n",
    "        np.cos(pairs * psi)\n",
    "        * (r0 - sources[:, None, None] * np.cos(psi))\n",
    "        / (\n",
    "            r0**2\n",
    "            + sources[:, None, None] ** 2\n",
    "            - 2 * r0 * sources[:, None, None] * np.cos(psi)\n",
    "            + zeta**2\n",
    "        )\n",
    "        ** 1.5,\n",
    "        half * wq,\n",
    "    )\n",
    ")\n",
    "finite = coulomb(gap)\n",
    "tangential = (\n",
    "    remanence\n",
    "    / (4 * np.pi)\n",
    "    * np.pi\n",
    "    / 720\n",
    "    * np.einsum(\n",
    "        \"k,kij,j->\",\n",
    "        charges,\n",
    "        np.cos(pairs * psi + np.pi / 2)\n",
    "        * (-sources[:, None, None] * np.sin(psi))\n",
    "        / (\n",
    "            gap**2\n",
    "            + sources[:, None, None] ** 2\n",
    "            - 2 * gap * sources[:, None, None] * np.cos(psi)\n",
    "            + zeta**2\n",
    "        )\n",
    "        ** 1.5,\n",
    "        half * wq,\n",
    "    )\n",
    ")\n",
    "print(\n",
    "    f\"finite ring by Coulomb integration of the magnetic charges: {finite:.4f} T, 2D solution {peak:.4f} T \"\n",
    "    f\"(end effect {100 * (finite / peak - 1):+.2f} %)\"\n",
    ")\n",
    "cap = Plane(origin=(0, 0, 0.03), normal=(0, 0, 1))\n",
    "for h, field, amplitude in zip(sizes, fields, amplitudes):\n",
    "    net, gross = (\n",
    "        integrate_plane(field, cap, component=2).value,\n",
    "        integrate_plane(field, cap, component=lambda B, p: np.abs(B[:, 2])).value,\n",
    "    )\n",
    "    print(\n",
    "        f\"gap cells {1e3 * h:.1f} mm: mid-plane air-gap amplitude {amplitude:.4f} T ({100 * (amplitude / finite - 1):+.2f} % from the \"\n",
    "        f\"Coulomb integration, end effect {100 * (amplitude / peak - 1):+.2f} %); net flux through z = 30 mm {net / gross:+.1e} of the flux through it\"\n",
    "    )\n",
    "print(\n",
    "    f\"change of the mid-plane amplitude between the meshes: {100 * (amplitudes[1] / amplitudes[0] - 1):+.3f} %\"\n",
    ")\n",
    "computed = fields[-1].evaluate(ring_at(gap, 1e-6))\n",
    "across = -computed[90, 0] * np.sin(phi[90]) + computed[90, 1] * np.cos(phi[90])\n",
    "print(\n",
    "    f\"B_phi at 45 deg: {across:.4f} T, Coulomb integration {abs(tangential):.4f} T ({100 * (abs(across) / abs(tangential) - 1):+.2f} %), \"\n",
    "    f\"2D solution {peak:.4f} T ({100 * (abs(tangential) / peak - 1):+.2f} %)\"\n",
    ")\n",
    "print(\n",
    "    f\"largest deviation from the cos(2 phi) shape in the mid-plane: {100 * np.abs(radial(computed) - amplitudes[-1] * np.cos(pairs * phi)).max() / amplitudes[-1]:.2f} %\"\n",
    ")\n",
    "bore = np.linalg.norm(fields[-1].evaluate(ring_at(0.5 * inner, 1e-6)), axis=1).max()\n",
    "print(\n",
    "    f\"largest field in the bore (r = 10 mm, mid-plane): {1e3 * bore:.1f} mT, against {1e3 * peak:.0f} mT in the air gap\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The induction in the mid-plane, the air-gap field over the angle against the 2D solution, and the\n",
    "radial air-gap field at $\\varphi=0$ along the rotor, which falls off beyond its end."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "z = np.linspace(0.0, 0.05, 51)\n",
    "along = fields[-1].evaluate(\n",
    "    np.column_stack((np.full_like(z, gap), np.full_like(z, 1e-6), z))\n",
    ")[:, 0]\n",
    "fig = plots.figure(layout=[[\"map\", \"angle\"], [\"map\", \"length\"]], size=(16, 10))\n",
    "plots.section(\n",
    "    fields[-1],\n",
    "    plane=Plane(origin=(0, 0, 1e-6), normal=(0, 0, 1)),\n",
    "    component=lambda B, p: np.linalg.norm(B, axis=1),\n",
    "    limits=(0, 1.0),\n",
    "    contours=11,\n",
    "    subdivisions=2,\n",
    "    symmetry={\"planes\": [((1, 0, 0), (0, 0, 0)), ((0, 1, 0), (0, 0, 0))]},\n",
    "    label=\"|B| [T]\",\n",
    "    xlimits=(-0.045, 0.045),\n",
    "    ylimits=(-0.045, 0.045),\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    title=\"Induction in the mid-plane\",\n",
    "    ax=fig[\"map\"],\n",
    ")\n",
    "plots.line(\n",
    "    np.degrees(phi),\n",
    "    points={\n",
    "        \"B_r\": (np.degrees(phi)[::5], radial(computed)[::5]),\n",
    "        \"B_φ\": (\n",
    "            np.degrees(phi)[::5],\n",
    "            (-computed[:, 0] * np.sin(phi) + computed[:, 1] * np.cos(phi))[::5],\n",
    "        ),\n",
    "    },\n",
    "    reference={\n",
    "        \"2D solution, B_r\": peak * np.cos(pairs * phi),\n",
    "        \"2D solution, B_φ\": peak * np.sin(pairs * phi),\n",
    "    },\n",
    "    xlabel=\"angle φ [deg]\",\n",
    "    ylabel=\"induction 2 mm outside the magnet [T]\",\n",
    "    title=\"Air-gap field in the mid-plane\",\n",
    "    ax=fig[\"angle\"],\n",
    ")\n",
    "plots.line(\n",
    "    1e3 * z,\n",
    "    {\"finite rotor\": along},\n",
    "    hlines={\"2D solution\": peak},\n",
    "    vlines={\"end of the rotor\": 1e3 * half},\n",
    "    xlabel=\"distance from the mid-plane z [mm]\",\n",
    "    ylabel=\"B_r 2 mm outside the magnet at φ = 0 [T]\",\n",
    "    title=\"End effect\",\n",
    "    ax=fig[\"length\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Build the ring from discrete segments with one magnetisation direction each, as real rotors are\n",
    "made, and see the air-gap field approach the ideal one with the number of segments; lengthen the\n",
    "rotor in `halbach_rotor_field_geometry.py` until the mid-plane field reaches the 2D value; or turn\n",
    "the magnetisation the other way round ($+\\sin p\\varphi$), which sends the field into the bore."
   ]
  }
 ]
}
