本文整理汇总了Python中networkx.number_of_nodes方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.number_of_nodes方法的具体用法?Python networkx.number_of_nodes怎么用?Python networkx.number_of_nodes使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.number_of_nodes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: tree
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import number_of_nodes [as 别名]
def tree(start, height, r=2, role_start=0):
"""Builds a balanced r-tree of height h
INPUT:
-------------
start : starting index for the shape
height : int height of the tree
r : int number of branches per node
role_start : starting index for the roles
OUTPUT:
-------------
graph : a tree shape graph, with ids beginning at start
roles : list of the roles of the nodes (indexed starting at role_start)
"""
graph = nx.balanced_tree(r, height)
roles = [0] * graph.number_of_nodes()
return graph, roles
示例2: as_tree
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import number_of_nodes [as 别名]
def as_tree(graph, root=OPENSTACK_CLUSTER, reverse=False):
if nx.__version__ >= '2.0':
linked_graph = json_graph.node_link_graph(
graph, attrs={'name': 'graph_index'})
else:
linked_graph = json_graph.node_link_graph(graph)
if 0 == nx.number_of_nodes(linked_graph):
return {}
if reverse:
linked_graph = linked_graph.reverse()
if nx.__version__ >= '2.0':
return json_graph.tree_data(
linked_graph,
root=root,
attrs={'id': 'graph_index', 'children': 'children'})
else:
return json_graph.tree_data(linked_graph, root=root)
示例3: test_iterators
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import number_of_nodes [as 别名]
def test_iterators(self):
G=self.G()
G.add_edges_from([('A', 'B'), ('A', 'C'), ('B', 'D'),
('C', 'B'), ('C', 'D')])
G.add_nodes_from('GJK')
assert_equal(sorted(G.nodes_iter()),
['A', 'B', 'C', 'D', 'G', 'J', 'K'])
assert_edges_equal(G.edges_iter(),
[('A', 'B'), ('A', 'C'), ('B', 'D'), ('C', 'B'), ('C', 'D')])
assert_equal(sorted([v for k,v in G.degree_iter()]),
[0, 0, 0, 2, 2, 3, 3])
assert_equal(sorted(G.degree_iter(),key=str),
[('A', 2), ('B', 3), ('C', 3), ('D', 2),
('G', 0), ('J', 0), ('K', 0)])
assert_equal(sorted(G.neighbors_iter('A')),['B', 'C'])
assert_raises(nx.NetworkXError,G.neighbors_iter,'X')
G.clear()
assert_equal(nx.number_of_nodes(G),0)
assert_equal(nx.number_of_edges(G),0)
示例4: test_margulis_gabber_galil_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import number_of_nodes [as 别名]
def test_margulis_gabber_galil_graph():
try:
# Scipy is required for conversion to an adjacency matrix.
# We also use scipy for computing the eigenvalues,
# but this second use could be done using only numpy.
import numpy as np
import scipy.linalg
has_scipy = True
except ImportError as e:
has_scipy = False
for n in 2, 3, 5, 6, 10:
g = margulis_gabber_galil_graph(n)
assert_equal(number_of_nodes(g), n*n)
for node in g:
assert_equal(g.degree(node), 8)
assert_equal(len(node), 2)
for i in node:
assert_equal(int(i), i)
assert_true(0 <= i < n)
if has_scipy:
# Eigenvalues are already sorted using the scipy eigvalsh,
# but the implementation in numpy does not guarantee order.
w = sorted(scipy.linalg.eigvalsh(adjacency_matrix(g).A))
assert_less(w[-2], 5*np.sqrt(2))
示例5: test_iterators
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import number_of_nodes [as 别名]
def test_iterators(self):
G = self.G()
G.add_edges_from([('A', 'B'), ('A', 'C'), ('B', 'D'),
('C', 'B'), ('C', 'D')])
G.add_nodes_from('GJK')
assert_equal(sorted(G.nodes()),
['A', 'B', 'C', 'D', 'G', 'J', 'K'])
assert_edges_equal(G.edges(),
[('A', 'B'), ('A', 'C'), ('B', 'D'), ('C', 'B'), ('C', 'D')])
assert_equal(sorted([v for k, v in G.degree()]),
[0, 0, 0, 2, 2, 3, 3])
assert_equal(sorted(G.degree(), key=str),
[('A', 2), ('B', 3), ('C', 3), ('D', 2),
('G', 0), ('J', 0), ('K', 0)])
assert_equal(sorted(G.neighbors('A')), ['B', 'C'])
assert_raises(nx.NetworkXError, G.neighbors, 'X')
G.clear()
assert_equal(nx.number_of_nodes(G), 0)
assert_equal(nx.number_of_edges(G), 0)
示例6: test_margulis_gabber_galil_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import number_of_nodes [as 别名]
def test_margulis_gabber_galil_graph():
try:
# Scipy is required for conversion to an adjacency matrix.
# We also use scipy for computing the eigenvalues,
# but this second use could be done using only numpy.
import numpy as np
import scipy.linalg
has_scipy = True
except ImportError as e:
has_scipy = False
for n in 2, 3, 5, 6, 10:
g = margulis_gabber_galil_graph(n)
assert_equal(number_of_nodes(g), n * n)
for node in g:
assert_equal(g.degree(node), 8)
assert_equal(len(node), 2)
for i in node:
assert_equal(int(i), i)
assert_true(0 <= i < n)
if has_scipy:
# Eigenvalues are already sorted using the scipy eigvalsh,
# but the implementation in numpy does not guarantee order.
w = sorted(scipy.linalg.eigvalsh(adjacency_matrix(g).A))
assert_less(w[-2], 5 * np.sqrt(2))
示例7: _modularity_generator
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import number_of_nodes [as 别名]
def _modularity_generator(self):
"""Calculating the sparse modularity matrix."""
degs = nx.degree(self._graph)
e_count = self._graph.number_of_edges()
n_count = self._graph.number_of_nodes()
modularity_mat_shape = (n_count, n_count)
indices_1 = np.array([edge[0] for edge in self._graph.edges()] + [edge[1] for edge in self._graph.edges()])
indices_2 = np.array([edge[1] for edge in self._graph.edges()] + [edge[0] for edge in self._graph.edges()])
scores = [1.0-(float(degs[e[0]]*degs[e[1]])/(2*e_count)) for e in self._graph.edges()]
scores = scores + [1.0-(float(degs[e[1]]*degs[e[0]])/(2*e_count)) for e in self._graph.edges()]
mod_matrix = coo_matrix((scores, (indices_1, indices_2)), shape=modularity_mat_shape)
return mod_matrix
示例8: _setup_matrices
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import number_of_nodes [as 别名]
def _setup_matrices(self):
"""Creating parameter matrices and target matrices."""
self._number_of_nodes = nx.number_of_nodes(self._graph)
self._M = np.random.uniform(0, 1, (self._number_of_nodes, self.dimensions))
self._U = np.random.uniform(0, 1, (self._number_of_nodes, self.dimensions))
self._H = np.random.uniform(0, 1, (self._number_of_nodes, self.clusters))
self._C = np.random.uniform(0, 1, (self.clusters, self.dimensions))
self._B1 = nx.adjacency_matrix(self._graph, nodelist=range(self._graph.number_of_nodes()))
self._B2 = self._modularity_generator()
self._X = np.transpose(self._U)
overlaps = self._B1.dot(self._B1)
self._S = self._B1 + self.eta*self._B1*(overlaps)
示例9: watts_strogatz_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import number_of_nodes [as 别名]
def watts_strogatz_graph(N, deg, dia, dim, domain):
'''
Parameters of the graph:
n (int) – The number of nodes
k (int) – Each node is joined with its k nearest neighbors in a ring topology.
p (float) – The probability of rewiring each edge
Average Degree is solely decided by k
Diameter depends on the value of p
:return: Graph Object
'''
strt_time = time()
p = 0.2
G = nx.watts_strogatz_graph(n=N, k=deg, p=p)
lcc, _ = graph_util.get_nk_lcc_undirected(G)
best_G = lcc
best_diam = nx.algorithms.diameter(best_G)
best_avg_deg = np.mean(list(dict(nx.degree(best_G)).values()))
end_time = time()
print('Graph_Name: Watts_Strogatz_Graph')
print('Num_Nodes: ', nx.number_of_nodes(best_G), ' Avg_Deg : ', best_avg_deg, ' Diameter: ', best_diam)
print('TIME: ', end_time - strt_time)
return best_G, best_avg_deg, best_diam
########################################################################
示例10: powerlaw_cluster_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import number_of_nodes [as 别名]
def powerlaw_cluster_graph(N, deg, dia, dim, domain):
'''
Parameters of the graph:
n (int) – the number of nodes
m (int) – the number of random edges to add for each new node
p (float,) – Probability of adding a triangle after adding a random edge
Formula for m: (m^2)- (Nm)/2 + avg_deg * (N/2) = 0 => From this equation we need to find m :
p : Does not vary the average degree or diameter so much. : Higher value of p may cause average degree to overshoot intended average_deg
so we give the control of average degree to parameter m: by setting a lower value of p: 0.1
:return: Graph Object
'''
## Calculating thof nodes: 10\nNumber of edges: 16\nAverage degree: 3.2000'
strt_time = time()
m = int(round((N - np.sqrt(N ** 2 - 4 * deg * N)) / 4))
p = 0.2
## G at center:
G = nx.powerlaw_cluster_graph(n=N, m=m, p=p)
lcc, _ = graph_util.get_nk_lcc_undirected(G)
best_G = lcc
best_diam = nx.algorithms.diameter(best_G)
best_avg_deg = np.mean(list(dict(nx.degree(best_G)).values()))
end_time = time()
print('Graph_Name: powerlaw_cluster_graph')
print('Num_Nodes: ', nx.number_of_nodes(best_G), ' Avg_Deg : ', best_avg_deg, ' Diameter: ', best_diam)
print('TIME: ', end_time - strt_time)
return best_G, best_avg_deg, best_diam
#####################################################################
示例11: get_clustering_coeff
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import number_of_nodes [as 别名]
def get_clustering_coeff(edge_list):
G = nx.from_edgelist(edgelist=edge_list)
clust_coeff = nx.average_clustering(G)
# print(nx.number_of_nodes(G), ' : ',clust_coeff)
return clust_coeff
示例12: test_size
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import number_of_nodes [as 别名]
def test_size(self):
num_nodes = nx.number_of_nodes(self.graph)
self.assertEqual(num_nodes, 3971, "Should be 3971.")
num_edges = nx.number_of_edges(self.graph)
self.assertEqual(num_edges, 28202, "Should be 28202.")
示例13: write_summary_file
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import number_of_nodes [as 别名]
def write_summary_file(self,path,append=True):
'''
Writes summary information about this network to a file
**Optional Arguments**
- *append* = True if summary information should be appended to the file. If so the file is written as a csv spreadsheet.
Default is true. If False is passed, a single, detailed summary is written for this network.
'''
if append: #write summary information in spreadsheet formant
exists = os.path.exists(path)
f = open(path,"a")
if not exists: #write header
f.write("name,#nodes,#edges\n") #todo add other stuff here
#write data
f.write("%s,%s,%s\n" % (self.basename,self.graph.number_of_nodes(),self.graph.number_of_edges()))
f.close()
else: #write detailed information
import networkx as nx
f = open(path,"w")
f.write("Summary:")
f.write("Name: %s\n" % self.basename)
f.write("#nodes: %s\n" % self.graph.number_of_nodes())
f.write("#edges: %s\n" % self.graph.number_of_edges())
f.write("Detail")
f.write("Degree sequence: %s" % str(list(nx.degree(self.graph).values())))
f.write("Node list: %s" % str(self.graph.nodes(data=False)))
f.write("Edge list: %s" % str(self.graph.edges(data=False)))
f.write("Node attributes: %s" % str(self.graph.nodes(data=True)))
f.write("Edge attributes: %s" % str(self.graph.edges(data=True)))
f.close()
示例14: __len__
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import number_of_nodes [as 别名]
def __len__(self):
"""
:return: the number of nodes in the graph
"""
return nx.number_of_nodes(self.graph)
示例15: skeleton_to_swc
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import number_of_nodes [as 别名]
def skeleton_to_swc(skeleton, offset, resolution):
import networkx as nx
g = nx.Graph()
g.add_nodes_from(skeleton.nodes())
g.add_edges_from((e.u, e.v) for e in skeleton.edges())
# Find a directed tree for mapping to a skeleton.
if nx.number_of_nodes(g) > 1:
# This discards cyclic edges in the graph.
t = nx.bfs_tree(nx.minimum_spanning_tree(g), g.nodes()[0])
else:
t = nx.DiGraph()
t.add_nodes_from(g)
# Copy node attributes
for n in t.nodes_iter():
loc = skeleton.locations(n)
# skeletopyze is z, y, x (as it should be).
loc = np.array(loc)
loc = np.multiply(loc + offset, resolution)
t.node[n].update({'x': loc[0],
'y': loc[1],
'z': loc[2],
'radius': skeleton.diameters(n) / 2.0})
# Set parent node ID
for n, nbrs in t.adjacency_iter():
for nbr in nbrs:
t.node[nbr]['parent_id'] = n
if 'radius' not in t.node[nbr]:
t.node[nbr]['radius'] = -1
return [[
node_id,
0,
n['x'], n['y'], n['z'],
n['radius'],
n.get('parent_id', -1)] for node_id, n in t.nodes(data=True)]