简体   繁体   中英

get ordered nodes in components of directed acyclic networkx DiGraph

I have a directed graph with subgraphs where the order of nodes is important.

Example my graph would have two subgraphs, all linear 1-->2-->3 & 9-->8-->7-->6

note: the node names will be random and unique, no cycles in the graphs

NG = nx.DiGraph()
NG.add_edges_from([(1,2),(2,3)])
NG.add_edges_from([(9,8),(8,7),(7,6)])

I need to get the subgraphs or a list of nodes in the subgraphs with the nodes ordered according to their connection.

I've tried

[i.nodes() for i in list(nx.weakly_connected_component_subgraphs(NG))]

resulting in list of nodelists, almost right, but not ordered according to their connections:

[[1, 2, 3], [8, 9, 6, 7]]

How would I need to proceed to get the list of ordered nodelists. ie:

[[1, 2, 3], [9, 8, 7, 6]]

I'm assuming that you are sure these are "Directed Acyclic Graphs".

Then nx.topological_sort(G) sorts the nodes in a graph according to the order you want: that is, if u appears before v , that means there is no path from v to u (but possibly a path from u to v ). If you use nx.weakly_connected_component_subgraphs(G) you get a generator for the subgraphs you're interested in. So the approach I recommend is to first find the subgraphs and then sort the nodes.

[nx.topological_sort(H) for H in nx.weakly_connected_component_subgraphs(NG)]

Should get what you want.


An alternate more efficient method:

The previous code will not be the most efficient code possible, but it is simple. Creating each subgraph H takes time that could be avoided. A more efficient method would do weakly_connected_components(NG) (which generates lists of the nodes in each subgraph rather than the subgraph themselves). This would create lists like you have already. Then you do the topological sort:

[nx.topological_sort(NG, nbunch=subgraph_nodes) for subgraph_nodes in nx.weakly_connected_components(NG)]

This will be more efficient. What it does is first it generates the list of nodes in each component. Then it goes through sorting the nodes in each component. If you do this, you should take a look at the source for topological_sort . It will return a sorted list of all nodes that are reachable from any node it nbunch . In your case this is just nbunch , but more generally it does not just have to return nbunch .


Note: in your code there is no need for list(...) . You would get the same result without it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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