Skip to content

Commit

Permalink
Added code to check directed and almost directed cycles
Browse files Browse the repository at this point in the history
Signed-off-by: “Aryan <“aryanroy5678@gmail.com”>
  • Loading branch information
“Aryan committed Jul 30, 2023
1 parent 3fc61a4 commit 6132669
Showing 1 changed file with 48 additions and 1 deletion.
49 changes: 48 additions & 1 deletion pywhy_graphs/algorithms/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -606,7 +606,38 @@ def inducing_path(G, node_x: Node, node_y: Node, L: Set = None, S: Set = None):
return (path_exists, path)


def valid_mag(G):
def _find_adc(G):

"""Finds an Almost Directed Cycles in a mixed edge graph.
Parameters
----------
G : Graph
The graph.
Returns
-------
adc_present : bool
A boolean indicating whether an almost directed cycle is present or not.
"""

adc_present = False

undedges = G.undirected_edges

for elem in G.nodes:
ancestors = nx.ancestors(G.sub_directed_graph(), elem)
descendants = nx.descendants(G.sub_directed_graph(), elem)
for elem in undedges:
if (elem[0] in ancestors and elem[1] in descendants) or (
elem[1] in ancestors and elem[0] in descendants
): # there is an undirected edge from one of the ancestors to a descendant
return not adc_present

return adc_present


def valid_mag(G: CPDAG):
"""Checks if the provided graph is a valid MAG.
Parameters
Expand All @@ -622,4 +653,20 @@ def valid_mag(G):
"""
is_valid = False

directed_sub_graph = G.sub_directed_graph()

# check if there are any directed cyclces
try:
nx.find_cycle(directed_sub_graph) # raises a NetworkXNoCycle error
return is_valid
except nx.NetworkXNoCycle:
pass

# check if there are any almost directed cycles

if _find_adc(G): # if there is an ADC, it's not a valid MAG
return is_valid

# check if there are any inducing paths between non-adjacent nodes

return is_valid

0 comments on commit 6132669

Please sign in to comment.