import networkx as nx
def multiG_to_G(MG, aggr_func=max):
rG = nx.Graph()
# add nodes
rG.add_nodes_from([n for n in MG.nodes()])
# extract edge and their weights
edge_weight_dict = {}
for u, v, e_attr in MG.edges(data=True):
e, weight = (u, v), e_attr['weight']
if e in edge_weight_dict:
edge_weight_dict[e].append(weight)
else:
edge_weight_dict[e] = [weight]
# add edges by aggregating their weighy by `aggr_func`
for e, e_weight_lst in edge_weight_dict.items():
rG.add_edge(*e, weight=aggr_func(e_weight_lst))
return rG
MG = nx.MultiGraph()
MG.add_edge(0, 1, weight=10)
MG.add_edge(1, 0, weight=3)
MG.add_edge(0, 1, weight=5)
print("== MG edges with weight ")
print(MG.edges(data=True))
print("== nx.Graph(MG) edges ")
# nx.Graph(MG)의 형태로 변환하면, "가장 최근에 add한 edge만 추가됨"
G = nx.Graph(MG)
print(G.edges(data=True))
print("== MG to G by max weight ")
MG_max_weight = multiG_to_G(MG, aggr_func=max)
print(MG_max_weight.edges(data=True))
print("== MG to G by sum weight ")
MG_sum_weight = multiG_to_G(MG, aggr_func=sum)
print(MG_sum_weight.edges(data=True))
print("== MG to G by min weight ")
MG_min_weight = multiG_to_G(MG, aggr_func=min)
print(MG_min_weight.edges(data=True))
== MG edges with weight
[(0, 1, {'weight': 10}), (0, 1, {'weight': 3}), (0, 1, {'weight': 5})]
== nx.Graph(MG) edges
[(0, 1, {'weight': 5})]
== MG to G by max weight
[(0, 1, {'weight': 10})]
== MG to G by sum weight
[(0, 1, {'weight': 18})]
== MG to G by min weight
댓글남기기