
    wg                     P   d Z ddlmZmZ ddlmZmZ ddlmZ ddl	Z
ddlmZmZ g dZ ed       ed	      e
j                  dd
                     Ze
j                  dd       Zd Zd Z G d de      Zd Zd Ze
j                  dd       Zd Z ed       e
j                  d      d               Ze
j                  d d       Z ed       ed	       e
j                  d      dd                     Zd Zd Z ed       ed	      e
j                  d                      Zy)!zL
========================
Cycle finding algorithms
========================
    )Counterdefaultdict)combinationsproduct)infN)not_implemented_forpairwise)cycle_basissimple_cyclesrecursive_simple_cycles
find_cycleminimum_cycle_basischordless_cyclesgirthdirected
multigraphc                 R   t         j                  |       }g }|r||j                         d   }|g}||i}|t               i}|r|j	                         }||   }| |   D ]  }	|	|vr|||	<   |j                  |	       |h||	<   $|	|k(  r|j                  |g       <|	|vsA||	   }
|	|g}||   }||
vr|j                  |       ||   }||
vr|j                  |       |j                  |       ||	   j                  |        |r|D ]  }|j	                  |d        d}|r|S )av  Returns a list of cycles which form a basis for cycles of G.

    A basis for cycles of a network is a minimal collection of
    cycles such that any cycle in the network can be written
    as a sum of cycles in the basis.  Here summation of cycles
    is defined as "exclusive or" of the edges. Cycle bases are
    useful, e.g. when deriving equations for electric circuits
    using Kirchhoff's Laws.

    Parameters
    ----------
    G : NetworkX Graph
    root : node, optional
       Specify starting node for basis.

    Returns
    -------
    A list of cycle lists.  Each cycle list is a list of nodes
    which forms a cycle (loop) in G.

    Examples
    --------
    >>> G = nx.Graph()
    >>> nx.add_cycle(G, [0, 1, 2, 3])
    >>> nx.add_cycle(G, [0, 3, 4, 5])
    >>> nx.cycle_basis(G, 0)
    [[3, 4, 5, 0], [1, 2, 3, 0]]

    Notes
    -----
    This is adapted from algorithm CACM 491 [1]_.

    References
    ----------
    .. [1] Paton, K. An algorithm for finding a fundamental set of
       cycles of a graph. Comm. ACM 12, 9 (Sept 1969), 514-518.

    See Also
    --------
    simple_cycles
    minimum_cycle_basis
    Nr   )dictfromkeyspopitemsetpopappendadd)Grootgnodescyclesstackpredusedzzusednbrpncyclepnodes                 _/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/networkx/algorithms/cycles.pyr
   r
      sW   \ ]]1FF
<>>#A&Dd|ce}		AGEt %d? !DILL%!"DIAXMM1#&%cB !HEQA2+Q G 2+ LLOMM%(IMM!$!% (  	#DJJtT"	#9 : M    c              #      K   ||dk(  ry|dk  rt        d       j                         }d  j                  j                         D        E d{    ||dk(  ry j	                         rk|sit                j                  j                         D ]B  \  }fd|j                         D        }fd|D        E d{    j                         D |r5t        j                  d  j                  j                         D               n4t        j                  d	  j                  j                         D               |h|d
k(  rc|r`t                j                  j                         D ]9  \  } fdj                  |      D        E d{    j                         ; y|rt         |      E d{    yt         |      E d{    y7 7 7 J7 "7 w)a  Find simple cycles (elementary circuits) of a graph.

    A "simple cycle", or "elementary circuit", is a closed path where
    no node appears twice.  In a directed graph, two simple cycles are distinct
    if they are not cyclic permutations of each other.  In an undirected graph,
    two simple cycles are distinct if they are not cyclic permutations of each
    other nor of the other's reversal.

    Optionally, the cycles are bounded in length.  In the unbounded case, we use
    a nonrecursive, iterator/generator version of Johnson's algorithm [1]_.  In
    the bounded case, we use a version of the algorithm of Gupta and
    Suzumura [2]_. There may be better algorithms for some cases [3]_ [4]_ [5]_.

    The algorithms of Johnson, and Gupta and Suzumura, are enhanced by some
    well-known preprocessing techniques.  When `G` is directed, we restrict our
    attention to strongly connected components of `G`, generate all simple cycles
    containing a certain node, remove that node, and further decompose the
    remainder into strongly connected components.  When `G` is undirected, we
    restrict our attention to biconnected components, generate all simple cycles
    containing a particular edge, remove that edge, and further decompose the
    remainder into biconnected components.

    Note that multigraphs are supported by this function -- and in undirected
    multigraphs, a pair of parallel edges is considered a cycle of length 2.
    Likewise, self-loops are considered to be cycles of length 1.  We define
    cycles as sequences of nodes; so the presence of loops and parallel edges
    does not change the number of simple cycles in a graph.

    Parameters
    ----------
    G : NetworkX Graph
       A networkx graph. Undirected, directed, and multigraphs are all supported.

    length_bound : int or None, optional (default=None)
       If `length_bound` is an int, generate all simple cycles of `G` with length at
       most `length_bound`.  Otherwise, generate all simple cycles of `G`.

    Yields
    ------
    list of nodes
       Each cycle is represented by a list of nodes along the cycle.

    Examples
    --------
    >>> G = nx.DiGraph([(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)])
    >>> sorted(nx.simple_cycles(G))
    [[0], [0, 1, 2], [0, 2], [1, 2], [2]]

    To filter the cycles so that they don't include certain nodes or edges,
    copy your graph and eliminate those nodes or edges before calling.
    For example, to exclude self-loops from the above example:

    >>> H = G.copy()
    >>> H.remove_edges_from(nx.selfloop_edges(G))
    >>> sorted(nx.simple_cycles(H))
    [[0, 1, 2], [0, 2], [1, 2]]

    Notes
    -----
    When `length_bound` is None, the time complexity is $O((n+e)(c+1))$ for $n$
    nodes, $e$ edges and $c$ simple circuits.  Otherwise, when ``length_bound > 1``,
    the time complexity is $O((c+n)(k-1)d^k)$ where $d$ is the average degree of
    the nodes of `G` and $k$ = `length_bound`.

    Raises
    ------
    ValueError
        when ``length_bound < 0``.

    References
    ----------
    .. [1] Finding all the elementary circuits of a directed graph.
       D. B. Johnson, SIAM Journal on Computing 4, no. 1, 77-84, 1975.
       https://doi.org/10.1137/0204007
    .. [2] Finding All Bounded-Length Simple Cycles in a Directed Graph
       A. Gupta and T. Suzumura https://arxiv.org/abs/2105.10094
    .. [3] Enumerating the cycles of a digraph: a new preprocessing strategy.
       G. Loizou and P. Thanish, Information Sciences, v. 27, 163-182, 1982.
    .. [4] A search strategy for the elementary cycles of a directed graph.
       J.L. Szwarcfiter and P.E. Lauer, BIT NUMERICAL MATHEMATICS,
       v. 16, no. 2, 192-204, 1976.
    .. [5] Optimal Listing of Cycles and st-Paths in Undirected Graphs
        R. Ferreira and R. Grossi and A. Marino and N. Pisanti and R. Rizzi and
        G. Sacomoto https://arxiv.org/abs/1205.2766

    See Also
    --------
    cycle_basis
    chordless_cycles
    Nr   !length bound must be non-negativec              3   2   K   | ]  \  }}||v s|g  y wN .0vGvs      r)   	<genexpr>z simple_cycles.<locals>.<genexpr>   s     :2!r':      c              3   H   K   | ]  \  }}|v s|t        |      f  y wr.   lenr1   r2   Guvvisiteds      r)   r4   z simple_cycles.<locals>.<genexpr>   s#     Sfaa7lQCMS   ""c              3   8   K   | ]  \  }}|d kD  s|g  ywr6   Nr/   )r1   r2   mus      r)   r4   z simple_cycles.<locals>.<genexpr>   s     A41a1q5AAs   	c              3   D   K   | ]  \  }}|D ]  }||k7  s	||f   y wr.   r/   r1   rA   Gur2   s       r)   r4   z simple_cycles.<locals>.<genexpr>   s*     O%!R"OQQ1vOvO     c              3   D   K   | ]  \  }}|D ]  }||k7  s	||f   y wr.   r/   rC   s       r)   r4   z simple_cycles.<locals>.<genexpr>   s*     M2M1a1faVMVMrE      c              3   L   K   | ]  }j                  |      s|g  y wr.   has_edge)r1   r2   r   rA   s     r)   r4   z simple_cycles.<locals>.<genexpr>   s'       

1a@PQFs   $	$)
ValueErroris_directedadjitemsis_multigraphr   r   nxDiGraphGraphintersection_directed_cycle_search_undirected_cycle_search)r   length_boundr   rD   multiplicityrA   r<   s   `    @@r)   r   r   i   s    z 1A@AA}}H::::LA$5%UU[[] 	EArS
SLA<AAAKKN	 JJO155;;=OOHHMMM LA$5eG 2$+$8$8$<   A	
 	)!\:::+A|<<<A ; B 	;<s\   AG'GA/G'GCG'G!)G' G#G'G%G'G'!G'#G'%G'c              #     K   t         j                  } ||       D cg c]  }t        |      dk\  s| }}|r|j                         }| j	                  |      }t        t        |            }|t        ||g      E d{    nt        ||g|      E d{    | j                  |       |j                  d  ||      D               |ryyc c}w 7 T7 ?w)a  A dispatch function for `simple_cycles` for directed graphs.

    We generate all cycles of G through binary partition.

        1. Pick a node v in G which belongs to at least one cycle
            a. Generate all cycles of G which contain the node v.
            b. Recursively generate all cycles of G \ v.

    This is accomplished through the following:

        1. Compute the strongly connected components SCC of G.
        2. Select and remove a biconnected component C from BCC.  Select a
           non-tree edge (u, v) of a depth-first search of G[C].
        3. For each simple cycle P containing v in G[C], yield P.
        4. Add the biconnected components of G[C \ v] to BCC.

    If the parameter length_bound is not None, then step 3 will be limited to
    simple cycles of length at most length_bound.

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

    length_bound : int or None
       If length_bound is an int, generate all simple cycles of G with length at most length_bound.
       Otherwise, generate all simple cycles of G.

    Yields
    ------
    list of nodes
       Each cycle is represented by a list of nodes along the cycle.
    rG   Nc              3   >   K   | ]  }t        |      d k\  s|  ywrG   Nr8   r1   cs     r)   r4   z)_directed_cycle_search.<locals>.<genexpr>       <A!!<   )rP   strongly_connected_componentsr9   r   subgraphnextiter_johnson_cycle_search_bounded_cycle_searchremove_nodeextend)r   rV   sccr\   
componentsGcr2   s          r)   rT   rT      s     F 
*
*C V3s1v{!3J3
NNZZ]aM,R!555,R!lCCC	a<SW<<  4 6Cs9   CCCAC CCC5CCCc              #     K   t         j                  } ||       D cg c]  }t        |      dk\  s| }}|r|j                         }| j	                  |      }t        t        t        |j                                    } | j                  |  |t        ||      E d{    nt        |||      E d{    |j                  d  ||      D               |ryyc c}w 7 B7 .w)a  A dispatch function for `simple_cycles` for undirected graphs.

    We generate all cycles of G through binary partition.

        1. Pick an edge (u, v) in G which belongs to at least one cycle
            a. Generate all cycles of G which contain the edge (u, v)
            b. Recursively generate all cycles of G \ (u, v)

    This is accomplished through the following:

        1. Compute the biconnected components BCC of G.
        2. Select and remove a biconnected component C from BCC.  Select a
           non-tree edge (u, v) of a depth-first search of G[C].
        3. For each (v -> u) path P remaining in G[C] \ (u, v), yield P.
        4. Add the biconnected components of G[C] \ (u, v) to BCC.

    If the parameter length_bound is not None, then step 3 will be limited to simple paths
    of length at most length_bound.

    Parameters
    ----------
    G : NetworkX Graph
       An undirected graph

    length_bound : int or None
       If length_bound is an int, generate all simple cycles of G with length at most length_bound.
       Otherwise, generate all simple cycles of G.

    Yields
    ------
    list of nodes
       Each cycle is represented by a list of nodes along the cycle.
       Nc              3   >   K   | ]  }t        |      d k\  s|  yw)rk   Nr8   r[   s     r)   r4   z+_undirected_cycle_search.<locals>.<genexpr>Q  r]   r^   )rP   biconnected_componentsr9   r   r`   listra   rb   edgesremove_edgerc   rd   rf   )r   rV   bccr\   rh   ri   uvs          r)   rU   rU   "  s     F 
#
#C V3s1v{!3J3
NNZZ]$tBHH~&'r,R444,R\BBB<SW<<  4 5Bs9   C(CCA,C(!C$"C(7C&8$C(C(&C(c                       e Zd ZdZd Zd Zy)_NeighborhoodCachea  Very lightweight graph wrapper which caches neighborhoods as list.

    This dict subclass uses the __missing__ functionality to query graphs for
    their neighborhoods, and store the result as a list.  This is used to avoid
    the performance penalty incurred by subgraph views.
    c                     || _         y r.   )r   )selfr   s     r)   __init__z_NeighborhoodCache.__init__\  s	    r*   c                 @    t        | j                  |         x}| |<   |S r.   )rn   r   )rv   r2   r3   s      r)   __missing__z_NeighborhoodCache.__missing___  s!    DFF1I&T!W	r*   N)__name__
__module____qualname____doc__rw   ry   r/   r*   r)   rt   rt   T  s    r*   rt   c              #     K   t        |       } t        |      }t        t              }|d   }t        | |d            g}dg}|r#|d   }|D ]j  }||k(  r|dd  d|d<   ||vs|j	                  |       |j	                  d       |j	                  t        | |                |j                  |        n |j                          |j                         }	|j                         r\|rd|d<   |	h}
|
rn|
j                         }||v r8|j                  |       |
j                  ||          ||   j                          |
rOn| |	   D ]  }||   j                  |	        |r"yyw)a0  The main loop of the cycle-enumeration algorithm of Johnson.

    Parameters
    ----------
    G : NetworkX Graph or DiGraph
       A graph

    path : list
       A cycle prefix.  All cycles generated will begin with this prefix.

    Yields
    ------
    list of nodes
       Each cycle is represented by a list of nodes along the cycle.

    References
    ----------
        .. [1] Finding all the elementary circuits of a directed graph.
       D. B. Johnson, SIAM Journal on Computing 4, no. 1, 77-84, 1975.
       https://doi.org/10.1137/0204007

    r   FNT)
rt   r   r   rb   r   r   r   removeupdateclear)r   pathblockedBstartr   closednbrswr2   unblock_stackrA   s               r)   rc   rc   d  sb    0 	1A$iGCAGE!DH+EWF
Ry 	 AEz1g!r
'!Ae$T!A$Z(A	  IIK
Azz|!%F2J!"#%))+AG|q)%,,QqT2!

 $ 1  AaDHHQK 5 s   A#E)&CE)!E)'E)c              #   t  K   t        |       } |D ci c]  }|d }}t        t              }|d   }t        | |d            g}|g}|rg|d   }	|	D ]  }
|
|k(  r|dd  d|d<   t	        |      |j                  |
|      k  s4|j                  |
       |j                  |       t	        |      ||
<   |j                  t        | |
                 n |j                          |j                         }|j                         |rt        |d         |d<   |k  rp|fg}|r|j                         \  }|j                  ||      |z
  dz   k  r7|z
  dz   ||<   |j                  fd||   j                  |      D               |rhn| |   D ]  }
||
   j                  |        |rfyyc c}w w)az  The main loop of the cycle-enumeration algorithm of Gupta and Suzumura.

    Parameters
    ----------
    G : NetworkX Graph or DiGraph
       A graph

    path : list
       A cycle prefix.  All cycles generated will begin with this prefix.

    length_bound: int
        A length bound.  All cycles generated will have length at most length_bound.

    Yields
    ------
    list of nodes
       Each cycle is represented by a list of nodes along the cycle.

    References
    ----------
    .. [1] Finding All Bounded-Length Simple Cycles in a Directed Graph
       A. Gupta and T. Suzumura https://arxiv.org/abs/2105.10094

    r   r   Nr6   c              3   ,   K   | ]  }d z   |f  ywr?   r/   )r1   r   bls     r)   r4   z(_bounded_cycle_search.<locals>.<genexpr>  s     *V1BFA;*Vs   )rt   r   r   rb   r9   getr   r   minrf   
differencer   )r   r   rV   r2   lockr   r   r   blenr   r   relax_stackrA   r   s                @r)   rd   rd     s    2 	1AQAqDDCAGE!DH+E>D
Ry 	 AEz1gRTTXXa66AL)d)QT!A$Z(	  IIK
ABtBx,RL  "Awi!'OO-EBxx<0<"3Dq3HH"."3a"7Q#***V!PT@U*VV	 " 1  AaDHHQK 5   s#   F8
F3A(F8DF8!F81F8c           	   #   P   K   ||dk(  ry|dk  rt        d       j                         } j                         }|r*d  j                  j	                         D        E d{    n)d  j                  j	                         D        E d{    ||dk(  ry|rGt        j                  d  j                  j	                         D              j                  d	      }n6t        j                  d
  j                  j	                         D              d}|r|sj                         }t                j                  j	                         D ]  \  }}|r?d |j	                         D        }|D ]"  \  }}	|	dkD  sj                  ||f||ff       $ Gfd|j	                         D        }|D ](  \  }}	|	dk(  r||g |	dkD  sj                  ||       * j                  |        |ryj                  j	                         D ]\  \  }}
|
D cg c]  }j                  ||      s||g }}|E d{    j                  |       j                  d |D               ^ ||dk(  ry|rt
        j                  } fd}nt
        j                   }fd} |      D cg c]  }t#        |      dkD  s| }}|r|j%                         }t'        t)        |            }j+                  |      }dx}} |||      D ]M  \  }}|r| |)t-        |      }||nt-        |j+                  |            }t/        ||||      E d{    O |j1                  d  |j+                  ||hz
              D               |ryy7 -7 c c}w 7 _c c}w 7 Ow)a  Find simple chordless cycles of a graph.

    A `simple cycle` is a closed path where no node appears twice.  In a simple
    cycle, a `chord` is an additional edge between two nodes in the cycle.  A
    `chordless cycle` is a simple cycle without chords.  Said differently, a
    chordless cycle is a cycle C in a graph G where the number of edges in the
    induced graph G[C] is equal to the length of `C`.

    Note that some care must be taken in the case that G is not a simple graph
    nor a simple digraph.  Some authors limit the definition of chordless cycles
    to have a prescribed minimum length; we do not.

        1. We interpret self-loops to be chordless cycles, except in multigraphs
           with multiple loops in parallel.  Likewise, in a chordless cycle of
           length greater than 1, there can be no nodes with self-loops.

        2. We interpret directed two-cycles to be chordless cycles, except in
           multi-digraphs when any edge in a two-cycle has a parallel copy.

        3. We interpret parallel pairs of undirected edges as two-cycles, except
           when a third (or more) parallel edge exists between the two nodes.

        4. Generalizing the above, edges with parallel clones may not occur in
           chordless cycles.

    In a directed graph, two chordless cycles are distinct if they are not
    cyclic permutations of each other.  In an undirected graph, two chordless
    cycles are distinct if they are not cyclic permutations of each other nor of
    the other's reversal.

    Optionally, the cycles are bounded in length.

    We use an algorithm strongly inspired by that of Dias et al [1]_.  It has
    been modified in the following ways:

        1. Recursion is avoided, per Python's limitations

        2. The labeling function is not necessary, because the starting paths
            are chosen (and deleted from the host graph) to prevent multiple
            occurrences of the same path

        3. The search is optionally bounded at a specified length

        4. Support for directed graphs is provided by extending cycles along
            forward edges, and blocking nodes along forward and reverse edges

        5. Support for multigraphs is provided by omitting digons from the set
            of forward edges

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

    length_bound : int or None, optional (default=None)
       If length_bound is an int, generate all simple cycles of G with length at
       most length_bound.  Otherwise, generate all simple cycles of G.

    Yields
    ------
    list of nodes
       Each cycle is represented by a list of nodes along the cycle.

    Examples
    --------
    >>> sorted(list(nx.chordless_cycles(nx.complete_graph(4))))
    [[1, 0, 2], [1, 0, 3], [2, 0, 3], [2, 1, 3]]

    Notes
    -----
    When length_bound is None, and the graph is simple, the time complexity is
    $O((n+e)(c+1))$ for $n$ nodes, $e$ edges and $c$ chordless cycles.

    Raises
    ------
    ValueError
        when length_bound < 0.

    References
    ----------
    .. [1] Efficient enumeration of chordless cycles
       E. Dias and D. Castonguay and H. Longo and W.A.R. Jradi
       https://arxiv.org/abs/1309.1051

    See Also
    --------
    simple_cycles
    Nr   r,   c              3   f   K   | ])  \  }}t        |j                  |d             dk(  s%|g + yw)r/   r6   N)r9   r   r0   s      r)   r4   z#chordless_cycles.<locals>.<genexpr>B  s,     NEArc"&&B-6HA6MQCNs   &11c              3   2   K   | ]  \  }}||v s|g  y wr.   r/   r0   s      r)   r4   z#chordless_cycles.<locals>.<genexpr>D  s     >EAra2gQC>r5   r6   c              3   B   K   | ]  \  }}||vs|D ]  }||f 
  y wr.   r/   rC   s       r)   r4   z#chordless_cycles.<locals>.<genexpr>M  s+     T%!RARKQSTA1vTvT   F)as_viewc              3   B   K   | ]  \  }}||vs|D ]  }||f 
  y wr.   r/   rC   s       r)   r4   z#chordless_cycles.<locals>.<genexpr>P  s*     R2!2+rR!aVRVRr   c              3   <   K   | ]  \  }}|t        |      f  y wr.   r8   )r1   r2   r;   s      r)   r4   z#chordless_cycles.<locals>.<genexpr>j  s     G&!SCHGs   c              3   H   K   | ]  \  }}|v s|t        |      f  y wr.   r8   r:   s      r)   r4   z#chordless_cycles.<locals>.<genexpr>o  s#     W&!S!w,CHWr=   rG   c              3   ,   K   | ]  }|d d d     y wNr   r/   )r1   es     r)   r4   z#chordless_cycles.<locals>.<genexpr>  s     8A$B$8s   c              3      K   t        | j                  |   | j                  |         D ]1  \  }}j                  ||      r|||gj                  ||      f 3 y wr.   )r   r    succrJ   )Cr2   rA   r   Fr   s       r)   stemszchordless_cycles.<locals>.stems  s[     q	166!95 61zz!Q'a)QZZ1%5556s   ?AAc              3   V   K   fdt        |    d      D        E d {    y 7 w)Nc              3   R   K   | ]  \  }}||gj                  ||      f   y wr.   rI   )r1   rA   r   r   r2   s      r)   r4   z2chordless_cycles.<locals>.stems.<locals>.<genexpr>  s+     X$!Q!QAJJq!$45Xs   $'rG   )r   )r   r2   r   s    `r)   r   zchordless_cycles.<locals>.stems  s"     X,qQRtUVBWXXXs   )')c              3   >   K   | ]  }t        |      d kD  s|  ywrZ   r8   r[   s     r)   r4   z#chordless_cycles.<locals>.<genexpr>  s     Qc!fqj!Qr^   )rK   rL   rO   rM   rN   rP   rQ   to_undirectedrR   copyr   remove_edges_fromrp   r   rJ   r_   rm   r9   r   ra   rb   r`   rt   _chordless_cycle_searchrf   )r   rV   r   r   r   rA   rD   rW   r2   r@   Fudigonsseparater   r\   rh   FcFccBccSis_triangler   r<   s   `                    @@r)   r   r     sd    v 1A@AA}}H"JNQUU[[]NNN>QUU[[]>>>LA$5
 JJT155;;=TTOOEO*HHRRR& AeGUU[[] 	EArGBHHJG( >DAq1u++aVaV,<=>  XBHHJW( ,DAqAv !f1ua+	,
 A	( UU[[] 	9EAr&(=AJJq!,<q!f=F='888		9 LA$5 33	6 ,,	Y &a[7CFQJ!7J7
NNaMZZ]c#Bl 	NNA{;,R0C!"#0B1::a=0QC23QMMM	N 	QXajjaS.A%BQQ { 	O>t >> 8 Ns   AN&$N%)N&NC/N&?AN&AN&N0N6N&=N>A/N&-NNBN&N$9N&N&N&N&N&c              #   $  K   t        t              }|d   }d||d   <   |dd D ]  }||   D ]  }||xx   dz  cc<     t        | |d            g}|r|d   }	|	D ]x  }||   dk(  s|t        |      |k  s| |   }
||
v r	||gz    /||   }||v r9|D ]  }||xx   dz  cc<    |j	                  |       |j	                  t        |
              n6 |j                          ||j                            D ]  }||xx   dz  cc<    |ryyw)a  The main loop for chordless cycle enumeration.

    This algorithm is strongly inspired by that of Dias et al [1]_.  It has been
    modified in the following ways:

        1. Recursion is avoided, per Python's limitations

        2. The labeling function is not necessary, because the starting paths
            are chosen (and deleted from the host graph) to prevent multiple
            occurrences of the same path

        3. The search is optionally bounded at a specified length

        4. Support for directed graphs is provided by extending cycles along
            forward edges, and blocking nodes along forward and reverse edges

        5. Support for multigraphs is provided by omitting digons from the set
            of forward edges

    Parameters
    ----------
    F : _NeighborhoodCache
       A graph of forward edges to follow in constructing cycles

    B : _NeighborhoodCache
       A graph of blocking edges to prevent the production of chordless cycles

    path : list
       A cycle prefix.  All cycles generated will begin with this prefix.

    length_bound : int
       A length bound.  All cycles generated will have length at most length_bound.


    Yields
    ------
    list of nodes
       Each cycle is represented by a list of nodes along the cycle.

    References
    ----------
    .. [1] Efficient enumeration of chordless cycles
       E. Dias and D. Castonguay and H. Longo and W.A.R. Jradi
       https://arxiv.org/abs/1309.1051

    r   r6   NrG   r   )r   intrb   r9   r   r   )r   r   r   rV   r   targetr   r2   r   r   FwBws               r)   r   r     sK    ^ #G!WFGDG!"X 1 	AAJ!OJ	 !DG*E
Ry 	 AqzQL$8CI<TqTR<!*$1B|  (
a
(KKNLLb*	  IIKtxxz]  
a
 % s   A$D'D8BDD
undirectedT)mutates_inputc           
      ~  	
 	
fd
	
fdg t        t              t        t              	g | D ]9  }| j                  ||      sj	                  |g       | j                  ||       ; t        t        | t        t        |                         D ]  | j                  fd| D              }t        j                  |      }t        |fd      }| j                  |      }t        |      dkD  sct        |j                        }|D ]  }d|<   g 	|   dd   |||      } S )	a>  Find simple cycles (elementary circuits) of a directed graph.

    A `simple cycle`, or `elementary circuit`, is a closed path where
    no node appears twice. Two elementary circuits are distinct if they
    are not cyclic permutations of each other.

    This version uses a recursive algorithm to build a list of cycles.
    You should probably use the iterator version called simple_cycles().
    Warning: This recursive version uses lots of RAM!
    It appears in NetworkX for pedagogical value.

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

    Returns
    -------
    A list of cycles, where each cycle is represented by a list of nodes
    along the cycle.

    Example:

    >>> edges = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)]
    >>> G = nx.DiGraph(edges)
    >>> nx.recursive_simple_cycles(G)
    [[0], [2], [0, 1, 2], [0, 2], [1, 2]]

    Notes
    -----
    The implementation follows pp. 79-80 in [1]_.

    The time complexity is $O((n+e)(c+1))$ for $n$ nodes, $e$ edges and $c$
    elementary circuits.

    References
    ----------
    .. [1] Finding all the elementary circuits of a directed graph.
       D. B. Johnson, SIAM Journal on Computing 4, no. 1, 77-84, 1975.
       https://doi.org/10.1137/0204007

    See Also
    --------
    simple_cycles, cycle_basis
    c                 f    |    r+d| <   |    r  |    j                                |    ryyy)z6Recursively unblock and remove nodes from B[thisnode].FN)r   )thisnoder   _unblockr   s    r)   r   z)recursive_simple_cycles.<locals>._unblock/  s=    8 %GHH+8*+ H+ r*   c                 ,   d}	j                  |        d| <   ||    D ]1  }||k(  r
j                  	d d         d}|   r% |||      s0d}3 |r	 |        n&||    D ]  }| |   vs|   j                  |          	j                          |S )NFT)r   r   )r   	startnode	componentr   nextnoder   r   r   circuitr   results        r)   r   z(recursive_simple_cycles.<locals>.circuit6  s    H !(+ 	"H9$d1g&X&8Y	:!F	" X%h/ 11X;.hK&&x01 	
r*   c              3   :   K   | ]  }|      k\  s|  y wr.   r/   )r1   r(   orderingss     r)   r4   z*recursive_simple_cycles.<locals>.<genexpr>\  s      RtHTNhqk4QdRs   c                 ,    t        fd| D              S )Nc              3   (   K   | ]	  }|     y wr.   r/   )r1   nr   s     r)   r4   z<recursive_simple_cycles.<locals>.<lambda>.<locals>.<genexpr>`  s     4MQXa[4Ms   )r   )nsr   s    r)   <lambda>z)recursive_simple_cycles.<locals>.<lambda>`  s    4M"4M1M r*   keyr6   FN)r   boolrn   rJ   r   rp   r   zipranger9   r`   rP   r_   r   __getitem__)r   r2   r`   
strongcompmincompr   r   r(   dummyr   r   r   r   r   r   r   r   s            @@@@@@@@r)   r   r     s3   d, ( D$GDAF
   ::aMM1#MM!Q  C5Q=)*H =::RqRR 55h?
j&MNJJw'	y>AI8+?+?@I!   %$
  Iy)<E= Mr*   c                 J   | j                         r|dv rd }n|dk(  rd }n|dk(  rd }t               }g }d}| j                  |      D ]  }||v rg }|h}	|h}
d}t        j                  | ||      D ]  } |      \  }}||v r|J||k7  rE	 	 |j                         } ||      d   }|
j                  |       |r ||d	         d   }||k(  rnD|j                  |       ||
v r|j                  |       |} n&|	j                  |       |
j                  |       |} |r nB|j                  |	        t        |      d
k(  sJ t        j                  j                  d      t        |      D ]  \  }} |      \  }}||k(  s n |d S # t        $ r g }|h}
Y w xY w)a  Returns a cycle found via depth-first traversal.

    The cycle is a list of edges indicating the cyclic path.
    Orientation of directed edges is controlled by `orientation`.

    Parameters
    ----------
    G : graph
        A directed/undirected graph/multigraph.

    source : node, list of nodes
        The node from which the traversal begins. If None, then a source
        is chosen arbitrarily and repeatedly until all edges from each node in
        the graph are searched.

    orientation : None | 'original' | 'reverse' | 'ignore' (default: None)
        For directed graphs and directed multigraphs, edge traversals need not
        respect the original orientation of the edges.
        When set to 'reverse' every edge is traversed in the reverse direction.
        When set to 'ignore', every edge is treated as undirected.
        When set to 'original', every edge is treated as directed.
        In all three cases, the yielded edge tuples add a last entry to
        indicate the direction in which that edge was traversed.
        If orientation is None, the yielded edge has no direction indicated.
        The direction is respected, but not reported.

    Returns
    -------
    edges : directed edges
        A list of directed edges indicating the path taken for the loop.
        If no cycle is found, then an exception is raised.
        For graphs, an edge is of the form `(u, v)` where `u` and `v`
        are the tail and head of the edge as determined by the traversal.
        For multigraphs, an edge is of the form `(u, v, key)`, where `key` is
        the key of the edge. When the graph is directed, then `u` and `v`
        are always in the order of the actual directed edge.
        If orientation is not None then the edge tuple is extended to include
        the direction of traversal ('forward' or 'reverse') on that edge.

    Raises
    ------
    NetworkXNoCycle
        If no cycle was found.

    Examples
    --------
    In this example, we construct a DAG and find, in the first call, that there
    are no directed cycles, and so an exception is raised. In the second call,
    we ignore edge orientations and find that there is an undirected cycle.
    Note that the second call finds a directed cycle while effectively
    traversing an undirected graph, and so, we found an "undirected cycle".
    This means that this DAG structure does not form a directed tree (which
    is also known as a polytree).

    >>> G = nx.DiGraph([(0, 1), (0, 2), (1, 2)])
    >>> nx.find_cycle(G, orientation="original")
    Traceback (most recent call last):
        ...
    networkx.exception.NetworkXNoCycle: No cycle found.
    >>> list(nx.find_cycle(G, orientation="ignore"))
    [(0, 1, 'forward'), (1, 2, 'forward'), (0, 2, 'reverse')]

    See Also
    --------
    simple_cycles
    )Noriginalc                     | d d S )NrG   r/   edges    r)   tailheadzfind_cycle.<locals>.tailhead  s    8Or*   reversec                     | d   | d   fS )Nr6   r   r/   r   s    r)   r   zfind_cycle.<locals>.tailhead  s    7DG##r*   ignorec                 0    | d   dk(  r
| d   | d   fS | d d S )Nr   r   r6   r   rG   r/   r   s    r)   r   zfind_cycle.<locals>.tailhead  s,    Bx9$AwQ''8Or*   Nr6   r   r   zNo cycle found.)rL   r   nbunch_iterrP   edge_dfsr   r   
IndexErrorr   rf   r   r   r9   	exceptionNetworkXNoCycle	enumerate)r   sourceorientationr   exploredr&   
final_node
start_nodero   seenactive_nodesprevious_headr   tailheadpopped_edgepopped_head	last_headis                      r)   r   r   l  s   H ==?k-??	 
		!	$ 
	 	
 uHEJmmF+ ;>
!|"|KK:{; &	%D!$JD$x(T]-B 9&+iik '/{&;A&>$++K8$,U2Y$7$:	9,!  LL|#U#!
  & $M&	%P OOD!o;>t 5zQll**+<==
 U# 4d^
d:
 9S &  "(,vs   FF"!F"weight)
edge_attrsc                 X     t         fdt        j                         D        g       S )aP  Returns a minimum weight cycle basis for G

    Minimum weight means a cycle basis for which the total weight
    (length for unweighted graphs) of all the cycles is minimum.

    Parameters
    ----------
    G : NetworkX Graph
    weight: string
        name of the edge attribute to use for edge weights

    Returns
    -------
    A list of cycle lists.  Each cycle list is a list of nodes
    which forms a cycle (loop) in G. Note that the nodes are not
    necessarily returned in a order by which they appear in the cycle

    Examples
    --------
    >>> G = nx.Graph()
    >>> nx.add_cycle(G, [0, 1, 2, 3])
    >>> nx.add_cycle(G, [0, 3, 4, 5])
    >>> nx.minimum_cycle_basis(G)
    [[5, 4, 3, 0], [3, 2, 1, 0]]

    References:
        [1] Kavitha, Telikepalli, et al. "An O(m^2n) Algorithm for
        Minimum Cycle Basis of Graphs."
        http://link.springer.com/article/10.1007/s00453-007-9064-z
        [2] de Pina, J. 1995. Applications of shortest path methods.
        Ph.D. thesis, University of Amsterdam, Netherlands

    See Also
    --------
    simple_cycles, cycle_basis
    c              3   T   K   | ]  }t        j                  |             ! y wr.   )_min_cycle_basisr`   )r1   r\   r   r   s     r)   r4   z&minimum_cycle_basis.<locals>.<genexpr>6  s!     UQ	!**Q-	0Us   %()sumrP   connected_components)r   r   s   ``r)   r   r     s*    R U":Q:QRS:TU
 r*   c                 ^   g }t        t        j                  | d d            }| j                  |z
  |D ch c]	  \  }}||f c}}z
  }|D cg c]  }|h }}|r|j	                         }	t        | |	|      }
|j                  |
D cg c]  \  }}|	 c}}       |D cg c]\  t        fd|
D              dz  rAD ch c]  }||	vs|d d d   |	vs| c}|	D ch c]  }|vs|d d d   vs| c}z  n^ }}}|r|S c c}}w c c}w c c}}w c c}w c c}w c c}}w )NF)r   datac              3   >   K   | ]  }|v xs
 |d d d   v   y wr   r/   )r1   r   orths     r)   r4   z#_min_cycle_basis.<locals>.<genexpr>R  s)     GaAI04R4D0Gs   rG   r   )rn   rP   minimum_spanning_edgesro   r   
_min_cycler   r   )r   r   cb
tree_edgesrA   r2   chordsr   set_orthbasecycle_edgesr   r   s              ` r)   r   r   ;  sO   	B b//$UKLJWWz!
$C1aV$CCF $**4*H*
||~ D&1
		-A1-. !
 
  G;GG!K !IqATMQttWD5HI"Katmq2wd7J1KL 
 
 " I+ %D +
 . JK
sM   D
DD
% D)	D
DDD)$	D$.
D$9D$=	D)
D)c           
         t        j                         }| j                  |d      D ]M  \  }}}||f|v s||f|v r|j                  ||dff|df|fg|       1|j                  ||f|df|dffg|       O t         j                  }| D ci c]  }| ||||dfd       }	}t        |	|	j                        }
|
df}t        j                  ||
|d      }|D cg c]  }|| v r|n|d    }}t        t        |            }t               }|D ]K  }||v r|j                  |       |ddd	   |v r|j                  |ddd	          ;|j                  |       M g }|D ]b  }||v r#|j                  |       |j                  |       *|ddd	   |v s5|j                  |ddd	          |j                  |ddd	          d |S c c}w c c}w )
z
    Computes the minimum weight cycle in G,
    orthogonal to the vector orth as per [p. 338, 1]
    Use (u, 1) to indicate the lifted copy of u (denoted u' in paper).
    r6   )r   default)	Gi_weightr	  )r   r   r   r   r   Nr   )rP   rR   ro   add_edges_fromshortest_path_lengthr   r   shortest_pathrn   r	   r   r   r   r   )r   r   r   GirA   r2   wtsplr   liftr   end
min_path_imin_pathedgelistedgesetr   min_edgelists                     r)   r   r   Y  s    
B GGG3 H1bq6T>aVt^Aq6{aVQK8BG1vAA'78BG	H 
!
!CMNOAs2aA{CCODO $((#E!*C!!"U3{SJ 0::!Q!V1%:H: HX&'HeG <NN1ttWNN1TrT7#KKN L $<"NN1ttW$B$(NN1TrT7#$ ? P ;s   G	Gc                    t         x}}t        j                  j                  j                  j
                  }t        j                  j                  j                  j                  }| D ]Z  }|di}t        j                  | |      D ];  \  }}}	||   }
|
|kD  r 0|	|u r	|
dz   ||<    |	|u }|
|
z   dz   |z
  }||k  s5|}|
|z
  }= \ |S )a  Returns the girth of the graph.

    The girth of a graph is the length of its shortest cycle, or infinity if
    the graph is acyclic. The algorithm follows the description given on the
    Wikipedia page [1]_, and runs in time O(mn) on a graph with m edges and n
    nodes.

    Parameters
    ----------
    G : NetworkX Graph

    Returns
    -------
    int or math.inf

    Examples
    --------
    All examples below (except P_5) can easily be checked using Wikipedia,
    which has a page for each of these famous graphs.

    >>> nx.girth(nx.chvatal_graph())
    4
    >>> nx.girth(nx.tutte_graph())
    4
    >>> nx.girth(nx.petersen_graph())
    5
    >>> nx.girth(nx.heawood_graph())
    6
    >>> nx.girth(nx.pappus_graph())
    6
    >>> nx.girth(nx.path_graph(5))
    inf

    References
    ----------
    .. [1] `Wikipedia: Girth <https://en.wikipedia.org/wiki/Girth_(graph_theory)>`_

    r   r6   rG   )r   rP   
algorithms	traversalbreadth_first_search	TREE_EDGE
LEVEL_EDGEbfs_labeled_edges)r   r   depth_limit	tree_edge
level_edger   depthrA   r2   labeldudeltalengths                r)   r   r     s    T EK''<<FFI((==HHJ - A//15 	-KAq%qBK	!6a +b1u,E>"E"$u*K	-	-& Lr*   r.   )NN) r}   collectionsr   r   	itertoolsr   r   mathr   networkxrP   networkx.utilsr   r	   __all___dispatchabler
   r   rT   rU   r   rt   rc   rd   r   r   r   r   r   r   r   r   r/   r*   r)   <module>r-     s   - +   8 Z \"J  # !JZ C= C=L/=d/=d  9 x: z OR ORdJ Z \"%j & #jZ \ \~ Z \"X&) ' # !)X<2j Z \"=  # !=r*   