{
 "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 parallel-wire line\n",
    "\n",
    "Two parallel round wires of radius $a$ with centre spacing $D$ in air form a balanced\n",
    "transmission line (twin lead). Unlike a coaxial cable, the fields are not enclosed: they reach\n",
    "into the unbounded surroundings and decay away from the line. For the TEM wave the transverse\n",
    "electric field solves Laplace's equation of the cross-section,\n",
    "\n",
    "$$\\nabla\\cdot(\\varepsilon_0\\nabla\\phi)=0,\\qquad \\phi=\\pm V/2\\ \\text{on the two wires},$$\n",
    "\n",
    "and the magnetic field is the electric field turned by 90° and divided by $\\eta_0=\\sqrt{\\mu_0/\\varepsilon_0}$.\n",
    "The capacitance per metre follows from the charge on one wire, $C'=Q'/V$, or from the field\n",
    "energy $W'=\\tfrac12C'V^2$; the inductance from $L'C'=\\mu_0\\varepsilon_0$; and the\n",
    "characteristic impedance is $Z_0=\\sqrt{L'/C'}$.\n",
    "\n",
    "| quantity | value |\n",
    "|---|---|\n",
    "| wire radius $a$ | 0.5 mm |\n",
    "| centre spacing $D$ | 5 mm |\n",
    "| surroundings | air, truncated at radii of 25, 50 and 125 mm, grounded |\n",
    "\n",
    "The air comes from the CAD files `parallel_wire_line_impedance.step` (125 mm), `..._r50.step` and\n",
    "`..._r25.step` with the faces `left.outer_wall`, `right.outer_wall` and `outer_wall`, written by\n",
    "`parallel_wire_line_impedance_geometry.py` with the CAD objects of OneSimulation. The model\n",
    "lives on its cross-section. With antisymmetric wire voltages the potential far away vanishes, so\n",
    "grounding the far boundary changes the result only by the order of $(D/R)^2$.\n",
    "\n",
    "**Reference** (D. M. Pozar, *Microwave Engineering*, 4th ed., Wiley 2012, Table 2.1;\n",
    "S. Ramo, J. R. Whinnery, T. Van Duzer, *Fields and Waves in Communication Electronics*, 3rd ed.,\n",
    "Wiley 1994, §1.16). The field outside the wires is that of two line charges at $x=\\pm s$ with\n",
    "$s=\\sqrt{D^2/4-a^2}$; the wire surfaces are equipotential circles of this pair, and\n",
    "\n",
    "$$C'=\\frac{\\pi\\varepsilon_0}{\\operatorname{arccosh}(D/2a)},\\qquad\n",
    "  Z_0=\\frac{\\eta_0}{\\pi}\\operatorname{arccosh}\\frac{D}{2a},\\qquad\n",
    "  \\phi(x,0)=\\frac{V}{2\\operatorname{arccosh}(D/2a)}\\ln\\left|\\frac{x+s}{x-s}\\right| .$$"
   ]
  },
  {
   "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.results.comparisons import convergence\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": [
    "## Geometry and mesh\n",
    "\n",
    "`load` returns the air pieces; `section` cuts each at half length. Quadratic triangles grow from\n",
    "the wires to the far boundary. The figure shows the smallest piece, in which the wires are visible."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "parts = {\n",
    "    radius: load(f\"parallel_wire_line_impedance{suffix}.step\")\n",
    "    for radius, suffix in ((0.125, \"\"), (0.050, \"_r50\"), (0.025, \"_r25\"))\n",
    "}\n",
    "sections = {\n",
    "    radius: part.section((0, 0, 1), origin=(0, 0, part.size[2] / 2))\n",
    "    for radius, part in parts.items()\n",
    "}\n",
    "surface = {face.id: face for face in parts[0.125].faces}\n",
    "a, spacing = (\n",
    "    surface[\"right.outer_wall\"].radius,\n",
    "    surface[\"right.outer_wall\"].center[0] - surface[\"left.outer_wall\"].center[0],\n",
    ")\n",
    "meshes = {\n",
    "    radius: TriangularMesher(\n",
    "        target_size=radius / 12,\n",
    "        grading=0.2,\n",
    "        local_sizes={\"left.outer_wall\": 0.08e-3, \"right.outer_wall\": 0.08e-3},\n",
    "        size_field=lambda points, radius=radius: np.clip(\n",
    "            0.15 * np.hypot(points[:, 0], points[:, 1]), 0.2e-3, radius / 12\n",
    "        ),\n",
    "    ).generate(section)\n",
    "    for radius, section in sections.items()\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 5.5))\n",
    "plots.geometry(\n",
    "    parts[0.025],\n",
    "    selection={\n",
    "        \"wires\": parts[0.025].boundaries[\"left.outer_wall\"]\n",
    "        | parts[0.025].boundaries[\"right.outer_wall\"]\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=35, azimuth=-60),\n",
    "    title=\"Air around the line, 25 mm radius\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0.025],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"{meshes[0.025].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "One electrostatic solve per air cylinder with $+V/2$ and $-V/2$ on the wires and the far\n",
    "boundary grounded; the reaction of the potential on the right wire is its charge per metre."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "eps0, mu0, voltage = (\n",
    "    float(VacuumPermittivity().evaluate()),\n",
    "    float(VacuumPermeability().evaluate()),\n",
    "    1.0,\n",
    ")\n",
    "models = {\n",
    "    radius: PoissonEquation(\n",
    "        domain=section.domain(), permittivity=VacuumPermittivity(), charge_density=0.0\n",
    "    )\n",
    "    for radius, section in sections.items()\n",
    "}\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "results = {\n",
    "    radius: Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Parallel-wire line\",\n",
    "            geometry=section,\n",
    "            physics=(models[radius],),\n",
    "            boundary_conditions=(\n",
    "                FixedPotential(\n",
    "                    boundary=section.boundaries[\"right.outer_wall\"],\n",
    "                    physics=models[radius],\n",
    "                    value=voltage / 2,\n",
    "                ),\n",
    "                FixedPotential(\n",
    "                    boundary=section.boundaries[\"left.outer_wall\"],\n",
    "                    physics=models[radius],\n",
    "                    value=-voltage / 2,\n",
    "                ),\n",
    "                FixedPotential(\n",
    "                    boundary=section.boundaries.outer_wall,\n",
    "                    physics=models[radius],\n",
    "                    value=0.0,\n",
    "                ),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=meshes[radius],\n",
    "        numerics=numerics,\n",
    "    ).solve_stationary()\n",
    "    for radius, section in sections.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Line constants and impedance\n",
    "\n",
    "The grounded far boundary pulls a little extra charge onto the wires; the effect falls off as\n",
    "$(D/R)^2$, so the three air cylinders extrapolate to the unbounded line."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "closed_capacitance = np.pi * eps0 / np.arccosh(spacing / (2 * a))\n",
    "closed_impedance = np.sqrt(mu0 / eps0) / np.pi * np.arccosh(spacing / (2 * a))\n",
    "energy = lambda E, position: 0.5 * eps0 * np.sum(E**2, axis=1)\n",
    "charge = {\n",
    "    radius: result.field(models[radius].potential).reaction(\n",
    "        sections[radius].boundaries[\"right.outer_wall\"]\n",
    "    )\n",
    "    / voltage\n",
    "    for radius, result in results.items()\n",
    "}\n",
    "print(\n",
    "    \"air radius   triangles   C' from Q [pF/m]   C' from W [pF/m]   Z0 [ohm]   deviation of Z0\"\n",
    ")\n",
    "for radius, result in results.items():\n",
    "    from_energy = (\n",
    "        2\n",
    "        * result.field(models[radius].electric_field).integrate(component=energy).value\n",
    "        / voltage**2\n",
    "    )\n",
    "    impedance = np.sqrt(mu0 * eps0) / charge[radius]\n",
    "    print(\n",
    "        f\"{1e3 * radius:7.0f} mm {meshes[radius].cell_count:11d} {1e12 * charge[radius]:18.4f} {1e12 * from_energy:18.4f} {impedance:10.4f} \"\n",
    "        f\"{100 * (impedance / closed_impedance - 1):+13.4f} %\"\n",
    "    )\n",
    "study = convergence(list(charge.values()), [spacing / radius for radius in charge])\n",
    "extrapolated = np.sqrt(mu0 * eps0) / study.extrapolated\n",
    "print(\n",
    "    f\"unbounded line (Richardson extrapolation in D/R): C' = {1e12 * study.extrapolated:.4f} pF/m, Z0 = {extrapolated:.4f} ohm \"\n",
    "    f\"({100 * (extrapolated / closed_impedance - 1):+.4f} %); observed order {study.order:.2f}\"\n",
    ")\n",
    "print(\n",
    "    f\"closed form: C' = {1e12 * closed_capacitance:.4f} pF/m, L' = {1e9 * mu0 * eps0 / closed_capacitance:.2f} nH/m, Z0 = {closed_impedance:.4f} ohm\"\n",
    ")\n",
    "\n",
    "s = np.sqrt(spacing**2 / 4 - a**2)\n",
    "line_charge = (\n",
    "    lambda x: voltage\n",
    "    / (2 * np.arccosh(spacing / (2 * a)))\n",
    "    * np.log(np.abs((x + s) / (x - s)))\n",
    ")\n",
    "x = np.concatenate(\n",
    "    (\n",
    "        np.linspace(-20e-3, -spacing / 2 - a * 1.02, 30),\n",
    "        np.linspace(-spacing / 2 + a * 1.02, spacing / 2 - a * 1.02, 15),\n",
    "        np.linspace(spacing / 2 + a * 1.02, 20e-3, 30),\n",
    "    )\n",
    ")\n",
    "potential = (\n",
    "    results[0.125]\n",
    "    .field(models[0.125].potential)\n",
    "    .evaluate(np.column_stack((x, np.zeros_like(x))))\n",
    "    .ravel()\n",
    ")\n",
    "print(\n",
    "    f\"potential on the x axis against the line-charge solution: largest deviation {100 * np.abs(potential - line_charge(x)).max() / voltage:.3f} % of V\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = np.concatenate(\n",
    "    (\n",
    "        np.linspace(-20e-3, -spacing / 2 - a, 200),\n",
    "        np.linspace(-spacing / 2 + a, spacing / 2 - a, 100),\n",
    "        np.linspace(spacing / 2 + a, 20e-3, 200),\n",
    "    )\n",
    ")\n",
    "fig = plots.figure(1, 2, size=(14, 5.2))\n",
    "plots.surface(\n",
    "    results[0.125].field(models[0.125].potential),\n",
    "    limits=(-0.5, 0.5),\n",
    "    contours=21,\n",
    "    subdivisions=2,\n",
    "    label=\"potential [V]\",\n",
    "    title=\"Equipotentials around the wires\",\n",
    "    xlimits=(-10e-3, 10e-3),\n",
    "    ylimits=(-7e-3, 7e-3),\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"simulation\": (1e3 * x, potential)},\n",
    "    reference={\"line-charge pair\": (1e3 * fine, line_charge(fine))},\n",
    "    vlines=[\n",
    "        1e3 * (-spacing / 2 - a),\n",
    "        1e3 * (-spacing / 2 + a),\n",
    "        1e3 * (spacing / 2 - a),\n",
    "        1e3 * (spacing / 2 + a),\n",
    "    ],\n",
    "    xlabel=\"x on the line through both wires [mm]\",\n",
    "    ylabel=\"potential [V]\",\n",
    "    title=\"Potential through the wires\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Move the wires apart in `parallel_wire_line_impedance_geometry.py` and write the STEP file\n",
    "again: the impedance grows with the logarithm of the spacing. Put the line above a grounded\n",
    "plane (a cut through the air cylinder) and compare the impedance with the method of images."
   ]
  }
 ]
}
