我有一个文件,其边缘有很好的重复。
重复是双向的,这意味着我多次A-> B,而且多次B-> A。
我需要净边缘,这意味着添加所有A-> B并减去所有B-> A。其结果应该是A-> B或B-> A边,且具有正值(如A-> B负)应为B-> A。
我从这个脚本开始(在Networkx : Convert multigraph into simple graph with weighted edges找到),它表现良好,所有A-> B的和,,但也将B-> A到A-> B的和边缘,当我需要它减去时。
初始代码
import networkx as nx
# weighted MultiGraph
M = nx.MultiGraph()
M.add_edge(1,2,weight=7)
M.add_edge(1,2,weight=19)
M.add_edge(2,3,weight=42)
# create weighted graph from M
G = nx.Graph()
for u,v,data in M.edges(data=True):
w = data['weight'] if 'weight' in data else 1.0
if G.has_edge(u,v):
G[u][v]['weight'] += w
else:
G.add_edge(u, v, weight=w)
print(G.edges(data=True))
# [(1, 2, {'weight': 26}), (2, 3, {'weight': 42})]
然后我添加了B-> A边
#trying to subtract from 1->2 edge above
M.add_edge(2,1,weight=26)
#reprocess entire calculations
G = nx.Graph()
for u,v,data in M.edges(data=True):
w = data['weight'] if 'weight' in data else 1.0
if G.has_edge(u,v):
G[u][v]['weight'] += w
else:
G.add_edge(u, v, weight=w)
print(G.edges(data=True))
#results shows edge above added 26, not subtracted
#[(1, 2, {'weight': 52}), (2, 3, {'weight': 42})]