{
 "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 parallel current-carrying wires\n",
    "\n",
    "Two straight, very long round wires of radius $a=0.1$ m have their axes $d=1$ m apart and carry\n",
    "the same current $I=1$ A in the same direction. Each wire sits in the magnetic field of the other\n",
    "and is pulled towards it. Until 2019 this force defined the ampere: $2\\cdot10^{-7}$ N per metre\n",
    "of wire for 1 A at 1 m.\n",
    "\n",
    "The wires are long, so the field is the same in every cross-section and the vector potential\n",
    "has only the component $A_z(x,y)$. OneSimulation solves the planar magnetostatic equation\n",
    "\n",
    "$$-\\nabla\\cdot\\big(\\mu_0^{-1}\\nabla A_z\\big)=J_z,\\qquad \\mathbf B=\\nabla\\times(A_z\\hat{\\mathbf z}),$$\n",
    "\n",
    "with quadratic Lagrange elements, a uniform current density in each wire and magnetic insulation\n",
    "($A_z=0$) on a circle of 10 m radius. The force per metre on a wire is the Maxwell stress\n",
    "integrated around it (`magnetic_force`).\n",
    "\n",
    "The domain is the cross-section at half length of `parallel_wires_ampere_force_2d.step`, a 1 m\n",
    "piece of an air cylinder of 10 m radius; the wires are the sections of\n",
    "`parallel_wires_ampere_force_2d_left.step` and `_right.step`. The script\n",
    "`parallel_wires_ampere_force_2d_geometry.py` builds them with the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference.** Ampère's force law for two long parallel currents (Jackson, *Classical\n",
    "Electrodynamics*, 3rd ed., Sec. 5.2; the SI definition of the ampere before 2019):\n",
    "\n",
    "$$\\frac{F}{\\ell}=\\frac{\\mu_0I^2}{2\\pi d}.$$\n",
    "\n",
    "It holds for round wires of any radius. The insulated circle acts like two image currents\n",
    "$-I$ at $x=\\pm2R^2/d$; they change the force by the factor $1+d/(2R^2/d-d/2)-d/(2R^2/d+d/2)$, here\n",
    "$1+2.5\\cdot10^{-5}$, which is included."
   ]
  },
  {
   "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 TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.magnetostatics import (\n",
    "    MagneticInsulation,\n",
    "    Magnetostatics,\n",
    "    RegionCurrent,\n",
    "    magnetic_force,\n",
    ")\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",
    "`section` cuts the three parts at half length. The current density is assigned at the quadrature\n",
    "points inside the wire sections, so the triangles are small near the wire surfaces and grow\n",
    "towards the outer circle. Splitting every triangle into four once and twice gives the finer\n",
    "meshes, with 6, 12 and 24 cells per wire radius."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mid = lambda name: load(f\"parallel_wires_ampere_force_2d{name}.step\").section(\n",
    "    (0, 0, 1), origin=(0, 0, 0.5)\n",
    ")\n",
    "air, left, right = mid(\"\"), mid(\"_left\"), mid(\"_right\")\n",
    "radius, outer = right.size[0] / 2, air.size[0] / 2\n",
    "spacing = right.bounding_box[0][0] - left.bounding_box[0][0]\n",
    "cells = (6, 12, 24)\n",
    "distance = lambda points: np.minimum(\n",
    "    np.hypot(points[:, 0] + spacing / 2, points[:, 1]),\n",
    "    np.hypot(points[:, 0] - spacing / 2, points[:, 1]),\n",
    ")\n",
    "meshes = [\n",
    "    TriangularMesher(\n",
    "        target_size=outer / 6,\n",
    "        refinements=level,\n",
    "        size_field=lambda points: np.clip(\n",
    "            radius / 6 + 0.25 * np.abs(distance(points) - radius), radius / 6, outer / 6\n",
    "        ),\n",
    "    ).generate(air)\n",
    "    for level in range(3)\n",
    "]\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    [\n",
    "        load(\"parallel_wires_ampere_force_2d.step\").named(\"air\"),\n",
    "        load(\"parallel_wires_ampere_force_2d_left.step\").named(\"left wire\"),\n",
    "        load(\"parallel_wires_ampere_force_2d_right.step\").named(\"right wire\"),\n",
    "    ],\n",
    "    camera=plots.Camera(elevation=60, azimuth=-90),\n",
    "    title=\"1 m piece of the wires in the air cylinder\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Coarsest mesh: {meshes[0].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Both wires carry 1 A in $+z$ as a uniform current density over their circular section."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "current = 1.0\n",
    "mu0 = float(VacuumPermeability().evaluate())\n",
    "model = Magnetostatics(\n",
    "    domain=air.domain(),\n",
    "    permeability=VacuumPermeability(),\n",
    "    current_sources=tuple(\n",
    "        RegionCurrent.axial(wire, current, area=np.pi * radius**2, within=air.domain())\n",
    "        for wire in (left, right)\n",
    "    ),\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Parallel wires\",\n",
    "    geometry=air,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        MagneticInsulation(boundary=air.boundaries.all, physics=model),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2), quadrature_order=4),\n",
    "    linear_solver=SparseDirect(),\n",
    ")\n",
    "results = [\n",
    "    Simulation(problem=problem, mesh=mesh, numerics=numerics).solve_stationary()\n",
    "    for mesh in meshes\n",
    "]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The force per metre on each wire on the three meshes against Ampère's law."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "ampere = mu0 * current**2 / (2 * np.pi * spacing)\n",
    "image = 2 * outer**2 / spacing\n",
    "exact = ampere * (1 + spacing / (image - spacing / 2) - spacing / (image + spacing / 2))\n",
    "forces = [\n",
    "    (\n",
    "        magnetic_force(result, model, right).force,\n",
    "        magnetic_force(result, model, left).force,\n",
    "    )\n",
    "    for result in results\n",
    "]\n",
    "print(\n",
    "    f\"Ampère's law: {1e7 * ampere:.6f}e-7 N/m (with the images of the insulated circle {1e7 * exact:.6f}e-7 N/m)\"\n",
    ")\n",
    "print(\n",
    "    \"cells per radius   triangles   force on the right wire [1e-7 N/m]   deviation   left + right [% of the force]\"\n",
    ")\n",
    "for n, mesh, (on_right, on_left) in zip(cells, meshes, forces):\n",
    "    print(\n",
    "        f\"{n:16d} {mesh.cell_count:11d} {1e7 * on_right[0]:22.6f} {100 * (-on_right[0] / exact - 1):+17.4f} % \"\n",
    "        f\"{100 * np.linalg.norm(on_right + on_left) / exact:14.4f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The flux density around the wires and along the line through both axes against the superposed\n",
    "fields of the two wires (linear inside each wire, $1/r$ outside)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x = np.linspace(-1.5, 1.5, 601)\n",
    "wire_field = lambda r: np.where(\n",
    "    np.abs(r) < radius, r / radius**2, np.sign(r) / np.maximum(np.abs(r), radius)\n",
    ")\n",
    "superposed = (\n",
    "    mu0\n",
    "    * current\n",
    "    / (2 * np.pi)\n",
    "    * (wire_field(x + spacing / 2) + wire_field(x - spacing / 2))\n",
    ")\n",
    "marks = x[::12]\n",
    "computed = (\n",
    "    results[-1]\n",
    "    .field(model.magnetic_flux_density)\n",
    "    .evaluate(np.column_stack((marks, np.zeros_like(marks))))[:, 1]\n",
    ")\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.surface(\n",
    "    results[-1].field(model.magnetic_flux_density),\n",
    "    component=lambda B, position: 1e6 * np.linalg.norm(B, axis=1),\n",
    "    limits=(0, 2.2),\n",
    "    contours=12,\n",
    "    subdivisions=2,\n",
    "    label=\"|B| [µT]\",\n",
    "    title=\"Flux density around the wires\",\n",
    "    xlimits=(-1.5, 1.5),\n",
    "    ylimits=(-1.2, 1.2),\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"simulation\": (marks, 1e6 * computed)},\n",
    "    reference={\"superposed wire fields\": (x, 1e6 * superposed)},\n",
    "    vlines=[\n",
    "        -spacing / 2 - radius,\n",
    "        -spacing / 2 + radius,\n",
    "        spacing / 2 - radius,\n",
    "        spacing / 2 + radius,\n",
    "    ],\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"B_y on the line through both axes [µT]\",\n",
    "    title=\"Field along the line through the wires\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Reverse one current and the wires repel with the same force; change the wire radius or the\n",
    "spacing in `parallel_wires_ampere_force_2d_geometry.py` and write the STEP files again: the\n",
    "force depends on the spacing only, as long as the wires are round and do not touch."
   ]
  }
 ]
}
