Last active
June 9, 2023 03:23
-
-
Save Zulko/7629206 to your computer and use it in GitHub Desktop.
This is a function to merge several nodes into one in a Networkx graph
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is a function to merge several nodes into one in a Networkx graph | |
def merge_nodes(G,nodes, new_node, attr_dict=None, **attr): | |
""" | |
Merges the selected `nodes` of the graph G into one `new_node`, | |
meaning that all the edges that pointed to or from one of these | |
`nodes` will point to or from the `new_node`. | |
attr_dict and **attr are defined as in `G.add_node`. | |
""" | |
G.add_node(new_node, attr_dict, **attr) # Add the 'merged' node | |
for n1,n2,data in G.edges(data=True): | |
# For all edges related to one of the nodes to merge, | |
# make an edge going to or coming from the `new gene`. | |
if n1 in nodes: | |
G.add_edge(new_node,n2,data) | |
elif n2 in nodes: | |
G.add_edge(n1,new_node,data) | |
for n in nodes: # remove the merged nodes | |
G.remove_node(n) |
Hi, Nice function.
But if the graph is a weighted graph then u should also add one more line to your function that new_node.weight = nodes.weight (nodes sent for merging)
There is an issue with this code. For example if we merge two nodes and both have a connection with same node then we have to add the edge weights of both connections when we make new edge.
@bilalzahid make a pull request!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, thanks for sharing this function.
FYI -- I noticed a problem if new_node is in nodes: all new_node related edges get deleted at the end. If you always check if the 'current working node' is not new_node it seems to fix it.
Cheers!