简体   繁体   English

networkx将加权有向图改为无向

[英]networkx change weighted directed graph to undirected

Is a built-in function in networkx could change weighted directed graph to undirected? networkx中的内置函数是否可以将加权有向图更改为无向? The functionality should change two directed edges (n1,n2,5) and (n2,n1,7) to one (n1,n2,12). 该功能应该将两个有向边(n1,n2,5)和(n2,n1,7)改为一个(n1,n2,12)。

I searched a long time and didn't fund out one. 我搜索了很长时间,并没有资助一个。

Networkx has a to_undirected function but it doesn't sum weights, it is just updating weight with the last found edge weight from the original graph: Networkx有一个to_undirected函数但它没有加权,它只是用原始图中最后找到的边权重来更新权重:

If edges in both directions (u, v) and (v, u) exist in the graph, attributes for the new undirected edge will be a combination of the attributes of the directed edges. 如果图中存在两个方向(u,v)和(v,u)的边,则新的无向边的属性将是有向边的属性的组合。 The edge data is updated in the (arbitrary) order that the edges are encountered. 边缘数据以遇到边缘的(任意)顺序更新。 For more customized control of the edge attributes use add_edge(). 要获得更多自定义边缘属性的控制,请使用add_edge()。

You should do it manually like this: 你应该像这样手动完成:

G = nx.DiGraph()
G.add_weighted_edges_from([
    (1,2,3),
    (1,3,4),
    (2,1,5),
    (2,3,1),
    (3,2,2)
])
UG = G.to_undirected()
for node in G:
    for ngbr in nx.neighbors(G, node):
        if node in nx.neighbors(G, ngbr):
            UG.edges[node, ngbr]['weight'] = (
                G.edges[node, ngbr]['weight'] + G.edges[ngbr, node]['weight']
            )
UG.edges.data('weight')

will return summarized weights: 将返回汇总的权重:

EdgeDataView([(1, 2, 8), (1, 3, 4), (2, 3, 3)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM