{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "language": "python",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  },
  "fundamentals": {
   "title": "Which resistor can carry its current through another path?",
   "lead": "A short circuit diagram leads to a matrix that describes both voltage differences and sensitivity to losing an edge. Change one conductance and follow where the current goes.",
   "unit_slug": "edge-leverage-in-a-resistor-network"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f0dca5ad2395",
   "metadata": {},
   "source": [
    "# Which resistor can carry its current through another path?\n",
    "\n",
    "A short circuit diagram leads to a matrix that describes both voltage differences and sensitivity to losing an edge. Change one conductance and follow where the current goes."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0973e6fea860",
   "metadata": {
    "fundamentals": {
     "section": "derive-the-model"
    }
   },
   "source": [
    "## Ground a node and derive the electrical leverage\n",
    "\n",
    "Nodes A, B and C form a triangular loop. Node D connects only to C. Every edge is an ideal linear resistor. Orient an edge from node $i$ to node $j$ and give it an incidence vector $b_e$ with a +1 at $i$ and a −1 at $j$. Its current under nodal voltages $v$ is $g_e b_e^T v$, where conductance $g_e$ is measured in siemens. Kirchhoff's current law sums all outgoing currents into the net injection $f$. It gives\n",
    "\n",
    "$$Lv=f,\\qquad L=\\sum_e g_e b_eb_e^T.$$\n",
    "\n",
    "Adding a constant to every potential preserves all currents. Fix the potential of D at zero and remove its row and column. For a connected network the resulting grounded matrix is positive definite. Inject one ampere at one end of an edge and withdraw it at the other. With grounded coordinates the voltage difference per unit current is the effective resistance $R_e=b_e^T L_g^{-1} b_e$. The fraction of this test current that flows through the tested edge is $\\ell_e=g_eR_e$. A bridge carries the full ampere. A parallel path reduces its share.\n",
    "\n",
    "There is also a global check on the calculation. The sum of all the leverages is $\\mathrm{tr}(L_g^{-1}\\sum_e g_e b_e b_e^T)=n-1$ on a connected graph with $n$ nodes. Each leverage depends only on the graph and its conductances. The actual current in a specified operating condition also depends on the chosen source and sink."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e22984c75703",
   "metadata": {
    "fundamentals": {
     "section": "worked-prediction"
    }
   },
   "source": [
    "## Solve the triangle by hand\n",
    "\n",
    "With 1 S on every branch, the detour A–C–B consists of two 1 Ω resistors in series. Inject 1 A at A and extract it at B. The detour's 0.5 S combines with the direct 1 S, so the measured drop is $1/1.5=2/3$ V. The direct current is 2/3 A. The dead-end C–D branch carries zero current in this experiment. When tested between its own endpoints, however, C–D carries the entire test current. The four leverages are consequently $2/3,2/3,2/3,1$ and sum to three.\n",
    "\n",
    "Double A–B's conductance to 2 S. Its leverage rises to $2/2.5=0.8$, while the voltage needed for the same 1 A drops to 0.4 V. This is why the two traces in the experiment have opposite slopes. Rerun with a weaker bridge. Its resistance increases, yet its leverage stays equal to one."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3697f193609",
   "metadata": {
    "fundamentals": {
     "section": "choose-inputs",
     "notebook_only": true
    }
   },
   "source": [
    "## Set the experimental inputs\n",
    "\n",
    "Edit these values, then run the calculation and both figures again."
   ]
  },
  {
   "cell_type": "code",
   "id": "1781de69e0aa",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "teal, orange, blue = \"#19596a\", \"#aa462a\", \"#3868a0\"\n",
    "def axes(xlabel, ylabel):\n",
    "    fig, ax = plt.subplots(figsize=(7, 4), constrained_layout=True)\n",
    "    ax.set(xlabel=xlabel, ylabel=ylabel)\n",
    "    ax.grid(alpha=0.2)\n",
    "    return fig, ax"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "72c650572b95",
   "metadata": {},
   "source": [
    "direct_siemens = 1.0\n",
    "bridge_siemens = 1.0"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "01ddd179d804",
   "metadata": {},
   "source": [
    "assert direct_siemens > 0 and bridge_siemens > 0\n",
    "edges = [(0, 1), (1, 2), (2, 0), (2, 3)]\n",
    "B = np.zeros((4, 4))\n",
    "for col, (i, j) in enumerate(edges):\n",
    "    B[i, col], B[j, col] = 1, -1\n",
    "grounded = B[:-1]\n",
    "\n",
    "def network(g):\n",
    "    weights = np.array([g, 1., 1., bridge_siemens])\n",
    "    L = (grounded * weights) @ grounded.T\n",
    "    voltage = np.linalg.solve(L, grounded)\n",
    "    R = np.sum(grounded * voltage, axis=0)\n",
    "    return R, weights * R\n",
    "\n",
    "resistance, leverage = network(direct_siemens)\n",
    "assert np.isclose(leverage.sum(), 3) and np.isclose(leverage[-1], 1)\n",
    "assert np.isclose(resistance[0], 1/(direct_siemens + .5))\n",
    "print(\"Edge    resistance (ohm)    leverage\")\n",
    "for label, r, share in zip([\"AB\",\"BC\",\"CA\",\"CD\"], resistance, leverage):\n",
    "    print(f\"{label:3} {r:13.5f} {share:12.5f}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "f936084e21f6",
   "metadata": {
    "fundamentals": {
     "figure": {
      "file": "linear-algebra-linear-algebra-methods-1.png",
      "alt": "A triangular circuit with a pendant connection displays the current fraction carried by each tested edge.",
      "caption": "Each label gives the share of a separate one-ampere test between that edge's endpoints. The pendant branch remains at unity for any positive conductance."
     }
    }
   },
   "source": [
    "coords = np.array([[-1.,0],[1.,0],[0,1.3],[0,2.25]])\n",
    "fig, ax = axes(\"Network position\", \"Network position\")\n",
    "for (i,j), share in zip(edges, leverage):\n",
    "    ends = coords[[i,j]]\n",
    "    ax.plot(*ends.T, color=teal, lw=1.5+3*share, zorder=1)\n",
    "    center = ends.mean(axis=0)\n",
    "    ax.text(*center, f\"{share:.3f}\", ha=\"center\", va=\"center\",\n",
    "            bbox=dict(facecolor=\"white\", edgecolor=\"none\", pad=2))\n",
    "for (x,y), label in zip(coords,\"ABCD\"):\n",
    "    ax.scatter(x,y,s=440,color=blue,zorder=3)\n",
    "    ax.text(x,y,label,ha=\"center\",va=\"center\",color=\"white\",zorder=4)\n",
    "ax.set_aspect(\"equal\"); ax.set_xlim(-1.35,1.35); ax.set_ylim(-.3,2.56)\n",
    "ax.axis(\"off\")\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "a0e570ed45ac",
   "metadata": {
    "fundamentals": {
     "notebook_only": true
    }
   },
   "source": [
    "Each label gives the share of a separate one-ampere test between that edge's endpoints. The pendant branch remains at unity for any positive conductance."
   ]
  },
  {
   "cell_type": "code",
   "id": "9c2a882df48a",
   "metadata": {
    "fundamentals": {
     "figure": {
      "file": "linear-algebra-linear-algebra-methods-2.png",
      "alt": "An increasing direct conductance raises the fraction of test current through AB and lowers its effective resistance.",
      "caption": "The current-share curve tends to one as the direct branch dominates the detour. The voltage per ampere falls from two ohms toward zero."
     }
    }
   },
   "source": [
    "sweep = np.geomspace(min(.05, direct_siemens),max(20, direct_siemens),120)\n",
    "result = [network(g) for g in sweep]\n",
    "fig, ax = axes(\"Direct conductance AB (S)\", \"Current share (dimensionless)\")\n",
    "ax.semilogx(sweep, [s[0] for r,s in result], color=teal, label=\"AB current share\")\n",
    "ax.scatter(direct_siemens, leverage[0], color=teal)\n",
    "right = ax.twinx(); right.set_ylabel(\"Effective resistance AB (Ω)\")\n",
    "right.plot(sweep, [r[0] for r,s in result], color=orange, label=\"Effective resistance\")\n",
    "right.scatter(direct_siemens, resistance[0], color=orange)\n",
    "ax.legend(loc=\"center left\"); right.legend(loc=\"center right\")\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "4000facb1d2d",
   "metadata": {
    "fundamentals": {
     "notebook_only": true
    }
   },
   "source": [
    "The current-share curve tends to one as the direct branch dominates the detour. The voltage per ampere falls from two ohms toward zero."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2868751c281c",
   "metadata": {
    "fundamentals": {
     "section": "problem-1"
    }
   },
   "source": [
    "## Exercise · remove the direct branch\n",
    "\n",
    "How much does the terminal resistance rise when the 1 S direct edge is removed? What changes if the bridge is removed instead?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "02a720ad866e",
   "metadata": {
    "fundamentals": {
     "solution": true
    }
   },
   "source": [
    "For A and B the sole remaining connection consists of two 1 Ω resistors, so resistance rises from 2/3 Ω to 2 Ω, an increase of 4/3 Ω. Removing C–D instead isolates D. Measurements within the triangle remain finite, but a test injecting current at D and withdrawing it at C no longer has a finite DC voltage solution."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f19f011e5924",
   "metadata": {
    "fundamentals": {
     "section": "problem-2"
    }
   },
   "source": [
    "## Exercise · differentiate the measured voltage\n",
    "\n",
    "Under a fixed one-ampere A-to-B test, find the sensitivity of the terminal resistance to the direct conductance at 1 S."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6d932c80de1d",
   "metadata": {
    "fundamentals": {
     "solution": true
    }
   },
   "source": [
    "For variable $g$ the resistance is $1/(g+0.5)$. Differentiation gives $-1/(g+0.5)^2=-4/9$ Ω/S at the chosen point. The magnitude equals the square of the voltage drop per ampere across that branch. Differentiating $L_gv=f$ at fixed injection gives the same result for any branch, $\\partial (f^Tv)/\\partial g_e=-(b_e^Tv)^2$ for the unit test."
   ]
  }
 ]
}
