Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

python - Networkx: how to split nodes into two, effectively disconnecting edges?

How do I split a node in an undirected graph into two new nodes so that two edges that allowed a path through the original node would now be two dead ends? I need to preserve the properties of the original node into the new nodes. Here is an example:

    |                          |
4---1---2---3---5    =>    4---1---2   2---3---5
    |                          |
   (one graph)            (two disjointed graphs)
question from:https://stackoverflow.com/questions/65853641/networkx-how-to-split-nodes-into-two-effectively-disconnecting-edges

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't see a way to have the same name for two nodes in the same graph.

Here is a function that duplicates the node, renames it, and rebuilds the edges:

def split_node(G, node):

    edges = G.edges(node, data=True)
    
    new_edges = []
    new_nodes = []

    H = G.__class__()
    H.add_nodes_from(G.subgraph(node))
    
    for i, (s, t, data) in enumerate(edges):
        
        new_node = '{}_{}'.format(node, i)
        I = nx.relabel_nodes(H, {node:new_node})
        new_nodes += list(I.nodes(data=True))
        new_edges.append((new_node, t, data))
    
    G.remove_node(node)
    G.add_nodes_from(new_nodes)
    G.add_edges_from(new_edges)
    
    return G

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...