{
 "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": [
    "# Surface field of a high-voltage insulator with a grading ring\n",
    "\n",
    "A composite long-rod insulator for a 110 kV line: a fibreglass core in a silicone housing\n",
    "($\\varepsilon_r=4.3$), 1 m long with 16 sheds, hangs from the grounded crossarm; its lower fitting\n",
    "carries the conductor at the peak phase voltage $V_0=\\sqrt2\\cdot110/\\sqrt3$ kV $=89.8$ kV. The\n",
    "insulator itself has almost no capacitance to the line, so the field crowds at the high-voltage\n",
    "end: the sheds next to the lower fitting take a large share of the voltage, and the surface field\n",
    "there can start corona and age the silicone. A grading ring around the high-voltage end spreads\n",
    "the field over a larger part of the insulator.\n",
    "\n",
    "At 50 Hz the field is quasi-static: $-\\nabla\\cdot(\\varepsilon\\nabla V)=0$ in the air and in the\n",
    "housing. The insulator, the ring and the fittings are rotationally symmetric, so a 30° sector is\n",
    "modelled. The air comes from `high_voltage_insulator_grading_ring.step` (with ring) and\n",
    "`high_voltage_insulator_grading_ring_no_ring.step`, with the face groups `crossarm`, `live`,\n",
    "`grounded_fitting`, `symmetry` and `outer`; the housing comes from\n",
    "`high_voltage_insulator_grading_ring_housing.step`. The script\n",
    "`high_voltage_insulator_grading_ring_geometry.py` builds them with the CAD objects of\n",
    "OneSimulation.\n",
    "\n",
    "| faces | condition |\n",
    "|---|---|\n",
    "| `live`: lower fitting (and ring) | $V=V_0$ |\n",
    "| `crossarm`, `grounded_fitting` | $V=0$ |\n",
    "| `symmetry`: the two sector planes | $\\mathbf D\\cdot\\mathbf n=0$ |\n",
    "| `outer`: wall and bottom of the air cylinder, 1.5 m away | $\\mathbf D\\cdot\\mathbf n=0$ |\n",
    "\n",
    "**Reference.** There is no closed form for the field of a shed insulator. The result is checked\n",
    "by a mesh study of the peak field along the insulator. The design\n",
    "guidance is that of CIGRE Technical Brochure 284 (*Use of corona rings to control the electrical\n",
    "field along transmission line composite insulators*, 2005): without a ring the surface field near\n",
    "the live end exceeds the corona onset of about 0.4–0.45 kV/mm in the air at the surface; the ring\n",
    "should bring it well below that."
   ]
  },
  {
   "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 VacuumPermittivity\n",
    "from onesim.meshing import LocalRefinement, TetrahedralMesher\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.electrostatics import (\n",
    "    FixedPotential,\n",
    "    PoissonEquation,\n",
    "    ZeroNormalElectricDisplacement,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation, regionwise\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",
    "`load` returns the two air regions and the housing. The housing is embedded in the mesh; the cells\n",
    "are fine on the housing and the live parts and grow towards the outer faces. The variant with the\n",
    "ring is meshed three times for a mesh study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "regions = {\n",
    "    \"with ring\": load(\"high_voltage_insulator_grading_ring.step\"),\n",
    "    \"without ring\": load(\"high_voltage_insulator_grading_ring_no_ring.step\"),\n",
    "}\n",
    "housing = load(\"high_voltage_insulator_grading_ring_housing.step\")\n",
    "sizes = (0.008, 0.0057, 0.004)\n",
    "mesher = lambda air, size: TetrahedralMesher(\n",
    "    target_size=0.25,\n",
    "    embedded_regions=(housing,),\n",
    "    refinements=(\n",
    "        LocalRefinement(region=housing, target_size=size),\n",
    "        LocalRefinement(region=air.boundaries.live, target_size=size),\n",
    "    ),\n",
    ").generate(air)\n",
    "study_meshes = [mesher(regions[\"with ring\"], size) for size in sizes]\n",
    "meshes = {\n",
    "    \"with ring\": study_meshes[1],\n",
    "    \"without ring\": mesher(regions[\"without ring\"], sizes[1]),\n",
    "}\n",
    "\n",
    "air = regions[\"with ring\"]\n",
    "fig = plots.figure(1, 3, size=(16, 7))\n",
    "plots.geometry(\n",
    "    air.section(\n",
    "        (-np.sin(np.radians(15)), np.cos(np.radians(15)), 0.0), origin=(0.0, 0.0, 0.0)\n",
    "    ),\n",
    "    labels=False,\n",
    "    title=\"Air: meridian section with fittings and ring\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.geometry(\n",
    "    [housing.named(\"silicone housing\")],\n",
    "    camera=plots.Camera(elevation=15, azimuth=-60),\n",
    "    title=\"Sector of the housing\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"with ring\"],\n",
    "    groups=(\"live\", \"grounded_fitting\", \"symmetry\"),\n",
    "    camera=plots.Camera(elevation=5, azimuth=-90),\n",
    "    title=f\"{meshes['with ring'].cell_count} tetrahedra\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`regionwise` gives the core and the sheds the permittivity of silicone. One solve per mesh."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "voltage, eps_r = np.sqrt(2) * 110e3 / np.sqrt(3), 4.3\n",
    "eps0 = float(VacuumPermittivity().evaluate())\n",
    "shed = lambda z: np.clip(np.floor((z + 0.45) / 0.06 + 0.5), 0, 15)\n",
    "in_housing = lambda points: (\n",
    "    (np.abs(points[:, 2]) < 0.5) & (np.hypot(points[:, 0], points[:, 1]) < 0.012)\n",
    ") | (\n",
    "    (np.abs(points[:, 2] - (-0.448 + 0.06 * shed(points[:, 2]))) < 0.002)\n",
    "    & (\n",
    "        np.hypot(points[:, 0], points[:, 1])\n",
    "        < np.where(shed(points[:, 2]) % 2 == 0, 0.06, 0.045)\n",
    "    )\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "\n",
    "\n",
    "def solve(air, mesh):\n",
    "    \"\"\"Potential and field with the live parts at the peak phase voltage.\"\"\"\n",
    "    model = PoissonEquation(\n",
    "        domain=air.volume,\n",
    "        charge_density=0.0,\n",
    "        permittivity=regionwise(\n",
    "            ((in_housing, eps0 * eps_r),), default=eps0, unit=\"F/m\"\n",
    "        ),\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"Insulator\",\n",
    "        geometry=air,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            FixedPotential(boundary=air.boundaries.live, physics=model, value=voltage),\n",
    "            FixedPotential(\n",
    "                boundary=air.boundaries.crossarm | air.boundaries.grounded_fitting,\n",
    "                physics=model,\n",
    "                value=0.0,\n",
    "            ),\n",
    "            ZeroNormalElectricDisplacement(\n",
    "                boundary=air.boundaries.symmetry | air.boundaries.outer, physics=model\n",
    "            ),\n",
    "        ),\n",
    "    )\n",
    "    result = Simulation(\n",
    "        problem=problem, mesh=mesh, numerics=numerics\n",
    "    ).solve_stationary()\n",
    "    return result.field(model.potential), result.field(model.electric_field)\n",
    "\n",
    "\n",
    "study = [solve(regions[\"with ring\"], mesh) for mesh in study_meshes]\n",
    "solutions = {\n",
    "    \"with ring\": study[1],\n",
    "    \"without ring\": solve(regions[\"without ring\"], meshes[\"without ring\"]),\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Field and potential along the surface of the core, 0.5 mm outside it in the air between the sheds,\n",
    "from the live fitting to the grounded one."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "z = np.linspace(-0.49, 0.49, 981)\n",
    "along = np.column_stack(\n",
    "    (\n",
    "        0.0125 * np.cos(np.radians(15)) * np.ones_like(z),\n",
    "        0.0125 * np.sin(np.radians(15)) * np.ones_like(z),\n",
    "        z,\n",
    "    )\n",
    ")\n",
    "between = np.abs(z + 0.448 - 0.06 * shed(z)) > 0.003\n",
    "strength = lambda solution: 1e-6 * np.linalg.norm(solution[1].evaluate(along), axis=1)\n",
    "peaks = [strength(solution)[between].max() for solution in study]\n",
    "print(\"cell size [mm]   tetrahedra   peak field on the core surface [kV/mm]\")\n",
    "for size, mesh, value in zip(sizes, study_meshes, peaks):\n",
    "    print(f\"{1e3 * size:14.1f} {mesh.cell_count:12d} {value:20.4f}\")\n",
    "print(\n",
    "    f\"spread over the three meshes {100 * (max(peaks) - min(peaks)) / peaks[-1]:.1f} % of the finest value\"\n",
    ")\n",
    "for label, solution in solutions.items():\n",
    "    field, potential = strength(solution), solution[0].evaluate(along).reshape(-1)\n",
    "    print(\n",
    "        f\"{label:12s}: peak {field[between].max():.3f} kV/mm at {1e3 * (z[between][np.argmax(field[between])] + 0.5):.0f} mm above the live end; \"\n",
    "        f\"lowest 100 mm of the insulator carry {100 * (1 - potential[np.argmin(np.abs(z + 0.4))] / voltage):.1f} % of the voltage\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The field strength in the meridian plane near the live end with and without the ring, and the\n",
    "field and the potential along the core."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "near_end = dict(\n",
    "    xlimits=(0.0, 0.2), ylimits=(-0.62, -0.2), xlabel=\"r [m]\", ylabel=\"z [m]\"\n",
    ")\n",
    "kv_per_mm = lambda E, position: 1e-6 * np.linalg.norm(E, axis=1)\n",
    "cut = Plane(origin=(0.0, 1e-6, 0.0), normal=(0.0, 1.0, 0.0))\n",
    "fig = plots.figure(\n",
    "    layout=[\n",
    "        [\"without ring\", \"with ring\", \"profile\"],\n",
    "        [\"without ring\", \"with ring\", \"potential\"],\n",
    "    ],\n",
    "    size=(18, 10),\n",
    ")\n",
    "for label in (\"without ring\", \"with ring\"):\n",
    "    plots.section(\n",
    "        solutions[label][1],\n",
    "        plane=cut,\n",
    "        component=kv_per_mm,\n",
    "        limits=(0, 0.6),\n",
    "        contours=13,\n",
    "        subdivisions=2,\n",
    "        label=\"|E| [kV/mm]\",\n",
    "        title=f\"Field near the live end, {label}\",\n",
    "        ax=fig[label],\n",
    "        **near_end,\n",
    "    )\n",
    "plots.line(\n",
    "    1e3 * (z + 0.5),\n",
    "    {\n",
    "        label: np.where(between, strength(solution), np.nan)\n",
    "        for label, solution in solutions.items()\n",
    "    },\n",
    "    hlines={\"corona onset, about 0.45 kV/mm\": 0.45},\n",
    "    xlimits=(0, 1000),\n",
    "    xlabel=\"distance from the live end [mm]\",\n",
    "    ylabel=\"|E| at the core surface [kV/mm]\",\n",
    "    title=\"Field along the insulator\",\n",
    "    ax=fig[\"profile\"],\n",
    ")\n",
    "plots.line(\n",
    "    1e3 * (z + 0.5),\n",
    "    {\n",
    "        label: 1e-3 * solution[0].evaluate(along).reshape(-1)\n",
    "        for label, solution in solutions.items()\n",
    "    },\n",
    "    reference={\"uniform grading\": 1e-3 * voltage * (0.5 - z)},\n",
    "    xlabel=\"distance from the live end [mm]\",\n",
    "    ylabel=\"potential [kV]\",\n",
    "    title=\"Potential along the insulator\",\n",
    "    ax=fig[\"potential\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Move the ring up or down, or change its tube radius in\n",
    "`high_voltage_insulator_grading_ring_geometry.py` and write the STEP files again: too low and it\n",
    "leaves the first sheds unshielded, too high and its own surface field rises. A second, smaller\n",
    "ring at the crossarm end evens out the grounded side."
   ]
  }
 ]
}
