I have a graph with adjacency matrix of the form below (a 6-node graph where self-edges are 0 and no_connections are marked Inf and other edges are 1):
{1: {1: 0, 2: 1, 3: inf, 4: inf, 5: inf, 6: inf}, 2: {1: 1, 2: 0, 3: inf, 4: 1, 5: 1, 6: inf}, 3: {1: inf, 2: inf, 3: 0, 4: 1, 5: inf, 6: inf}, 4: {1: inf, 2: 1, 3: 1, 4: 0, 5: 1, 6: 1}, 5: {1: inf, 2: 1, 3: inf, 4: 1, 5: 0, 6: inf}, 6: {1: inf, 2: inf, 3: inf, 4: 1, 5: inf, 6: 0}}
I want to use networkx package for its all_simple_paths function to find all simple paths from a source to a destination but when I call
nx.all_simple_paths(graph, src, dst)
it gives: AttributeError: 'dict' object has no attribute 'is_multigraph'
I currently do not have the graph in any other format. How should I resolve this issue?
Thanks.
Your graph is currently stored as a dictionary. It's a little unfair to expect networkx to work automagically on any data structure you choose. Even if it were set up to handle a dictionary in the way you've done it, how would it know how to interpret a 0 or inf
?
To use networkx commands you'll need your graph to be in the networkx Graph format.
import networkx as nx
D = {1: {1: 0, 2: 1, 3: float('inf'), 4: float('inf'), 5: float('inf'), 6: float('inf')}, 2: {1: 1, 2: 0, 3: float('inf'), 4: 1, 5: 1, 6: float('inf')}, 3: {1: float('inf'), 2: float('inf'), 3: 0, 4: 1, 5: float('inf'), 6: float('inf')}, 4: {1: float('inf'), 2: 1, 3: 1, 4: 0, 5: 1, 6: 1}, 5: {1: float('inf'), 2: 1, 3: float('inf'), 4: 1, 5: 0, 6: float('inf')}, 6: {1: float('inf'), 2: float('inf'), 3: float('inf'), 4: 1, 5: float('inf'), 6: 0}}
G=nx.Graph()
for node, neighbor_dict in D.items():
G.add_node(node)
for neighbor, val in neighbor_dict.items():
if val !=0 and val <float('inf'):
G.add_edge(node, neighbor, weight=val)
for path in nx.all_simple_paths(G,1,3):
print path
>[1, 2, 4, 3]
>[1, 2, 5, 4, 3]