I'm looking at using networkx to create and maintain a Directed Acyclic Graph(DAG).
What is the preferred way to check if adding an edge will cause the DiGraph to no longer be a DAG?
for an example graph:
import networkx as nx
G = nx.DiGraph()
G.add_edges_from([(1,2), (1,3), (2,4)]) # no cycles so far
we get:
>>> G
1 2 3
2 4
3
4
>>> nx.is_directed_acyclic_graph(G)
True
when we add a cycle to the graph:
G.add_edge(4,1) # now we have a cycle
we get:
>>> G
1 2 3
2 4
3
4 1
>>> nx.is_directed_acyclic_graph(G)
False
How should I check if a new edge will cause a cycle? The best I've come up with so far has been something like:
def add_dependency(G, n1, n2):
if n2 in nx.ancestors(G, n1):
print('this will create a cycle')
else:
print(f"add {n2} as edge of {n1}")
G.add_edge(n1, n2)
Is there a better way to do this?