{
 "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": [
    "# RLGC parameters of a coaxial cable\n",
    "\n",
    "A transmission line is described by four parameters per metre: series resistance $R'$ and\n",
    "inductance $L'$, shunt conductance $G'$ and capacitance $C'$. From them follow the characteristic\n",
    "impedance and the propagation constant\n",
    "\n",
    "$$Z_0=\\sqrt{\\frac{R'+j\\omega L'}{G'+j\\omega C'}},\\qquad \\gamma=\\alpha+j\\beta=\\sqrt{(R'+j\\omega L')(G'+j\\omega C')} .$$\n",
    "\n",
    "The cable has a copper inner conductor of radius $a=0.45$ mm, a polyethylene dielectric\n",
    "($\\varepsilon_r=2.25$, loss tangent $\\tan\\delta=2\\cdot10^{-4}$) to $b=1.47$ mm and a copper shield\n",
    "to $c=1.62$ mm ($\\sigma=5.8\\cdot10^7$ S/m). Three 2D cross-section problems give the parameters:\n",
    "\n",
    "- **electrostatics** in the dielectric, $\\nabla\\cdot(\\varepsilon\\nabla V)=0$ with 1 V between the\n",
    "  conductors: $C'=Q'/U$;\n",
    "- **steady current** in the dielectric with the loss conductivity $\\sigma_d=\\omega\\varepsilon\\tan\\delta$\n",
    "  in place of the permittivity: $G'=I'/U$;\n",
    "- **eddy currents** in the whole section, go and return current of 1 A in inner conductor and\n",
    "  shield (solid conductors): $R'+j\\omega L'=Z'$ from the conductor voltages.\n",
    "\n",
    "The cable comes from the CAD files `coax_rlgc_frequency_sweep*.step`; the script\n",
    "`coax_rlgc_frequency_sweep_geometry.py` builds them with the CAD objects of OneSimulation. The\n",
    "two-dimensional model is their section at half length.\n",
    "\n",
    "**Reference.** $C'=2\\pi\\varepsilon/\\ln(b/a)$, $G'=\\omega C'\\tan\\delta$; the internal impedance of a\n",
    "round wire $Z_i=\\frac{k\\,J_0(ka)}{2\\pi a\\sigma J_1(ka)}$ with $k=\\sqrt{-j\\omega\\mu_0\\sigma}$, of the\n",
    "tubular shield with its current on the inside\n",
    "$Z_s=\\frac{q}{2\\pi b\\sigma}\\,\\frac{I_0(qb)K_1(qc)+K_0(qb)I_1(qc)}{I_1(qc)K_1(qb)-I_1(qb)K_1(qc)}$ with\n",
    "$q=\\sqrt{j\\omega\\mu_0\\sigma}$ (Schelkunoff, *Bell Syst. Tech. J.* 13, 1934, 532; Ramo, Whinnery and\n",
    "Van Duzer, *Fields and Waves in Communication Electronics*, 3rd ed., 1994, §5.16), and the external\n",
    "inductance $\\mu_0\\ln(b/a)/(2\\pi)$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import VacuumPermeability, VacuumPermittivity, 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, SparseDirect\n",
    "from onesim.physics.electrostatics import FixedPotential, PoissonEquation\n",
    "from onesim.physics.magnetostatics import (\n",
    "    Coil,\n",
    "    EddyCurrents,\n",
    "    MagneticInsulation,\n",
    "    coil_impedance,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.special import iv, jv, kv\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and meshes\n",
    "\n",
    "`load` returns each part, `section` its cross-section. The dielectric annulus carries the electric\n",
    "problems; the whole section with inner conductor and shield as regions the eddy currents, with\n",
    "triangles of 8 µm at the conductor surfaces that resolve the skin depth of 6.6 µm at 100 MHz with\n",
    "quadratic elements."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "name = \"coax_rlgc_frequency_sweep\"\n",
    "cut = lambda part: load(f\"{name}{part}.step\").section((0, 0, 1), origin=(0, 0, 0.0005))\n",
    "cable, inner, dielectric, shield = (\n",
    "    cut(\"\"),\n",
    "    cut(\"_inner\").named(\"inner\"),\n",
    "    cut(\"_dielectric\"),\n",
    "    cut(\"_shield\").named(\"shield\"),\n",
    ")\n",
    "a, b, c = inner.size[0] / 2, dielectric.size[0] / 2, cable.size[0] / 2\n",
    "electric_mesh = TriangularMesher(target_size=(b - a) / 12, refinements=1).generate(\n",
    "    dielectric\n",
    ")\n",
    "radius = lambda p: np.hypot(p[:, 0], p[:, 1])\n",
    "skin = lambda p: np.minimum(np.abs(radius(p) - a), np.abs(radius(p) - b))\n",
    "magnetic_mesh = TriangularMesher(\n",
    "    target_size=1e-4,\n",
    "    embedded_regions=(inner, shield),\n",
    "    size_field=lambda p: np.clip(8e-6 + 0.8 * skin(p), 8e-6, 1e-4),\n",
    ").generate(cable)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    [\n",
    "        load(f\"{name}_{part}.step\").named(label)\n",
    "        for part, label in (\n",
    "            (\"inner\", \"inner conductor\"),\n",
    "            (\"dielectric\", \"dielectric\"),\n",
    "            (\"shield\", \"shield\"),\n",
    "        )\n",
    "    ],\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=35, azimuth=-60),\n",
    "    title=\"1 mm piece: inner conductor, dielectric, shield\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    magnetic_mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Section for the eddy currents: {magnetic_mesh.cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Capacitance and conductance\n",
    "\n",
    "The same `PoissonEquation` twice: with the permittivity, and with the loss conductivity of the\n",
    "dielectric at each frequency in its place."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "eps0, mu0, sigma, er, tan_delta = (\n",
    "    float(VacuumPermittivity().evaluate()),\n",
    "    float(VacuumPermeability().evaluate()),\n",
    "    5.8e7,\n",
    "    2.25,\n",
    "    2e-4,\n",
    ")\n",
    "frequencies = np.array([1e4, 1e5, 1e6, 1e7, 1e8])\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2), quadrature_order=4),\n",
    "    linear_solver=SparseDirect(),\n",
    ")\n",
    "sides = dielectric.boundaries\n",
    "per_volt = {}\n",
    "for label, value in [(\"C\", er * eps0)] + [\n",
    "    (f, 2 * np.pi * f * er * eps0 * tan_delta) for f in frequencies\n",
    "]:\n",
    "    model = PoissonEquation(\n",
    "        domain=dielectric.domain(),\n",
    "        permittivity=regionwise(\n",
    "            (), default=value, unit=\"F/m\" if label == \"C\" else \"S/m\"\n",
    "        ),\n",
    "        charge_density=0.0,\n",
    "    )\n",
    "    result = Simulation(\n",
    "        problem=Problem(\n",
    "            name=f\"Cable dielectric, {label}\",\n",
    "            geometry=dielectric,\n",
    "            physics=(model,),\n",
    "            boundary_conditions=(\n",
    "                FixedPotential(boundary=sides.inner_wall, physics=model, value=1.0),\n",
    "                FixedPotential(boundary=sides.outer_wall, physics=model, value=0.0),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=electric_mesh,\n",
    "        numerics=numerics,\n",
    "    ).solve_stationary()\n",
    "    per_volt[label] = result.field(model.potential).reaction(sides.inner_wall)\n",
    "capacitance = per_volt[\"C\"]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Series impedance\n",
    "\n",
    "`EddyCurrents` with the inner conductor and the shield as solid conductors carrying 1 A each way;\n",
    "the sum of their voltages per metre is $R'+j\\omega L'$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "series = {}\n",
    "for f in frequencies:\n",
    "    coils = (\n",
    "        Coil(inner, current=1.0, conductor=\"massive\"),\n",
    "        Coil(shield, current=1.0, conductor=\"massive\", direction=-1),\n",
    "    )\n",
    "    model = EddyCurrents(\n",
    "        domain=cable.domain(),\n",
    "        permeability=VacuumPermeability(),\n",
    "        frequency=f,\n",
    "        coils=coils,\n",
    "        conductivity=regionwise(\n",
    "            {\"inner\": sigma, \"shield\": sigma}, default=0.0, unit=\"S/m\"\n",
    "        ),\n",
    "    )\n",
    "    result = Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Cable section\",\n",
    "            geometry=cable,\n",
    "            physics=(model,),\n",
    "            boundary_conditions=(\n",
    "                MagneticInsulation(boundary=cable.boundaries.all, physics=model),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=magnetic_mesh,\n",
    "        numerics=Numerics(\n",
    "            spatial=FiniteElement(element=Lagrange(order=2), quadrature_order=4),\n",
    "            linear_solver=ComplexSparseDirect(),\n",
    "        ),\n",
    "    ).solve_stationary()\n",
    "    series[f] = sum(coil_impedance(result, model, coil) for coil in coils)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "All four parameters, the characteristic impedance and the attenuation against the closed forms."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "k = lambda f: np.sqrt(-1j * 2 * np.pi * f * mu0 * sigma)\n",
    "exact_series = lambda f: (\n",
    "    k(f) * jv(0, k(f) * a) / (2 * np.pi * a * sigma * jv(1, k(f) * a))\n",
    "    + (\n",
    "        lambda q: q\n",
    "        / (2 * np.pi * b * sigma)\n",
    "        * (iv(0, q * b) * kv(1, q * c) + kv(0, q * b) * iv(1, q * c))\n",
    "        / (iv(1, q * c) * kv(1, q * b) - iv(1, q * b) * kv(1, q * c))\n",
    "    )(np.sqrt(1j * 2 * np.pi * f * mu0 * sigma))\n",
    "    + 1j * 2 * np.pi * f * mu0 / (2 * np.pi) * np.log(b / a)\n",
    ")\n",
    "exact_c = 2 * np.pi * er * eps0 / np.log(b / a)\n",
    "print(\n",
    "    f\"C' = {1e12 * capacitance:.3f} pF/m, closed form {1e12 * exact_c:.3f} pF/m ({100 * (capacitance / exact_c - 1):+.3f} %)\"\n",
    ")\n",
    "print(\n",
    "    \"f [Hz]      R' [Ohm/m]  ref.      L' [nH/m]  ref.      G' [µS/m]  ref.      |Z0| [Ohm]  ref.     alpha [dB/m]  ref.\"\n",
    ")\n",
    "z0, attenuation = [], []\n",
    "for f in frequencies:\n",
    "    omega = 2 * np.pi * f\n",
    "    Z, Ze, G, Ge = series[f], exact_series(f), per_volt[f], omega * exact_c * tan_delta\n",
    "    gamma = np.sqrt(Z * (G + 1j * omega * capacitance))\n",
    "    gamma_exact = np.sqrt(Ze * (Ge + 1j * omega * exact_c))\n",
    "    impedance = np.sqrt(Z / (G + 1j * omega * capacitance))\n",
    "    impedance_exact = np.sqrt(Ze / (Ge + 1j * omega * exact_c))\n",
    "    z0.append(abs(impedance))\n",
    "    attenuation.append(8.686 * gamma.real)\n",
    "    print(\n",
    "        f\"{f:9.0e} {Z.real:10.4f} {Ze.real:9.4f} {1e9 * Z.imag / omega:10.2f} {1e9 * Ze.imag / omega:9.2f} {1e6 * G:10.4f} {1e6 * Ge:9.4f}\"\n",
    "        f\" {abs(impedance):10.3f} {abs(impedance_exact):8.3f} {8.686 * gamma.real:12.5f} {8.686 * gamma_exact.real:9.5f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The parameters follow the closed forms over four decades: $R'$ grows with the square root of the\n",
    "frequency once the skin depth is below the conductor size, $L'$ falls to its external part, $G'$\n",
    "grows in proportion to the frequency, and $Z_0$ approaches $\\sqrt{L'/C'}\\approx 50\\,\\Omega$.\n",
    "\n",
    "## Figure\n",
    "\n",
    "Characteristic impedance and attenuation over frequency against the closed forms."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "f = np.logspace(4, 8, 81)\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.line(\n",
    "    x=f,\n",
    "    y={\n",
    "        \"closed form\": np.abs(\n",
    "            np.sqrt(exact_series(f) / (2j * np.pi * f * exact_c * (1 - 1j * tan_delta)))\n",
    "        )\n",
    "    },\n",
    "    points={\"simulation\": (frequencies, z0)},\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"frequency [Hz]\",\n",
    "    ylabel=\"|Z0| [Ohm]\",\n",
    "    title=\"Characteristic impedance\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    x=f,\n",
    "    y={\n",
    "        \"closed form\": 8.686\n",
    "        * np.real(\n",
    "            np.sqrt(exact_series(f) * 2j * np.pi * f * exact_c * (1 - 1j * tan_delta))\n",
    "        )\n",
    "    },\n",
    "    points={\"simulation\": (frequencies, attenuation)},\n",
    "    scale=\"loglog\",\n",
    "    xlabel=\"frequency [Hz]\",\n",
    "    ylabel=\"attenuation [dB/m]\",\n",
    "    title=\"Attenuation\",\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",
    "Give the dielectric a frequency-dependent loss tangent, or replace the copper shield by a braid of\n",
    "lower conductivity and watch the attenuation rise."
   ]
  }
 ]
}
