{
 "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 field of a three-phase power line over three spans\n",
    "\n",
    "A 400 kV line carries its three phase bundles in one horizontal row, 9 m apart. Between two towers\n",
    "300 m apart the conductors sag from the crossarm at 30 m to 20 m above ground at mid-span, so the\n",
    "field on the ground changes along the span: it is strongest under the lowest point. Each phase\n",
    "carries $I=1000$ A (rms) of a symmetric three-phase system,\n",
    "$i_k(t)=\\sqrt2I\\cos(\\omega t-2\\pi k/3)$.\n",
    "\n",
    "Air and ground are not magnetic, and at 50 Hz the currents induced in the ground spread over a\n",
    "depth of the order of a kilometre (Carson), so the field near the line is the free-space field of\n",
    "the conductor currents. OneSimulation integrates it in 3D with the Biot-Savart law along the\n",
    "centre lines of the conductors,\n",
    "\n",
    "$$\\mathbf B(\\mathbf r)=\\frac{\\mu_0}{4\\pi}\\sum_k i_k\\int\\frac{\\mathrm d\\boldsymbol\\ell_k\\times(\\mathbf r-\\mathbf r')}{|\\mathbf r-\\mathbf r'|^3},$$\n",
    "\n",
    "over the middle span and the two neighbouring ones. The steel of the towers is left out, and so\n",
    "are the shield wires, which carry no current in this model. The rms flux density follows from\n",
    "the two quadrature parts, $B_\\mathrm{rms}^2=\\tfrac12\\big(|\\mathbf B(0)|^2+|\\mathbf B(90°)|^2\\big)$.\n",
    "\n",
    "The towers come from `power_line_magnetic_field_3d.step`, the conductors from\n",
    "`power_line_magnetic_field_3d_phase_a.step`, `_phase_b.step` and `_phase_c.step`. The script\n",
    "`power_line_magnetic_field_3d_geometry.py` builds them with the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference.** Far from the towers the conductors are nearly straight and horizontal; the field of\n",
    "long straight currents at the local conductor height (Ampère's law, superposed; CIGRE Technical\n",
    "Brochure 373, 2009) is then a close estimate:\n",
    "\n",
    "$$\\mathbf B=\\frac{\\mu_0}{2\\pi}\\sum_k i_k\\,\\frac{\\hat{\\mathbf x}\\times(\\mathbf r-\\mathbf r_k)}{|\\mathbf r-\\mathbf r_k|^2}.$$\n",
    "\n",
    "At mid-span it uses the lowest height (20 m), at the tower the attachment height (30 m); the sag\n",
    "makes the 3D field differ from both. A study over the number of line pieces checks the\n",
    "integration."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import VacuumPermeability\n",
    "from onesim.physics.magnetostatics import magnetic_induction, polygon_line_quadrature\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and line discretization\n",
    "\n",
    "`load` returns the towers and the conductors. Span, attachment height and lowest point are read\n",
    "from the parts; the conductor centre lines are parabolic arcs through them. Each span is divided\n",
    "into straight pieces carrying a two-point Gauss rule."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "towers = load(\"power_line_magnetic_field_3d.step\")\n",
    "phases = [\n",
    "    load(f\"power_line_magnetic_field_3d_{name}.step\")\n",
    "    for name in (\"phase_a\", \"phase_b\", \"phase_c\")\n",
    "]\n",
    "bundle = 0.2\n",
    "span = towers.size[0] - 2.0\n",
    "lowest = phases[0].bounding_box[0][2] + bundle\n",
    "attach = phases[0].bounding_box[1][2] - bundle\n",
    "lateral = [0.5 * (part.bounding_box[0][1] + part.bounding_box[1][1]) for part in phases]\n",
    "sag_height = (\n",
    "    lambda x: lowest\n",
    "    + 4 * (attach - lowest) * ((np.mod(x + span / 2, span) - span / 2) / span) ** 2\n",
    ")\n",
    "gauss, gauss_weights = (\n",
    "    np.array((0.5 - 0.5 / np.sqrt(3), 0.5 + 0.5 / np.sqrt(3))),\n",
    "    np.array((0.5, 0.5)),\n",
    ")\n",
    "pieces = (8, 32, 128)\n",
    "lines = {\n",
    "    n: [\n",
    "        polygon_line_quadrature(\n",
    "            np.column_stack((x, np.full_like(x, y), sag_height(x))),\n",
    "            gauss,\n",
    "            gauss_weights,\n",
    "            closed=False,\n",
    "        )\n",
    "        for y in lateral\n",
    "        for x in (np.linspace(-1.5 * span, 1.5 * span, 3 * n + 1),)\n",
    "    ]\n",
    "    for n in pieces\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(15, 5.5))\n",
    "plots.geometry(\n",
    "    [\n",
    "        towers.named(\"towers\"),\n",
    "        *(\n",
    "            part.named(name)\n",
    "            for part, name in zip(phases, (\"phase a\", \"phase b\", \"phase c\"))\n",
    "        ),\n",
    "    ],\n",
    "    camera=plots.Camera(elevation=20, azimuth=-60),\n",
    "    title=\"Towers and conductors over three spans\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"{n} pieces per span\": (lines[n][0].points[:, 0], lines[n][0].points[:, 2])\n",
    "        for n in pieces[:2]\n",
    "    },\n",
    "    vlines=[-span / 2, span / 2],\n",
    "    xlabel=\"x along the line [m]\",\n",
    "    ylabel=\"height [m]\",\n",
    "    title=\"Quadrature points on phase a\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Field of the three phases\n",
    "\n",
    "The field is linear in the currents: the field of each phase for 1 A is integrated once, and the\n",
    "instantaneous fields at $\\omega t=0$ and $90°$ are their weighted sums."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "current = 1000.0\n",
    "mu0 = float(VacuumPermeability().evaluate())\n",
    "weights = {\n",
    "    phase: np.sqrt(2) * current * np.cos(phase - 2 * np.pi * np.arange(3) / 3)\n",
    "    for phase in (0.0, np.pi / 2)\n",
    "}\n",
    "x_grid, y_grid = np.linspace(-150.0, 150.0, 31), np.linspace(-60.0, 60.0, 81)\n",
    "ground = np.stack(np.meshgrid(x_grid, y_grid, indexing=\"ij\"), axis=-1).reshape(-1, 2)\n",
    "ground = np.column_stack((ground, np.ones(len(ground))))\n",
    "unit_fields = {\n",
    "    n: [\n",
    "        magnetic_induction(ground, line.points, line.line_elements, permeability=mu0)\n",
    "        for line in lines[n]\n",
    "    ]\n",
    "    for n in pieces\n",
    "}\n",
    "rms = {\n",
    "    n: np.sqrt(\n",
    "        0.5\n",
    "        * sum(\n",
    "            np.sum(\n",
    "                sum(w * B for w, B in zip(weights[phase], unit_fields[n])) ** 2, axis=1\n",
    "            )\n",
    "            for phase in weights\n",
    "        )\n",
    "    )\n",
    "    for n in pieces\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The quadrature study at the strongest point, the field under the lowest point and at the tower\n",
    "against the straight-line estimate, and the change along the span."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "line_field = (\n",
    "    lambda h, i: mu0\n",
    "    / (2 * np.pi)\n",
    "    * np.sum(\n",
    "        i * 1j / np.conj(y_grid[:, None] + 1j - (np.array(lateral) + 1j * h)), axis=1\n",
    "    )\n",
    ")\n",
    "straight = lambda h: np.sqrt(\n",
    "    0.5 * sum(np.abs(line_field(h, i)) ** 2 for i in weights.values())\n",
    ")\n",
    "finest = rms[pieces[-1]].reshape(len(x_grid), len(y_grid))\n",
    "peak = np.argmax(rms[pieces[-1]])\n",
    "print(\"pieces per span   largest rms flux density 1 m above ground [µT]\")\n",
    "for n in pieces:\n",
    "    print(\n",
    "        f\"{n:15d} {1e6 * rms[n][peak]:20.4f}   ({100 * (rms[n][peak] / rms[pieces[-1]][peak] - 1):+.4f} % from the finest)\"\n",
    "    )\n",
    "mid, tower = np.argmin(np.abs(x_grid)), np.argmin(np.abs(x_grid - span / 2))\n",
    "for label, row, z in ((\"mid-span\", mid, lowest), (\"at the tower\", tower, attach)):\n",
    "    estimate = straight(z)\n",
    "    print(\n",
    "        f\"{label:13s}: largest {1e6 * finest[row].max():.3f} µT, straight lines at {z:.0f} m {1e6 * estimate.max():.3f} µT \"\n",
    "        f\"({100 * (finest[row].max() / estimate.max() - 1):+.1f} %)\"\n",
    "    )\n",
    "print(\n",
    "    f\"the field under the lowest point is {finest[mid].max() / finest[tower].max():.2f} times the field at the tower; \"\n",
    "    \"public reference level (ICNIRP 2010, 50 Hz): 200 µT\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The rms flux density 1 m above ground over the middle span, and the profiles across the line at\n",
    "mid-span and at the tower against the straight-line estimates."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.heatmap(\n",
    "    x_grid,\n",
    "    y_grid,\n",
    "    1e6 * finest,\n",
    "    limits=(0, 1e6 * finest.max()),\n",
    "    contours=10,\n",
    "    label=\"rms |B| 1 m above ground [µT]\",\n",
    "    xlabel=\"x along the line [m]\",\n",
    "    ylabel=\"y across the line [m]\",\n",
    "    title=\"Flux density over the span\",\n",
    "    aspect=\"auto\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"3D, mid-span\": (y_grid[::4], 1e6 * finest[mid, ::4]),\n",
    "        \"3D, at the tower\": (y_grid[::4], 1e6 * finest[tower, ::4]),\n",
    "    },\n",
    "    reference={\n",
    "        f\"straight lines at {lowest:.0f} m\": (y_grid, 1e6 * straight(lowest)),\n",
    "        f\"straight lines at {attach:.0f} m\": (y_grid, 1e6 * straight(attach)),\n",
    "    },\n",
    "    xlabel=\"y across the line [m]\",\n",
    "    ylabel=\"rms flux density 1 m above ground [µT]\",\n",
    "    title=\"Profiles across the line\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add a second circuit with reversed phase order in `power_line_magnetic_field_3d_geometry.py` to\n",
    "see the field drop away from the line, give the shield wires their induced currents, or raise\n",
    "the lowest point to find the height at which the field under the line stays below a design value."
   ]
  }
 ]
}
