def calculate_katz_centrality(graph):
"""
Compute the katz centrality for nodes.
"""
# if not graph.is_directed():
# raise nx.NetworkXError( \
# "katz_centrality() not defined for undirected graphs.")
print "\n\tCalculating Katz Centrality..."
print "\tWarning: This might take a long time larger pedigrees."
g = graph
A = nx.adjacency_matrix(g)
from scipy import linalg as LA
max_eign = float(np.real(max(LA.eigvals(A.todense()))))
print "\t-Max.Eigenvalue(A) ", round(max_eign, 3)
kt = nx.katz_centrality(g, tol=1.0e-4, alpha=1/max_eign-0.01, beta=1.0, max_iter=999999)
nx.set_node_attributes(g, 'katz', kt)
katz_sorted = sorted(kt.items(), key=itemgetter(1), reverse=True)
for key, value in katz_sorted[0:10]:
print "\t > ", key, round(value, 4)
return g, kt
python类adjacency_matrix()的实例源码
example_synthetic_timing_netsize_nodes_ernos_renyi.py 文件源码
项目:mrqap-python
作者: lisette-espin
项目源码
文件源码
阅读 33
收藏 0
点赞 0
评论 0
def generateGraph(nnodes, edgeprob, directed, pathtosave):
if os.path.exists(pathtosave):
matrix = np.loadtxt(pathtosave)
else:
shape = (nnodes,nnodes)
G = nx.fast_gnp_random_graph(n=nnodes, p=edgeprob, directed=directed)
matrix = nx.adjacency_matrix(G)
if pathtosave is not None:
np.savetxt(pathtosave, matrix.toarray(), fmt='%d',)
print nx.info(G)
matrix = matrix.toarray()
return matrix
#######################################################################
# Main
#######################################################################
def __init__(self, vertex_num=5, p=0.5, directed=False, network_file=None, vertex_value_file=None, adjMatrix=None):
""" the init constructor
:param vertex_num:
:param network_file:
:param vertex_value_file:
:member variable
self.adjMatrix
self.G
self.malicious_node
"""
self.vertex_num = vertex_num
self.G = self.init_network(vertex_num, p,directed, network_file, adjMatrix)
self.adjMatrix = nx.adjacency_matrix(self.G).todense().view(np.ndarray).reshape(self.vertex_num, self.vertex_num)
self.init_vertex_value(self.G, vertex_value_file)
self.malicious_node = []
def load_data(dataset):
# load the data: x, tx, allx, graph
names = ['x', 'tx', 'allx', 'graph']
objects = []
for i in range(len(names)):
objects.append(pkl.load(open("data/ind.{}.{}".format(dataset, names[i]))))
x, tx, allx, graph = tuple(objects)
test_idx_reorder = parse_index_file("data/ind.{}.test.index".format(dataset))
test_idx_range = np.sort(test_idx_reorder)
if dataset == 'citeseer':
# Fix citeseer dataset (there are some isolated nodes in the graph)
# Find isolated nodes, add them as zero-vecs into the right position
test_idx_range_full = range(min(test_idx_reorder), max(test_idx_reorder)+1)
tx_extended = sp.lil_matrix((len(test_idx_range_full), x.shape[1]))
tx_extended[test_idx_range-min(test_idx_range), :] = tx
tx = tx_extended
features = sp.vstack((allx, tx)).tolil()
features[test_idx_reorder, :] = features[test_idx_range, :]
adj = nx.adjacency_matrix(nx.from_dict_of_lists(graph))
return adj, features
def read_graph(filename,g_type):
with open('data/'+filename,'rb') as f:
if g_type == "undirected":
G = nx.read_weighted_edgelist(f)
else:
G = nx.read_weighted_edgelist(f,create_using=nx.DiGraph())
node_idx = G.nodes()
adj_matrix = np.asarray(nx.adjacency_matrix(G, nodelist=None,weight='weight').todense())
return adj_matrix, node_idx
def draw_adjacency_matrix(G, node_order=None, partitions=[], colors=[]):
"""
- G is a networkx graph
- node_order (optional) is a list of nodes, where each node in G
appears exactly once
- partitions is a list of node lists, where each node in G appears
in exactly one node list
- colors is a list of strings indicating what color each
partition should be
If partitions is specified, the same number of colors needs to be
specified.
"""
adjacency_matrix = nx.to_numpy_matrix(G, dtype=np.bool, nodelist=node_order)
# Plot adjacency matrix in toned-down black and white
fig = plt.figure(figsize=(8, 8)) # in inches
plt.imshow(adjacency_matrix,
cmap="Paired",
interpolation="none")
# The rest is just if you have sorted nodes by a partition and want to
# highlight the module boundaries
assert len(partitions) == len(colors)
ax = plt.gca()
for partition, color in zip(partitions, colors):
current_idx = 0
for module in partition:
ax.add_patch(patches.Rectangle((current_idx, current_idx),
len(module), # Width
len(module), # Height
facecolor="none",
edgecolor=color,
linewidth="1"))
current_idx += len(module)
plt.show()
def busmap_by_spectral_clustering(network, n_clusters, **kwds):
lines = network.lines.loc[:,['bus0', 'bus1']].assign(weight=1./network.lines.x).set_index(['bus0','bus1'])
G = OrderedGraph()
G.add_nodes_from(network.buses.index)
G.add_edges_from((u,v,dict(weight=w)) for (u,v),w in lines.itertuples())
return pd.Series(sk_spectral_clustering(nx.adjacency_matrix(G), n_clusters, **kwds) + 1,
index=network.buses.index)
def test_closure_and_cclosure_against_networkx():
""" Test 'clusure' and 'cclosure' on 'metric' againt the NetworkX shortest_path (Rion's testing) """
G = nx.Graph()
G.add_nodes_from([0,1,2,3,4])
G.add_edges_from([(0,1), (1,2), (2,3), (3,4)], weight=0.1)
G.add_edges_from([(0,4)], weight=0.8)
# Extract Adjacency Matrix from G
A = nx.adjacency_matrix(G)
# Transform distance into a similarity
x = np.ravel(A[A > 0])
A[A > 0] = (1.0 / (x + 1.0))
for n1, n2 in combinations(G.nodes(),2):
# Tests all three methods of computing all shortest paths ('closure','cclosure', and 'nx.all_shortest_paths')
c_dist, c_paths = clo.closure(A, source=n1, target=n2, kind='metric')
c_paths = [n for n in c_paths] # convers numbers to letters
cc_dist, cc_paths = clo.cclosure(A, source=n1, target=n2, retpath=1, kind='metric')
cc_paths = [n for n in cc_paths] if cc_paths is not None else ''
nx_paths = list(nx.all_shortest_paths(G, source=n1, target=n2, weight='weight'))[0]
assert nx_paths == c_paths, "NetworkX and Python 'closure' differ"
assert nx_paths == cc_paths, "NetworkX and Cython 'cclosure' differ"
assert c_paths == cc_paths, "Python 'closure' and Cython 'cclosure' differ"
def random_corpus(self, rnd):
N = self.getN()
if isinstance(N, str):
self.log.warning('Random graph size missing (-n): Using 100 nodes.')
N = 100
if rnd == 'uniform':
data = np.random.randint(0, 2, (N, N))
#np.fill_diagonal(data, 1)
elif rnd.startswith('clique'):
try :
K = int(rnd[len('clique'):])
except ValueError:
K = 42
data = getClique(N, K=K)
#Data = nx.adjacency_matrix(G, np.random.permutation(range(N))).A
elif rnd in ('BA', 'barabasi-albert'):
data = nx.adjacency_matrix(nx.barabasi_albert_graph(N, m=int(0.95*N)) ).A
elif rnd == 'alternate':
#data = np.empty((N,N),int)
data = np.zeros((N,N), int)
type_rd = 2
if type_rd == 1:
# degree alternating with frequency fr
fr = 3
data[:, ::fr] = 1
elif type_rd == 2:
# degree equal
data[:, ::2] = 1
data[::2] = np.roll(data[::2], 1)
return data
else:
raise NotImplementedError()
return data
def directed_modularity_matrix(G, nodelist=None):
""" INCLUDED FOR TESTING PURPOSES - Not implemented yet.
Return the directed modularity matrix of G.
The modularity matrix is the matrix B = A - <A>, where A is the adjacency
matrix and <A> is the expected adjacency matrix, assuming that the graph
is described by the configuration model.
More specifically, the element B_ij of B is defined as
B_ij = A_ij - k_i(out) k_j(in)/m
where k_i(in) is the in degree of node i, and k_j(out) is the out degree
of node j, with m the number of edges in the graph.
Parameters
----------
G : DiGraph
A NetworkX DiGraph
nodelist : list, optional
The rows and columns are ordered according to the nodes in nodelist.
If nodelist is None, then the ordering is produced by G.nodes().
Returns
-------
B : Numpy matrix
The modularity matrix of G.
Notes
-----
NetworkX defines the element A_ij of the adjacency matrix as 1 if there
is a link going from node i to node j. Leicht and Newman use the opposite
definition. This explains the different expression for B_ij.
See Also
--------
to_numpy_matrix
adjacency_matrix
laplacian_matrix
modularity_matrix
References
----------
.. [1] E. A. Leicht, M. E. J. Newman,
"Community structure in directed networks",
Phys. Rev Lett., vol. 100, no. 11, p. 118703, 2008.
"""
if nodelist is None:
nodelist = G.nodes()
A = nx.to_scipy_sparse_matrix(G, nodelist=nodelist, format='csr')
k_in = A.sum(axis=0)
k_out = A.sum(axis=1)
m = G.number_of_edges()
# Expected adjacency matrix
X = k_out * k_in / m
return A - X
def plot_ibp(model, target_dir=None, block=False, columns=[0], separate=False, K=4):
G = nx.from_numpy_matrix(model.Y(), nx.DiGraph())
F = model.leftordered()
W = model._W
# Plot Adjacency Matrix
draw_adjmat(model._Y)
# Plot Log likelihood
plot_csv(target_dir=target_dir, columns=columns, separate=separate)
#W[np.where(np.logical_and(W>-1.6, W<1.6))] = 0
#W[W <= -1.6]= -1
#W[W >= 1.6] = 1
# KMeans test
clusters = kmeans(F, K=K)
nodelist_kmeans = [k[0] for k in sorted(zip(range(len(clusters)), clusters), key=lambda k: k[1])]
adj_mat_kmeans = nx.adjacency_matrix(G, nodelist=nodelist_kmeans).A
draw_adjmat(adj_mat_kmeans, title='KMeans on feature matrix')
# Adjacency matrix generation
draw_adjmat(model.generate(nodelist_kmeans), title='Generated Y from ILFRM')
# training Rescal
R = rescal(model._Y, K)
R = R[nodelist_kmeans, :][:, nodelist_kmeans]
draw_adjmat(R, 'Rescal generated')
# Networks Plots
f = plt.figure()
ax = f.add_subplot(121)
title = 'Features matrix, K = %d' % model._K
ax.set_title(title)
ColorMap(F, pixelspervalue=5, title=title, ax=ax)
ax = f.add_subplot(122)
ax.set_title('W')
img = ax.imshow(W, interpolation='None')
plt.colorbar(img)
f = plt.figure()
ax = f.add_subplot(221)
ax.set_title('Spectral')
nx.draw_spectral(G, axes=ax)
ax = f.add_subplot(222)
ax.set_title('Spring')
nx.draw(G, axes=ax)
ax = f.add_subplot(223)
ax.set_title('Random')
nx.draw_random(G, axes=ax)
ax = f.add_subplot(224)
ax.set_title('graphviz')
try:
nx.draw_graphviz(G, axes=ax)
except:
pass
display(block=block)