Currents/voltages graph for an electrical circuit The 2019 Stack Overflow Developer Survey Results Are InSolving “Resistance between two nodes on a grid” problem in MathematicaCircuit drawing in MathematicaMerging (combining) tables of graph relationships (2-mode to 1-mode network)Reduce distances between vertices of graph to minimum possible?How can I sequentially apply different graph embeddings?Plotting a network or a graph with given coordinates for verticesEquivalent of RadialOutside for Graph VertexLabelsInvisible graph edgesHow to make the vertices move with the VertexRenderingFunction graphics when clicking and dragging vertices of a layered graphHow to delete unnecessary resistances in a resistance networkEvaluate the electrical resistance between any two points of a circuit

Geography at the pixel level

What could be the right powersource for 15 seconds lifespan disposable giant chainsaw?

Does HR tell a hiring manager about salary negotiations?

Deal with toxic manager when you can't quit

How do I free up internal storage if I don't have any apps downloaded?

Why didn't the Event Horizon Telescope team mention Sagittarius A*?

Can a rogue use sneak attack with weapons that have the thrown property even if they are not thrown?

Will it cause any balance problems to have PCs level up and gain the benefits of a long rest mid-fight?

Is bread bad for ducks?

What to do when moving next to a bird sanctuary with a loosely-domesticated cat?

How to charge AirPods to keep battery healthy?

How much of the clove should I use when using big garlic heads?

The phrase "to the numbers born"?

Relationship between Gromov-Witten and Taubes' Gromov invariant

Mathematics of imaging the black hole

Why isn't the black hole white?

Correct punctuation for showing a character's confusion

If I can cast sorceries at instant speed, can I use sorcery-speed activated abilities at instant speed?

How to type a long/em dash `—`

How to support a colleague who finds meetings extremely tiring?

Button changing its text & action. Good or terrible?

Can we generate random numbers using irrational numbers like π and e?

A word that means fill it to the required quantity

Flight paths in orbit around Ceres?



Currents/voltages graph for an electrical circuit



The 2019 Stack Overflow Developer Survey Results Are InSolving “Resistance between two nodes on a grid” problem in MathematicaCircuit drawing in MathematicaMerging (combining) tables of graph relationships (2-mode to 1-mode network)Reduce distances between vertices of graph to minimum possible?How can I sequentially apply different graph embeddings?Plotting a network or a graph with given coordinates for verticesEquivalent of RadialOutside for Graph VertexLabelsInvisible graph edgesHow to make the vertices move with the VertexRenderingFunction graphics when clicking and dragging vertices of a layered graphHow to delete unnecessary resistances in a resistance networkEvaluate the electrical resistance between any two points of a circuit










2












$begingroup$


I am trying to design the network graph for an electrical circuit. I have done this by hand so far. Here is the code for the voltages graph



g = Graph[0, 1, 2, 3, 4,
0 -> 1, 1 -> 2, 2 -> 1, 3 -> 2, 4 -> 3, 0 -> 4, 4 -> 0, 1 -> 3];
PropertyValue[g, VertexLabels] = Table[i -> StringForm["(`1`)", i], i, 0, EdgeCount[basic]];

PropertyValue[g, 0 -> 1, EdgeLabels] = Placed[2, 1/2, 1/2, 0];
PropertyValue[g, 1 -> 3, EdgeLabels] = Placed[10, 1/2, 3/2, 1/2];
PropertyValue[g, 1 -> 2, EdgeLabels] = Placed[2, 1/2, -1/2, -1/2];
PropertyValue[g, 0 -> 4, EdgeLabels] = Placed[3, 1/2, -1/2, 1/2];


Here is the result:



enter image description here



I have a similar one for currents and now I need to apply Kirchhoff's laws and the only way out of this right now is doing it by hand. So my question is: is there any other more efficient way around what I am doing here?










share|improve this question









New contributor




Victor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$











  • $begingroup$
    Please note that I have just started using Mathematica a few weeks ago!
    $endgroup$
    – Victor
    5 hours ago










  • $begingroup$
    A circuit of resistors is not a directed graph. It is undirected. It does make sense to orient edges so that we can distinguish between currents flowing in opposite direction (there's a frame of reference), but you have edges going in both directions between the same vertices. It's not clear what you are trying to represent with that.
    $endgroup$
    – Szabolcs
    4 hours ago










  • $begingroup$
    @Szabolcs edge 4->0 may represent a resistor (with current flowing from 4 to 0) and edge 0->4 may represent a voltage source.
    $endgroup$
    – Victor
    4 hours ago










  • $begingroup$
    @Szabolcs although not in English, please take a look at the two diagrams in the middle of page 8 of this document. That's an example of what I have to do here, or the figures at the top of page 23 in this document
    $endgroup$
    – Victor
    4 hours ago











  • $begingroup$
    "Sagetile de pe laturi indica sensurile referinta ale curentilor si tensiunilor", thus the edge directions do not have physical meaning, they only serve as a reference for the current values and voltage difference values. (I can read Romanian.)
    $endgroup$
    – Szabolcs
    3 hours ago















2












$begingroup$


I am trying to design the network graph for an electrical circuit. I have done this by hand so far. Here is the code for the voltages graph



g = Graph[0, 1, 2, 3, 4,
0 -> 1, 1 -> 2, 2 -> 1, 3 -> 2, 4 -> 3, 0 -> 4, 4 -> 0, 1 -> 3];
PropertyValue[g, VertexLabels] = Table[i -> StringForm["(`1`)", i], i, 0, EdgeCount[basic]];

PropertyValue[g, 0 -> 1, EdgeLabels] = Placed[2, 1/2, 1/2, 0];
PropertyValue[g, 1 -> 3, EdgeLabels] = Placed[10, 1/2, 3/2, 1/2];
PropertyValue[g, 1 -> 2, EdgeLabels] = Placed[2, 1/2, -1/2, -1/2];
PropertyValue[g, 0 -> 4, EdgeLabels] = Placed[3, 1/2, -1/2, 1/2];


Here is the result:



enter image description here



I have a similar one for currents and now I need to apply Kirchhoff's laws and the only way out of this right now is doing it by hand. So my question is: is there any other more efficient way around what I am doing here?










share|improve this question









New contributor




Victor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$











  • $begingroup$
    Please note that I have just started using Mathematica a few weeks ago!
    $endgroup$
    – Victor
    5 hours ago










  • $begingroup$
    A circuit of resistors is not a directed graph. It is undirected. It does make sense to orient edges so that we can distinguish between currents flowing in opposite direction (there's a frame of reference), but you have edges going in both directions between the same vertices. It's not clear what you are trying to represent with that.
    $endgroup$
    – Szabolcs
    4 hours ago










  • $begingroup$
    @Szabolcs edge 4->0 may represent a resistor (with current flowing from 4 to 0) and edge 0->4 may represent a voltage source.
    $endgroup$
    – Victor
    4 hours ago










  • $begingroup$
    @Szabolcs although not in English, please take a look at the two diagrams in the middle of page 8 of this document. That's an example of what I have to do here, or the figures at the top of page 23 in this document
    $endgroup$
    – Victor
    4 hours ago











  • $begingroup$
    "Sagetile de pe laturi indica sensurile referinta ale curentilor si tensiunilor", thus the edge directions do not have physical meaning, they only serve as a reference for the current values and voltage difference values. (I can read Romanian.)
    $endgroup$
    – Szabolcs
    3 hours ago













2












2








2





$begingroup$


I am trying to design the network graph for an electrical circuit. I have done this by hand so far. Here is the code for the voltages graph



g = Graph[0, 1, 2, 3, 4,
0 -> 1, 1 -> 2, 2 -> 1, 3 -> 2, 4 -> 3, 0 -> 4, 4 -> 0, 1 -> 3];
PropertyValue[g, VertexLabels] = Table[i -> StringForm["(`1`)", i], i, 0, EdgeCount[basic]];

PropertyValue[g, 0 -> 1, EdgeLabels] = Placed[2, 1/2, 1/2, 0];
PropertyValue[g, 1 -> 3, EdgeLabels] = Placed[10, 1/2, 3/2, 1/2];
PropertyValue[g, 1 -> 2, EdgeLabels] = Placed[2, 1/2, -1/2, -1/2];
PropertyValue[g, 0 -> 4, EdgeLabels] = Placed[3, 1/2, -1/2, 1/2];


Here is the result:



enter image description here



I have a similar one for currents and now I need to apply Kirchhoff's laws and the only way out of this right now is doing it by hand. So my question is: is there any other more efficient way around what I am doing here?










share|improve this question









New contributor




Victor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$




I am trying to design the network graph for an electrical circuit. I have done this by hand so far. Here is the code for the voltages graph



g = Graph[0, 1, 2, 3, 4,
0 -> 1, 1 -> 2, 2 -> 1, 3 -> 2, 4 -> 3, 0 -> 4, 4 -> 0, 1 -> 3];
PropertyValue[g, VertexLabels] = Table[i -> StringForm["(`1`)", i], i, 0, EdgeCount[basic]];

PropertyValue[g, 0 -> 1, EdgeLabels] = Placed[2, 1/2, 1/2, 0];
PropertyValue[g, 1 -> 3, EdgeLabels] = Placed[10, 1/2, 3/2, 1/2];
PropertyValue[g, 1 -> 2, EdgeLabels] = Placed[2, 1/2, -1/2, -1/2];
PropertyValue[g, 0 -> 4, EdgeLabels] = Placed[3, 1/2, -1/2, 1/2];


Here is the result:



enter image description here



I have a similar one for currents and now I need to apply Kirchhoff's laws and the only way out of this right now is doing it by hand. So my question is: is there any other more efficient way around what I am doing here?







graphs-and-networks physics






share|improve this question









New contributor




Victor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Victor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 4 hours ago









Szabolcs

164k14448946




164k14448946






New contributor




Victor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 5 hours ago









VictorVictor

1134




1134




New contributor




Victor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Victor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Victor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











  • $begingroup$
    Please note that I have just started using Mathematica a few weeks ago!
    $endgroup$
    – Victor
    5 hours ago










  • $begingroup$
    A circuit of resistors is not a directed graph. It is undirected. It does make sense to orient edges so that we can distinguish between currents flowing in opposite direction (there's a frame of reference), but you have edges going in both directions between the same vertices. It's not clear what you are trying to represent with that.
    $endgroup$
    – Szabolcs
    4 hours ago










  • $begingroup$
    @Szabolcs edge 4->0 may represent a resistor (with current flowing from 4 to 0) and edge 0->4 may represent a voltage source.
    $endgroup$
    – Victor
    4 hours ago










  • $begingroup$
    @Szabolcs although not in English, please take a look at the two diagrams in the middle of page 8 of this document. That's an example of what I have to do here, or the figures at the top of page 23 in this document
    $endgroup$
    – Victor
    4 hours ago











  • $begingroup$
    "Sagetile de pe laturi indica sensurile referinta ale curentilor si tensiunilor", thus the edge directions do not have physical meaning, they only serve as a reference for the current values and voltage difference values. (I can read Romanian.)
    $endgroup$
    – Szabolcs
    3 hours ago
















  • $begingroup$
    Please note that I have just started using Mathematica a few weeks ago!
    $endgroup$
    – Victor
    5 hours ago










  • $begingroup$
    A circuit of resistors is not a directed graph. It is undirected. It does make sense to orient edges so that we can distinguish between currents flowing in opposite direction (there's a frame of reference), but you have edges going in both directions between the same vertices. It's not clear what you are trying to represent with that.
    $endgroup$
    – Szabolcs
    4 hours ago










  • $begingroup$
    @Szabolcs edge 4->0 may represent a resistor (with current flowing from 4 to 0) and edge 0->4 may represent a voltage source.
    $endgroup$
    – Victor
    4 hours ago










  • $begingroup$
    @Szabolcs although not in English, please take a look at the two diagrams in the middle of page 8 of this document. That's an example of what I have to do here, or the figures at the top of page 23 in this document
    $endgroup$
    – Victor
    4 hours ago











  • $begingroup$
    "Sagetile de pe laturi indica sensurile referinta ale curentilor si tensiunilor", thus the edge directions do not have physical meaning, they only serve as a reference for the current values and voltage difference values. (I can read Romanian.)
    $endgroup$
    – Szabolcs
    3 hours ago















$begingroup$
Please note that I have just started using Mathematica a few weeks ago!
$endgroup$
– Victor
5 hours ago




$begingroup$
Please note that I have just started using Mathematica a few weeks ago!
$endgroup$
– Victor
5 hours ago












$begingroup$
A circuit of resistors is not a directed graph. It is undirected. It does make sense to orient edges so that we can distinguish between currents flowing in opposite direction (there's a frame of reference), but you have edges going in both directions between the same vertices. It's not clear what you are trying to represent with that.
$endgroup$
– Szabolcs
4 hours ago




$begingroup$
A circuit of resistors is not a directed graph. It is undirected. It does make sense to orient edges so that we can distinguish between currents flowing in opposite direction (there's a frame of reference), but you have edges going in both directions between the same vertices. It's not clear what you are trying to represent with that.
$endgroup$
– Szabolcs
4 hours ago












$begingroup$
@Szabolcs edge 4->0 may represent a resistor (with current flowing from 4 to 0) and edge 0->4 may represent a voltage source.
$endgroup$
– Victor
4 hours ago




$begingroup$
@Szabolcs edge 4->0 may represent a resistor (with current flowing from 4 to 0) and edge 0->4 may represent a voltage source.
$endgroup$
– Victor
4 hours ago












$begingroup$
@Szabolcs although not in English, please take a look at the two diagrams in the middle of page 8 of this document. That's an example of what I have to do here, or the figures at the top of page 23 in this document
$endgroup$
– Victor
4 hours ago





$begingroup$
@Szabolcs although not in English, please take a look at the two diagrams in the middle of page 8 of this document. That's an example of what I have to do here, or the figures at the top of page 23 in this document
$endgroup$
– Victor
4 hours ago













$begingroup$
"Sagetile de pe laturi indica sensurile referinta ale curentilor si tensiunilor", thus the edge directions do not have physical meaning, they only serve as a reference for the current values and voltage difference values. (I can read Romanian.)
$endgroup$
– Szabolcs
3 hours ago




$begingroup$
"Sagetile de pe laturi indica sensurile referinta ale curentilor si tensiunilor", thus the edge directions do not have physical meaning, they only serve as a reference for the current values and voltage difference values. (I can read Romanian.)
$endgroup$
– Szabolcs
3 hours ago










1 Answer
1






active

oldest

votes


















3












$begingroup$

A resistor network can be represented with an undirected (multi-)graph. We are going to orient each edge to obtain a directed graph, so we have a reference for which direction the current is flowing.



Let $B$ be the vertex-edge incidence matrix of the oriented graph. This can be obtained with IncidenceMatrix.



Let $v=(v_1, dots, v_n)$ be the vector of voltages at each node, $j=(j_1, dots, j_m)$ the vector of currents through each edge, and $c = (c_1, dots, c_m)$ the conductance of each resistor.



Let us put a voltage between nodes $s$ and $t$.



Kirchoff's current law tells us that the sum of currents is zero at each node except $s$ and $t$ where it is some $i$ and $-i$ respectively. In matrix notation, the sum of currents at each node is $Bj$.



Ohm's law tells us that $j = c (B^T v)$.



Putting the two together we get the sum of currents at each node as $B C B^T v$ where $C$ is a diagonal matrix obtained from $c$.



Now in Mathematica,



edges = 
1 -> 2,
1 -> 2,
1 -> 3,
2 -> 4,
4 -> 3,
5 -> 6,
6 -> 4,
5 -> 1
;

SeedRandom[42];
conductances = RandomReal[0.1, 1, Length[edges]]

g = Graph[edges]


enter image description here



b = IncidenceMatrix[g]

c = DiagonalMatrix@SparseArray[conductances]

s = 1; t = 6; (* index of sink and source node *)
totalCurrent = 1 (* total current from s to t *)


Now we can get the voltages at each node.



voltages = 
LinearSolve[
b.c.Transpose[b],
ReplacePart[
ConstantArray[0, VertexCount[g]],
s -> -totalCurrent, t -> totalCurrent
]
]


This system is underdetermined (corresponding to the fact that there's no reference for the voltages and only voltage differences make sense), but luckily Mathematica is smart enough to deal with that.



Get the current through each edge:



currents = conductances (voltages.b)


Get the effective resistance between s and t:



effectiveResistance = (voltages[[t]] - voltages[[s]])/current



Unfortunately, Mathematica is not capable of styling parallel edges differently. Below I'll use a simple graph (no multi-edges) to illustrate how to visualize the result.



Let this be our graph:



ug = Graph[GraphData["GreatRhombicuboctahedralGraph"], 
GraphStyle -> "BasicBlack", VertexSize -> 0.5];


We orient edges in an arbitrary way:



g = DirectedGraph[ug, "Acyclic"]


Then use the above code, but set the same conductance for all edges,



conductances = N@ConstantArray[1, EdgeCount[g]];


and choose



s = 1; t = 12;


Visualize voltages:



Graph[
ug,
VertexStyle ->
Thread[VertexList[ug] -> ColorData["Rainbow"] /@ Rescale[voltages]],
VertexSize -> s -> 1, t -> 1
]


enter image description here



Visualize current magnitudes though each edge:



Graph[ug,
EdgeStyle -> Prepend[
Thread[EdgeList[ug] -> (ColorData["Rainbow"] /@ Rescale@Abs[currents])],
Thickness[0.02]],
VertexSize -> s -> 1, t -> 1
]


enter image description here






share|improve this answer











$endgroup$












  • $begingroup$
    This is really clever! Thank you so much! One question: you added two edges 1 -> 2 in the edges list. Is that correct?
    $endgroup$
    – Victor
    3 hours ago










  • $begingroup$
    @Victor Yes, I did that on purpose to illustrate that the method works even with multigraphs. These two edges represent two resistors in parallel. In general, Mathematica does not deal well with multigraphs, so it's good to know that there's no problem here (IncidenceMatrix can handle them). Visualization will be troublesome though, so I added a non-multigraph example for that.
    $endgroup$
    – Szabolcs
    3 hours ago










  • $begingroup$
    Thank you so much! It became clearer!
    $endgroup$
    – Victor
    3 hours ago











Your Answer





StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["$", "$"], ["\\(","\\)"]]);
);
);
, "mathjax-editing");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "387"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);






Victor is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f195035%2fcurrents-voltages-graph-for-an-electrical-circuit%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









3












$begingroup$

A resistor network can be represented with an undirected (multi-)graph. We are going to orient each edge to obtain a directed graph, so we have a reference for which direction the current is flowing.



Let $B$ be the vertex-edge incidence matrix of the oriented graph. This can be obtained with IncidenceMatrix.



Let $v=(v_1, dots, v_n)$ be the vector of voltages at each node, $j=(j_1, dots, j_m)$ the vector of currents through each edge, and $c = (c_1, dots, c_m)$ the conductance of each resistor.



Let us put a voltage between nodes $s$ and $t$.



Kirchoff's current law tells us that the sum of currents is zero at each node except $s$ and $t$ where it is some $i$ and $-i$ respectively. In matrix notation, the sum of currents at each node is $Bj$.



Ohm's law tells us that $j = c (B^T v)$.



Putting the two together we get the sum of currents at each node as $B C B^T v$ where $C$ is a diagonal matrix obtained from $c$.



Now in Mathematica,



edges = 
1 -> 2,
1 -> 2,
1 -> 3,
2 -> 4,
4 -> 3,
5 -> 6,
6 -> 4,
5 -> 1
;

SeedRandom[42];
conductances = RandomReal[0.1, 1, Length[edges]]

g = Graph[edges]


enter image description here



b = IncidenceMatrix[g]

c = DiagonalMatrix@SparseArray[conductances]

s = 1; t = 6; (* index of sink and source node *)
totalCurrent = 1 (* total current from s to t *)


Now we can get the voltages at each node.



voltages = 
LinearSolve[
b.c.Transpose[b],
ReplacePart[
ConstantArray[0, VertexCount[g]],
s -> -totalCurrent, t -> totalCurrent
]
]


This system is underdetermined (corresponding to the fact that there's no reference for the voltages and only voltage differences make sense), but luckily Mathematica is smart enough to deal with that.



Get the current through each edge:



currents = conductances (voltages.b)


Get the effective resistance between s and t:



effectiveResistance = (voltages[[t]] - voltages[[s]])/current



Unfortunately, Mathematica is not capable of styling parallel edges differently. Below I'll use a simple graph (no multi-edges) to illustrate how to visualize the result.



Let this be our graph:



ug = Graph[GraphData["GreatRhombicuboctahedralGraph"], 
GraphStyle -> "BasicBlack", VertexSize -> 0.5];


We orient edges in an arbitrary way:



g = DirectedGraph[ug, "Acyclic"]


Then use the above code, but set the same conductance for all edges,



conductances = N@ConstantArray[1, EdgeCount[g]];


and choose



s = 1; t = 12;


Visualize voltages:



Graph[
ug,
VertexStyle ->
Thread[VertexList[ug] -> ColorData["Rainbow"] /@ Rescale[voltages]],
VertexSize -> s -> 1, t -> 1
]


enter image description here



Visualize current magnitudes though each edge:



Graph[ug,
EdgeStyle -> Prepend[
Thread[EdgeList[ug] -> (ColorData["Rainbow"] /@ Rescale@Abs[currents])],
Thickness[0.02]],
VertexSize -> s -> 1, t -> 1
]


enter image description here






share|improve this answer











$endgroup$












  • $begingroup$
    This is really clever! Thank you so much! One question: you added two edges 1 -> 2 in the edges list. Is that correct?
    $endgroup$
    – Victor
    3 hours ago










  • $begingroup$
    @Victor Yes, I did that on purpose to illustrate that the method works even with multigraphs. These two edges represent two resistors in parallel. In general, Mathematica does not deal well with multigraphs, so it's good to know that there's no problem here (IncidenceMatrix can handle them). Visualization will be troublesome though, so I added a non-multigraph example for that.
    $endgroup$
    – Szabolcs
    3 hours ago










  • $begingroup$
    Thank you so much! It became clearer!
    $endgroup$
    – Victor
    3 hours ago















3












$begingroup$

A resistor network can be represented with an undirected (multi-)graph. We are going to orient each edge to obtain a directed graph, so we have a reference for which direction the current is flowing.



Let $B$ be the vertex-edge incidence matrix of the oriented graph. This can be obtained with IncidenceMatrix.



Let $v=(v_1, dots, v_n)$ be the vector of voltages at each node, $j=(j_1, dots, j_m)$ the vector of currents through each edge, and $c = (c_1, dots, c_m)$ the conductance of each resistor.



Let us put a voltage between nodes $s$ and $t$.



Kirchoff's current law tells us that the sum of currents is zero at each node except $s$ and $t$ where it is some $i$ and $-i$ respectively. In matrix notation, the sum of currents at each node is $Bj$.



Ohm's law tells us that $j = c (B^T v)$.



Putting the two together we get the sum of currents at each node as $B C B^T v$ where $C$ is a diagonal matrix obtained from $c$.



Now in Mathematica,



edges = 
1 -> 2,
1 -> 2,
1 -> 3,
2 -> 4,
4 -> 3,
5 -> 6,
6 -> 4,
5 -> 1
;

SeedRandom[42];
conductances = RandomReal[0.1, 1, Length[edges]]

g = Graph[edges]


enter image description here



b = IncidenceMatrix[g]

c = DiagonalMatrix@SparseArray[conductances]

s = 1; t = 6; (* index of sink and source node *)
totalCurrent = 1 (* total current from s to t *)


Now we can get the voltages at each node.



voltages = 
LinearSolve[
b.c.Transpose[b],
ReplacePart[
ConstantArray[0, VertexCount[g]],
s -> -totalCurrent, t -> totalCurrent
]
]


This system is underdetermined (corresponding to the fact that there's no reference for the voltages and only voltage differences make sense), but luckily Mathematica is smart enough to deal with that.



Get the current through each edge:



currents = conductances (voltages.b)


Get the effective resistance between s and t:



effectiveResistance = (voltages[[t]] - voltages[[s]])/current



Unfortunately, Mathematica is not capable of styling parallel edges differently. Below I'll use a simple graph (no multi-edges) to illustrate how to visualize the result.



Let this be our graph:



ug = Graph[GraphData["GreatRhombicuboctahedralGraph"], 
GraphStyle -> "BasicBlack", VertexSize -> 0.5];


We orient edges in an arbitrary way:



g = DirectedGraph[ug, "Acyclic"]


Then use the above code, but set the same conductance for all edges,



conductances = N@ConstantArray[1, EdgeCount[g]];


and choose



s = 1; t = 12;


Visualize voltages:



Graph[
ug,
VertexStyle ->
Thread[VertexList[ug] -> ColorData["Rainbow"] /@ Rescale[voltages]],
VertexSize -> s -> 1, t -> 1
]


enter image description here



Visualize current magnitudes though each edge:



Graph[ug,
EdgeStyle -> Prepend[
Thread[EdgeList[ug] -> (ColorData["Rainbow"] /@ Rescale@Abs[currents])],
Thickness[0.02]],
VertexSize -> s -> 1, t -> 1
]


enter image description here






share|improve this answer











$endgroup$












  • $begingroup$
    This is really clever! Thank you so much! One question: you added two edges 1 -> 2 in the edges list. Is that correct?
    $endgroup$
    – Victor
    3 hours ago










  • $begingroup$
    @Victor Yes, I did that on purpose to illustrate that the method works even with multigraphs. These two edges represent two resistors in parallel. In general, Mathematica does not deal well with multigraphs, so it's good to know that there's no problem here (IncidenceMatrix can handle them). Visualization will be troublesome though, so I added a non-multigraph example for that.
    $endgroup$
    – Szabolcs
    3 hours ago










  • $begingroup$
    Thank you so much! It became clearer!
    $endgroup$
    – Victor
    3 hours ago













3












3








3





$begingroup$

A resistor network can be represented with an undirected (multi-)graph. We are going to orient each edge to obtain a directed graph, so we have a reference for which direction the current is flowing.



Let $B$ be the vertex-edge incidence matrix of the oriented graph. This can be obtained with IncidenceMatrix.



Let $v=(v_1, dots, v_n)$ be the vector of voltages at each node, $j=(j_1, dots, j_m)$ the vector of currents through each edge, and $c = (c_1, dots, c_m)$ the conductance of each resistor.



Let us put a voltage between nodes $s$ and $t$.



Kirchoff's current law tells us that the sum of currents is zero at each node except $s$ and $t$ where it is some $i$ and $-i$ respectively. In matrix notation, the sum of currents at each node is $Bj$.



Ohm's law tells us that $j = c (B^T v)$.



Putting the two together we get the sum of currents at each node as $B C B^T v$ where $C$ is a diagonal matrix obtained from $c$.



Now in Mathematica,



edges = 
1 -> 2,
1 -> 2,
1 -> 3,
2 -> 4,
4 -> 3,
5 -> 6,
6 -> 4,
5 -> 1
;

SeedRandom[42];
conductances = RandomReal[0.1, 1, Length[edges]]

g = Graph[edges]


enter image description here



b = IncidenceMatrix[g]

c = DiagonalMatrix@SparseArray[conductances]

s = 1; t = 6; (* index of sink and source node *)
totalCurrent = 1 (* total current from s to t *)


Now we can get the voltages at each node.



voltages = 
LinearSolve[
b.c.Transpose[b],
ReplacePart[
ConstantArray[0, VertexCount[g]],
s -> -totalCurrent, t -> totalCurrent
]
]


This system is underdetermined (corresponding to the fact that there's no reference for the voltages and only voltage differences make sense), but luckily Mathematica is smart enough to deal with that.



Get the current through each edge:



currents = conductances (voltages.b)


Get the effective resistance between s and t:



effectiveResistance = (voltages[[t]] - voltages[[s]])/current



Unfortunately, Mathematica is not capable of styling parallel edges differently. Below I'll use a simple graph (no multi-edges) to illustrate how to visualize the result.



Let this be our graph:



ug = Graph[GraphData["GreatRhombicuboctahedralGraph"], 
GraphStyle -> "BasicBlack", VertexSize -> 0.5];


We orient edges in an arbitrary way:



g = DirectedGraph[ug, "Acyclic"]


Then use the above code, but set the same conductance for all edges,



conductances = N@ConstantArray[1, EdgeCount[g]];


and choose



s = 1; t = 12;


Visualize voltages:



Graph[
ug,
VertexStyle ->
Thread[VertexList[ug] -> ColorData["Rainbow"] /@ Rescale[voltages]],
VertexSize -> s -> 1, t -> 1
]


enter image description here



Visualize current magnitudes though each edge:



Graph[ug,
EdgeStyle -> Prepend[
Thread[EdgeList[ug] -> (ColorData["Rainbow"] /@ Rescale@Abs[currents])],
Thickness[0.02]],
VertexSize -> s -> 1, t -> 1
]


enter image description here






share|improve this answer











$endgroup$



A resistor network can be represented with an undirected (multi-)graph. We are going to orient each edge to obtain a directed graph, so we have a reference for which direction the current is flowing.



Let $B$ be the vertex-edge incidence matrix of the oriented graph. This can be obtained with IncidenceMatrix.



Let $v=(v_1, dots, v_n)$ be the vector of voltages at each node, $j=(j_1, dots, j_m)$ the vector of currents through each edge, and $c = (c_1, dots, c_m)$ the conductance of each resistor.



Let us put a voltage between nodes $s$ and $t$.



Kirchoff's current law tells us that the sum of currents is zero at each node except $s$ and $t$ where it is some $i$ and $-i$ respectively. In matrix notation, the sum of currents at each node is $Bj$.



Ohm's law tells us that $j = c (B^T v)$.



Putting the two together we get the sum of currents at each node as $B C B^T v$ where $C$ is a diagonal matrix obtained from $c$.



Now in Mathematica,



edges = 
1 -> 2,
1 -> 2,
1 -> 3,
2 -> 4,
4 -> 3,
5 -> 6,
6 -> 4,
5 -> 1
;

SeedRandom[42];
conductances = RandomReal[0.1, 1, Length[edges]]

g = Graph[edges]


enter image description here



b = IncidenceMatrix[g]

c = DiagonalMatrix@SparseArray[conductances]

s = 1; t = 6; (* index of sink and source node *)
totalCurrent = 1 (* total current from s to t *)


Now we can get the voltages at each node.



voltages = 
LinearSolve[
b.c.Transpose[b],
ReplacePart[
ConstantArray[0, VertexCount[g]],
s -> -totalCurrent, t -> totalCurrent
]
]


This system is underdetermined (corresponding to the fact that there's no reference for the voltages and only voltage differences make sense), but luckily Mathematica is smart enough to deal with that.



Get the current through each edge:



currents = conductances (voltages.b)


Get the effective resistance between s and t:



effectiveResistance = (voltages[[t]] - voltages[[s]])/current



Unfortunately, Mathematica is not capable of styling parallel edges differently. Below I'll use a simple graph (no multi-edges) to illustrate how to visualize the result.



Let this be our graph:



ug = Graph[GraphData["GreatRhombicuboctahedralGraph"], 
GraphStyle -> "BasicBlack", VertexSize -> 0.5];


We orient edges in an arbitrary way:



g = DirectedGraph[ug, "Acyclic"]


Then use the above code, but set the same conductance for all edges,



conductances = N@ConstantArray[1, EdgeCount[g]];


and choose



s = 1; t = 12;


Visualize voltages:



Graph[
ug,
VertexStyle ->
Thread[VertexList[ug] -> ColorData["Rainbow"] /@ Rescale[voltages]],
VertexSize -> s -> 1, t -> 1
]


enter image description here



Visualize current magnitudes though each edge:



Graph[ug,
EdgeStyle -> Prepend[
Thread[EdgeList[ug] -> (ColorData["Rainbow"] /@ Rescale@Abs[currents])],
Thickness[0.02]],
VertexSize -> s -> 1, t -> 1
]


enter image description here







share|improve this answer














share|improve this answer



share|improve this answer








edited 3 hours ago

























answered 3 hours ago









SzabolcsSzabolcs

164k14448946




164k14448946











  • $begingroup$
    This is really clever! Thank you so much! One question: you added two edges 1 -> 2 in the edges list. Is that correct?
    $endgroup$
    – Victor
    3 hours ago










  • $begingroup$
    @Victor Yes, I did that on purpose to illustrate that the method works even with multigraphs. These two edges represent two resistors in parallel. In general, Mathematica does not deal well with multigraphs, so it's good to know that there's no problem here (IncidenceMatrix can handle them). Visualization will be troublesome though, so I added a non-multigraph example for that.
    $endgroup$
    – Szabolcs
    3 hours ago










  • $begingroup$
    Thank you so much! It became clearer!
    $endgroup$
    – Victor
    3 hours ago
















  • $begingroup$
    This is really clever! Thank you so much! One question: you added two edges 1 -> 2 in the edges list. Is that correct?
    $endgroup$
    – Victor
    3 hours ago










  • $begingroup$
    @Victor Yes, I did that on purpose to illustrate that the method works even with multigraphs. These two edges represent two resistors in parallel. In general, Mathematica does not deal well with multigraphs, so it's good to know that there's no problem here (IncidenceMatrix can handle them). Visualization will be troublesome though, so I added a non-multigraph example for that.
    $endgroup$
    – Szabolcs
    3 hours ago










  • $begingroup$
    Thank you so much! It became clearer!
    $endgroup$
    – Victor
    3 hours ago















$begingroup$
This is really clever! Thank you so much! One question: you added two edges 1 -> 2 in the edges list. Is that correct?
$endgroup$
– Victor
3 hours ago




$begingroup$
This is really clever! Thank you so much! One question: you added two edges 1 -> 2 in the edges list. Is that correct?
$endgroup$
– Victor
3 hours ago












$begingroup$
@Victor Yes, I did that on purpose to illustrate that the method works even with multigraphs. These two edges represent two resistors in parallel. In general, Mathematica does not deal well with multigraphs, so it's good to know that there's no problem here (IncidenceMatrix can handle them). Visualization will be troublesome though, so I added a non-multigraph example for that.
$endgroup$
– Szabolcs
3 hours ago




$begingroup$
@Victor Yes, I did that on purpose to illustrate that the method works even with multigraphs. These two edges represent two resistors in parallel. In general, Mathematica does not deal well with multigraphs, so it's good to know that there's no problem here (IncidenceMatrix can handle them). Visualization will be troublesome though, so I added a non-multigraph example for that.
$endgroup$
– Szabolcs
3 hours ago












$begingroup$
Thank you so much! It became clearer!
$endgroup$
– Victor
3 hours ago




$begingroup$
Thank you so much! It became clearer!
$endgroup$
– Victor
3 hours ago










Victor is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















Victor is a new contributor. Be nice, and check out our Code of Conduct.












Victor is a new contributor. Be nice, and check out our Code of Conduct.











Victor is a new contributor. Be nice, and check out our Code of Conduct.














Thanks for contributing an answer to Mathematica Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f195035%2fcurrents-voltages-graph-for-an-electrical-circuit%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Францішак Багушэвіч Змест Сям'я | Біяграфія | Творчасць | Мова Багушэвіча | Ацэнкі дзейнасці | Цікавыя факты | Спадчына | Выбраная бібліяграфія | Ушанаванне памяці | У філатэліі | Зноскі | Літаратура | Спасылкі | НавігацыяЛяхоўскі У. Рупіўся дзеля Бога і людзей: Жыццёвы шлях Лявона Вітан-Дубейкаўскага // Вольскі і Памідораў з песняй пра немца Адвакат, паэт, народны заступнік Ашмянскі веснікВ Минске появится площадь Богушевича и улица Сырокомли, Белорусская деловая газета, 19 июля 2001 г.Айцец беларускай нацыянальнай ідэі паўстаў у бронзе Сяргей Аляксандравіч Адашкевіч (1918, Мінск). 80-я гады. Бюст «Францішак Багушэвіч».Яўген Мікалаевіч Ціхановіч. «Партрэт Францішка Багушэвіча»Мікола Мікалаевіч Купава. «Партрэт зачынальніка новай беларускай літаратуры Францішка Багушэвіча»Уладзімір Іванавіч Мелехаў. На помніку «Змагарам за родную мову» Барэльеф «Францішак Багушэвіч»Памяць пра Багушэвіча на Віленшчыне Страчаная сталіца. Беларускія шыльды на вуліцах Вільні«Krynica». Ideologia i przywódcy białoruskiego katolicyzmuФранцішак БагушэвічТворы на knihi.comТворы Францішка Багушэвіча на bellib.byСодаль Уладзімір. Францішак Багушэвіч на Лідчыне;Луцкевіч Антон. Жыцьцё і творчасьць Фр. Багушэвіча ў успамінах ягоных сучасьнікаў // Запісы Беларускага Навуковага таварыства. Вільня, 1938. Сшытак 1. С. 16-34.Большая российская1188761710000 0000 5537 633Xn9209310021619551927869394п

Беларусь Змест Назва Гісторыя Геаграфія Сімволіка Дзяржаўны лад Палітычныя партыі Міжнароднае становішча і знешняя палітыка Адміністрацыйны падзел Насельніцтва Эканоміка Культура і грамадства Сацыяльная сфера Узброеныя сілы Заўвагі Літаратура Спасылкі НавігацыяHGЯOiТоп-2011 г. (па версіі ej.by)Топ-2013 г. (па версіі ej.by)Топ-2016 г. (па версіі ej.by)Топ-2017 г. (па версіі ej.by)Нацыянальны статыстычны камітэт Рэспублікі БеларусьШчыльнасць насельніцтва па краінахhttp://naviny.by/rubrics/society/2011/09/16/ic_articles_116_175144/А. Калечыц, У. Ксяндзоў. Спробы засялення краю неандэртальскім чалавекам.І ў Менску былі мамантыА. Калечыц, У. Ксяндзоў. Старажытны каменны век (палеаліт). Першапачатковае засяленне тэрыторыіГ. Штыхаў. Балты і славяне ў VI—VIII стст.М. Клімаў. Полацкае княства ў IX—XI стст.Г. Штыхаў, В. Ляўко. Палітычная гісторыя Полацкай зямліГ. Штыхаў. Дзяржаўны лад у землях-княствахГ. Штыхаў. Дзяржаўны лад у землях-княствахБеларускія землі ў складзе Вялікага Княства ЛітоўскагаЛюблінская унія 1569 г."The Early Stages of Independence"Zapomniane prawdy25 гадоў таму было аб'яўлена, што Язэп Пілсудскі — беларус (фота)Наша вадаДакументы ЧАЭС: Забруджванне тэрыторыі Беларусі « ЧАЭС Зона адчужэнняСведения о политических партиях, зарегистрированных в Республике Беларусь // Министерство юстиции Республики БеларусьСтатыстычны бюлетэнь „Полаўзроставая структура насельніцтва Рэспублікі Беларусь на 1 студзеня 2012 года і сярэднегадовая колькасць насельніцтва за 2011 год“Индекс человеческого развития Беларуси — не было бы нижеБеларусь занимает первое место в СНГ по индексу развития с учетом гендерного факцёраНацыянальны статыстычны камітэт Рэспублікі БеларусьКанстытуцыя РБ. Артыкул 17Трансфармацыйныя задачы БеларусіВыйсце з крызісу — далейшае рэфармаванне Беларускі рубель — сусветны лідар па дэвальвацыяхПра змену коштаў у кастрычніку 2011 г.Бядней за беларусаў у СНД толькі таджыкіСярэдні заробак у верасні дасягнуў 2,26 мільёна рублёўЭканомікаГаласуем за ТОП-100 беларускай прозыСучасныя беларускія мастакіАрхитектура Беларуси BELARUS.BYА. Каханоўскі. Культура Беларусі ўсярэдзіне XVII—XVIII ст.Анталогія беларускай народнай песні, гуказапісы спеваўБеларускія Музычныя IнструментыБеларускі рок, які мы страцілі. Топ-10 гуртоў«Мясцовы час» — нязгаслая легенда беларускай рок-музыкіСЯРГЕЙ БУДКІН. МЫ НЯ ЗНАЕМ СВАЁЙ МУЗЫКІМ. А. Каладзінскі. НАРОДНЫ ТЭАТРМагнацкія культурныя цэнтрыПублічная дыскусія «Беларуская новая пьеса: без беларускай мовы ці беларуская?»Беларускія драматургі па-ранейшаму лепш ставяцца за мяжой, чым на радзіме«Працэс незалежнага кіно пайшоў, і дзяржаву турбуе яго непадкантрольнасць»Беларускія філосафы ў пошуках прасторыВсе идём в библиотекуАрхіваванаАб Нацыянальнай праграме даследавання і выкарыстання касмічнай прасторы ў мірных мэтах на 2008—2012 гадыУ космас — разам.У суседнім з Барысаўскім раёне пабудуюць Камандна-вымяральны пунктСвяты і абрады беларусаў«Мірныя бульбашы з малой краіны» — 5 непраўдзівых стэрэатыпаў пра БеларусьМ. Раманюк. Беларускае народнае адзеннеУ Беларусі скарачаецца колькасць злачынстваўЛукашэнка незадаволены мінскімі ўладамі Крадзяжы складаюць у Мінску каля 70% злачынстваў Узровень злачыннасці ў Мінскай вобласці — адзін з самых высокіх у краіне Генпракуратура аналізуе стан са злачыннасцю ў Беларусі па каэфіцыенце злачыннасці У Беларусі стабілізавалася крымінагеннае становішча, лічыць генпракурорЗамежнікі сталі здзяйсняць у Беларусі больш злачынстваўМУС Беларусі турбуе рост рэцыдыўнай злачыннасціЯ з ЖЭСа. Дазволіце вас абкрасці! Рэйтынг усіх службаў і падраздзяленняў ГУУС Мінгарвыканкама вырасАб КДБ РБГісторыя Аператыўна-аналітычнага цэнтра РБГісторыя ДКФРТаможняagentura.ruБеларусьBelarus.by — Афіцыйны сайт Рэспублікі БеларусьСайт урада БеларусіRadzima.org — Збор архітэктурных помнікаў, гісторыя Беларусі«Глобус Беларуси»Гербы и флаги БеларусиАсаблівасці каменнага веку на БеларусіА. Калечыц, У. Ксяндзоў. Старажытны каменны век (палеаліт). Першапачатковае засяленне тэрыторыіУ. Ксяндзоў. Сярэдні каменны век (мезаліт). Засяленне краю плямёнамі паляўнічых, рыбакоў і збіральнікаўА. Калечыц, М. Чарняўскі. Плямёны на тэрыторыі Беларусі ў новым каменным веку (неаліце)А. Калечыц, У. Ксяндзоў, М. Чарняўскі. Гаспадарчыя заняткі ў каменным векуЭ. Зайкоўскі. Духоўная культура ў каменным векуАсаблівасці бронзавага веку на БеларусіФарміраванне супольнасцей ранняга перыяду бронзавага векуФотографии БеларусиРоля беларускіх зямель ва ўтварэнні і ўмацаванні ВКЛВ. Фадзеева. З гісторыі развіцця беларускай народнай вышыўкіDMOZGran catalanaБольшая российскаяBritannica (анлайн)Швейцарскі гістарычны15325917611952699xDA123282154079143-90000 0001 2171 2080n9112870100577502ge128882171858027501086026362074122714179пппппп

ValueError: Expected n_neighbors <= n_samples, but n_samples = 1, n_neighbors = 6 (SMOTE) The 2019 Stack Overflow Developer Survey Results Are InCan SMOTE be applied over sequence of words (sentences)?ValueError when doing validation with random forestsSMOTE and multi class oversamplingLogic behind SMOTE-NC?ValueError: Error when checking target: expected dense_1 to have shape (7,) but got array with shape (1,)SmoteBoost: Should SMOTE be ran individually for each iteration/tree in the boosting?solving multi-class imbalance classification using smote and OSSUsing SMOTE for Synthetic Data generation to improve performance on unbalanced dataproblem of entry format for a simple model in KerasSVM SMOTE fit_resample() function runs forever with no result