NetworkX — Get all Paths from all sources to sinks
Posted on Wed 04 November 2015 in Tech
Often when I'm working with graphs and a set of masses in a spectrum I need to be able to iterate over all paths for all sources and sinks in that graph. Especially if I'm looking to compare multiple ideal spectrums against a given spectrum. Here's some code that will allow me to quickly iterate over all source->sink paths in a given graph G.
```python
!/usr/bin/env python
""" Shane Dowling, 04 Nov 2015 Will iterate over all sources, sinks and get all paths """ import networkx as nx G = nx.DiGraph() # Fill in a few edges sink_nodes = [node for node, outdegree in G.out_degree(G.nodes()).items() if outdegree == 0] source_nodes = [node for node, indegree in G.in_degree(G.nodes()).items() if indegree == 0] for [(source, sink) for sink in sink_nodes for source in source_nodes]: for path in nx.all_simple_paths(G, source=source, target=sink): print(path) ```