I would like to get a subgraph (red area) by node: The subgraph is composed of all the nodes reachable from the input node.
like G.subgraph(3) returns a new DiGraph from the red area.
For example I create a DiGraph as this:
import networkx as nx
G = nx.DiGraph()
G.add_path([1,2,3,4])
G.add_path([3,'a','b'])
A = nx.to_agraph(G)
A.layout()
A.draw('graph.png')
I looked into https://networkx.github.io/documentation/latest/reference/generated/networkx.Graph.subgraph.html and converting it to unidirectional. I tested out_egdes, strong/weak_connected_component, but its never worked. I also looked How to find subgraphs in a directed graph without converting to undirected graph? and Networkx: extract the connected component containing a given node (directed graph).
I know that Subgraph does not work in DiGraph.
Can someone please show me how to do this ? Would be nice if the resulting Graph is also a DiGraph
According to my understanding that the criteria of creation of the subgraph depends on the nodes reachable from the input node. Then the following recursive function should be sufficient to get the job done.
I copied your code to create the graph, initialized an empty Directed graph and called the function as follows:
The resulted Digraph is shown in the figure.
Use build-in traversal algorithms may get better performance, support bi-direction option, and avoid recursive depth limitation.
Or the concise version for uni-direction:
The build-in version is 3 times fast than recursive one in my case. It subgraph 3000 from 5000 nodes :
The result of create_subgraph(G, 3) is shown in figure:
To elaborate on @vaettchen's cryptic comment on How to extract a subgraph from a dot file
grab a
gvpr
command file,reduce.g
from https://gist.github.com/blabber/74b8d9ed59d0b2ad0d7a734113996424#file-reduce-grun
gvpr
onreduce.g
:gvpr -f reduce.g -a '"3" 10' mygraph.dot > myreduced.graph.dot
where
-a
are the parameters to thereduce.g
program, i.e. target node=3 and hops to follow. If you skip-a
it'll tell you about it.This script takes exactly two parameter. 1: name of node, 2: number of hops
Now, as it stands
reduce.g
does seem to modify the graph quite a bit - I switched from horizontal to vertical orientation.BTW, since feeding parameters into
bash
script stumped me quite a bit with the quotes, I am adding what does work.gvpr -f reduce.g -a " \"$node_to_select\" 10" mygraph.dot