{
 "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": [
    "# Heating of buried power cables\n",
    "\n",
    "Three single-core cables of a 132 kV circuit lie in flat formation, 1 m deep and 0.3 m apart.\n",
    "Each cable has a copper conductor (1000 mm²), an XLPE insulation, a lead sheath and a\n",
    "polyethylene jacket. The conductors carry 1200 A. The ground surface and the deep ground are at\n",
    "20 °C. The cables are long, so the temperature varies only over the cross-section:\n",
    "\n",
    "$$-\\nabla\\cdot\\big(k\\,\\nabla T\\big)=q,\\qquad q=\\frac{W}{A_c}\\ \\text{in each conductor}.$$\n",
    "\n",
    "The conductivity $k$ jumps by three orders of magnitude between copper and XLPE. The cables heat\n",
    "each other, so the middle one runs hottest.\n",
    "\n",
    "| layer | outer radius | thermal conductivity |\n",
    "|---|---|---|\n",
    "| copper conductor | 19.0 mm | 400 W/(m K) |\n",
    "| XLPE insulation | 35.0 mm | 1/3.5 W/(m K) |\n",
    "| lead sheath | 37.5 mm | 35 W/(m K) |\n",
    "| PE jacket | 41.5 mm | 1/3.5 W/(m K) |\n",
    "| soil | - | 1.0 W/(m K) |\n",
    "\n",
    "**Loss.** IEC 60287-1-1 gives the conductor an AC resistance of 25.8 µΩ/m at its 90 °C limit, so\n",
    "each cable releases $W=I^2R'_{ac}=37.1$ W per metre.\n",
    "\n",
    "The soil block (80 m wide, 40 m deep) comes from the CAD file `buried_cables_heating.step` with\n",
    "the faces `surface`, `bottom` and `sides`; the files `buried_cables_heating_conductor.step`,\n",
    "`..._insulation.step`, `..._sheath.step` and `..._jacket.step` hold the layers of the three\n",
    "cables. The script `buried_cables_heating_geometry.py` builds all of them with the CAD objects of\n",
    "OneSimulation. The model is their cross-section."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "from dataclasses import replace\n",
    "\n",
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import (\n",
    "    Geometric,\n",
    "    disc_blocks,\n",
    "    explicit_mesh,\n",
    "    merge_blocks,\n",
    "    o_grid,\n",
    "    rectangle_block,\n",
    ")\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.heat_transfer import FixedTemperature, HeatConduction, HeatFlux\n",
    "from onesim.simulation import Problem, Simulation, regionwise\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()\n",
    "\n",
    "ground = load(\"buried_cables_heating.step\")\n",
    "plane = dict(normal=(0, 0, 1), origin=(0, 0, ground.size[2] / 2))\n",
    "layers = {\n",
    "    name: load(f\"buried_cables_heating_{name}.step\")\n",
    "    for name in (\"conductor\", \"insulation\", \"sheath\", \"jacket\")\n",
    "}\n",
    "regions = {name: layer.sections(**plane) for name, layer in layers.items()}\n",
    "radii = (0.019, 0.035, 0.0375, 0.0415)\n",
    "conductivities = (400.0, 1 / 3.5, 35.0, 1 / 3.5)\n",
    "soil, depth, spacing, half_width = 1.0, 1.0, 0.3, ground.size[0] / 2\n",
    "centres = ((-spacing, -depth), (0.0, -depth), (spacing, -depth))\n",
    "surface_temperature, loss = 20.0, 1200.0**2 * 25.795e-6"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reference: the IEC 60287 thermal circuit\n",
    "\n",
    "The standard replaces the field by thermal resistances per metre: insulation\n",
    "$T_1=\\frac{\\rho_1}{2\\pi}\\ln\\frac{r_i}{r_c}$, jacket $T_3=\\frac{\\rho_3}{2\\pi}\\ln\\frac{r_e}{r_s}$ and\n",
    "soil $T_4=\\frac{\\rho_4}{2\\pi}\\ln\\big(u+\\sqrt{u^2-1}\\big)$ with $u=L/r_e$. A neighbour at the\n",
    "distance $d$ adds $\\frac{\\rho_4}{2\\pi}\\ln\\frac{d'}{d}$, where $d'$ is the distance to its mirror\n",
    "image above the ground surface (Neher and McGrath, 1957)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "r_c, r_i, r_s, r_e = radii\n",
    "neighbour = lambda d: np.log(np.hypot(d, 2 * depth) / d) / (2 * np.pi * soil)\n",
    "circuit = surface_temperature + loss * (\n",
    "    3.5 / (2 * np.pi) * (np.log(r_i / r_c) + np.log(r_e / r_s))\n",
    "    + np.log(depth / r_e + np.sqrt((depth / r_e) ** 2 - 1)) / (2 * np.pi * soil)\n",
    "    + np.array(\n",
    "        [\n",
    "            neighbour(spacing) + neighbour(2 * spacing),\n",
    "            2 * neighbour(spacing),\n",
    "            neighbour(spacing) + neighbour(2 * spacing),\n",
    "        ]\n",
    "    )\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "Blocks with straight and circular sides cover the cross-section of the soil block: `disc_blocks`\n",
    "gives each cable rings with a node line on every layer interface, `o_grid` continues them to a\n",
    "square of side 0.3 m, and eight graded rectangles fill the soil around the three squares.\n",
    "`merge_blocks` joins them, every quadrilateral is split into two triangles, and `explicit_mesh`\n",
    "hands the triangles to the cross-section of the soil block, whose sides are named `x_min` ...\n",
    "`y_max` (the ground surface is `y_max`)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "section = ground.section(**plane)\n",
    "rings = lambda n: round(3 * n / 4)\n",
    "count = lambda length, n: max(\n",
    "    3,\n",
    "    int(\n",
    "        np.ceil(\n",
    "            np.log(1 + length * (2.0 ** (4 / n) - 1) * n / spacing)\n",
    "            / np.log(2.0 ** (4 / n))\n",
    "        )\n",
    "    ),\n",
    ")\n",
    "xs = (\n",
    "    (-half_width, half_width - 1.5 * spacing, \"end\"),\n",
    "    (-1.5 * spacing, 3 * spacing, None),\n",
    "    (1.5 * spacing, half_width - 1.5 * spacing, \"start\"),\n",
    ")\n",
    "ys = (\n",
    "    (-half_width, half_width - depth - spacing / 2, \"end\"),\n",
    "    (-depth - spacing / 2, spacing, None),\n",
    "    (-depth + spacing / 2, depth - spacing / 2, \"start\"),\n",
    ")\n",
    "blocks = lambda n: [\n",
    "    block\n",
    "    for centre in centres\n",
    "    for block in (\n",
    "        *disc_blocks(centre, radii, n, (round(3 * n / 8), rings(n), 2, 2)),\n",
    "        *o_grid(\n",
    "            centre,\n",
    "            radii[-1],\n",
    "            spacing / 2,\n",
    "            n,\n",
    "            rings(n),\n",
    "            inner_name=None,\n",
    "            radial_grading=Geometric(rings(n), first=0.35 / rings(n)),\n",
    "        ),\n",
    "    )\n",
    "] + [\n",
    "    rectangle_block(\n",
    "        (x0, y0),\n",
    "        lx,\n",
    "        ly,\n",
    "        (count(lx, n) if x_toward else 3 * n, count(ly, n) if y_toward else n),\n",
    "        (\n",
    "            x_toward and Geometric(count(lx, n), first=spacing / n, toward=x_toward),\n",
    "            y_toward and Geometric(count(ly, n), first=spacing / n, toward=y_toward),\n",
    "        ),\n",
    "    )\n",
    "    for i, (x0, lx, x_toward) in enumerate(xs)\n",
    "    for j, (y0, ly, y_toward) in enumerate(ys)\n",
    "    if (i, j) != (1, 1)\n",
    "]\n",
    "planar = {n: merge_blocks(blocks(n)).triangulated() for n in (8, 12, 16)}\n",
    "meshes = {\n",
    "    n: explicit_mesh(section, mesh.coordinates, mesh.cells)\n",
    "    for n, mesh in planar.items()\n",
    "}\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.geometry(\n",
    "    [layer.named(name) for name, layer in layers.items()],\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=30, azimuth=-60),\n",
    "    title=\"Conductor, insulation, sheath and jacket of the three cables\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[12],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Cross-section of the soil block: {meshes[12].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Conductivity and heat source are given region by region through the cross-sections of the cable\n",
    "layers (`sections` returns the three pieces of each layer); the soil is the default. The ground surface and the bottom are held at 20 °C, the sides\n",
    "are insulated. Quadratic elements on all three meshes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "conductivity = regionwise(\n",
    "    tuple(\n",
    "        (piece, k)\n",
    "        for pieces, k in zip(regions.values(), conductivities)\n",
    "        for piece in pieces\n",
    "    ),\n",
    "    default=soil,\n",
    "    unit=\"W/m/K\",\n",
    ")\n",
    "heating = regionwise(\n",
    "    tuple((piece, loss / (np.pi * radii[0] ** 2)) for piece in regions[\"conductor\"]),\n",
    "    default=0.0,\n",
    "    unit=\"W/m^3\",\n",
    ")\n",
    "material = replace(\n",
    "    IsotropicSolid(\n",
    "        density=1000.0,\n",
    "        specific_heat_capacity=1000.0,\n",
    "        thermal_conductivity=1.0,\n",
    "        youngs_modulus=1e9,\n",
    "        poisson_ratio=0.3,\n",
    "        thermal_expansion_coefficient=0.0,\n",
    "    ),\n",
    "    thermal_conductivity=conductivity,\n",
    ")\n",
    "\n",
    "\n",
    "faces = section.boundaries\n",
    "model = HeatConduction(domain=section.domain(), material=material, heating=heating)\n",
    "problem = Problem(\n",
    "    name=\"Buried cables\",\n",
    "    geometry=section,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        FixedTemperature(\n",
    "            boundary=faces.y_max | faces.y_min, physics=model, value=surface_temperature\n",
    "        ),\n",
    "        HeatFlux(boundary=faces.x_min | faces.x_max, physics=model, value=0.0),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "results = [\n",
    "    Simulation(problem=problem, mesh=mesh, numerics=numerics).solve_stationary()\n",
    "    for mesh in meshes.values()\n",
    "]\n",
    "runs = [\n",
    "    (result.field(model.temperature), result.field(model.heat_flux), mesh)\n",
    "    for result, mesh in zip(results, meshes.values())\n",
    "]\n",
    "temperature, heat_flux, mesh = runs[-1]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Conductor temperatures on the three meshes, taken at the centre of each conductor (the copper is\n",
    "isothermal to a few millikelvin), against the thermal circuit. The circuit treats\n",
    "every neighbour as a line source in uniform soil, so a difference of a few hundredths of a kelvin\n",
    "remains."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "conductors = np.array([T.evaluate(np.array(centres)).ravel() for T, _, _ in runs])\n",
    "print(\"triangles     left    middle     right   [°C]\")\n",
    "for (_, _, m), values in zip(runs, conductors):\n",
    "    print(f\"{m.cell_count:9d} \" + \" \".join(f\"{value:9.4f}\" for value in values))\n",
    "print(\"IEC       \" + \" \".join(f\"{value:9.4f}\" for value in circuit))\n",
    "print(\n",
    "    \"difference on the finest mesh [K]: \"\n",
    "    + \", \".join(f\"{value:+.3f}\" for value in conductors[-1] - circuit)\n",
    ")\n",
    "leaving = temperature.boundary_flux(faces.y_max) + temperature.boundary_flux(\n",
    "    faces.y_min\n",
    ")\n",
    "print(f\"energy balance: generated {3 * loss:.3f} W/m, leaving {leaving:.3f} W/m\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The temperature of the cross-section, the middle cable with its mesh, the heat flux through the\n",
    "ground surface against the line-source formula $q(x)=\\sum_n W L/[\\pi((x-x_n)^2+L^2)]$, and the\n",
    "mesh study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x = np.linspace(-3, 3, 241)\n",
    "surface_flux = heat_flux.evaluate(np.column_stack((x, np.zeros_like(x))))[:, 1]\n",
    "line_sources = sum(\n",
    "    loss * depth / (np.pi * ((x - cx) ** 2 + depth**2)) for cx, _ in centres\n",
    ")\n",
    "peak = float(temperature.values.max())\n",
    "\n",
    "fig = plots.figure(2, 2, size=(14, 10))\n",
    "plots.surface(\n",
    "    temperature,\n",
    "    limits=(surface_temperature, peak),\n",
    "    contours=12,\n",
    "    subdivisions=2,\n",
    "    label=\"T [°C]\",\n",
    "    title=\"Temperature of the cross-section\",\n",
    "    xlimits=(-1.2, 1.2),\n",
    "    ylimits=(-2.0, 0.0),\n",
    "    ylabel=\"y [m] (ground surface at y = 0)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.surface(\n",
    "    temperature,\n",
    "    limits=(peak - 30, peak),\n",
    "    contours=12,\n",
    "    edges=True,\n",
    "    subdivisions=1,\n",
    "    label=\"T [°C]\",\n",
    "    title=\"Middle cable and its mesh\",\n",
    "    xlimits=(-0.07, 0.07),\n",
    "    ylimits=(-depth - 0.07, -depth + 0.07),\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    x,\n",
    "    {\"finite elements\": surface_flux},\n",
    "    reference={\"line sources and images\": line_sources},\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"heat flux out of the ground [W/m²]\",\n",
    "    title=\"Heat flux through the ground surface\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    [m.cell_count for _, _, m in runs],\n",
    "    {\n",
    "        \"outer conductors\": conductors[:, 0] - circuit[0],\n",
    "        \"middle conductor\": conductors[:, 1] - circuit[1],\n",
    "    },\n",
    "    hlines={\"IEC 60287\": 0.0},\n",
    "    markers=True,\n",
    "    xlabel=\"number of triangles\",\n",
    "    ylabel=\"finite elements - IEC 60287 [K]\",\n",
    "    title=\"Mesh study\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the current until the middle conductor reaches the 90 °C limit of XLPE: that is the rated\n",
    "current of the circuit. Put the cables into a trench with a better-conducting backfill, or make\n",
    "the soil conductivity temperature-dependent to model the drying of the soil around hot cables."
   ]
  }
 ]
}
