Most elegant way to find node's predecessors with networkX
There is a predecessor (and predecessor_iter) method: http://networkx.lanl.gov/reference/generated/networkx.DiGraph.predecessors.html#networkx.DiGraph.predecessors
Also there is nothing stopping you from accessing the data structure directly as G.pred
In [1]: import networkx as nx
In [2]: G = nx.DiGraph() # a directed graph
In [3]: G.add_edge('a', 'b')
In [4]: G.predecessors('b')
Out[4]: ['a']
In [5]: G.pred['b']
Out[5]: {'a': {}}
Another way to implement this can be as follows:
Creating the basic graph
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_edges_from([('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E','F'), ('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G'), ('Q', 'D')])
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'),node_size = 50)
nx.draw_networkx_edges(G, pos, edge_color='r', arrows=True)
nx.draw_networkx_labels(G, pos)
plt.show()
Finding Downstream Edges
print("Downstream Edges of 'B' (just example)-->")
print(list(nx.dfs_edges(G,'B')))
Finding Upstream Edges
print("Upstream Edges of 'B' (just example)-->")
print(list(nx.edge_dfs(G,'B', orientation='reverse')))
More details in this blog