Dave
Dave

Reputation: 8109

How to treat a `networkx.digraph` as un-directed

I have a directed graph G represented as a networkx.digraph. I want to be able to do shortest-path computations on the undirected version of that graph. How do I get an object that is the undirected version of that graph.

I know it will involve making a graph view, however the documentation for generic_graph_view is not very useful in explaining how to achieve this; nor is the code itself for some one that is not familiar with the internals of the library.

Upvotes: 0

Views: 66

Answers (1)

cookesd
cookesd

Reputation: 1336

You can just pass your directed graph to nx.Graph

G=nx.fast_gnp_random_graph(10,.2,directed=True)
G_undirected = nx.Graph(G)

print(G.edges)
# OutEdgeView([(0, 1), (0, 5), (1, 0), (1, 2), (1, 6), (1, 9),
# (2, 7), (2, 9), (3, 4), (4, 7), (5, 4), (6, 0), (7, 8),
# (8, 9), (9, 4)])

print(G_undirected.edges)
# EdgeView([(0, 1), (0, 5), (0, 6), (1, 2), (1, 6), (1, 9), (2, 7),
# (2, 9), (3, 4), (4, 7), (4, 5), (4, 9), (7, 8), (8, 9)])

Upvotes: 2

Related Questions