本文整理汇总了Python中networkx.Graph.number_of_edges方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.number_of_edges方法的具体用法?Python Graph.number_of_edges怎么用?Python Graph.number_of_edges使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx.Graph
的用法示例。
在下文中一共展示了Graph.number_of_edges方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_small_world_graph
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import number_of_edges [as 别名]
def generate_small_world_graph(self):
max_edges = self.NODE_COUNT*(self.NODE_COUNT-1)/2
if self.EDGE_COUNT > max_edges:
return complete_graph(self.NODE_COUNT)
graph = Graph()
graph.add_nodes_from(range(self.NODE_COUNT))
edges = performer.edge_indices.flatten()
probabilities = performer.probabilities.flatten()
for trial in range(len(edges)-9):
edge_index = numpy.random.choice(edges, p=probabilities)
source, destination = self.edge_nodes(edge_index)
graph.add_edge(source, destination, length = self.link_length(source, destination),
weight = self.edge_weight(source, destination))
probabilities[edge_index] = 0
probabilities /= sum(probabilities)
if max(graph.degree().values()) > self.DEGREE_MAX:
graph.remove_edge(source, destination)
if graph.number_of_edges() > self.EDGE_COUNT:
victim = random.choice(graph.edges())
graph.remove_edge(victim[0], victim[1])
if self.constraints_satisfied(graph):
print 'performer.generate_small_world_graph:',
print self.BENCHMARK, self.NODE_COUNT, self.EDGE_COUNT, trial
self.process_graph(graph)
return graph
示例2: test_algorithms
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import number_of_edges [as 别名]
def test_algorithms(algorithms, graph: Graph, k):
print()
print("Testing graph with {0} nodes and {1} edges, expected result: {2}"
.format(graph.number_of_nodes(), graph.number_of_edges(), k))
for algorithm, name in algorithms:
start_time = time.time()
args = inspect.getfullargspec(algorithm)[0]
if len(args) == 2:
result = len(algorithm(graph))
else:
result = len(algorithm(graph, k))
print("{0}: {1}, time: {2}".format(name, result, time.time() - start_time))
assert k == result, "Wrong result!"
示例3: open
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import number_of_edges [as 别名]
__author__ = 'zplin'
import sys
import json
import csv
from os import path
import numpy as np
from networkx import Graph, transitivity, clustering, average_shortest_path_length, connected_component_subgraphs
from networkx.readwrite import json_graph
if __name__ == '__main__':
with open(sys.argv[1]) as g_file:
data = json.load(g_file)
g = Graph(json_graph.node_link_graph(data))
print('Number of nodes:', g.number_of_nodes())
print('Average degree:', 2 * g.number_of_edges()/g.number_of_nodes())
print('Transitivity:', transitivity(g))
cc = clustering(g)
print('Average clustering coefficient:', np.mean(list(cc.values())))
for subgraph in connected_component_subgraphs(g):
if subgraph.number_of_nodes() > 1:
print('Average shortest path length for subgraph of', subgraph.number_of_nodes(), ':',
average_shortest_path_length(subgraph))
# Calculating average clustering coefficient for different degrees
degree_cc = {}
for node, degree in g.degree_iter():
if degree not in degree_cc:
degree_cc[degree] = []
degree_cc[degree].append(cc[node])
with open(path.join(path.dirname(sys.argv[1]), 'clustering.csv'), 'w', newline='') as cc_file:
示例4: Network
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import number_of_edges [as 别名]
#.........这里部分代码省略.........
self.networkname = name
self.directed = int(directed)
self.hierarchical = int(hierarchical)
self.hypergraph = int(hypergraph)
if src is None and not pickled_graph is None:
self.load_pickled_graphml(pickled_graph)
else:
if not src is None:
# generates NetworkX Graph
self.graph = self.parse_network_graphml(src)
elif not graph is None:
self.graph = graph
else:
if self.directed:
from networkx import DiGraph
self.graph = DiGraph()
logger.info("Initialize with empty directed Graph")
else:
from networkx import Graph
self.graph = Graph()
logger.info("Initialize with empty undirected Graph")
# initializes the weight key of the graph
# with the first edgekey
if len(self.edgekeys) > 0:
edgk = self.edgekeys.keys()
if not 'weight' in edgk:
self.set_weight_key(edgk[0])
else:
# try grabbing first edge from the graph
if self.graph.number_of_edges() > 0:
it = self.graph.edges_iter(data=True)
edg = it.next()
if len(edg[2]) > 0:
# if it has a weigth key, just leave it
edgk = edg[2].keys()
if not 'weight' in edgk:
self.set_weight_key(edgk[0])
else:
pass
# logger.error('Cannot set weight key for network : ' + self.networkname)
def _name_default(self):
return self.networkname
def _active_default(self):
return False
def _active_changed(self , value):
if value:
n = self.name
if ' [Active]' not in n:
self.name = "%s [Active]" % n
# XXX: do refactor with threaded loading of surfaces
# and default spring force layout for graph rendering!
# see also TraitsUI Demos: Multi thread demo
# load the surface containers data
# make a deep copy of the already loaded surface containers
import copy
self.surfaces = copy.deepcopy(self.surfaces_loaded)
for surfcont in self.surfaces:
示例5: print
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import number_of_edges [as 别名]
print('{0}/{1} nodes processed'.format(i, n))
print('Delete {0} orphaned nodes'.format(len(orphaned)))
graph.remove_nodes_from(orphaned)
print('Calculate offset')
points = [node[1]['pos'] for node in graph.nodes(data=True)]
min_x = min(points, key=lambda p: p[0])[0]
min_y = min(points, key=lambda p: p[1])[1]
for node in graph.nodes_iter():
pos = (graph.node[node]['pos'][0] - min_x, graph.node[node]['pos'][1] - min_y)
graph.node[node]['pos'] = pos
print('Translated data by ({0}, {1})'.format(-min_x, -min_y))
print('Calculate edge weights')
n = graph.number_of_edges()
i = 0
for edge in graph.edges():
lat1 = math.radians(graph.node[edge[0]]['lat'])
lon1 = math.radians(graph.node[edge[0]]['lon'])
lat2 = math.radians(graph.node[edge[1]]['lat'])
lon2 = math.radians(graph.node[edge[1]]['lon'])
graph[edge[0]][edge[1]]['weight'] = distance(lat1, lon1, lat2, lon2)
i += 1
print('{0}/{1} edges processed'.format(i, n), end='\r')
print('{0}/{1} edges processed'.format(i, n))
print('Write {0}'.format(output_file))
write_gpickle(graph, output_file)
stop = timeit.default_timer()
示例6: test_algorithms
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import number_of_edges [as 别名]
def test_algorithms(algorithms, graph: nx.Graph):
print()
print("Testing graph with {0} nodes and {1} edges".format(graph.number_of_nodes(), graph.number_of_edges()))
results = []
for algorithm, name in algorithms:
# make a copy of the graph in case the algorithm mutates it
graph_copy = graph.copy()
start_time = time.time()
result = len(algorithm.get_fbvs(graph_copy))
print("{0}: {1}, time: {2}".format(name, result, time.time() - start_time))
results.append(result)
assert results.count(results[0]) == len(results), "The algorithms's results are not the same!"
示例7: open
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import number_of_edges [as 别名]
ips = {}
# filter all relays in this consensus to those that
# have a descriptor, are running, and are fast
for relay in consensus.relays:
if (relay in descriptors):
sd = descriptors[relay] # server descriptor
rse = consensus.relays[relay] # router status entry
if "Running" in rse.flags and "Fast" in rse.flags:
if relay not in ips: ips[relay] = []
ips[relay].append(sd.address)
# build edges between every relay that could have been
# selected in a path together
for r1 in ips:
for r2 in ips:
if r1 is r2: continue
g.add_edges_from(product(ips[r1], ips[r2]))
nsf_i += 1
# check if we should do a checkpoint and save our progress
if nsf_i == nsf_len or "01-00-00-00" in fname:
chkpntstart = fname[0:10]
with open("relaypairs.{0}--{1}.json".format(chkpntstart, chkpntend), 'wb') as f: json.dump(g.edges(), f)
print ""
print('Num addresses: {0}'.format(g.number_of_nodes()))
print('Num unique pairs: {0}'.format(g.number_of_edges()))
# write final graph to disk
with open(out_file, 'wb') as f: json.dump(g.edges(), f)
##########