本文整理汇总了Python中networkx.degree方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.degree方法的具体用法?Python networkx.degree怎么用?Python networkx.degree使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.degree方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: decode_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def decode_graph(adj, prefix):
adj = np.asmatrix(adj)
G = nx.from_numpy_matrix(adj)
# G.remove_nodes_from(nx.isolates(G))
print('num of nodes: {}'.format(G.number_of_nodes()))
print('num of edges: {}'.format(G.number_of_edges()))
G_deg = nx.degree_histogram(G)
G_deg_sum = [a * b for a, b in zip(G_deg, range(0, len(G_deg)))]
print('average degree: {}'.format(sum(G_deg_sum) / G.number_of_nodes()))
if nx.is_connected(G):
print('average path length: {}'.format(nx.average_shortest_path_length(G)))
print('average diameter: {}'.format(nx.diameter(G)))
G_cluster = sorted(list(nx.clustering(G).values()))
print('average clustering coefficient: {}'.format(sum(G_cluster) / len(G_cluster)))
cycle_len = []
cycle_all = nx.cycle_basis(G, 0)
for item in cycle_all:
cycle_len.append(len(item))
print('cycles', cycle_len)
print('cycle count', len(cycle_len))
draw_graph(G, prefix=prefix)
示例2: dataset_reader
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def dataset_reader(path):
"""
Function to read the graph and features from a json file.
:param path: The path to the graph json.
:return graph: The graph object.
:return features: Features hash table.
:return name: Name of the graph.
"""
name = path.strip(".json").split("/")[-1]
data = json.load(open(path))
graph = nx.from_edgelist(data["edges"])
if "features" in data.keys():
features = data["features"]
else:
features = nx.degree(graph)
features = {int(k): v for k, v in features.items()}
return graph, features, name
示例3: hub_dominance
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def hub_dominance(graph, communities, **kwargs):
"""Hub dominance.
The hub dominance of a community is defined as the ratio of the degree of its most connected node w.r.t. the theoretically maximal degree within the community.
:param graph: a networkx/igraph object
:param communities: NodeClustering object
:param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**.
:return: If **summary==True** a FitnessResult object, otherwise a list of floats.
Example:
>>> from cdlib.algorithms import louvain
>>> from cdlib import evaluation
>>> g = nx.karate_club_graph()
>>> communities = louvain(g)
>>> scd = evaluation.hub_dominance(g,communities)
"""
return __quality_indexes(graph, communities,
lambda graph, coms: max([x[1] for x in
list(nx.degree(nx.subgraph(graph, coms)))]) / (len(coms) - 1),
**kwargs)
示例4: test_info
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def test_info(self):
G=nx.path_graph(5)
info=nx.info(G)
expected_graph_info='\n'.join(['Name: path_graph(5)',
'Type: Graph',
'Number of nodes: 5',
'Number of edges: 4',
'Average degree: 1.6000'])
assert_equal(info,expected_graph_info)
info=nx.info(G,n=1)
expected_node_info='\n'.join(
['Node 1 has the following properties:',
'Degree: 2',
'Neighbors: 0 2'])
assert_equal(info,expected_node_info)
示例5: test_info_digraph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def test_info_digraph(self):
G=nx.DiGraph(name='path_graph(5)')
G.add_path([0,1,2,3,4])
info=nx.info(G)
expected_graph_info='\n'.join(['Name: path_graph(5)',
'Type: DiGraph',
'Number of nodes: 5',
'Number of edges: 4',
'Average in degree: 0.8000',
'Average out degree: 0.8000'])
assert_equal(info,expected_graph_info)
info=nx.info(G,n=1)
expected_node_info='\n'.join(
['Node 1 has the following properties:',
'Degree: 2',
'Neighbors: 2'])
assert_equal(info,expected_node_info)
assert_raises(nx.NetworkXError,nx.info,G,n=-1)
示例6: test_info
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def test_info(self):
G = nx.path_graph(5)
G.name = "path_graph(5)"
info = nx.info(G)
expected_graph_info = '\n'.join(['Name: path_graph(5)',
'Type: Graph',
'Number of nodes: 5',
'Number of edges: 4',
'Average degree: 1.6000'])
assert_equal(info, expected_graph_info)
info = nx.info(G, n=1)
expected_node_info = '\n'.join(
['Node 1 has the following properties:',
'Degree: 2',
'Neighbors: 0 2'])
assert_equal(info, expected_node_info)
示例7: test_info_digraph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def test_info_digraph(self):
G = nx.DiGraph(name='path_graph(5)')
nx.add_path(G, [0, 1, 2, 3, 4])
info = nx.info(G)
expected_graph_info = '\n'.join(['Name: path_graph(5)',
'Type: DiGraph',
'Number of nodes: 5',
'Number of edges: 4',
'Average in degree: 0.8000',
'Average out degree: 0.8000'])
assert_equal(info, expected_graph_info)
info = nx.info(G, n=1)
expected_node_info = '\n'.join(
['Node 1 has the following properties:',
'Degree: 2',
'Neighbors: 2'])
assert_equal(info, expected_node_info)
assert_raises(nx.NetworkXError, nx.info, G, n=-1)
示例8: _mean_node_degree
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def _mean_node_degree(graph, degree):
"""
Calculates mean node degree in a graph.
"""
return np.mean(list(dict(graph.nodes(degree)).values()))
示例9: _modularity_generator
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [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
示例10: watts_strogatz_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [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
########################################################################
示例11: powerlaw_cluster_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [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
#####################################################################
示例12: node_degree
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def node_degree(graph, name="degree"):
"""
Calculates node degree for each node.
Wrapper around ``networkx.degree()``.
Parameters
----------
graph : networkx.Graph
Graph representing street network.
Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`
name : str (default 'degree')
calculated attribute name
Returns
-------
Graph
networkx.Graph
Examples
--------
>>> network_graph = mm.node_degree(network_graph)
"""
netx = graph.copy()
degree = dict(nx.degree(netx))
nx.set_node_attributes(netx, degree, name)
return netx
示例13: _proportion
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def _proportion(graph, degree):
"""
Calculates the proportion of intersection types in a graph.
"""
import collections
values = list(dict(graph.nodes(degree)).values())
counts = collections.Counter(values)
return counts
示例14: fields_degree
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def fields_degree(self, topk):
degree = nx.degree(self.__G)
sorted_degree = sorted(degree.items(), key=operator.itemgetter(1))
sorted_degree.reverse()
topk_nodes = sorted_degree[:topk]
return topk_nodes
示例15: write_summary_file
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [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()