本文整理汇总了Python中networkx.Graph.degree方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.degree方法的具体用法?Python Graph.degree怎么用?Python Graph.degree使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx.Graph
的用法示例。
在下文中一共展示了Graph.degree方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_small_world_graph
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import degree [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: polygon_skeleton
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import degree [as 别名]
def polygon_skeleton(polygon, density=10):
""" Given a buffer polygon, return a skeleton graph.
"""
skeleton = Graph()
points = []
for ring in polygon_rings(polygon):
points.extend(densify_line(list(ring.coords), density))
if len(points) <= 4:
# don't bother with this one
return skeleton
print >> stderr, ' ', len(points), 'perimeter points',
rbox = '\n'.join( ['2', str(len(points))] + ['%.2f %.2f' % (x, y) for (x, y) in points] + [''] )
qvoronoi = Popen('qvoronoi o'.split(), stdin=PIPE, stdout=PIPE)
output, error = qvoronoi.communicate(rbox)
voronoi_lines = output.splitlines()
if qvoronoi.returncode:
raise _QHullFailure('Failed with code %s' % qvoronoi.returncode)
vert_count, poly_count = map(int, voronoi_lines[1].split()[:2])
for (index, line) in enumerate(voronoi_lines[2:2+vert_count]):
point = Point(*map(float, line.split()[:2]))
if point.within(polygon):
skeleton.add_node(index, dict(point=point))
for line in voronoi_lines[2+vert_count:2+vert_count+poly_count]:
indexes = map(int, line.split()[1:])
for (v, w) in zip(indexes, indexes[1:] + indexes[:1]):
if v not in skeleton.node or w not in skeleton.node:
continue
v1, v2 = skeleton.node[v]['point'], skeleton.node[w]['point']
line = LineString([(v1.x, v1.y), (v2.x, v2.y)])
if line.within(polygon):
skeleton.add_edge(v, w, dict(line=line, length=line.length))
removing = True
while removing:
removing = False
for index in skeleton.nodes():
if skeleton.degree(index) == 1:
depth = skeleton.node[index].get('depth', 0)
if depth < 20:
other = skeleton.neighbors(index)[0]
skeleton.node[other]['depth'] = depth + skeleton.edge[index][other]['line'].length
skeleton.remove_node(index)
removing = True
print >> stderr, 'contain', len(skeleton.edge), 'internal edges.'
return skeleton
示例3: make_colors
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import degree [as 别名]
def make_colors(graph: nx.Graph) -> map:
names = graph.nodes()
longest = max(names)
raw = [levenshtein_distance(x, longest) for x in names]
largest_raw = max(raw)
degrees = [graph.degree(x) for x in graph]
largest_degrees = max(degrees)
return map(lambda x, y: x + y,
[int(10 * x/largest_degrees) for x in degrees],
[10 * x/largest_raw for x in raw])
示例4: polygon_dots_skeleton
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import degree [as 别名]
def polygon_dots_skeleton(polygon, points):
'''
'''
skeleton = Graph()
rbox = '\n'.join( ['2', str(len(points))] + ['%.2f %.2f' % (x, y) for (x, y) in points] + [''] )
qvoronoi = Popen('qvoronoi o'.split(), stdin=PIPE, stdout=PIPE)
output, error = qvoronoi.communicate(rbox)
voronoi_lines = output.splitlines()
if qvoronoi.returncode:
raise _QHullFailure('Failed with code %s' % qvoronoi.returncode)
vert_count, poly_count = map(int, voronoi_lines[1].split()[:2])
for (index, line) in enumerate(voronoi_lines[2:2+vert_count]):
point = Point(*map(float, line.split()[:2]))
if point.within(polygon):
skeleton.add_node(index, dict(point=point))
for line in voronoi_lines[2+vert_count:2+vert_count+poly_count]:
indexes = map(int, line.split()[1:])
for (v, w) in zip(indexes, indexes[1:] + indexes[:1]):
if v not in skeleton.node or w not in skeleton.node:
continue
v1, v2 = skeleton.node[v]['point'], skeleton.node[w]['point']
line = LineString([(v1.x, v1.y), (v2.x, v2.y)])
if line.within(polygon):
skeleton.add_edge(v, w, dict(line=line, length=line.length))
removing = True
while removing:
removing = False
for index in skeleton.nodes():
if skeleton.degree(index) == 1:
depth = skeleton.node[index].get('depth', 0)
if depth < 20:
other = skeleton.neighbors(index)[0]
skeleton.node[other]['depth'] = depth + skeleton.edge[index][other]['line'].length
skeleton.remove_node(index)
removing = True
logging.debug('found %d skeleton edges' % len(skeleton.edge))
return skeleton
示例5: save
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import degree [as 别名]
def save(self, output_dir, save_src):
with open(path.join(output_dir, 'commits.csv'), 'w', newline='') as commits_file:
writer = csv.DictWriter(commits_file, ['min_fitness', 'change_size'])
writer.writeheader()
writer.writerows(self._revisions)
with open(path.join(output_dir, 'methods.csv'), 'w', newline='') as methods_file:
writer = csv.DictWriter(methods_file, ['method', 'class', 'ref_count'])
writer.writeheader()
for method_name, in_degree in self._method_call_graph.in_degree_iter():
writer.writerow({
'method': method_name,
'class': self._method_call_graph.node[method_name]['class_name'],
'ref_count': in_degree
})
with open(path.join(output_dir, 'methods.json'), 'w') as methods_file:
data = json_graph.node_link_data(self._method_call_graph)
json.dump(data, methods_file, skipkeys=True, default=lambda d: None)
association_graph = Graph()
for e in self._method_call_graph.edges_iter():
association_graph.add_edge(
self._method_call_graph.node[e[0]]['class_name'],
self._method_call_graph.node[e[1]]['class_name'])
for e in self._inheritance_graph.edges_iter():
association_graph.add_edge(*e)
with open(path.join(output_dir, 'classes.csv'), 'w', newline='') as classes_file:
writer = csv.DictWriter(classes_file, ['class', 'subclasses', 'lines', 'degree'])
writer.writeheader()
for class_name, in_degree in self._inheritance_graph.in_degree_iter():
klass = self._inheritance_graph.node[class_name]['class']
java_printer = JavaPrinter()
klass.accept(java_printer)
writer.writerow({'class': class_name,
'subclasses': in_degree,
'lines': java_printer.result.count('\n') + 1,
'degree': association_graph.degree(class_name)
if class_name in association_graph else 0
})
if save_src:
with open(path.join(output_dir, 'src', class_name + '.java'), 'w') as java_file:
java_file.write(java_printer.result)
with open(path.join(output_dir, 'classes.json'), 'w') as classes_file:
data = json_graph.node_link_data(association_graph)
json.dump(data, classes_file, skipkeys=True)
示例6: diffusion_kernel
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import degree [as 别名]
def diffusion_kernel(G: nx.Graph, heat: dict, rp: float, n: int) -> nx.Graph:
'''
Perform the diffusion kernel algorithm in a Graph object G and heat toward stable state
:param G: the undirected graph G
:param heat: the heat dict, should have same length with G, contain the node name and the heat value
:param n: the repeat times
:param rp: restart probability.
:param threshold: the threshold to check the convergence of the heat, if not n == -1, the loop will stop when the
threshold is reached
:return: the graph with heat property in the node's property
'''
heat_vector = np.array([heat[x] for x in G.nodes])
A = nx.to_numpy_matrix(G)
D = np.diag(list(dict(G.degree()).values()))
L = D - A
I = np.eye(len(G))
sim = (I - rp * L / n) ** n
h = np.dot(heat_vector, np.array(sim))
GG = copy.deepcopy(G)
for n, v in zip(list(GG.nodes), h):
GG.nodes[n]['heat'] = v
return GG
示例7: print
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import degree [as 别名]
i = 0
print('Apply shapefile')
for node in graph.nodes():
p = Point(graph.node[node]['lon'], graph.node[node]['lat'])
if not shape_file.contains(p):
graph.remove_node(node)
i += 1
print('{0}/{1} nodes processed'.format(i, n), end='\r')
print('{0}/{1} nodes processed'.format(i, n))
print('Search for orphaned nodes')
orphaned = set()
n = graph.number_of_nodes()
i = 0
for node in graph.nodes_iter():
if graph.degree(node) == 0:
orphaned.add(node)
i += 1
print('{0}/{1} nodes processed'.format(i, n), end='\r')
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