
    wg                        d Z ddlZddlmZ ddlmZ ddlmZmZm	Z	m
Z
 ddlmZ ddlZddlmZmZmZ g dZej(                  Zej,                  d	        Zej,                  d
        Zej,                  d        Zej,                  d        Zej,                  d        Zej,                  d        Zej,                  d%d       Z ed      ej,                  d               Zej,                  d        Z ej,                  dd      d&d       Z  ed       ej,                  dd      d%d              Z! ed       ej,                  d      d               Z" ed      ej,                  d%d              Z# ed       ej,                  ddi      d'd              Z$ ed       ej,                  ddi      d(d              Z%ej,                  d        Z& ed        ed       ej,                  d      d!                      Z' ed      ej,                  d"               Z( ed      ej,                  d#               Z) ed      ej,                  d$               Z*y))zAlgorithms for directed acyclic graphs (DAGs).

Note that most of these functions are only guaranteed to work for DAGs.
In general, these functions do not check for acyclic-ness, so it is up
to the user to check for that.
    N)deque)partial)chaincombinationsproductstarmap)gcd)arbitrary_elementnot_implemented_forpairwise)descendants	ancestorstopological_sort lexicographical_topological_sortall_topological_sortstopological_generationsis_directed_acyclic_graphis_aperiodictransitive_closuretransitive_closure_dagtransitive_reduction
antichainsdag_longest_pathdag_longest_path_lengthdag_to_branchingcompute_v_structuresc                 `    t        j                  | |      D ch c]  \  }}|	 c}}S c c}}w )a_  Returns all nodes reachable from `source` in `G`.

    Parameters
    ----------
    G : NetworkX Graph
    source : node in `G`

    Returns
    -------
    set()
        The descendants of `source` in `G`

    Raises
    ------
    NetworkXError
        If node `source` is not in `G`.

    Examples
    --------
    >>> DG = nx.path_graph(5, create_using=nx.DiGraph)
    >>> sorted(nx.descendants(DG, 2))
    [3, 4]

    The `source` node is not a descendant of itself, but can be included manually:

    >>> sorted(nx.descendants(DG, 2) | {2})
    [2, 3, 4]

    See also
    --------
    ancestors
    nx	bfs_edgesGsourceparentchilds       \/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/networkx/algorithms/dag.pyr   r   '   s(    D (*||Av'>?mfeE???s   *c                 d    t        j                  | |d      D ch c]  \  }}|	 c}}S c c}}w )a\  Returns all nodes having a path to `source` in `G`.

    Parameters
    ----------
    G : NetworkX Graph
    source : node in `G`

    Returns
    -------
    set()
        The ancestors of `source` in `G`

    Raises
    ------
    NetworkXError
        If node `source` is not in `G`.

    Examples
    --------
    >>> DG = nx.path_graph(5, create_using=nx.DiGraph)
    >>> sorted(nx.ancestors(DG, 2))
    [0, 1]

    The `source` node is not an ancestor of itself, but can be included manually:

    >>> sorted(nx.ancestors(DG, 2) | {2})
    [0, 1, 2]

    See also
    --------
    descendants
    T)reverser   r!   s       r&   r   r   L   s*    D (*||Avt'LMmfeEMMMs   ,c                 d    	 t        t        |       d       y# t        j                  $ r Y yw xY w)z/Decides whether the directed graph has a cycle.r   )maxlenFT)r   r   r   NetworkXUnfeasibler"   s    r&   	has_cycler-   q   s6    q!!,     s    //c                 >    | j                         xr t        |        S )a  Returns True if the graph `G` is a directed acyclic graph (DAG) or
    False if not.

    Parameters
    ----------
    G : NetworkX graph

    Returns
    -------
    bool
        True if `G` is a DAG, False otherwise

    Examples
    --------
    Undirected graph::

        >>> G = nx.Graph([(1, 2), (2, 3)])
        >>> nx.is_directed_acyclic_graph(G)
        False

    Directed graph with cycle::

        >>> G = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
        >>> nx.is_directed_acyclic_graph(G)
        False

    Directed acyclic graph::

        >>> G = nx.DiGraph([(1, 2), (2, 3)])
        >>> nx.is_directed_acyclic_graph(G)
        True

    See also
    --------
    topological_sort
    )is_directedr-   r,   s    r&   r   r   }   s    L ==?/9Q<//    c           	   #     K   | j                         st        j                  d      | j                         }| j	                         D ci c]  \  }}|dkD  s|| }}}| j	                         D cg c]  \  }}|dk(  s| }}}|ru|}g }|D ]e  }|| vrt        d      | j                  |      D ]@  }	 ||xx   |rt        | |   |         ndz  cc<   ||   dk(  s-|j                  |       ||= B g | |ru|rt        j                  d      yc c}}w c c}}w # t        $ r}	t        d      |	d}	~	ww xY ww)a  Stratifies a DAG into generations.

    A topological generation is node collection in which ancestors of a node in each
    generation are guaranteed to be in a previous generation, and any descendants of
    a node are guaranteed to be in a following generation. Nodes are guaranteed to
    be in the earliest possible generation that they can belong to.

    Parameters
    ----------
    G : NetworkX digraph
        A directed acyclic graph (DAG)

    Yields
    ------
    sets of nodes
        Yields sets of nodes representing each generation.

    Raises
    ------
    NetworkXError
        Generations are defined for directed graphs only. If the graph
        `G` is undirected, a :exc:`NetworkXError` is raised.

    NetworkXUnfeasible
        If `G` is not a directed acyclic graph (DAG) no topological generations
        exist and a :exc:`NetworkXUnfeasible` exception is raised.  This can also
        be raised if `G` is changed while the returned iterator is being processed

    RuntimeError
        If `G` is changed while the returned iterator is being processed.

    Examples
    --------
    >>> DG = nx.DiGraph([(2, 1), (3, 1)])
    >>> [sorted(generation) for generation in nx.topological_generations(DG)]
    [[2, 3], [1]]

    Notes
    -----
    The generation in which a node resides can also be determined by taking the
    max-path-distance from the node to the farthest leaf node. That value can
    be obtained with this function using `enumerate(topological_generations(G))`.

    See also
    --------
    topological_sort
    2Topological sort not defined on undirected graphs.r   Graph changed during iteration   N8Graph contains a cycle or graph changed during iteration)r/   r   NetworkXErroris_multigraph	in_degreeRuntimeError	neighborslenKeyErrorappendr+   )
r"   
multigraphvdindegree_mapzero_indegreethis_generationnoder%   errs
             r&   r   r      sd    b ==?STT"J%&[[]<TQa!eAqD<L<#$;;=;41aAFQ;M;
'# 
	,D1}"#CDDT* ,R '*3qwu~+>RSS'  &!+!((/$U+,
	,    ##F
 	
 ' =;   R&'GHcQRsZ   A	EDDE4DD1E8 D$E!E $E$	D>-D99D>>Ec              #   X   K   t        j                  |       D ]  }|E d{     y7 w)a  Returns a generator of nodes in topologically sorted order.

    A topological sort is a nonunique permutation of the nodes of a
    directed graph such that an edge from u to v implies that u
    appears before v in the topological sort order. This ordering is
    valid only if the graph has no directed cycles.

    Parameters
    ----------
    G : NetworkX digraph
        A directed acyclic graph (DAG)

    Yields
    ------
    nodes
        Yields the nodes in topological sorted order.

    Raises
    ------
    NetworkXError
        Topological sort is defined for directed graphs only. If the graph `G`
        is undirected, a :exc:`NetworkXError` is raised.

    NetworkXUnfeasible
        If `G` is not a directed acyclic graph (DAG) no topological sort exists
        and a :exc:`NetworkXUnfeasible` exception is raised.  This can also be
        raised if `G` is changed while the returned iterator is being processed

    RuntimeError
        If `G` is changed while the returned iterator is being processed.

    Examples
    --------
    To get the reverse order of the topological sort:

    >>> DG = nx.DiGraph([(1, 2), (2, 3)])
    >>> list(reversed(list(nx.topological_sort(DG))))
    [3, 2, 1]

    If your DiGraph naturally has the edges representing tasks/inputs
    and nodes representing people/processes that initiate tasks, then
    topological_sort is not quite what you need. You will have to change
    the tasks to nodes with dependence reflected by edges. The result is
    a kind of topological sort of the edges. This can be done
    with :func:`networkx.line_graph` as follows:

    >>> list(nx.topological_sort(nx.line_graph(DG)))
    [(1, 2), (2, 3)]

    Notes
    -----
    This algorithm is based on a description and proof in
    "Introduction to Algorithms: A Creative Approach" [1]_ .

    See also
    --------
    is_directed_acyclic_graph, lexicographical_topological_sort

    References
    ----------
    .. [1] Manber, U. (1989).
       *Introduction to Algorithms - A Creative Approach.* Addison-Wesley.
    N)r   r   )r"   
generations     r&   r   r      s/     B 003 
s   *(*c              #   Z  K   | j                         sd}t        j                  |      d t        |       D ci c]  \  }}||
 c}}fd}| j	                         D ci c]  \  }}|dkD  s|| }}}| j	                         D cg c]  \  }}|dk(  s ||       }	}}t        j                  |	       |	rt        j                  |	      \  }
}
}|| vrt        d      | j                  |      D ]<  \  }
}	 ||xx   dz  cc<   ||   dk(  s	 t        j                  |	 ||             ||= > | |	r|rd	}t        j                  |      yc c}}w c c}}w c c}}w # t        $ r}t        d      |d}~ww xY w# t        $ r}t        | d      d}~ww xY ww)
a  Generate the nodes in the unique lexicographical topological sort order.

    Generates a unique ordering of nodes by first sorting topologically (for which there are often
    multiple valid orderings) and then additionally by sorting lexicographically.

    A topological sort arranges the nodes of a directed graph so that the
    upstream node of each directed edge precedes the downstream node.
    It is always possible to find a solution for directed graphs that have no cycles.
    There may be more than one valid solution.

    Lexicographical sorting is just sorting alphabetically. It is used here to break ties in the
    topological sort and to determine a single, unique ordering.  This can be useful in comparing
    sort results.

    The lexicographical order can be customized by providing a function to the `key=` parameter.
    The definition of the key function is the same as used in python's built-in `sort()`.
    The function takes a single argument and returns a key to use for sorting purposes.

    Lexicographical sorting can fail if the node names are un-sortable. See the example below.
    The solution is to provide a function to the `key=` argument that returns sortable keys.


    Parameters
    ----------
    G : NetworkX digraph
        A directed acyclic graph (DAG)

    key : function, optional
        A function of one argument that converts a node name to a comparison key.
        It defines and resolves ambiguities in the sort order.  Defaults to the identity function.

    Yields
    ------
    nodes
        Yields the nodes of G in lexicographical topological sort order.

    Raises
    ------
    NetworkXError
        Topological sort is defined for directed graphs only. If the graph `G`
        is undirected, a :exc:`NetworkXError` is raised.

    NetworkXUnfeasible
        If `G` is not a directed acyclic graph (DAG) no topological sort exists
        and a :exc:`NetworkXUnfeasible` exception is raised.  This can also be
        raised if `G` is changed while the returned iterator is being processed

    RuntimeError
        If `G` is changed while the returned iterator is being processed.

    TypeError
        Results from un-sortable node names.
        Consider using `key=` parameter to resolve ambiguities in the sort order.

    Examples
    --------
    >>> DG = nx.DiGraph([(2, 1), (2, 5), (1, 3), (1, 4), (5, 4)])
    >>> list(nx.lexicographical_topological_sort(DG))
    [2, 1, 3, 5, 4]
    >>> list(nx.lexicographical_topological_sort(DG, key=lambda x: -x))
    [2, 5, 1, 4, 3]

    The sort will fail for any graph with integer and string nodes. Comparison of integer to strings
    is not defined in python.  Is 3 greater or less than 'red'?

    >>> DG = nx.DiGraph([(1, "red"), (3, "red"), (1, "green"), (2, "blue")])
    >>> list(nx.lexicographical_topological_sort(DG))
    Traceback (most recent call last):
    ...
    TypeError: '<' not supported between instances of 'str' and 'int'
    ...

    Incomparable nodes can be resolved using a `key` function. This example function
    allows comparison of integers and strings by returning a tuple where the first
    element is True for `str`, False otherwise. The second element is the node name.
    This groups the strings and integers separately so they can be compared only among themselves.

    >>> key = lambda node: (isinstance(node, str), node)
    >>> list(nx.lexicographical_topological_sort(DG, key=key))
    [1, 2, 3, 'blue', 'green', 'red']

    Notes
    -----
    This algorithm is based on a description and proof in
    "Introduction to Algorithms: A Creative Approach" [1]_ .

    See also
    --------
    topological_sort

    References
    ----------
    .. [1] Manber, U. (1989).
       *Introduction to Algorithms - A Creative Approach.* Addison-Wesley.
    r2   Nc                     | S N )rD   s    r&   keyz-lexicographical_topological_sort.<locals>.key  s    Kr0   c                       |       |    | fS rJ   rK   )rD   rL   
nodeid_maps    r&   create_tuplez6lexicographical_topological_sort.<locals>.create_tuple  s    4y*T*D00r0   r   r3   r4   zJ
Consider using `key=` parameter to resolve ambiguities in the sort order.r5   )r/   r   r6   	enumerater8   heapqheapifyheappopr9   edgesr<   heappush	TypeErrorr+   )r"   rL   msginrO   r?   r@   rA   rB   _rD   r%   rE   rN   s    `            @r&   r   r   9  s    B ==?Bs##
{	 $-Q<041a!Q$0J1 &'[[]<TQa!eAqD<L<12IA!q&\!_IMI	MM- 
]]=1
1dq=?@@ 	(HAuNU#q(# E"a'NN=,u2EF
 !'	( 
' * H##C(( ? 1
 =I  N"#CD#MN
 ! #%jk s   ;F+EF+)E#7E#<F+E) 
E)*AF+E/F+F7F+,F+/	F	8FF		F+	F(F##F((F+
undirectedc              #     	K   | j                         st        j                  d      t        | j	                               	t        | j	                         D cg c]  \  }}|dk(  s| c}}      }g }g }	 t        	fd|D              sJ t        |      t        |       k(  rt        |       t        |      dkD  rt        |      t        |      k(  sJ |j                         }| j                  |      D ]  \  }}	|xx   dz  cc<   	|   dk\  rJ  t        |      dkD  r5	|d      dkD  r*|j                          t        |      dkD  r	|d      dkD  r*|j                  |       |d   |d   k(  r|j                          nnt        |      dkD  rnt        |      dk(  rt        j                  d      |j                         }| j                  |      D ]6  \  }}	|xx   dz  cc<   	|   dk\  sJ 	|   dk(  s&|j                  |       8 |j                  |       t        |      t        |      k  r|j                  |       t        |      dk(  ryc c}}w w)a  Returns a generator of _all_ topological sorts of the directed graph G.

    A topological sort is a nonunique permutation of the nodes such that an
    edge from u to v implies that u appears before v in the topological sort
    order.

    Parameters
    ----------
    G : NetworkX DiGraph
        A directed graph

    Yields
    ------
    topological_sort_order : list
        a list of nodes in `G`, representing one of the topological sort orders

    Raises
    ------
    NetworkXNotImplemented
        If `G` is not directed
    NetworkXUnfeasible
        If `G` is not acyclic

    Examples
    --------
    To enumerate all topological sorts of directed graph:

    >>> DG = nx.DiGraph([(1, 2), (2, 3), (2, 4)])
    >>> list(nx.all_topological_sorts(DG))
    [[1, 2, 4, 3], [1, 2, 3, 4]]

    Notes
    -----
    Implements an iterative version of the algorithm given in [1].

    References
    ----------
    .. [1] Knuth, Donald E., Szwarcfiter, Jayme L. (1974).
       "A Structured Program to Generate All Topological Sorting Arrangements"
       Information Processing Letters, Volume 2, Issue 6, 1974, Pages 153-157,
       ISSN 0020-0190,
       https://doi.org/10.1016/0020-0190(74)90001-5.
       Elsevier (North-Holland), Amsterdam
    r2   r   c              3   .   K   | ]  }|   d k(    ywr   NrK   ).0r?   counts     r&   	<genexpr>z(all_topological_sorts.<locals>.<genexpr>  s     ,Q58q=,s   r4   zGraph contains a cycle.N)r/   r   r6   dictr8   r   allr;   listpop	out_edges
appendleftr+   r=   )
r"   r?   r@   Dbasescurrent_sortqrZ   jr`   s
            @r&   r   r     sI    ^ ==?STT EQ[[]5TQa1fq56AEL ,!,,,,|A&|$$ l#a'5zS%6666 $$&
 KKN )DAq!HMH 8q=(=) !fqjU1R5\A%5EEG !fqjU1R5\A%5 QR5E"I% IIK
 7 l#a'< 1v{++,EFF A A  1aAQx1}$}8q=HHQK	 
 " 5zC--Qu:?s  6s4   AI)I#
(I#
,B+I)AI)<I)A*I)A#I)c                    | j                         st        j                  d      t        |       dk(  rt        j                  d      t        |       }|di}|g}d}d}|rPg }|D ]?  }| |   D ]5  }||v rt        |||   ||   z
  dz         } |j                  |       |||<   7 A |}|dz  }|rPt        |      t        |       k(  r|dk(  S |dk(  xr9 t        j                  | j                  t        |       t        |      z
              S )a  Returns True if `G` is aperiodic.

    A directed graph is aperiodic if there is no integer k > 1 that
    divides the length of every cycle in the graph.

    Parameters
    ----------
    G : NetworkX DiGraph
        A directed graph

    Returns
    -------
    bool
        True if the graph is aperiodic False otherwise

    Raises
    ------
    NetworkXError
        If `G` is not directed

    Examples
    --------
    A graph consisting of one cycle, the length of which is 2. Therefore ``k = 2``
    divides the length of every cycle in the graph and thus the graph
    is *not aperiodic*::

        >>> DG = nx.DiGraph([(1, 2), (2, 1)])
        >>> nx.is_aperiodic(DG)
        False

    A graph consisting of two cycles: one of length 2 and the other of length 3.
    The cycle lengths are coprime, so there is no single value of k where ``k > 1``
    that divides each cycle length and therefore the graph is *aperiodic*::

        >>> DG = nx.DiGraph([(1, 2), (2, 3), (3, 1), (1, 4), (4, 1)])
        >>> nx.is_aperiodic(DG)
        True

    A graph consisting of two cycles: one of length 2 and the other of length 4.
    The lengths of the cycles share a common factor ``k = 2``, and therefore
    the graph is *not aperiodic*::

        >>> DG = nx.DiGraph([(1, 2), (2, 1), (3, 4), (4, 5), (5, 6), (6, 3)])
        >>> nx.is_aperiodic(DG)
        False

    An acyclic graph, therefore the graph is *not aperiodic*::

        >>> DG = nx.DiGraph([(1, 2), (2, 3)])
        >>> nx.is_aperiodic(DG)
        False

    Notes
    -----
    This uses the method outlined in [1]_, which runs in $O(m)$ time
    given $m$ edges in `G`. Note that a graph is not aperiodic if it is
    acyclic as every integer trivial divides length 0 cycles.

    References
    ----------
    .. [1] Jarvis, J. P.; Shier, D. R. (1996),
       "Graph-theoretic analysis of finite Markov chains,"
       in Shier, D. R.; Wallenius, K. T., Applied Mathematical Modeling:
       A Multidisciplinary Approach, CRC Press.
    z.is_aperiodic not defined for undirected graphsr   zGraph has no nodes.r4   )r/   r   r6   r;   NetworkXPointlessConceptr
   r	   r=   r   subgraphset)	r"   slevels
this_levelglev
next_levelur?   s	            r&   r   r   ?  s%   F ==?OPP
1v{))*?@@!AVFJ	A
C

 	$AqT $;Avay6!94q89A%%a( #F1I$	$  
q  6{c!fAvAvK"//!**SVc&k5I*JKKr0   T)preserve_all_attrsreturns_graphc                    | j                         |dvrt        j                  d      | D ]  |0j                  fdt        j                  |       D               5|du r4j                  fdt        j                  |       hz  D               m|du srj                  fdt        j
                  |       D                S )aI
  Returns transitive closure of a graph

    The transitive closure of G = (V,E) is a graph G+ = (V,E+) such that
    for all v, w in V there is an edge (v, w) in E+ if and only if there
    is a path from v to w in G.

    Handling of paths from v to v has some flexibility within this definition.
    A reflexive transitive closure creates a self-loop for the path
    from v to v of length 0. The usual transitive closure creates a
    self-loop only if a cycle exists (a path from v to v with length > 0).
    We also allow an option for no self-loops.

    Parameters
    ----------
    G : NetworkX Graph
        A directed/undirected graph/multigraph.
    reflexive : Bool or None, optional (default: False)
        Determines when cycles create self-loops in the Transitive Closure.
        If True, trivial cycles (length 0) create self-loops. The result
        is a reflexive transitive closure of G.
        If False (the default) non-trivial cycles create self-loops.
        If None, self-loops are not created.

    Returns
    -------
    NetworkX graph
        The transitive closure of `G`

    Raises
    ------
    NetworkXError
        If `reflexive` not in `{None, True, False}`

    Examples
    --------
    The treatment of trivial (i.e. length 0) cycles is controlled by the
    `reflexive` parameter.

    Trivial (i.e. length 0) cycles do not create self-loops when
    ``reflexive=False`` (the default)::

        >>> DG = nx.DiGraph([(1, 2), (2, 3)])
        >>> TC = nx.transitive_closure(DG, reflexive=False)
        >>> TC.edges()
        OutEdgeView([(1, 2), (1, 3), (2, 3)])

    However, nontrivial (i.e. length greater than 0) cycles create self-loops
    when ``reflexive=False`` (the default)::

        >>> DG = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
        >>> TC = nx.transitive_closure(DG, reflexive=False)
        >>> TC.edges()
        OutEdgeView([(1, 2), (1, 3), (1, 1), (2, 3), (2, 1), (2, 2), (3, 1), (3, 2), (3, 3)])

    Trivial cycles (length 0) create self-loops when ``reflexive=True``::

        >>> DG = nx.DiGraph([(1, 2), (2, 3)])
        >>> TC = nx.transitive_closure(DG, reflexive=True)
        >>> TC.edges()
        OutEdgeView([(1, 2), (1, 1), (1, 3), (2, 3), (2, 2), (3, 3)])

    And the third option is not to create self-loops at all when ``reflexive=None``::

        >>> DG = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
        >>> TC = nx.transitive_closure(DG, reflexive=None)
        >>> TC.edges()
        OutEdgeView([(1, 2), (1, 3), (2, 3), (2, 1), (3, 1), (3, 2)])

    References
    ----------
    .. [1] https://www.ics.uci.edu/~eppstein/PADS/PartialOrder.py
    >   FNTz-Incorrect value for the parameter `reflexive`c              3   6   K   | ]  }|   vs|f  y wrJ   rK   r_   rx   TCr?   s     r&   ra   z%transitive_closure.<locals>.<genexpr>  s      UarRSunq!fU   	Tc              3   6   K   | ]  }|   vs|f  y wrJ   rK   r}   s     r&   ra   z%transitive_closure.<locals>.<genexpr>  s$      ar!unAr   Fc              3   B   K   | ]  }|d       vs|d    f  yw)r4   NrK   )r_   er~   r?   s     r&   ra   z%transitive_closure.<locals>.<genexpr>  s+     XAadRTUVRWFWq!A$iXs   )copyr   r6   add_edges_fromr   edge_bfs)r"   	reflexiver~   r?   s     @@r&   r   r     s    T 
B++NOO YUbnnQ.BUU$  "q! 4s :  %XQ1BXXY Ir0   c           	          |t        t        |             }| j                         }t        |      D ]1  |j	                  fdt        j                  |d      D               3 |S )aF  Returns the transitive closure of a directed acyclic graph.

    This function is faster than the function `transitive_closure`, but fails
    if the graph has a cycle.

    The transitive closure of G = (V,E) is a graph G+ = (V,E+) such that
    for all v, w in V there is an edge (v, w) in E+ if and only if there
    is a non-null path from v to w in G.

    Parameters
    ----------
    G : NetworkX DiGraph
        A directed acyclic graph (DAG)

    topo_order: list or tuple, optional
        A topological order for G (if None, the function will compute one)

    Returns
    -------
    NetworkX DiGraph
        The transitive closure of `G`

    Raises
    ------
    NetworkXNotImplemented
        If `G` is not directed
    NetworkXUnfeasible
        If `G` has a cycle

    Examples
    --------
    >>> DG = nx.DiGraph([(1, 2), (2, 3)])
    >>> TC = nx.transitive_closure_dag(DG)
    >>> TC.edges()
    OutEdgeView([(1, 2), (1, 3), (2, 3)])

    Notes
    -----
    This algorithm is probably simple enough to be well-known but I didn't find
    a mention in the literature.
    c              3   &   K   | ]  }|f 
 y wrJ   rK   )r_   rx   r?   s     r&   ra   z)transitive_closure_dag.<locals>.<genexpr>,  s     OQ1a&O      )re   r   r   reversedr   r   descendants_at_distance)r"   
topo_orderr~   r?   s      @r&   r   r     si    X *1-.
	
B j! P
O"*D*DRA*NOOP Ir0   )rz   c                   	 t        |       sd}t        j                  |      t        j                         }|j	                  | j                                i }t        | j                        }| D ]  	t        | 	         }| 	   D ]W  }||v r8||vr,t        j                  | |      D ch c]  \  }}|	 c}}||<   |||   z  }||xx   dz  cc<   ||   dk(  sU||= Y |j                  	fd|D                |S c c}}w )a  Returns transitive reduction of a directed graph

    The transitive reduction of G = (V,E) is a graph G- = (V,E-) such that
    for all v,w in V there is an edge (v,w) in E- if and only if (v,w) is
    in E and there is no path from v to w in G with length greater than 1.

    Parameters
    ----------
    G : NetworkX DiGraph
        A directed acyclic graph (DAG)

    Returns
    -------
    NetworkX DiGraph
        The transitive reduction of `G`

    Raises
    ------
    NetworkXError
        If `G` is not a directed acyclic graph (DAG) transitive reduction is
        not uniquely defined and a :exc:`NetworkXError` exception is raised.

    Examples
    --------
    To perform transitive reduction on a DiGraph:

    >>> DG = nx.DiGraph([(1, 2), (2, 3), (1, 3)])
    >>> TR = nx.transitive_reduction(DG)
    >>> list(TR.edges)
    [(1, 2), (2, 3)]

    To avoid unnecessary data copies, this implementation does not return a
    DiGraph with node/edge data.
    To perform transitive reduction on a DiGraph and transfer node/edge data:

    >>> DG = nx.DiGraph()
    >>> DG.add_edges_from([(1, 2), (2, 3), (1, 3)], color="red")
    >>> TR = nx.transitive_reduction(DG)
    >>> TR.add_nodes_from(DG.nodes(data=True))
    >>> TR.add_edges_from((u, v, DG.edges[u, v]) for u, v in TR.edges)
    >>> list(TR.edges(data=True))
    [(1, 2, {'color': 'red'}), (2, 3, {'color': 'red'})]

    References
    ----------
    https://en.wikipedia.org/wiki/Transitive_reduction

    z8Directed Acyclic Graph required for transitive_reductionr4   r   c              3   &   K   | ]  }|f 
 y wrJ   rK   )r_   r?   rx   s     r&   ra   z'transitive_reduction.<locals>.<genexpr>v  s     1Q1a&1r   )r   r   r6   DiGraphadd_nodes_fromnodesrc   r8   rq   	dfs_edgesr   )
r"   rW   TRr   check_countu_nbrsr?   xyrx   s
            @r&   r   r   1  s	   f %Q'Hs##	Baggi Kq{{#K 
2QqT1 	#AF{K'46LLA4F%GDAqa%GKN+a.(NaN1~"N	# 	1&11
2 I &Hs   *C>
c              #     K   |t        t        j                  |             }t        j                  | |      }g t        t	        |            fg}|rh|j                         \  }}| |rK|j                         }||gz   }|D cg c]  }|||   v r|||   v r| }	}|j                  ||	f       |rK|rgyyc c}w w)a  Generates antichains from a directed acyclic graph (DAG).

    An antichain is a subset of a partially ordered set such that any
    two elements in the subset are incomparable.

    Parameters
    ----------
    G : NetworkX DiGraph
        A directed acyclic graph (DAG)

    topo_order: list or tuple, optional
        A topological order for G (if None, the function will compute one)

    Yields
    ------
    antichain : list
        a list of nodes in `G` representing an antichain

    Raises
    ------
    NetworkXNotImplemented
        If `G` is not directed

    NetworkXUnfeasible
        If `G` contains a cycle

    Examples
    --------
    >>> DG = nx.DiGraph([(1, 2), (1, 3)])
    >>> list(nx.antichains(DG))
    [[], [3], [2], [2, 3], [1]]

    Notes
    -----
    This function was originally developed by Peter Jipsen and Franco Saliola
    for the SAGE project. It's included in NetworkX with permission from the
    authors. Original SAGE code at:

    https://github.com/sagemath/sage/blob/master/src/sage/combinat/posets/hasse_diagram.py

    References
    ----------
    .. [1] Free Lattices, by R. Freese, J. Jezek and J. B. Nation,
       AMS, Vol 42, 1995, p. 226.
    N)re   r   r   r   r   rf   r=   )
r"   r   r~   antichains_stacks	antichainstackr   new_antichaint	new_stacks
             r&   r   r   z  s     ` "--a01
		"	"1j	1Bd8J#789:
.224E 		A%OM$)Pq11:11:PIP$$mY%?@	   Qs*   BC B;B;B;C 6C 9C weightdefault_weight)
edge_attrsc                 0  
 | sg S |t        j                  |       }i 
|D ]  }| j                  |   j                         D cg c]Q  \  }}
|   d   | j	                         rt        |j                         fd      n|j                        z   |fS }}}|rt        |d       nd|f}|d   dk\  r|nd|f
|<    d}t        

fd      }g }	||k7  r!|	j                  |       |}
|   d   }||k7  r!|	j                          |	S c c}}w )a  Returns the longest path in a directed acyclic graph (DAG).

    If `G` has edges with `weight` attribute the edge data are used as
    weight values.

    Parameters
    ----------
    G : NetworkX DiGraph
        A directed acyclic graph (DAG)

    weight : str, optional
        Edge data key to use for weight

    default_weight : int, optional
        The weight of edges that do not have a weight attribute

    topo_order: list or tuple, optional
        A topological order for `G` (if None, the function will compute one)

    Returns
    -------
    list
        Longest path

    Raises
    ------
    NetworkXNotImplemented
        If `G` is not directed

    Examples
    --------
    >>> DG = nx.DiGraph(
    ...     [(0, 1, {"cost": 1}), (1, 2, {"cost": 1}), (0, 2, {"cost": 42})]
    ... )
    >>> list(nx.all_simple_paths(DG, 0, 2))
    [[0, 1, 2], [0, 2]]
    >>> nx.dag_longest_path(DG)
    [0, 1, 2]
    >>> nx.dag_longest_path(DG, weight="cost")
    [0, 2]

    In the case where multiple valid topological orderings exist, `topo_order`
    can be used to specify a specific ordering:

    >>> DG = nx.DiGraph([(0, 1), (0, 2)])
    >>> sorted(nx.all_topological_sorts(DG))  # Valid topological orderings
    [[0, 1, 2], [0, 2, 1]]
    >>> nx.dag_longest_path(DG, topo_order=[0, 1, 2])
    [0, 1]
    >>> nx.dag_longest_path(DG, topo_order=[0, 2, 1])
    [0, 2]

    See also
    --------
    dag_longest_path_length

    Nr   c                 (    | j                        S rJ   get)r   r   r   s    r&   <lambda>z"dag_longest_path.<locals>.<lambda>  s    QUU6>5R r0   rL   c                     | d   S Nr   rK   )r   s    r&   r   z"dag_longest_path.<locals>.<lambda>  s
    QqT r0   c                     |    d   S r   rK   )r   dists    r&   r   z"dag_longest_path.<locals>.<lambda>  s    Q
 r0   r4   )
r   r   preditemsr7   maxvaluesr   r=   r(   )r"   r   r   r   r?   rx   datausmaxupathr   s    ``       @r&   r   r     s;   x 	((+
D 3 66!9??,
 4 Q
 ( +RS#fn-. 
 
 /1s2>*q!fq'Q,$QFQ#3& 	AD*+AD
q&AGAJ q&
 	LLNK7
s   ADc           	      X    t        j                         }d} j                         rMt        |      D ]=  \  t	                fd      }|       |   j                        z  }? |S t        |      D ]   \  |       j                        z  }" |S )a.  Returns the longest path length in a DAG

    Parameters
    ----------
    G : NetworkX DiGraph
        A directed acyclic graph (DAG)

    weight : string, optional
        Edge data key to use for weight

    default_weight : int, optional
        The weight of edges that do not have a weight attribute

    Returns
    -------
    int
        Longest path length

    Raises
    ------
    NetworkXNotImplemented
        If `G` is not directed

    Examples
    --------
    >>> DG = nx.DiGraph(
    ...     [(0, 1, {"cost": 1}), (1, 2, {"cost": 1}), (0, 2, {"cost": 42})]
    ... )
    >>> list(nx.all_simple_paths(DG, 0, 2))
    [[0, 1, 2], [0, 2]]
    >>> nx.dag_longest_path_length(DG)
    2
    >>> nx.dag_longest_path_length(DG, weight="cost")
    42

    See also
    --------
    dag_longest_path
    r   c                 :          |    j                        S rJ   r   )r   r"   r   rx   r?   r   s    r&   r   z)dag_longest_path_length.<locals>.<lambda>M  s    1Q471:>>&.+Q r0   r   )r   r   r7   r   r   r   )r"   r   r   r   path_lengthrX   rx   r?   s   ```   @@r&   r   r     s    T q&.9DKTN 	BDAqAaDG!QRA1Q471:>>&.AAK	B  TN 	?DAq1Q47;;v~>>K	? r0   c           	          d | j                         D        }d | j                         D        }t        t        j                  |       }t        t        |t        ||                  S )aq  Yields root-to-leaf paths in a directed acyclic graph.

    `G` must be a directed acyclic graph. If not, the behavior of this
    function is undefined. A "root" in this graph is a node of in-degree
    zero and a "leaf" a node of out-degree zero.

    When invoked, this function iterates over each path from any root to
    any leaf. A path is a list of nodes.

    c              3   2   K   | ]  \  }}|d k(  s|  ywr^   rK   r_   r?   r@   s      r&   ra   z%root_to_leaf_paths.<locals>.<genexpr>b  s     341aAFQ3   c              3   2   K   | ]  \  }}|d k(  s|  ywr^   rK   r   s      r&   ra   z%root_to_leaf_paths.<locals>.<genexpr>c  s     5DAqa1fa5r   )r8   
out_degreer   r   all_simple_pathschainir   r   )r"   rootsleaves	all_pathss       r&   root_to_leaf_pathsr   V  sO     41;;=3E5ALLN5F++Q/I')WUF%;<==r0   r>   c                     t        |       rd}t        j                  |      t        |       }t        j                  |      }|j                  d       |j                  d       |S )a*  Returns a branching representing all (overlapping) paths from
    root nodes to leaf nodes in the given directed acyclic graph.

    As described in :mod:`networkx.algorithms.tree.recognition`, a
    *branching* is a directed forest in which each node has at most one
    parent. In other words, a branching is a disjoint union of
    *arborescences*. For this function, each node of in-degree zero in
    `G` becomes a root of one of the arborescences, and there will be
    one leaf node for each distinct path from that root to a leaf node
    in `G`.

    Each node `v` in `G` with *k* parents becomes *k* distinct nodes in
    the returned branching, one for each parent, and the sub-DAG rooted
    at `v` is duplicated for each copy. The algorithm then recurses on
    the children of each copy of `v`.

    Parameters
    ----------
    G : NetworkX graph
        A directed acyclic graph.

    Returns
    -------
    DiGraph
        The branching in which there is a bijection between root-to-leaf
        paths in `G` (in which multiple paths may share the same leaf)
        and root-to-leaf paths in the branching (in which there is a
        unique path from a root to a leaf).

        Each node has an attribute 'source' whose value is the original
        node to which this node corresponds. No other graph, node, or
        edge attributes are copied into this new graph.

    Raises
    ------
    NetworkXNotImplemented
        If `G` is not directed, or if `G` is a multigraph.

    HasACycle
        If `G` is not acyclic.

    Examples
    --------
    To examine which nodes in the returned branching were produced by
    which original node in the directed acyclic graph, we can collect
    the mapping from source node to new nodes into a dictionary. For
    example, consider the directed diamond graph::

        >>> from collections import defaultdict
        >>> from operator import itemgetter
        >>>
        >>> G = nx.DiGraph(nx.utils.pairwise("abd"))
        >>> G.add_edges_from(nx.utils.pairwise("acd"))
        >>> B = nx.dag_to_branching(G)
        >>>
        >>> sources = defaultdict(set)
        >>> for v, source in B.nodes(data="source"):
        ...     sources[source].add(v)
        >>> len(sources["a"])
        1
        >>> len(sources["d"])
        2

    To copy node attributes from the original graph to the new graph,
    you can use a dictionary like the one constructed in the above
    example::

        >>> for source, nodes in sources.items():
        ...     for v in nodes:
        ...         B.nodes[v].update(G.nodes[source])

    Notes
    -----
    This function is not idempotent in the sense that the node labels in
    the returned branching may be uniquely generated each time the
    function is invoked. In fact, the node labels may not be integers;
    in order to relabel the nodes to be more readable, you can use the
    :func:`networkx.convert_node_labels_to_integers` function.

    The current implementation of this function uses
    :func:`networkx.prefix_tree`, so it is subject to the limitations of
    that function.

    z3dag_to_branching is only defined for acyclic graphsr   rb   )r-   r   	HasACycler   prefix_treeremove_node)r"   rW   pathsBs       r&   r   r   i  sU    p |Cll3q!E
uAMM!MM"Hr0   c                 P    ddl }|j                  dt        d       t        |       S )u;  Yields 3-node tuples that represent the v-structures in `G`.

    .. deprecated:: 3.4

       `compute_v_structures` actually yields colliders. It will be removed in
       version 3.6. Use `nx.dag.v_structures` or `nx.dag.colliders` instead.

    Colliders are triples in the directed acyclic graph (DAG) where two parent nodes
    point to the same child node. V-structures are colliders where the two parent
    nodes are not adjacent. In a causal graph setting, the parents do not directly
    depend on each other, but conditioning on the child node provides an association.

    Parameters
    ----------
    G : graph
        A networkx `~networkx.DiGraph`.

    Yields
    ------
    A 3-tuple representation of a v-structure
        Each v-structure is a 3-tuple with the parent, collider, and other parent.

    Raises
    ------
    NetworkXNotImplemented
        If `G` is an undirected graph.

    Examples
    --------
    >>> G = nx.DiGraph([(1, 2), (0, 4), (3, 1), (2, 4), (0, 5), (4, 5), (1, 5)])
    >>> nx.is_directed_acyclic_graph(G)
    True
    >>> list(nx.compute_v_structures(G))
    [(0, 4, 2), (0, 5, 4), (0, 5, 1), (4, 5, 1)]

    See Also
    --------
    v_structures
    colliders

    Notes
    -----
    This function was written to be used on DAGs, however it works on cyclic graphs
    too. Since colliders are referred to in the cyclic causal graph literature
    [2]_ we allow cyclic graphs in this function. It is suggested that you test if
    your input graph is acyclic as in the example if you want that property.

    References
    ----------
    .. [1]  `Pearl's PRIMER <https://bayes.cs.ucla.edu/PRIMER/primer-ch2.pdf>`_
            Ch-2 page 50: v-structures def.
    .. [2] A Hyttinen, P.O. Hoyer, F. Eberhardt, M J ̈arvisalo, (2013)
           "Discovering cyclic causal models with latent variables:
           a general SAT-based procedure", UAI'13: Proceedings of the Twenty-Ninth
           Conference on Uncertainty in Artificial Intelligence, pg 301–310,
           `doi:10.5555/3023638.3023669 <https://dl.acm.org/doi/10.5555/3023638.3023669>`_
    r   Nz

`compute_v_structures` actually yields colliders. It will be
removed in version 3.6. Use `nx.dag.v_structures` or `nx.dag.colliders`
instead.
   )category
stacklevel)warningswarnDeprecationWarning	colliders)r"   r   s     r&   r   r     s2    x MM $   Q<r0   c              #      K   t        |       D ]3  \  }}}| j                  ||      r| j                  ||      r-|||f 5 yw)ue  Yields 3-node tuples that represent the v-structures in `G`.

    Colliders are triples in the directed acyclic graph (DAG) where two parent nodes
    point to the same child node. V-structures are colliders where the two parent
    nodes are not adjacent. In a causal graph setting, the parents do not directly
    depend on each other, but conditioning on the child node provides an association.

    Parameters
    ----------
    G : graph
        A networkx `~networkx.DiGraph`.

    Yields
    ------
    A 3-tuple representation of a v-structure
        Each v-structure is a 3-tuple with the parent, collider, and other parent.

    Raises
    ------
    NetworkXNotImplemented
        If `G` is an undirected graph.

    Examples
    --------
    >>> G = nx.DiGraph([(1, 2), (0, 4), (3, 1), (2, 4), (0, 5), (4, 5), (1, 5)])
    >>> nx.is_directed_acyclic_graph(G)
    True
    >>> list(nx.dag.v_structures(G))
    [(0, 4, 2), (0, 5, 1), (4, 5, 1)]

    See Also
    --------
    colliders

    Notes
    -----
    This function was written to be used on DAGs, however it works on cyclic graphs
    too. Since colliders are referred to in the cyclic causal graph literature
    [2]_ we allow cyclic graphs in this function. It is suggested that you test if
    your input graph is acyclic as in the example if you want that property.

    References
    ----------
    .. [1]  `Pearl's PRIMER <https://bayes.cs.ucla.edu/PRIMER/primer-ch2.pdf>`_
            Ch-2 page 50: v-structures def.
    .. [2] A Hyttinen, P.O. Hoyer, F. Eberhardt, M J ̈arvisalo, (2013)
           "Discovering cyclic causal models with latent variables:
           a general SAT-based procedure", UAI'13: Proceedings of the Twenty-Ninth
           Conference on Uncertainty in Artificial Intelligence, pg 301–310,
           `doi:10.5555/3023638.3023669 <https://dl.acm.org/doi/10.5555/3023638.3023669>`_
    N)r   has_edge)r"   p1cp2s       r&   v_structuresr     sI     l q\ 	Ar

2r"ajjR&8q"+s   %AA
Ac              #      K   | j                   D ],  }t        | j                  |      d      D ]  \  }}|||f  . yw)ux  Yields 3-node tuples that represent the colliders in `G`.

    In a Directed Acyclic Graph (DAG), if you have three nodes A, B, and C, and
    there are edges from A to C and from B to C, then C is a collider [1]_ . In
    a causal graph setting, this means that both events A and B are "causing" C,
    and conditioning on C provide an association between A and B even if
    no direct causal relationship exists between A and B.

    Parameters
    ----------
    G : graph
        A networkx `~networkx.DiGraph`.

    Yields
    ------
    A 3-tuple representation of a collider
        Each collider is a 3-tuple with the parent, collider, and other parent.

    Raises
    ------
    NetworkXNotImplemented
        If `G` is an undirected graph.

    Examples
    --------
    >>> G = nx.DiGraph([(1, 2), (0, 4), (3, 1), (2, 4), (0, 5), (4, 5), (1, 5)])
    >>> nx.is_directed_acyclic_graph(G)
    True
    >>> list(nx.dag.colliders(G))
    [(0, 4, 2), (0, 5, 4), (0, 5, 1), (4, 5, 1)]

    See Also
    --------
    v_structures

    Notes
    -----
    This function was written to be used on DAGs, however it works on cyclic graphs
    too. Since colliders are referred to in the cyclic causal graph literature
    [2]_ we allow cyclic graphs in this function. It is suggested that you test if
    your input graph is acyclic as in the example if you want that property.

    References
    ----------
    .. [1] `Wikipedia: Collider in causal graphs <https://en.wikipedia.org/wiki/Collider_(statistics)>`_
    .. [2] A Hyttinen, P.O. Hoyer, F. Eberhardt, M J ̈arvisalo, (2013)
           "Discovering cyclic causal models with latent variables:
           a general SAT-based procedure", UAI'13: Proceedings of the Twenty-Ninth
           Conference on Uncertainty in Artificial Intelligence, pg 301–310,
           `doi:10.5555/3023638.3023669 <https://dl.acm.org/doi/10.5555/3023638.3023669>`_
    r   N)r   r   predecessors)r"   rD   r   r   s       r&   r   r   R  sK     l  !"1>>$#7; 	!FBtR. 	!!s   =?rJ   )F)r   r4   N)r   r4   )+__doc__rQ   collectionsr   	functoolsr   	itertoolsr   r   r   r   mathr	   networkxr   networkx.utilsr
   r   r   __all__from_iterabler   _dispatchabler   r   r-   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rK   r0   r&   <module>r      s9      ; ;   K K& 
		 !@ !@H !N !NH   %0 %0P J
 J
Z A AH J) J)Z \"s  #sl YL YLx T>X ?Xv \"T>4 ? #4n \"%D & #DN \">A  #>AB \"h(89:] ; #]@ \"h(89:2 ; #2j > >$ \"\"%] & # #]@ \"F  #FR \"6  #6r \"6!  #6!r0   