{
 "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": [
    "# Resistance of a straight and a bent copper wire\n",
    "\n",
    "A copper wire of radius $a=1$ mm and conductivity $\\sigma=5.96\\cdot10^{7}$ S/m carries a steady\n",
    "current. In the conductor the current density is $\\mathbf J=-\\sigma\\nabla V$ and charge is\n",
    "conserved, so the potential satisfies\n",
    "\n",
    "$$\\nabla\\cdot(\\sigma\\nabla V)=0 .$$\n",
    "\n",
    "This is the same equation as electrostatics with the permittivity replaced by the conductivity,\n",
    "and the \"charge\" on an electrode becomes the current through it. The voltage $U=1$ mV is applied\n",
    "between the two end faces; the surface of the wire is insulated. The resistance is $R=U/I$.\n",
    "\n",
    "Two pieces are computed: a straight piece of length $L=20$ mm (`wire_resistance_straight_and_bent.step`,\n",
    "faces `bottom`, `top`, `outer_wall`) and a quarter bend whose centreline radius is only twice the\n",
    "wire radius (`wire_resistance_straight_and_bent_bend.step`, faces `start` and `end`). The\n",
    "script `wire_resistance_straight_and_bent_geometry.py` builds both with the CAD objects of\n",
    "OneSimulation.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `bottom` / `start` | $V=U$ |\n",
    "| `top` / `end` | $V=0$ |\n",
    "| `outer_wall` / rest of the bend | insulated, $\\mathbf J\\cdot\\mathbf n=0$ |\n",
    "\n",
    "**Reference.** The straight wire has $R=L/(\\sigma\\pi a^2)$. In the bend the potential grows\n",
    "linearly with the angle, $V=U(1-\\varphi/\\theta)$, and the current density falls off as $1/r$ with\n",
    "the distance from the bend axis; integrating over the circular cross-section with centreline\n",
    "radius $R_b$ gives exactly (Smythe, *Static and Dynamic Electricity*, Ch. 6)\n",
    "\n",
    "$$R_\\mathrm{bend}=\\frac{\\theta}{2\\pi\\sigma\\left(R_b-\\sqrt{R_b^2-a^2}\\right)} ,$$\n",
    "\n",
    "lower than the estimate $\\theta R_b/(\\sigma\\pi a^2)$ from the centreline length, because the\n",
    "current crowds to the shorter inner side of the bend."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import TetrahedralMesher\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 (\n",
    "    FixedPotential,\n",
    "    PoissonEquation,\n",
    "    ZeroNormalElectricDisplacement,\n",
    ")\n",
    "from onesim.results.comparisons import convergence\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",
    "Both pieces are meshed with second-order tetrahedra whose faces follow the round surface\n",
    "(`geometry_order=2`), at three cell sizes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "straight, bend = load(\"wire_resistance_straight_and_bent.step\"), load(\n",
    "    \"wire_resistance_straight_and_bent_bend.step\"\n",
    ")\n",
    "radius, length = straight.size[0] / 2, straight.size[2]\n",
    "centreline = bend.size[0] - radius\n",
    "sizes = {\"straight\": (0.8e-3, 0.5e-3, 0.32e-3), \"bend\": (0.4e-3, 0.25e-3, 0.16e-3)}\n",
    "meshes = {\n",
    "    piece: [\n",
    "        TetrahedralMesher(target_size=size, geometry_order=2).generate(solid)\n",
    "        for size in sizes[piece]\n",
    "    ]\n",
    "    for piece, solid in ((\"straight\", straight), (\"bend\", bend))\n",
    "}\n",
    "\n",
    "view = plots.Camera(elevation=60, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    bend,\n",
    "    selection={\"start\": bend.boundaries.start, \"end\": bend.boundaries.end},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Quarter bend with its end faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"bend\"][1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{meshes['bend'][1].cell_count} curved tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The conductivity takes the place of the permittivity (`regionwise` with one value everywhere\n",
    "makes it a property law with its unit); the current through a terminal is the `reaction` of the\n",
    "fixed potential there."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "conductivity, voltage = 5.96e7, 1e-3\n",
    "ends = bend.boundaries\n",
    "pieces = {\n",
    "    \"straight\": (\n",
    "        straight,\n",
    "        straight.boundaries.bottom,\n",
    "        straight.boundaries.top,\n",
    "        straight.boundaries.outer_wall,\n",
    "    ),\n",
    "    \"bend\": (bend, ends.start, ends.end, ends.all - ends.start - ends.end),\n",
    "}\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "models = {\n",
    "    piece: PoissonEquation(\n",
    "        domain=solid.volume,\n",
    "        permittivity=regionwise((), default=conductivity, unit=\"S/m\"),\n",
    "        charge_density=0.0,\n",
    "    )\n",
    "    for piece, (solid, *_) in pieces.items()\n",
    "}\n",
    "results = {\n",
    "    piece: [\n",
    "        Simulation(\n",
    "            problem=Problem(\n",
    "                name=f\"Copper wire, {piece}\",\n",
    "                geometry=solid,\n",
    "                physics=(models[piece],),\n",
    "                boundary_conditions=(\n",
    "                    FixedPotential(boundary=high, physics=models[piece], value=voltage),\n",
    "                    FixedPotential(boundary=low, physics=models[piece], value=0.0),\n",
    "                    ZeroNormalElectricDisplacement(\n",
    "                        boundary=side, physics=models[piece]\n",
    "                    ),\n",
    "                ),\n",
    "            ),\n",
    "            mesh=mesh,\n",
    "            numerics=numerics,\n",
    "        ).solve_stationary()\n",
    "        for mesh in meshes[piece]\n",
    "    ]\n",
    "    for piece, (solid, high, low, side) in pieces.items()\n",
    "}\n",
    "potentials = {\n",
    "    piece: [result.field(models[piece].potential) for result in solved]\n",
    "    for piece, solved in results.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The resistance from the current through the high-voltage terminal, on three meshes, against the\n",
    "closed forms; the current through the other terminal closes the balance."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "exact = {\n",
    "    \"straight\": length / (conductivity * np.pi * radius**2),\n",
    "    \"bend\": (np.pi / 2)\n",
    "    / (2 * np.pi * conductivity * (centreline - np.sqrt(centreline**2 - radius**2))),\n",
    "}\n",
    "resistances = {\n",
    "    piece: [voltage / field.reaction(pieces[piece][1]) for field in fields]\n",
    "    for piece, fields in potentials.items()\n",
    "}\n",
    "print(\"piece      cell size [mm]   tetrahedra   R [µΩ]        exact [µΩ]   deviation\")\n",
    "for piece, values in resistances.items():\n",
    "    for size, mesh, value in zip(sizes[piece], meshes[piece], values):\n",
    "        print(\n",
    "            f\"{piece:9s} {1e3 * size:14.2f} {mesh.cell_count:12d} {1e6 * value:12.5f} {1e6 * exact[piece]:12.5f} {100 * (value / exact[piece] - 1):+11.4f} %\"\n",
    "        )\n",
    "    study = convergence(values, sizes[piece])\n",
    "    print(\n",
    "        f\"{piece:9s} observed order {study.order:.2f}, extrapolated {1e6 * study.extrapolated:.5f} µΩ ({100 * (study.extrapolated / exact[piece] - 1):+.5f} %)\"\n",
    "    )\n",
    "balance = potentials[\"bend\"][-1].reaction(bend.boundaries.end) / potentials[\"bend\"][\n",
    "    -1\n",
    "].reaction(bend.boundaries.start)\n",
    "print(f\"current balance in the bend: I_end / I_start = {balance:+.8f}\")\n",
    "print(\n",
    "    f\"centreline estimate for the bend {1e6 * (np.pi / 2) * centreline / (conductivity * np.pi * radius**2):.5f} µΩ: \"\n",
    "    f\"{100 * ((np.pi / 2) * centreline / (conductivity * np.pi * radius**2) / exact['bend'] - 1):+.2f} % above the exact value\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The potential and the current density in the mid-plane of the bend, the current density across\n",
    "the bend against the $1/r$ law, and the mesh study of both pieces."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "field = results[\"bend\"][-1].field(models[\"bend\"].electric_field)\n",
    "density = lambda E, position: conductivity * np.linalg.norm(E, axis=1) / 1e6\n",
    "r = np.linspace(centreline - 0.995 * radius, centreline + 0.995 * radius, 41)\n",
    "fine = np.linspace(centreline - radius, centreline + radius, 200)\n",
    "across = conductivity * np.linalg.norm(\n",
    "    field.evaluate(np.column_stack((r / np.sqrt(2), r / np.sqrt(2), np.zeros_like(r)))),\n",
    "    axis=1,\n",
    ")\n",
    "crowding = (\n",
    "    lambda r: voltage\n",
    "    / exact[\"bend\"]\n",
    "    / (2 * np.pi * (centreline - np.sqrt(centreline**2 - radius**2)) * r)\n",
    ")\n",
    "print(\n",
    "    f\"current density across the bend: largest deviation from the 1/r law {100 * np.abs(across / crowding(r) - 1).max():.3f} %\"\n",
    ")\n",
    "\n",
    "fig = plots.figure(\n",
    "    layout=[[\"potential\", \"density\"], [\"profile\", \"study\"]], size=(14, 11)\n",
    ")\n",
    "plots.section(\n",
    "    potentials[\"bend\"][-1],\n",
    "    plane=Plane(origin=(0, 0, 0), normal=(0, 0, 1)),\n",
    "    component=lambda V, position: 1e3 * np.ravel(V),\n",
    "    limits=(0, 1),\n",
    "    contours=11,\n",
    "    subdivisions=3,\n",
    "    label=\"potential [mV]\",\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    title=\"Potential in the mid-plane of the bend\",\n",
    "    ax=fig[\"potential\"],\n",
    ")\n",
    "plots.section(\n",
    "    field,\n",
    "    plane=Plane(origin=(0, 0, 0), normal=(0, 0, 1)),\n",
    "    component=density,\n",
    "    contours=10,\n",
    "    subdivisions=3,\n",
    "    label=\"|J| [A/mm²]\",\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    title=\"Current density: crowding on the inner side\",\n",
    "    ax=fig[\"density\"],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"simulation\": (1e3 * r, across / 1e6)},\n",
    "    reference={\"exact, J ∝ 1/r\": (1e3 * fine, crowding(fine) / 1e6)},\n",
    "    xlabel=\"distance from the bend axis r [mm]\",\n",
    "    ylabel=\"current density [A/mm²]\",\n",
    "    title=\"Current density across the bend\",\n",
    "    ax=fig[\"profile\"],\n",
    ")\n",
    "plots.convergence(\n",
    "    None,\n",
    "    {\n",
    "        piece: (\n",
    "            [1e3 * size for size in sizes[piece]],\n",
    "            [abs(value / exact[piece] - 1) for value in values],\n",
    "        )\n",
    "        for piece, values in resistances.items()\n",
    "    },\n",
    "    xlabel=\"cell size [mm]\",\n",
    "    ylabel=\"relative deviation of R\",\n",
    "    title=\"Mesh study\",\n",
    "    ax=fig[\"study\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the bend tighter in `wire_resistance_straight_and_bent_geometry.py` and the gap to the\n",
    "centreline estimate grows; give the wire a temperature-dependent conductivity and couple it to\n",
    "Joule heating; or compute the resistance of a crimp or a solder joint read from a CAD file."
   ]
  }
 ]
}
