{
 "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": [
    "# Electric field between coaxial cylinders\n",
    "\n",
    "A coaxial arrangement: an inner conductor (radius $a=10$ mm) at the potential $V_0=100$ V and a\n",
    "grounded outer conductor (radius $b=30$ mm), with vacuum in between. The arrangement is long and\n",
    "rotationally symmetric, so the potential depends on the radius only, and Laplace's equation in\n",
    "cylindrical coordinates becomes one-dimensional:\n",
    "\n",
    "$$\\frac{1}{r}\\frac{\\mathrm d}{\\mathrm dr}\\Big(\\varepsilon_0\\,r\\,\\frac{\\mathrm dV}{\\mathrm dr}\\Big)=0,\n",
    "  \\qquad V(a)=V_0,\\quad V(b)=0 .$$\n",
    "\n",
    "OneSimulation solves the Poisson equation of `onesim.physics.electrostatics` on a line from $a$ to\n",
    "$b$; the radial line space weights every integral with the cylinder area $2\\pi r\\,\\ell$, so the\n",
    "reaction of the potential on the inner end is the physical charge of a conductor piece of length\n",
    "$\\ell=20$ mm. The model is one-dimensional and needs no CAD file.\n",
    "\n",
    "| end | condition |\n",
    "|---|---|\n",
    "| $r=a$, inner conductor | $V=V_0$ |\n",
    "| $r=b$, outer conductor | $V=0$ |\n",
    "\n",
    "**Reference.** The coaxial capacitor has the closed-form solution (e.g. Jackson, *Classical\n",
    "Electrodynamics*, 3rd ed., Sec. 1.13)\n",
    "\n",
    "$$V(r)=V_0\\,\\frac{\\ln(b/r)}{\\ln(b/a)},\\qquad E_r(r)=\\frac{V_0}{r\\,\\ln(b/a)},\\qquad\n",
    "  \\frac{C}{\\ell}=\\frac{2\\pi\\varepsilon_0}{\\ln(b/a)} .$$"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d1 import Line\n",
    "from onesim.materials import VacuumPermittivity\n",
    "from onesim.meshing import StructuredLineMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import (\n",
    "    EmbeddedLineH1SpaceFactory,\n",
    "    FiniteElement,\n",
    "    Lagrange,\n",
    "    RevolvedLineH1SpaceFactory,\n",
    ")\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.electrostatics import FixedPotential, PoissonEquation\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": [
    "## Model\n",
    "\n",
    "The radial line runs along $x$ from $a$ to $b$; the axis of revolution is the $z$ axis.\n",
    "Linear and quadratic elements on 8, 16, 32 and 64 cells form the mesh study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "a, b, length, voltage = 0.010, 0.030, 0.020, 100.0\n",
    "radial_line = Line(start=(a, 0.0, 0.0), end=(b, 0.0, 0.0))\n",
    "ends = radial_line.boundaries\n",
    "model = PoissonEquation(\n",
    "    domain=radial_line.line, permittivity=VacuumPermittivity(), charge_density=0.0\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Coaxial capacitor\",\n",
    "    geometry=radial_line,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        FixedPotential(boundary=ends.start, physics=model, value=voltage),\n",
    "        FixedPotential(boundary=ends.end, physics=model, value=0.0),\n",
    "    ),\n",
    ")\n",
    "radial_space = EmbeddedLineH1SpaceFactory(\n",
    "    line_factory=RevolvedLineH1SpaceFactory(axis=(0.0, 0.0, 1.0), axial_length=length)\n",
    ")\n",
    "cells = (8, 16, 32, 64)\n",
    "runs = {\n",
    "    (order, n): Simulation(\n",
    "        problem=problem,\n",
    "        mesh=StructuredLineMesher(cells=n).generate(radial_line),\n",
    "        numerics=Numerics(\n",
    "            spatial=FiniteElement(\n",
    "                element=Lagrange(order=order), quadrature_order=5, provider=radial_space\n",
    "            ),\n",
    "            linear_solver=SparseDirect(),\n",
    "        ),\n",
    "    ).solve_stationary()\n",
    "    for order in (1, 2)\n",
    "    for n in cells\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the closed form\n",
    "\n",
    "Potential and field on a fine set of radii, and the capacitance per length from the charge on the\n",
    "inner conductor."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "eps0 = float(VacuumPermittivity().evaluate())\n",
    "r = np.linspace(a + 1e-5, b - 1e-5, 401)\n",
    "points = np.column_stack((r, np.zeros_like(r), np.zeros_like(r)))\n",
    "exact_potential = voltage * np.log(b / r) / np.log(b / a)\n",
    "exact_field = voltage / (r * np.log(b / a))\n",
    "exact_capacitance = 2 * np.pi * eps0 / np.log(b / a)\n",
    "errors = {}\n",
    "print(\n",
    "    \"elements    cells   potential error [% of V0]   field error [%]   C' [pF/m]   C' error\"\n",
    ")\n",
    "for (order, n), result in runs.items():\n",
    "    potential = result.field(model.potential).evaluate(points).reshape(-1)\n",
    "    field = result.field(model.electric_field).evaluate(points)[:, 0]\n",
    "    capacitance = result.field(model.potential).reaction(ends.start) / (\n",
    "        voltage * length\n",
    "    )\n",
    "    errors[order, n] = (\n",
    "        np.max(np.abs(potential - exact_potential)) / voltage,\n",
    "        np.max(np.abs(field / exact_field - 1)),\n",
    "        abs(capacitance / exact_capacitance - 1),\n",
    "    )\n",
    "    print(\n",
    "        f\"P{order} {n:12d} {100 * errors[order, n][0]:24.5f} {100 * errors[order, n][1]:17.4f} \"\n",
    "        f\"{1e12 * capacitance:11.4f} {errors[order, n][2]:10.1e}\"\n",
    "    )\n",
    "print(f\"closed form: C' = 2 pi eps0 / ln(b/a) = {1e12 * exact_capacitance:.4f} pF/m\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figures\n",
    "\n",
    "Potential and field on the coarsest quadratic mesh against the closed form, and the mesh study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "coarse = runs[2, 8]\n",
    "markers = np.linspace(a, b, 25)\n",
    "marks = np.column_stack((markers, np.zeros_like(markers), np.zeros_like(markers)))\n",
    "fig = plots.figure(1, 2, size=(12, 4.5))\n",
    "plots.line(\n",
    "    points={\n",
    "        \"P2, 8 cells\": (\n",
    "            1e3 * markers,\n",
    "            coarse.field(model.potential).evaluate(marks).reshape(-1),\n",
    "        )\n",
    "    },\n",
    "    reference={\"closed form\": (1e3 * r, exact_potential)},\n",
    "    xlabel=\"radius r [mm]\",\n",
    "    ylabel=\"potential [V]\",\n",
    "    title=\"Potential V(r)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"P2, 8 cells\": (\n",
    "            1e3 * markers,\n",
    "            coarse.field(model.electric_field).evaluate(marks)[:, 0],\n",
    "        )\n",
    "    },\n",
    "    reference={\"closed form\": (1e3 * r, exact_field)},\n",
    "    xlabel=\"radius r [mm]\",\n",
    "    ylabel=\"radial field [V/m]\",\n",
    "    title=\"Radial field E_r(r)\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()\n",
    "\n",
    "fig = plots.figure(1, 2, size=(12, 4.5))\n",
    "plots.convergence(\n",
    "    [(b - a) / n for n in cells],\n",
    "    {f\"P{order}\": [errors[order, n][1] for n in cells] for order in (1, 2)},\n",
    "    xlabel=\"cell size h [m]\",\n",
    "    ylabel=\"largest relative field error\",\n",
    "    title=\"Field\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.convergence(\n",
    "    [(b - a) / n for n in cells],\n",
    "    {f\"P{order}\": [errors[order, n][2] for n in cells] for order in (1, 2)},\n",
    "    xlabel=\"cell size h [m]\",\n",
    "    ylabel=\"relative error of C'\",\n",
    "    title=\"Capacitance per length\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the radii and see how the field at the inner conductor grows as $b/a$ shrinks; for a given\n",
    "outer radius it is smallest at $b/a=e$, the classic design rule for high-voltage cables. A\n",
    "`charge_density` turns the model into a space-charge problem, and a second dielectric layer shows\n",
    "the field jump at the interface."
   ]
  }
 ]
}
