gpt4 book ai didi

NetworkX - 删除节点并重新连接边缘

转载 作者:行者123 更新时间:2023-12-03 14:56:37 32 4
gpt4 key购买 nike

我在图中有一个节点,它充当一种“临时连接器”节点。我想删除该节点并更新图中的边,以便其所有直接前辈都指向其直接后继者。

networkx 中是否有内置功能可以做到这一点,还是我需要推出自己的解决方案?

例子:

我有图 1 > 2 > 3 .我想删除节点 2最后得到图形 1 > 3 .

这是我目前的做法:

In [230]: g = nx.DiGraph()

In [231]: g.add_edges_from([(1,2),(2,3)])

In [232]: g.edges()
Out[232]: [(1, 2), (2, 3)]

In [233]: predecessors = g.predecessors(2)

In [234]: successors = g.successors(2)

In [235]: new_edges = [(p,s) for p in predecessors for s in successors]

In [236]: new_edges
Out[236]: [(1, 3)]

In [237]: g.remove_node(2)

In [238]: g.add_edges_from(new_edges)

In [239]: g.nodes()
Out[239]: [1, 3]

In [240]: g.edges()
Out[240]: [(1, 3)]

最佳答案

我尝试在一个巨大的复杂图形上使用 mjvaak 的答案,但它没有用,因为它用不再存在的节点创建边。我通过简单地从 g0 中取出边缘来修复它。
所以我改变了:

edges = g.edges(node)
为了:
edges = g0.edges(node)
因此,固定代码如下:
def simplifyGraph(G):
''' Loop over the graph until all nodes of degree 2 have been removed and their incident edges fused '''

g = G.copy()

while any(degree==2 for _, degree in g.degree):

g0 = g.copy() #<- simply changing g itself would cause error `dictionary changed size during iteration`
for node, degree in g.degree():
if degree==2:

if g.is_directed(): #<-for directed graphs
a0,b0 = list(g0.in_edges(node))[0]
a1,b1 = list(g0.out_edges(node))[0]

else:
edges = g0.edges(node)
edges = list(edges.__iter__())
a0,b0 = edges[0]
a1,b1 = edges[1]

e0 = a0 if a0!=node else b0
e1 = a1 if a1!=node else b1

g0.remove_node(node)
g0.add_edge(e0, e1)
g = g0

return g
感谢 mjkvaak 的解决方案!它只需要对更大的图形稍作修改。

关于NetworkX - 删除节点并重新连接边缘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53353335/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com