我使用 python 多重处理来创建多个不同的 NetworkX 图,然后使用下面的函数来组合这些图。然而,虽然这个函数对于小图工作得很好,但对于较大的图,它会使用大量内存,并且会挂在我的系统和内存密集型 AWS 系统上(仅使用系统中总内存的大约三分之一)。有没有更有效的方法来执行以下功能?
def combine_graphs(graph1, graph2, graph2_weight = 1):
'''
Given two graphs of different edge (but same node) structure (and the same type),
combine the two graphs, summing all edge attributes and multiplying the second one's
attributes by the desired weights.
E.g. if graph1.edge[a][b] = {'a': 1, 'b':2} and
graph2.edge[a][b] = {'a': 3, 'c': 4},
with a weight of 1 the final graph edge should be
final_graph.edge[a][b] = {'a': 4, 'b': 2, 'c': 4} and with a weight
of .5 the final graph edge should be {'a': 2.5, 'b': 2, 'c': 2}.
Inputs: Two graphs to be combined and a weight to give to the second graph
'''
if type(graph1) != type(graph2) or len(set(graph2.nodes()) - set(graph1.nodes())) > 0:
raise Exception('Graphs must have the same type and graph 2 cannot have nodes that graph 1 does not have.')
# make a copy of the new graph to ensure that it doesn't change
new_graph = graph1.copy()
# iterate over graph2's edges, adding them to graph1
for node1, node2 in graph2.edges():
# if that edge already exists, now iterate over the attributes
if new_graph.has_edge(node1, node2):
for attr in graph2.edge[node1][node2]:
# if that attribute exists, sum the values, otherwise, simply copy attrs
if new_graph.edge[node1][node2].get(attr) is not None:
# try adding weighted value: if it fails, it's probably not numeric so add the full value (the only other option is a list)
try:
new_graph.edge[node1][node2][attr] += graph2.edge[node1][node2][attr] * graph2_weight
except:
new_graph.edge[node1][node2][attr] += graph2.edge[node1][node2][attr]
else:
try:
new_graph.edge[node1][node2][attr] = graph2.edge[node1][node2][attr] * graph2_weight
except:
new_graph.edge[node1][node2][attr] = graph2.edge[node1][node2][attr]
# otherwise, add the new edge with all its atributes -- first, iterate through those attributes to weight them
else:
attr_dict = graph2.edge[node1][node2]
for item in attr_dict:
try:
attr_dict[item] = attr_dict[item] * graph2_weight
except:
continue
new_graph.add_edge(node1, node2, attr_dict = attr_dict)
return new_graph