示例#1
0
def get_matrices(G):
    '''

    Parameters
    ----------
    G : NetworkX graph

    Returns
    -------
    T : Numpy array

    L : NumPy array
        Combinatorial Laplacian of G
    W :

    '''
    W = nx.to_numpy_matrix(G, nodelist=sorted(G.nodes()))
    L = nx.laplacian(G, nodelist=sorted(G.nodes()))
    D = W.sum(1)
    P = W / D
    D = np.array(D).flatten()
    Dsq = np.sqrt(D)
    Disq = (1 / Dsq)
    T = np.dot(np.diag(Dsq), P)
    T = np.dot(T, np.diag(Disq))
    T = (T + T.T) / 2 # Iron out numerical wrinkles

    return T, L, np.array(W)
def MaxImpedanceComputation(InputGraph):
	
	MaxTotalImpedance=0
	
	G=InputGraph.copy()
	number_of_vertices=G.order()
	vertexlist=G.nodes()
	
	for top_node in vertexlist:
		for ground_node in vertexlist:
			if ground_node<top_node:
				ordered_vertexlist=vertexlist[:]
				ordered_vertexlist.remove(top_node)
				ordered_vertexlist.remove(ground_node)
				ordered_vertexlist.insert(0,top_node)
				ordered_vertexlist.insert(0,ground_node)
				
				LaplacianMatrix=nx.laplacian(G,ordered_vertexlist)
				ConductanceMatrix=np.delete(LaplacianMatrix,0,0)
				ConductanceMatrix=np.delete(ConductanceMatrix,np.s_[0],1)
				InputVector=[0]*(number_of_vertices-1)
				InputVector[0]=1
				VoltageVector=linalg.solve(ConductanceMatrix,InputVector)
				TotalImpedance=VoltageVector[0]
				if TotalImpedance>MaxTotalImpedance:
					MaxTotalImpedance=TotalImpedance
	
	return MaxTotalImpedance
 def test_laplacian(self):
     "Graph Laplacian"
     NL=numpy.array([[ 3, -1, -1, -1, 0], 
                     [-1,  2, -1,  0, 0], 
                     [-1, -1,  2,  0, 0], 
                     [-1,  0,  0,  1, 0], 
                     [ 0,  0,  0,  0, 0]])
     assert_equal(nx.laplacian(self.G),NL)
示例#4
0
def findLaplacianKernel(g):
    pm = nx.laplacian(g)
    n = pm.shape[0]
    #print "Number of nodes: ", n
    e = np.matrix(np.ones(n)).transpose()
    f = (e*e.transpose())/n
    km = np.linalg.inv(pm - f) + f
    return km
def _compute_C(G):
    """Compute inverse of Laplacian."""
    try:
        import numpy as np
    except ImportError:
        raise ImportError("flow_closeness_centrality() requires NumPy: http://scipy.org/ ")
    L=nx.laplacian(G) # use ordering of G.nodes()
    # remove first row and column
    LR=L[1:,1:]
    LRinv=np.linalg.inv(LR)
    C=np.zeros(L.shape)
    C[1:,1:]=LRinv
    return C
示例#6
0
def test1():
    N = 3
    G = nx.cycle_graph(N)
    # Add self loop to all vertices
    for node in G.nodes():
        G.add_edge(node, node)

    Ln_nx = nx.normalized_laplacian(G)
    L_nx = nx.laplacian(G)

    A = nx.adj_matrix(G)

    # Using G.degree to compute D
    D1 = np.array([G.degree()[n] for n in G])
    Disqrt1 = np.array(1 / np.sqrt(D1))
    Disqrt1 = np.diag(Disqrt1)
    L1 = np.diag(D1) - A
    Ln1 = np.dot(np.dot(Disqrt1, L1), Disqrt1)

    # Using A.sum(1) to compute D
    D2 = np.array(np.sum(A, 1)).flatten()
    Disqrt2 = np.array(1 / np.sqrt(D2))
    Disqrt2 = np.diag(Disqrt2)
    L2 = np.diag(D2) - A
    Ln2 = np.dot(np.dot(Disqrt2, L2), Disqrt2)

    # Using G.degree and nx.laplacian to compute D
    L3 = nx.laplacian(G)
    Ln3 = np.dot(np.dot(Disqrt1, L3), Disqrt1)
    Ln3_ = np.dot(Disqrt1, np.dot(L3, Disqrt1))

    print "NetworkX version"
    print Ln_nx
    print "\nUsing G.degree to compute D"
    print Ln1
    print "\nUsing A.sum(1) to compute D"
    print Ln2
    print "\nUsing G.degree and nx.laplacian to compute D"
    print Ln3
def _compute_C(G,weight='weight'):
    """Inverse of Laplacian."""
    try:
        import numpy as np
    except ImportError:
        raise ImportError(
            """current_flow_betweenness_centrality() requires NumPy 
http://scipy.org/""")
    L=nx.laplacian(G,weight=weight) # use ordering of G.nodes() 
    # remove first row and column
    LR=L[1:,1:]
    LRinv=np.linalg.inv(LR)
    C=np.zeros(L.shape)
    C[1:,1:]=LRinv
    return C
示例#8
0
 def test_laplacian(self):
     "Graph Laplacian"
     NL = numpy.array([[3, -1, -1, -1, 0], [-1, 2, -1, 0, 0], [-1, -1, 2, 0, 0], [-1, 0, 0, 1, 0], [0, 0, 0, 0, 0]])
     WL = 0.5 * NL
     OL = 0.3 * NL
     assert_equal(nx.laplacian(self.G), NL)
     assert_equal(nx.laplacian(self.MG), NL)
     assert_equal(nx.laplacian(self.G, nodelist=[0, 1]), numpy.array([[1, -1], [-1, 1]]))
     assert_equal(nx.laplacian(self.WG), WL)
     assert_equal(nx.laplacian(self.WG, weight=None), NL)
     assert_equal(nx.laplacian(self.WG, weight="other"), OL)
示例#9
0
def make_T(N, add_selfloops=False):
    '''Compute the diffusion operator of an N-by-N grid graph.

    The difussion operator is defined as

    T = D^0.5 * P * D^-0.5, where D is the degree matrix, P=D^-1W is the random
    walk matrix, and W is the adjancency matrix.
    '''
    G = nx.grid_2d_graph(N, N)
    if add_selfloops:
        for n in G:
            G.add_edge(n, n)

    T, _ = get_T(G)
    L = nx.laplacian(G, nodelist=sorted(G.nodes()))

    return T, L
示例#10
0
def make_T(N, add_selfloops=False):
    '''Compute the diffusion operator of an N-by-N grid graph.

    The difussion operator is defined as

    T = D^0.5 * P * D^-0.5, where D is the degree matrix, P=D^-1W is the random
    walk matrix, and W is the adjancency matrix.
    '''
    G = nx.grid_2d_graph(N,N)
    if add_selfloops:
        for n in G:
            G.add_edge(n, n)
            
    T, _ = get_T(G)
    L = nx.laplacian(G, nodelist=sorted(G.nodes()))
    
    return T, L
示例#11
0
    def test_eigenvectors(self):
        try:
            import numpy as N
            eigenval=N.linalg.eigvals
        except ImportError:
            raise SkipTest('NumPy not available.')

        cs='ddiiddid'
        G=nxt.threshold_graph(cs)
        (tgeval,tgevec)=nxt.eigenvectors(cs)
        dot=N.dot
        assert_equal([ abs(dot(lv,lv)-1.0)<1e-9 for lv in tgevec ], [True]*8)
        lapl=nx.laplacian(G)
        tgev=[ dot(lv,dot(lapl,lv)) for lv in tgevec ]
        assert_true(sum([abs(c-d) for c,d in zip(tgev,tgeval)]) < 1e-9)
        tgev.sort()
        lev=list(eigenval(lapl))
        lev.sort()
        assert_true(sum([abs(c-d) for c,d in zip(tgev,lev)]) < 1e-9)
示例#12
0
    def test_eigenvectors(self):
        try:
            import numpy as N
            eigenval=N.linalg.eigvals
        except ImportError:
            raise SkipTest('NumPy not available.')

        cs='ddiiddid'
        G=nxt.threshold_graph(cs)
        (tgeval,tgevec)=nxt.eigenvectors(cs)
        dot=N.dot
        assert_equal([ abs(dot(lv,lv)-1.0)<1e-9 for lv in tgevec ], [True]*8)
        lapl=nx.laplacian(G)
        tgev=[ dot(lv,dot(lapl,lv)) for lv in tgevec ]
        assert_true(sum([abs(c-d) for c,d in zip(tgev,tgeval)]) < 1e-9)
        tgev.sort()
        lev=list(eigenval(lapl))
        lev.sort()
        assert_true(sum([abs(c-d) for c,d in zip(tgev,lev)]) < 1e-9)
示例#13
0
 def test_laplacian(self):
     "Graph Laplacian"
     NL = numpy.array([[3, -1, -1, -1, 0], [-1, 2, -1, 0, 0],
                       [-1, -1, 2, 0, 0], [-1, 0, 0, 1, 0], [0, 0, 0, 0,
                                                             0]])
     WL = 0.5 * NL
     OL = 0.3 * NL
     assert_equal(nx.laplacian(self.G), NL)
     assert_equal(nx.laplacian(self.MG), NL)
     assert_equal(nx.laplacian(self.G, nodelist=[0, 1]),
                  numpy.array([[1, -1], [-1, 1]]))
     assert_equal(nx.laplacian(self.WG), WL)
     assert_equal(nx.laplacian(self.WG, weight=None), NL)
     assert_equal(nx.laplacian(self.WG, weight='other'), OL)
示例#14
0
def norm_lap(G, nodelist=None, weight="weight"):
    # Graph or DiGraph, this is faster than above
    if nodelist is None:
        nodelist = G.nodes()
    n = len(nodelist)
    L = np.zeros((n, n))
    deg = np.zeros((n, n))
    index = dict((n, i) for i, n in enumerate(nodelist))
    for ui, u in enumerate(nodelist):
        totalwt = 0.0
        for v, data in G[u].items():
            try:
                vi = index[v]
            except KeyError:
                continue
            wt = data.get(weight, 1)
            L[ui, vi] = -wt
            if ui != vi:
                totalwt += wt
        print "tw", totalwt
        L[ui, ui] = totalwt
        if totalwt > 0.0:
            deg[ui, ui] = np.sqrt(1.0 / totalwt)

    Lnx = nx.laplacian(G)
    print "Matriced used by NetworkX"
    print "nx.laplacian(G)"
    print Lnx

    print "\nL"
    print L

    print "Disqrt"
    print deg
    L = np.dot(deg, np.dot(L, deg))
    return L
示例#15
0
def algebraic_distance(G, params={}):
    '''
    takes: graph G, computational parameters

    returns:
    a distance dictionary, d[node1][node2]  giving the distance between the nodes

    ref:
            RELAXATION-BASED COARSENING AND
            MULTISCALE GRAPH ORGANIZATION
            DORIT RON, ILYA SAFRO, AND ACHI BRANDT

    this code is not currently used in the main generator algorithm

    wishlist: use sparse matrices
    '''

    H = nx.convert_node_labels_to_integers(G, discard_old_labels=False)
    metric = params.get('metric', 'Linfinity')
    num_relaxations_r = params.get('num_relaxations_r', 10)
    num_test_vectors_K = params.get('num_test_vectors_K', 20)
    lazy_walk_param_w = params.get('lazy_walk_param_w', 0.5)

    if metric != 'Linfinity':
        raise Exception('Metric other than Linifinity not implemented')

    distance = {}
    for node1 in H:
        distance[node1] = {}
        for node2 in H:
            if node1 < node2:  #save time
                distance[node1][node2] = -np.inf

    LAP = nx.laplacian(H)
    diag_vec = np.diag(LAP)
    DIAG = np.diag(diag_vec)
    w_times_Dinv_times_D_minus_LAP = lazy_walk_param_w * np.dot(
        np.diag([1. / el for el in diag_vec]), DIAG - LAP)

    for t in xrange(num_test_vectors_K):
        x = npr.rand(H.number_of_nodes(), 1)

        for iteration in xrange(num_relaxations_r):
            x = (1 - lazy_walk_param_w) * x + np.dot(
                w_times_Dinv_times_D_minus_LAP, x)

        for node1 in H:
            for node2 in H:
                dis = abs(x[node1] - x[node2])[0]
                if node1 < node2 and dis > distance[node1][
                        node2]:  #to save time, compute just the upper triangle of the matrix
                    distance[node1][node2] = dis

    #generate the distance dictionary in the original node labels, and including the diagonal and lower triangle
    ret = {}
    for u in G:
        ret[u] = {}
        for v in G:
            node1 = H.node_labels[u]
            node2 = H.node_labels[v]
            if node1 < node2:
                ret[u][v] = distance[node1][node2]
            elif node1 > node2:
                ret[u][v] = distance[node2][node1]
            else:
                ret[u][v] = 0.
    return ret
# Setup the node list
nodelist = [(i, j) for i in range(numx) for j in range(numy)]


def node_to_pos2d(node):
    """Give a node number, return the point on the physical mesh."""
    return nodelist[node]


def pos_to_node2d(pos):
    """Give the position on the physical mesh, return the node."""
    return nodelist.index(pos)


L = np.matrix(nx.laplacian(G, nodelist=nodelist))

# The rhs of the diffusion equation
rhs = -D * L / h**2

# The main temperature array.
T = np.matrix(np.zeros((nnodes, ntimes)))

# Setting initial temperature. Here we create a temporary array that has the
# physical shape. We then set the temp using x,y coordinates and then reshape
# for the computation. This rehaping matches the nodelist above.
Tnot = np.matrix(np.zeros((numx, numy)))
Tnot[2, 2] = 100.0
Tnot.shape = (nnodes, 1)
T[:, 0] = Tnot
示例#17
0
文件: maxcut.py 项目: gharib85/picos
import cvxopt as cvx
import cvxopt.lapack
import numpy as np

#make G undirected
G = nx.Graph(G)

#allocate weights to the edges
for (i, j) in G.edges():
    G[i][j]['weight'] = c[i, j] + c[j, i]

maxcut = pic.Problem()
X = maxcut.add_variable('X', (N, N), 'symmetric')

#Laplacian of the graph
L = pic.new_param('L', 1 / 4. * nx.laplacian(G))

#ones on the diagonal
maxcut.add_constraint(pic.tools.diag_vect(X) == 1)
#X positive semidefinite
maxcut.add_constraint(X >> 0)

#objective
maxcut.set_objective('max', L | X)

#print maxcut
maxcut.solve(verbose=0)

#Cholesky factorization
V = X.value
示例#18
0
    for node in G.nodes():
        G.add_edge(node, node)

    Ln = norm_lap(G)
    Ln_aw = norm_lap_aw(G)

    print "\nNetworkX version"
    print Ln
    print "AJW version"
    print Ln_aw


if __name__ == "__main__x":
    N = 3
    G = nx.cycle_graph(N)

    print nx.laplacian(G)
    print laplacian_matrix_aw(G)
    nn
    # Add self loop to all vertices
    Gsl = G.copy()
    for node in Gsl.nodes():
        Gsl.add_edge(node, node)

    print nx.laplacian(Gsl)
    print laplacian_matrix_aw(Gsl)

if __name__ == "__main__":
    test1()
    test2()
示例#19
0
文件: maxcut.py 项目: gsagnol/picos
import cvxopt.lapack
import numpy as np

#make G undirected
G=nx.Graph(G)

#allocate weights to the edges
for (i,j) in G.edges():
        G[i][j]['weight']=c[i,j]+c[j,i]


maxcut = pic.Problem()
X=maxcut.add_variable('X',(N,N),'symmetric')

#Laplacian of the graph  
L=pic.new_param('L',1/4.*nx.laplacian(G))

#ones on the diagonal
maxcut.add_constraint(pic.tools.diag_vect(X)==1)
#X positive semidefinite
maxcut.add_constraint(X>>0)

#objective
maxcut.set_objective('max',L|X)

#print maxcut
maxcut.solve(verbose = 0)

#Cholesky factorization
V=X.value
示例#20
0
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

G = nx.Graph()
G.add_edges_from([(1, 2), (1, 3), (2, 3), (1, 4), (4, 5)])
G2 = nx.generators.random_graphs.fast_gnp_random_graph(10, .3)
# nx.adjacency_matrix(G)
L = nx.laplacian(G)  # L=D-A
# np.linalg.eigvals(L)
np.linalg.eig(L)
res = nx.laplacian_spectrum(G)
print res

print nx.normalized_laplacian(G)
c = nx.communicability(G)

# drawing
nx.draw(G)  # default using spring_layout: force-directed
# same as:
# pos = nx.spring_layout(G)
# nx.draw(G, pos)
nx.draw_random(G)
nx.draw_spectral(G)
plt.show()
plt.savefig('path.png')
plt.cla()

# random graph
G = nx.generators.random_graphs.random_regular_graph(6, 50)
plt.show()
示例#21
0
 def test_laplacian(self):
     "Graph Laplacian"
     NL = numpy.array([[3, -1, -1, -1, 0], [-1, 2, -1, 0, 0],
                       [-1, -1, 2, 0, 0], [-1, 0, 0, 1, 0], [0, 0, 0, 0,
                                                             0]])
     assert_equal(nx.laplacian(self.G), NL)
示例#22
0
文件: t_nx.py 项目: Catentropy/mylab
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt


G = nx.Graph()
G.add_edges_from([(1, 2), (1, 3), (2, 3), (1, 4), (4, 5)])
G2 = nx.generators.random_graphs.fast_gnp_random_graph(10, .3)
# nx.adjacency_matrix(G)
L = nx.laplacian(G)  # L=D-A
# np.linalg.eigvals(L)
np.linalg.eig(L)
res = nx.laplacian_spectrum(G)
print res

print nx.normalized_laplacian(G)
c = nx.communicability(G)

# drawing
nx.draw(G)  # default using spring_layout: force-directed
# same as:
# pos = nx.spring_layout(G)
# nx.draw(G, pos)
nx.draw_random(G)
nx.draw_spectral(G)
plt.show()
plt.savefig('path.png')
plt.cla()

# random graph
G = nx.generators.random_graphs.random_regular_graph(6, 50)