Skip to content

Instantly share code, notes, and snippets.

@aelguindy
Created February 5, 2012 21:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aelguindy/1747940 to your computer and use it in GitHub Desktop.
Save aelguindy/1747940 to your computer and use it in GitHub Desktop.
Quick Circuit Resistance Calculator
# SOURCE: http://elonen.iki.fi/code/misc-notes/python-gaussj/
def gauss_jordan(m, eps = 1.0/(10**10)):
"""Puts given matrix (2D array) into the Reduced Row Echelon Form.
Returns True if successful, False if 'm' is singular.
NOTE: make sure all the matrix items support fractions! Int matrix will NOT work!
Written by Jarno Elonen in April 2005, released into Public Domain"""
(h, w) = (len(m), len(m[0]))
for y in range(0,h):
maxrow = y
for y2 in range(y+1, h): # Find max pivot
if abs(m[y2][y]) > abs(m[maxrow][y]):
maxrow = y2
(m[y], m[maxrow]) = (m[maxrow], m[y])
if abs(m[y][y]) <= eps: # Singular?
return False
for y2 in range(y+1, h): # Eliminate column y
c = m[y2][y] / m[y][y]
for x in range(y, w):
m[y2][x] -= m[y][x] * c
for y in range(h-1, 0-1, -1): # Backsubstitute
c = m[y][y]
for y2 in range(0,y):
for x in range(w-1, y-1, -1):
m[y2][x] -= m[y][x] * m[y2][y] / c
m[y][y] /= c
for x in range(h, w): # Normalize row y
m[y][x] /= c
return True
def preprocess(edges, V):
lists = []
for i in range(V): lists.append([])
for fro, to, res in edges:
lists[fro].append((to, res))
lists[to].append((fro, res))
return lists
def make_eqns(lists, node1, node2):
coeffs = []
Vars = len(lists)
for i, l in enumerate(lists):
cs = [0.0]*Vars
cs[i] = sum(1/b for (a, b) in l)
for other, res in l:
cs[other] -= 1.0/res
coeffs.append(cs)
rhs = [0] * Vars
rhs[node1] = 1.0
rhs[node2] = -1.0
n = max(node1, node2)
coeffs = [c[:n] + c[n + 1:] for c in coeffs]
return coeffs[:-1], rhs[:-1]
def calculate_resistance(nodes, edges, source, destination):
src = source
dst = destination
ls = preprocess(edges, nodes)
a, b = make_eqns(ls, src, dst)
M = [a[i] + [b[i]] for i in range(len(a))]
gauss_jordan(M)
return abs(M[min(src, dst)][-1])
if __name__ == '__main__':
print calculate_resistance(4, [(0, 1, 1.0), (0, 2, 1.0), (0, 3, 1.0), (1, 3, 1.0), (2, 3, 1.0)], 0, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment