{
 "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": [
    "# Characteristic impedance of a coaxial cable\n",
    "\n",
    "A coaxial cable guides a TEM wave between an inner conductor of radius $a$ and a shield of\n",
    "inner radius $b$, separated by a dielectric of relative permittivity $\\varepsilon_r$. For a TEM\n",
    "wave the transverse fields are static fields of the cross-section: the electric field solves\n",
    "Laplace's equation for the potential difference $V$ between the conductors,\n",
    "\n",
    "$$\\nabla\\cdot(\\varepsilon\\nabla\\phi)=0,\\qquad \\phi=V\\ \\text{on the inner conductor},\\quad\n",
    "  \\phi=0\\ \\text{on the shield},$$\n",
    "\n",
    "and the magnetic field is the electric field turned by 90° and divided by the wave impedance\n",
    "$\\eta=\\sqrt{\\mu/\\varepsilon}$. The line constants per metre therefore follow from one 2D field\n",
    "solve: the capacitance $C'=Q'/V$ from the charge on the inner conductor (or from the field\n",
    "energy, $W'=\\tfrac12C'V^2$), and the inductance from $L'C'=\\mu\\varepsilon$. The characteristic\n",
    "impedance is\n",
    "\n",
    "$$Z_0=\\sqrt{\\frac{L'}{C'}}=\\frac{\\sqrt{\\mu\\varepsilon}}{C'} .$$\n",
    "\n",
    "The cable is a common 50 Ω type with a polyethylene dielectric:\n",
    "\n",
    "| quantity | value |\n",
    "|---|---|\n",
    "| inner conductor radius $a$ | 0.45 mm |\n",
    "| shield inner radius $b$ | 1.475 mm |\n",
    "| dielectric | polyethylene, $\\varepsilon_r=2.25$ |\n",
    "| offset of the inner conductor (second cable) | $d=0.40$ mm |\n",
    "\n",
    "The dielectric comes from the CAD files `coaxial_cable_impedance.step` (faces `inner_wall`,\n",
    "`outer_wall`) and `coaxial_cable_impedance_eccentric.step` (faces `conductor.outer_wall`,\n",
    "`outer_wall`), written by `coaxial_cable_impedance_geometry.py` with the CAD objects of\n",
    "OneSimulation. The model lives on their cross-sections.\n",
    "\n",
    "**Reference** (D. M. Pozar, *Microwave Engineering*, 4th ed., Wiley 2012, §2.2 and §3.5;\n",
    "S. Ramo, J. R. Whinnery, T. Van Duzer, *Fields and Waves in Communication Electronics*, 3rd ed.,\n",
    "Wiley 1994, §5.11). For the concentric and for the eccentric cable\n",
    "\n",
    "$$C'=\\frac{2\\pi\\varepsilon}{\\ln(b/a)},\\qquad\n",
    "  C'_{\\rm ecc}=\\frac{2\\pi\\varepsilon}{\\operatorname{arccosh}\\dfrac{a^2+b^2-d^2}{2ab}},\\qquad\n",
    "  Z_0=\\frac{\\eta}{2\\pi}\\ln\\frac ba .$$"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import VacuumPermeability, VacuumPermittivity\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 SparseDirect\n",
    "from onesim.physics.electrostatics import FixedPotential, PoissonEquation\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 dielectric; `section` cuts it at half length. Quadratic triangles are three\n",
    "times finer on the inner conductor than on the shield."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "parts = {\n",
    "    \"concentric\": load(\"coaxial_cable_impedance.step\"),\n",
    "    \"eccentric\": load(\"coaxial_cable_impedance_eccentric.step\"),\n",
    "}\n",
    "conductor = {\"concentric\": \"inner_wall\", \"eccentric\": \"conductor.outer_wall\"}\n",
    "sections = {\n",
    "    name: part.section((0, 0, 1), origin=(0, 0, part.size[2] / 2))\n",
    "    for name, part in parts.items()\n",
    "}\n",
    "a, b, offset = 0.45e-3, parts[\"concentric\"].size[0] / 2, 0.40e-3\n",
    "meshes = {\n",
    "    name: TriangularMesher(\n",
    "        target_size=0.12e-3, local_sizes={conductor[name]: 0.04e-3}\n",
    "    ).generate(section)\n",
    "    for name, section in sections.items()\n",
    "}\n",
    "\n",
    "fig = plots.figure(2, 2, size=(12, 11))\n",
    "for row, name in enumerate(parts):\n",
    "    plots.geometry(\n",
    "        parts[name],\n",
    "        selection={\n",
    "            \"inner conductor\": parts[name].boundaries[conductor[name]],\n",
    "            \"shield\": parts[name].boundaries.outer_wall,\n",
    "        },\n",
    "        labels=False,\n",
    "        camera=plots.Camera(elevation=35, azimuth=-60),\n",
    "        title=f\"Dielectric of the {name} cable\",\n",
    "        ax=fig[2 * row],\n",
    "    )\n",
    "    plots.mesh(\n",
    "        meshes[name],\n",
    "        groups=(\"all\",),\n",
    "        legend=False,\n",
    "        title=f\"{meshes[name].cell_count} triangles\",\n",
    "        ax=fig[2 * row + 1],\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "One electrostatic solve per cable with 1 V on the inner conductor and the shield grounded. The\n",
    "reaction of the potential on the inner conductor is its charge per metre."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "eps, mu, voltage = (\n",
    "    2.25 * float(VacuumPermittivity().evaluate()),\n",
    "    float(VacuumPermeability().evaluate()),\n",
    "    1.0,\n",
    ")\n",
    "models = {\n",
    "    name: PoissonEquation(\n",
    "        domain=section.domain(),\n",
    "        permittivity=regionwise((), default=eps, unit=\"F/m\"),\n",
    "        charge_density=0.0,\n",
    "    )\n",
    "    for name, section in sections.items()\n",
    "}\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "results = {\n",
    "    name: Simulation(\n",
    "        problem=Problem(\n",
    "            name=f\"{name} coaxial cable\",\n",
    "            geometry=section,\n",
    "            physics=(models[name],),\n",
    "            boundary_conditions=(\n",
    "                FixedPotential(\n",
    "                    boundary=section.boundaries[conductor[name]],\n",
    "                    physics=models[name],\n",
    "                    value=voltage,\n",
    "                ),\n",
    "                FixedPotential(\n",
    "                    boundary=section.boundaries.outer_wall,\n",
    "                    physics=models[name],\n",
    "                    value=0.0,\n",
    "                ),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=meshes[name],\n",
    "        numerics=numerics,\n",
    "    ).solve_stationary()\n",
    "    for name, section in sections.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Line constants and impedance\n",
    "\n",
    "Capacitance from the charge and from the field energy, inductance from $L'C'=\\mu\\varepsilon$,\n",
    "and the impedance, each against the closed form."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "closed_form = {\n",
    "    \"concentric\": 2 * np.pi * eps / np.log(b / a),\n",
    "    \"eccentric\": 2 * np.pi * eps / np.arccosh((a**2 + b**2 - offset**2) / (2 * a * b)),\n",
    "}\n",
    "energy = lambda E, position: 0.5 * eps * np.sum(E**2, axis=1)\n",
    "print(\n",
    "    \"cable        C' from Q [pF/m]   C' from W [pF/m]   closed form [pF/m]   L' [nH/m]    Z0 [ohm]   closed form [ohm]   deviation\"\n",
    ")\n",
    "for name, result in results.items():\n",
    "    from_charge = (\n",
    "        result.field(models[name].potential).reaction(\n",
    "            sections[name].boundaries[conductor[name]]\n",
    "        )\n",
    "        / voltage\n",
    "    )\n",
    "    from_energy = (\n",
    "        2\n",
    "        * result.field(models[name].electric_field).integrate(component=energy).value\n",
    "        / voltage**2\n",
    "    )\n",
    "    inductance, impedance = mu * eps / from_charge, np.sqrt(mu * eps) / from_charge\n",
    "    exact = np.sqrt(mu * eps) / closed_form[name]\n",
    "    print(\n",
    "        f\"{name:11s} {1e12 * from_charge:17.4f} {1e12 * from_energy:18.4f} {1e12 * closed_form[name]:20.4f} {1e9 * inductance:11.3f} \"\n",
    "        f\"{impedance:11.4f} {exact:19.4f} {100 * (impedance / exact - 1):+10.4f} %\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The field strength in both cross-sections on a common scale, and the radial field of the\n",
    "concentric cable against $E_r=V/(r\\ln(b/a))$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "strength = lambda E, position: 1e-3 * np.linalg.norm(E[:, :2], axis=1)\n",
    "r = np.linspace(a * 1.01, b * 0.99, 30)\n",
    "fine = np.linspace(a, b, 200)\n",
    "radial = strength(\n",
    "    results[\"concentric\"]\n",
    "    .field(models[\"concentric\"].electric_field)\n",
    "    .evaluate(np.column_stack((r, np.zeros_like(r)))),\n",
    "    None,\n",
    ")\n",
    "fig = plots.figure(1, 3, size=(19, 5))\n",
    "for index, name in enumerate(results):\n",
    "    plots.surface(\n",
    "        results[name].field(models[name].electric_field),\n",
    "        component=strength,\n",
    "        limits=(0, 3),\n",
    "        contours=13,\n",
    "        subdivisions=2,\n",
    "        label=\"|E| [kV/m] at 1 V\",\n",
    "        title=f\"Field strength, {name} cable\",\n",
    "        xlabel=\"x [m]\",\n",
    "        ylabel=\"y [m]\",\n",
    "        ax=fig[index],\n",
    "    )\n",
    "plots.line(\n",
    "    points={\"simulation\": (1e3 * r, radial)},\n",
    "    reference={\n",
    "        \"V / (r ln(b/a))\": (1e3 * fine, 1e-3 * voltage / (fine * np.log(b / a)))\n",
    "    },\n",
    "    xlabel=\"radius r [mm]\",\n",
    "    ylabel=\"|E| [kV/m] at 1 V\",\n",
    "    title=\"Radial field of the concentric cable\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the radii or the offset in `coaxial_cable_impedance_geometry.py` and write the STEP files\n",
    "again: a 75 Ω cable needs $b/a\\approx6.5$ with polyethylene. Give part of the dielectric a\n",
    "different permittivity with `regionwise` (a foam-filled cable) and the simple relation\n",
    "$L'C'=\\mu\\varepsilon$ no longer holds; the impedance then needs the inductance of the air-filled\n",
    "line, $Z_0=1/(c\\sqrt{C'C'_{\\rm air}})$."
   ]
  }
 ]
}
