>>> import gndemo >>> from scipy import * >>> import numpy as N >>> n = 5; >>> n = 4; >>> e = gndemo.path(n) # the edge list of a path graph >>> print e [[0, 1], [1, 2], [2, 3]] >>> a = gndemo.edges2adjmat(e) # generate an adjacency matrix >>> print a (0, 1) 1 (1, 0) 1 (1, 2) 1 (2, 1) 1 (2, 3) 1 (3, 2) 1 >>> l = gndemo.adjmat2lap(a) # generate the laplacian >>> print l (0, 0) 1.0 (1, 0) -1.0 (0, 1) -1.0 (1, 1) 2.0 (2, 1) -1.0 (1, 2) -1.0 (2, 2) 2.0 (3, 2) -1.0 (2, 3) -1.0 (3, 3) 1.0 >>> b = N.zeros(n) # create a right-hand side to solve >>> b[0] = 1 >>> b[-1] = -1 >>> print b [ 1 0 0 -1] >>> ans = linalg.iterative.cg(l,b) # solve the system >>> x = ans[0] >>> print x [ 1.5 0.5 -0.5 -1.5] >>> print l*x [ 1. 0. 0. -1.] >>> print linalg.norm(l*x - b) # check that we got a good answer 0.0 >>> n = 10000 # now, let's do a much larger path graph >>> e = gndemo.path(n) >>> a = gndemo.edges2adjmat(e) l = >>> >>> l = gndemo.adjmat2lap(a) >>> b = zeros(n) >>> b[0] = 1 >>> b[-1] = -1 >>> ans = linalg.iterative.cg(l,b) # this only took a few seconds >>> x = ans[0] >>> print linalg.norm(l*x - b) 0.0 # note: path graphs are about the worst case for this algorithm # random graphs, which we try next, are the best case # also note that my code for generating the matrices is painfully slow >>> e = gndemo.randGraph(n, 40*n) >>> a = gndemo.edges2adjmat(e) >>> l = gndemo.adjmat2lap(a) >>> b = zeros(n) >>> b[0] = 1 >>> b[-1] = -1 >>> ans = linalg.iterative.cg(l,b) >>> x = ans[0] >>> print linalg.norm(l*x - b) 9.90255546596e-006 # note: that was still pretty small error # here is a demo of solving for the flow given potentials at particular # vertices. In this exmple, I create a path graph on 10 vertices ( # numbered from 0 to 9), set the potential of vertex 0 to -1, the potential # of vertex 9 to 1, and then get all the induced potentials: # # note that this demo was done using ipython In [1]: from numpy import * In [2]: import gndemo In [3]: e = gndemo.path(10) In [4]: verts = array([0, 9]) In [5]: pots = array([-1, 1]) In [6]: x = gndemo.solvePotentials(e, verts, pots) In [7]: print x [-1. -0.77777778 -0.55555556 -0.33333333 -0.11111111 0.11111111 0.33333333 0.55555556 0.77777778 1. ]