{
 "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": [
    "# Position optimisation of grading rings on an insulator\n",
    "\n",
    "A rod insulator of length $L=1$ m and radius 4 cm (silicone rubber, $\\varepsilon_r=4.3$) carries\n",
    "a metal end fitting at each end: the upper one at the peak phase voltage $V_0=100$ kV, the lower\n",
    "one grounded. Without any field control, the field on the insulator surface peaks next to the\n",
    "fittings. Grading rings (torus, ring radius 15 cm, tube radius 2 cm) at the potential of the\n",
    "neighbouring fitting take over part of the charge and lower that peak. Their distance $s$ from the\n",
    "end of the rod is the design parameter: the surface field is lowest for one position, and with it\n",
    "the risk of flashover.\n",
    "\n",
    "The insulator and the rings are rotationally symmetric, so the potential satisfies\n",
    "\n",
    "$$\\frac1r\\frac{\\partial}{\\partial r}\\Bigl(r\\,\\varepsilon\\frac{\\partial V}{\\partial r}\\Bigr)\n",
    "  +\\frac{\\partial}{\\partial z}\\Bigl(\\varepsilon\\frac{\\partial V}{\\partial z}\\Bigr)=0$$\n",
    "\n",
    "in the meridian plane $(r,z)$, solved with quadratic elements and the axisymmetric measure\n",
    "$2\\pi r\\,dr\\,dz$.\n",
    "\n",
    "Half of the air around the insulator, with the fittings and rings cut out, comes from the CAD file\n",
    "`grading_ring_position_optimisation.step` ($s=10$ cm) and from one file for each other ring\n",
    "position, `..._00cm.step` to `..._30cm.step`; the rod is `grading_ring_position_optimisation_rod.step`.\n",
    "The script `grading_ring_position_optimisation_geometry.py` builds them with the CAD objects of\n",
    "OneSimulation.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| upper fitting and ring (`hv.*`) | $V=V_0$ |\n",
    "| lower fitting and ring (`ground.*`) | $V=0$ |\n",
    "| outer faces of the air (`air.*`) | $D_n=0$ |\n",
    "| axis $r=0$ (`part.x_min`) | symmetry, $D_n=0$ |\n",
    "\n",
    "**Reference.** There is no closed form for the optimum; it is the minimum of the computed surface\n",
    "field over the ring distance (Kuffel, Zaengl and Kuffel, *High Voltage Engineering:\n",
    "Fundamentals*, 2nd ed., Ch. 4 on field control; IEC/TS 60815). The computation is checked by a\n",
    "mesh study of the surface field at the optimum and by the charge balance: without any charge\n",
    "leaving through the outer faces, the charge on the high-voltage electrodes must equal minus the\n",
    "charge on the grounded ones."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import VacuumPermittivity\n",
    "from onesim.meshing import TriangularMesher, joined\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange, RevolvedH1SpaceFactory\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",
    "`section` with the plane $y=0$ returns the meridian half-plane of each solid. The air with the rod\n",
    "cut out and the rod itself are meshed with triangles that match on the rod surface and joined into\n",
    "one mesh, which carries the edge names of both: the ends of the rod (`top`, `bottom`) touch the\n",
    "fittings. The cells are 5 mm on the rod surface and on the conductors and grow with the distance."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "offsets = (0.0, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30)\n",
    "solids = {\n",
    "    s: load(\n",
    "        \"grading_ring_position_optimisation.step\"\n",
    "        if s == 0.10\n",
    "        else f\"grading_ring_position_optimisation_{round(100 * s):02d}cm.step\"\n",
    "    )\n",
    "    for s in offsets\n",
    "}\n",
    "rod = load(\"grading_ring_position_optimisation_rod.step\").section((0, 1, 0))\n",
    "planes = {s: solid.section((0, 1, 0)) for s, solid in solids.items()}\n",
    "rod_radius, length = rod.size[:2]\n",
    "selections = {\n",
    "    s: {edge.id: plane.boundaries[edge.id] for edge in plane.edges}\n",
    "    for s, plane in planes.items()\n",
    "}\n",
    "edges = lambda s, prefix: [name for name in selections[s] if name.startswith(prefix)]\n",
    "mesh_for = lambda s, h: joined(\n",
    "    [\n",
    "        TriangularMesher(\n",
    "            target_size=0.3,\n",
    "            grading=0.2,\n",
    "            hard_sizes={\"cut.outer_wall\": h},\n",
    "            local_sizes={edge: h for edge in edges(s, \"hv.\") + edges(s, \"ground.\")},\n",
    "        ).generate(planes[s] - rod),\n",
    "        TriangularMesher(target_size=2 * h, hard_sizes={\"outer_wall\": h}).generate(rod),\n",
    "    ],\n",
    "    geometry=planes[s],\n",
    ")\n",
    "meshes = {s: mesh_for(s, 0.005) for s in offsets}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6.5))\n",
    "plots.geometry(\n",
    "    [\n",
    "        solids[0.10].named(\"air\"),\n",
    "        load(\"grading_ring_position_optimisation_rod.step\").named(\"insulator\"),\n",
    "    ],\n",
    "    camera=plots.Camera(elevation=20, azimuth=-60),\n",
    "    title=\"Half of the air around the insulator\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0.10],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Meridian plane, {meshes[0.10].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`RevolvedH1SpaceFactory` makes the quadratic Lagrange space of the meridian plane axisymmetric.\n",
    "The permittivity is $4.3\\,\\varepsilon_0$ in the rod and $\\varepsilon_0$ in the air. Each ring\n",
    "position is one simulation; the position of 10 cm is also solved on two coarser meshes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "voltage, eps_r = 100e3, 4.3\n",
    "eps0 = float(VacuumPermittivity().evaluate())\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2), provider=RevolvedH1SpaceFactory()),\n",
    "    linear_solver=SparseDirect(),\n",
    ")\n",
    "runs = [(s, meshes[s]) for s in offsets] + [\n",
    "    (0.10, mesh_for(0.10, h)) for h in (0.020, 0.010)\n",
    "]\n",
    "models = [\n",
    "    PoissonEquation(\n",
    "        domain=planes[s].domain(),\n",
    "        permittivity=regionwise(((rod, eps_r * eps0),), default=eps0, unit=\"F/m\"),\n",
    "        charge_density=0.0,\n",
    "    )\n",
    "    for s, mesh in runs\n",
    "]\n",
    "results = [\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Grading rings\",\n",
    "            geometry=planes[s],\n",
    "            physics=(model,),\n",
    "            boundary_conditions=(\n",
    "                *(\n",
    "                    FixedPotential(\n",
    "                        boundary=selections[s][edge], physics=model, value=voltage\n",
    "                    )\n",
    "                    for edge in edges(s, \"hv.\")\n",
    "                ),\n",
    "                *(\n",
    "                    FixedPotential(\n",
    "                        boundary=selections[s][edge], physics=model, value=0.0\n",
    "                    )\n",
    "                    for edge in edges(s, \"ground.\")\n",
    "                ),\n",
    "                *(\n",
    "                    ZeroNormalElectricDisplacement(\n",
    "                        boundary=selections[s][edge], physics=model\n",
    "                    )\n",
    "                    for edge in edges(s, \"air.\") + edges(s, \"part.\")\n",
    "                ),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=mesh,\n",
    "        numerics=numerics,\n",
    "    ).solve_stationary()\n",
    "    for model, (s, mesh) in zip(models, runs)\n",
    "]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The design value is the largest field on the insulator surface, read just outside the rod and\n",
    "leaving out 1 cm next to each fitting, where the junction of metal, insulator and air makes the\n",
    "field singular. A parabola through the three best positions gives the optimum."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "z = np.linspace(0.01, length - 0.01, 393)\n",
    "surface = np.column_stack((np.full_like(z, rod_radius + 1e-6), z))\n",
    "profiles = [\n",
    "    np.linalg.norm(result.field(model.electric_field).evaluate(surface), axis=1)\n",
    "    for model, result in zip(models, results)\n",
    "]\n",
    "peaks = np.array([profile.max() for profile in profiles[: len(offsets)]])\n",
    "best = np.clip(np.argmin(peaks), 1, len(offsets) - 2)\n",
    "curve = np.polyfit(offsets[best - 1 : best + 2], peaks[best - 1 : best + 2], 2)\n",
    "optimum = -curve[1] / (2 * curve[0])\n",
    "print(\"ring distance s   largest surface field [kV/cm]\")\n",
    "for s, peak in zip(offsets, peaks):\n",
    "    print(f\"{100 * s:13.0f} cm {peak / 1e5:20.3f}\")\n",
    "print(\n",
    "    f\"optimum ring distance {100 * optimum:.1f} cm with {np.polyval(curve, optimum) / 1e5:.3f} kV/cm; \"\n",
    "    f\"rings at the ends (s = 0): {peaks[0] / 1e5:.3f} kV/cm, uniform field V0/L = {voltage / length / 1e5:.3f} kV/cm\"\n",
    ")\n",
    "\n",
    "study = [profiles[-2].max(), profiles[-1].max(), profiles[2].max()]\n",
    "print(\n",
    "    f\"mesh study at s = 10 cm (20, 10, 5 mm on the rod): {', '.join(f'{v / 1e5:.4f}' for v in study)} kV/cm; \"\n",
    "    f\"change between the two finest meshes {100 * (study[2] / study[1] - 1):+.3f} %\"\n",
    ")\n",
    "for (s, mesh), model, result in list(zip(runs, models, results))[: len(offsets) : 3]:\n",
    "    potential = result.field(model.potential)\n",
    "    high = sum(potential.reaction(selections[s][edge]) for edge in edges(s, \"hv.\"))\n",
    "    low = sum(potential.reaction(selections[s][edge]) for edge in edges(s, \"ground.\"))\n",
    "    print(\n",
    "        f\"s = {100 * s:4.0f} cm: charge on the high-voltage side {1e9 * high:.4f} nC, on the grounded side {1e9 * low:.4f} nC, \"\n",
    "        f\"balance {(high + low) / high:+.1e}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The field strength around the upper end at the optimum, the surface field along the rod for\n",
    "three ring positions, and the largest surface field against the ring distance."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = np.linspace(offsets[best - 1], offsets[best + 1], 100)\n",
    "index = int(np.argmin(np.abs(np.array(offsets) - optimum)))\n",
    "fig = plots.figure(layout=[[\"map\", \"profile\"], [\"map\", \"sweep\"]], size=(15, 10))\n",
    "plots.surface(\n",
    "    results[index].field(models[index].electric_field),\n",
    "    component=lambda E, position: np.linalg.norm(E[:, :2], axis=1) / 1e5,\n",
    "    limits=(0, 4),\n",
    "    contours=17,\n",
    "    subdivisions=2,\n",
    "    label=\"|E| [kV/cm]\",\n",
    "    xlimits=(0, 0.35),\n",
    "    ylimits=(0.55, 1.2),\n",
    "    xlabel=\"r [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    title=f\"Field near the high-voltage end, s = {100 * offsets[index]:.0f} cm\",\n",
    "    ax=fig[\"map\"],\n",
    ")\n",
    "plots.line(\n",
    "    z,\n",
    "    {\n",
    "        f\"s = {100 * offsets[i]:.0f} cm\": profiles[i] / 1e5\n",
    "        for i in (0, index, len(offsets) - 1)\n",
    "    },\n",
    "    xlabel=\"height on the insulator z [m]\",\n",
    "    ylabel=\"surface field [kV/cm]\",\n",
    "    title=\"Field along the insulator surface\",\n",
    "    ax=fig[\"profile\"],\n",
    ")\n",
    "plots.line(\n",
    "    fine * 100,\n",
    "    {\"parabola through the three best positions\": np.polyval(curve, fine) / 1e5},\n",
    "    points={\"simulation\": (100 * np.array(offsets), peaks / 1e5)},\n",
    "    vlines={\"optimum\": 100 * optimum},\n",
    "    ylimits=(0.95 * peaks.min() / 1e5, 1.05 * peaks.max() / 1e5),\n",
    "    xlabel=\"ring distance from the rod end s [cm]\",\n",
    "    ylabel=\"largest surface field [kV/cm]\",\n",
    "    title=\"Optimisation of the ring position\",\n",
    "    ax=fig[\"sweep\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the ring radius or the tube radius in `grading_ring_position_optimisation_geometry.py` and\n",
    "optimise both together; give the rod a weather shed profile; or put the ring only at the\n",
    "high-voltage end, where most of the stress is."
   ]
  }
 ]
}
