Bernardo Trindade
Bernardo Trindade

Reputation: 481

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)

Upvotes: 2

Views: 1569

Answers (1)

warped
warped

Reputation: 9481

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

Upvotes: 1

Related Questions