{
 "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": [
    "# AC resistance and sheath losses of a three-core power cable\n",
    "\n",
    "A submarine HVAC cable carries three phases in one jacket: copper conductors of 500 mm² (radius\n",
    "12.6 mm) insulated with XLPE, each core in a lead sheath (45 to 48 mm radius), the cores touching in a\n",
    "triangle with centre spacing $s=101$ mm. At 50 Hz the skin depth of copper (about 10 mm) is\n",
    "comparable with the conductor radius, so the current crowds towards the surface (skin effect) and\n",
    "towards the sides away from the neighbours (proximity effect); both raise the resistance above its\n",
    "DC value. The magnetic field of the phases also drives currents in the sheaths, which are bonded\n",
    "to each other and to earth at both ends of the cable and therefore carry circulating currents.\n",
    "\n",
    "OneSimulation solves the 2D eddy-current problem $\\nabla\\times(\\mu_0^{-1}\\nabla\\times A_z)+\n",
    "\\mathrm j\\omega\\sigma A_z=J_z$ with `EddyCurrents`: the conductors are massive coils carrying the\n",
    "balanced currents $\\hat I e^{-\\mathrm j2\\pi k/3}$, $\\hat I=1000$ A; the sheaths are massive\n",
    "conductors with zero voltage per unit length (bonded at both ends).\n",
    "\n",
    "| region | conductivity |\n",
    "|---|---|\n",
    "| copper at 90 °C | 45.5 MS/m |\n",
    "| lead at 80 °C | 3.77 MS/m |\n",
    "| insulation, filler, surroundings | 0 |\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| outer circle, $r=400$ mm | magnetic insulation, $A_z=0$ |\n",
    "\n",
    "The surroundings come from `three_core_cable_ac_losses.step`, the conductors and sheaths from one\n",
    "file each, `three_core_cable_ac_losses_conductor_a.step` to `..._sheath_c.step`; the script\n",
    "`three_core_cable_ac_losses_geometry.py` builds them with the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference** (IEC 60287-1-1:2006, §2.1.2 and §2.3.3; Anders, *Rating of Electric Power Cables*,\n",
    "1997, ch. 6). With the DC resistance $R'$ per metre and $x^2=8\\pi f\\cdot10^{-7}/R'$:\n",
    "\n",
    "$$y_s=\\frac{x^4}{192+0.8x^4},\\qquad\n",
    "  y_p=\\frac{x^4}{192+0.8x^4}\\Big(\\frac{d_c}{s}\\Big)^2\\Big[0.312\\Big(\\frac{d_c}{s}\\Big)^2+\\frac{1.18}{\\frac{x^4}{192+0.8x^4}+0.27}\\Big],\\qquad\n",
    "  R_\\mathrm{ac}=R'(1+y_s+y_p),$$\n",
    "\n",
    "and for sheaths bonded at both ends, with the sheath resistance $R_s$ per metre, the mean sheath\n",
    "diameter $d$ and $X=2\\omega\\cdot10^{-7}\\ln(2s/d)$, the loss factor\n",
    "$\\lambda_1=\\dfrac{R_s}{R_\\mathrm{ac}}\\,\\dfrac{1}{1+(R_s/X)^2}$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import VacuumPermeability, regionwise\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 ComplexSparseDirect\n",
    "from onesim.physics.magnetostatics import (\n",
    "    Coil,\n",
    "    EddyCurrents,\n",
    "    MagneticInsulation,\n",
    "    joule_losses,\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 plates at mid-depth. Quadratic triangles of 1.5 mm in the conductors (seven per\n",
    "skin depth), 1 mm in the sheaths and up to 40 mm far away; a second mesh with half the sizes in the\n",
    "metal checks the losses."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plates = {\"surroundings\": load(\"three_core_cable_ac_losses.step\")} | {\n",
    "    f\"{kind} {k}\": load(f\"three_core_cable_ac_losses_{kind}_{k}.step\")\n",
    "    for kind in (\"conductor\", \"sheath\")\n",
    "    for k in \"abc\"\n",
    "}\n",
    "cut = lambda part: part.section((0, 0, 1), origin=(0, 0, 0.001))\n",
    "disc = cut(plates[\"surroundings\"])\n",
    "regions = {\n",
    "    name: cut(part).named(name.replace(\" \", \"_\"))\n",
    "    for name, part in plates.items()\n",
    "    if name != \"surroundings\"\n",
    "}\n",
    "meshes = {\n",
    "    scale: TriangularMesher(\n",
    "        target_size=0.04,\n",
    "        embedded_regions=tuple(regions.values()),\n",
    "        grading=0.25,\n",
    "        region_sizes={\n",
    "            region: (0.0015 if \"conductor\" in name else 0.001) * scale\n",
    "            for name, region in regions.items()\n",
    "        },\n",
    "    ).generate(disc)\n",
    "    for scale in (1.0, 0.5)\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6.5))\n",
    "plots.geometry(\n",
    "    [part.named(name) for name, part in plates.items() if name != \"surroundings\"],\n",
    "    camera=plots.Camera(elevation=60, azimuth=-90),\n",
    "    title=\"Conductors and lead sheaths (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[1.0],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"{meshes[1.0].cell_count} quadratic triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Massive coils for the three phases and the three sheaths; the conductivity is given region by\n",
    "region."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "current, frequency = 1000.0, 50.0\n",
    "sigma = regionwise(\n",
    "    tuple(\n",
    "        (region, 4.55e7 if \"conductor\" in name else 3.77e6)\n",
    "        for name, region in regions.items()\n",
    "    ),\n",
    "    default=0.0,\n",
    "    unit=\"S/m\",\n",
    ")\n",
    "coils = tuple(\n",
    "    Coil(\n",
    "        regions[f\"conductor {k}\"],\n",
    "        conductor=\"massive\",\n",
    "        current=current * np.exp(-2j * np.pi * n / 3),\n",
    "    )\n",
    "    for n, k in enumerate(\"abc\")\n",
    ") + tuple(Coil(regions[f\"sheath {k}\"], conductor=\"massive\", voltage=0.0) for k in \"abc\")\n",
    "solve = lambda mesh: (\n",
    "    lambda m: (\n",
    "        Simulation(\n",
    "            problem=Problem(\n",
    "                name=\"Three-core cable\",\n",
    "                geometry=disc,\n",
    "                physics=(m,),\n",
    "                boundary_conditions=(\n",
    "                    MagneticInsulation(boundary=disc.boundaries.all, physics=m),\n",
    "                ),\n",
    "            ),\n",
    "            mesh=mesh,\n",
    "            numerics=Numerics(\n",
    "                spatial=FiniteElement(element=Lagrange(order=2), quadrature_order=4),\n",
    "                linear_solver=ComplexSparseDirect(),\n",
    "            ),\n",
    "        ).solve_stationary(),\n",
    "        m,\n",
    "    )\n",
    ")(\n",
    "    EddyCurrents(\n",
    "        domain=disc.domain(),\n",
    "        permeability=VacuumPermeability(),\n",
    "        conductivity=sigma,\n",
    "        frequency=frequency,\n",
    "        coils=coils,\n",
    "    )\n",
    ")\n",
    "runs = {scale: solve(mesh) for scale, mesh in meshes.items()}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The conductor losses give the AC resistance per phase, $R_\\mathrm{ac}=P_c/(3\\hat I^2/2)$; the\n",
    "sheath losses give the loss factor $\\lambda_1=P_s/P_c$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "area, sheath_area = np.pi * 0.0126**2, np.pi * (0.048**2 - 0.045**2)\n",
    "dc = 1 / (4.55e7 * area)\n",
    "rs = 1 / (3.77e6 * sheath_area)\n",
    "x4 = (8 * np.pi * frequency * 1e-7 / dc) ** 2\n",
    "f4 = x4 / (192 + 0.8 * x4)\n",
    "ys, yp = f4, f4 * (0.0252 / 0.101) ** 2 * (\n",
    "    0.312 * (0.0252 / 0.101) ** 2 + 1.18 / (f4 + 0.27)\n",
    ")\n",
    "rac_iec = dc * (1 + ys + yp)\n",
    "reactance = 2 * 2 * np.pi * frequency * 1e-7 * np.log(2 * 0.101 / 0.0930)\n",
    "lambda_iec = rs / rac_iec / (1 + (rs / reactance) ** 2)\n",
    "print(\n",
    "    f\"DC resistance R' = {1e6 * dc:.3f} uOhm/m; IEC 60287: y_s = {ys:.4f}, y_p = {yp:.4f}, R_ac = {1e6 * rac_iec:.3f} uOhm/m; sheath loss factor {lambda_iec:.4f}\"\n",
    ")\n",
    "print(\n",
    "    \"mesh                 conductor losses [W/m]   R_ac [uOhm/m]   R_ac / R'   sheath losses [W/m]   loss factor lambda_1\"\n",
    ")\n",
    "for scale, (result, m) in runs.items():\n",
    "    conductor_loss = sum(\n",
    "        joule_losses(result, m, regions[f\"conductor {k}\"]) for k in \"abc\"\n",
    "    )\n",
    "    sheath_loss = sum(joule_losses(result, m, regions[f\"sheath {k}\"]) for k in \"abc\")\n",
    "    rac = conductor_loss / (3 * current**2 / 2)\n",
    "    print(\n",
    "        f\"{'coarse' if scale == 1.0 else 'fine':8s} {meshes[scale].cell_count:7d} cells {conductor_loss:18.3f} {1e6 * rac:15.3f} {rac / dc:11.4f} {sheath_loss:19.3f} {sheath_loss / conductor_loss:20.4f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"fine mesh against IEC 60287: R_ac {rac / rac_iec - 1:+.1%}, loss factor {sheath_loss / conductor_loss / lambda_iec - 1:+.1%}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The magnitude of the current density at the instant of the peak current in phase a, on the fine\n",
    "mesh: the current crowds to the outer sides of the conductors, and the sheaths carry the induced\n",
    "circulating currents."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "result, m = runs[0.5]\n",
    "x, y = np.asarray(meshes[0.5].coordinates).T\n",
    "values = (\n",
    "    np.abs(result.field(m.current_density).evaluate(np.column_stack((x, y)))[:, 2])\n",
    "    / 1e6\n",
    ")\n",
    "fig = plots.figure(1, 2, size=(16, 6.5))\n",
    "plots.heatmap(\n",
    "    1e3 * x,\n",
    "    1e3 * y,\n",
    "    values,\n",
    "    triangles=np.asarray(meshes[0.5].cells),\n",
    "    limits=(0, np.percentile(values, 99.9)),\n",
    "    label=\"|J_z| [A/mm^2]\",\n",
    "    xlimits=(-110, 110),\n",
    "    ylimits=(-95, 120),\n",
    "    xlabel=\"x [mm]\",\n",
    "    ylabel=\"y [mm]\",\n",
    "    title=\"Current density, both-ends bonded sheaths\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "radii = np.linspace(-0.0125, 0.0125, 101)\n",
    "centre = np.array((0.0, 0.101 / np.sqrt(3)))\n",
    "plots.line(\n",
    "    1e3 * radii,\n",
    "    {\n",
    "        \"across conductor a, towards the cable axis\": np.abs(\n",
    "            result.field(m.current_density).evaluate(\n",
    "                centre + np.column_stack((0 * radii, radii))\n",
    "            )[:, 2]\n",
    "        )\n",
    "        / 1e6\n",
    "    },\n",
    "    hlines={\"DC current density\": current / area / 1e6},\n",
    "    ylimits=(0, None),\n",
    "    xlabel=\"position across the conductor [mm]\",\n",
    "    ylabel=\"|J_z| [A/mm^2]\",\n",
    "    title=\"Skin and proximity effect in conductor a\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Replace `voltage=0.0` by `current=0.0` for the sheaths to bond them at one end only: the circulating\n",
    "currents vanish and only the much smaller eddy-current losses remain. Adding the steel wire armour\n",
    "with a permeability and conductivity of its own raises both conductor and sheath losses."
   ]
  }
 ]
}
