
    h                     N   S r SSKJrJr  SSKJrJr  SSKJr  SSK	r
SSKJrJr  / SQr\" S5      \" S	5      \
R                  SS
 j5       5       5       r\
R                  SS j5       rS rS r " S S\5      rS rS r\
R                  SS j5       rS r\" S5      \
R                  " SS9S 5       5       r\
R                  S S j5       r\" S5      \" S	5      \
R                  " SS9SS j5       5       5       rS rS r\" S5      \" S	5      \
R                  S 5       5       5       rg)!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                  U 5      n/ nU(       Ga   Uc  UR                  5       S   nU/nX0nU[        5       0nU(       a  UR	                  5       nXg   nX    H  n	X;  a  XuU	'   UR                  U	5        U1Xi'   M$  X:X  a  UR                  U/5        M=  X;  d  MD  Xi   n
X/nXW   nX;  a  UR                  U5        X\   nX;  a  M  UR                  U5        UR                  U5        Xi   R                  U5        M     U(       a  M  U H  nUR	                  US5        M     SnU(       a  GM   U$ )a  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                 L/var/www/html/env/lib/python3.13/site-packages/networkx/algorithms/cycles.pyr
   r
      s3   \ ]]1FF
<>>#A&D|ce}		AGEt? !ILL%!"DIXMM1#&%B HEA+Q G + LLOMM%(IMM!$!  e( DJJtT" 9 &: M    c              #   $  ^ ^^#    Ub  US:X  a  gUS:  a  [        S5      eT R                  5       nS T R                  R                  5        5        Sh  vN   Ub  US:X  a  gT R	                  5       (       at  U(       dm  [        5       mT R                  R                  5        HE  u  mnU4S jUR                  5        5       nU4S jU 5        Sh  vN   TR                  T5        MG     U(       a6  [        R                  " S T R                  R                  5        5       5      m O5[        R                  " S	 T R                  R                  5        5       5      m Ubq  US
:X  ak  U(       ac  [        5       mT R                  R                  5        H;  u  mnU U4S jTR                  U5       5        Sh  vN   TR                  T5        M=     gU(       a  [        T U5       Sh  vN   g[        T U5       Sh  vN   g GN GN4 NQ N" N7f)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   :   #    U  H  u  pX;   d  M  U/v   M     g 7fN .0vGvs      r)   	<genexpr> simple_cycles.<locals>.<genexpr>   s     :!'   
   c              3   R   >#    U  H  u  pUT;   d  M  U[        U5      4v   M     g 7fr.   lenr1   r2   Guvvisiteds      r)   r4   r5      s#     S
faa7lMQCM
   ''c              3   @   >#    U  H  u  pUS :  d  M  TU/v   M     g7fr7   Nr/   )r1   r2   mus      r)   r4   r5      s     A<411q5A<s   c              3   N   #    U  H  u  pU  H  o3U:w  d  M
  X4v   M     M     g 7fr.   r/   r1   rB   Gur2   s       r)   r4   r5      s"     O=%!"QQvv"v=   %%c              3   N   #    U  H  u  pU  H  o3U:w  d  M
  X4v   M     M     g 7fr.   r/   rD   s       r)   r4   r5      s"     M11fVaVVrF      c              3   ^   >#    U  H"  nTR                  UT5      (       d  M  UT/v   M$     g 7fr.   has_edge)r1   r2   r   rB   s     r)   r4   r5      s(      $<q

1a@PFQF$<s   --)
ValueErroris_directedadjitemsis_multigraphr   r   nxDiGraphGraphintersection_directed_cycle_search_undirected_cycle_search)r   length_boundr   rE   multiplicityrB   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HHA=HHC$H8H
90H)H*H>H?HH
HHHc              #     #    [         R                  nU" U 5       Vs/ s H  n[        U5      S:  d  M  UPM     nnU(       a  UR                  5       nU R	                  U5      n[        [        U5      5      nUc  [        XV/5       Sh  vN   O[        XV/U5       Sh  vN   U R                  U5        UR                  S U" U5       5       5        U(       a  M  ggs  snf  NY NE7f)aM  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.
rH   Nc              3   H   #    U  H  n[        U5      S :  d  M  Uv   M     g7frH   Nr9   r1   cs     r)   r4   )_directed_cycle_search.<locals>.<genexpr>       <WA!!!W   "	")rQ   strongly_connected_componentsr:   r   subgraphnextiter_johnson_cycle_search_bounded_cycle_searchremove_nodeextend)r   rW   sccr]   
componentsGcr2   s          r)   rU   rU      s     F 
*
*C V3Vs1v{!VJ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&!:C(C(&C(c              #     #    [         R                  nU" U 5       Vs/ s H  n[        U5      S:  d  M  UPM     nnU(       a  UR                  5       nU R	                  U5      n[        [        [        UR                  5      5      5      nU R                  " U6   Uc  [        XV5       Sh  vN   O[        XVU5       Sh  vN   UR                  S U" U5       5       5        U(       a  M  ggs  snf  NG N47f)ab  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   H   #    U  H  n[        U5      S :  d  M  Uv   M     g7f)rm   Nr9   r\   s     r)   r4   +_undirected_cycle_search.<locals>.<genexpr>Q  r_   r`   )rQ   biconnected_componentsr:   r   rb   listrc   rd   edgesremove_edgere   rf   rh   )r   rW   bccr]   rj   rk   uvs          r)   rV   rV   "  s     F 
#
#C V3Vs1v{!VJ3
NNZZ]$tBHH~&'	r,R444,R\BBB<SW<< * 4 5Bs9   C7C.C.A1C7+C3,C7 C5)C7,C75C7c                   $    \ rS rSrSrS rS rSrg)_NeighborhoodCacheiT  a  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                     Xl         g r.   r   )selfr   s     r)   __init___NeighborhoodCache.__init__\  s    r*   c                 >    [        U R                  U   5      =o U'   U$ r.   )rq   r   )rz   r2   r3   s      r)   __missing___NeighborhoodCache.__missing___  s    DFF1I&!W	r*   ry   N)__name__
__module____qualname____firstlineno____doc__r{   r~   __static_attributes__r/   r*   r)   rw   rw   T  s    r*   rw   c              #     #    [        U 5      n [        U5      n[        [        5      nUS   n[        XS      5      /nS/nU(       Ga@  US   nU Hl  nX:X  a  USS v   SUS'   M  X;  d  M  UR	                  U5        UR	                  S5        UR	                  [        X   5      5        UR                  U5          O   UR                  5         UR                  5       n	UR                  5       (       ak  U(       a  SUS'   U	1n
U
(       aT  U
R                  5       nX;   a6  UR                  U5        U
R                  X;   5        X;   R                  5         U
(       a  MT  OX	    H  nX8   R                  U	5        M     U(       a  GM?  gg7f)a  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)
rw   r   r   rd   r   r   r   removeupdateclear)r   pathblockedBstartr   closednbrswr2   unblock_stackrB   s               r)   re   re   d  sL    0 	1A$iGCAGE!H+EWF
RyAz1g!r
!Ae$T!$Z(A  IIK
Azz||!%F2J!"#%))+A|q)%,,QT2

 $m ADHHQK 5 %s   A'F
-C0F
&F
F
c              #     ^#    [        U 5      n U Vs0 s H  o3S_M     nn[        [        5      nUS   n[        XS      5      /nU/nU(       Ga~  US   n	U	 H  n
X:X  a  USS v   SUS'   M  [	        U5      UR                  X5      :  d  M6  UR                  U
5        UR                  U5        [	        U5      XJ'   UR                  [        X
   5      5          O   UR                  5         UR                  5       nUR                  5       mU(       a  [        US   T5      US'   TU:  az  TU4/nU(       am  UR                  5       u  mnUR                  X5      UT-
  S-   :  a6  UT-
  S-   XL'   UR                  U4S jX\   R                  U5       5       5        U(       a  Mm  OX    H  n
XZ   R                  U5        M     U(       a  GM}  ggs  snf 7f)a6  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   Nr7   c              3   2   >#    U  H  nTS -   U4v   M     g7fr@   r/   )r1   r   bls     r)   r4   (_bounded_cycle_search.<locals>.<genexpr>  s     *V@U1BFA;@Us   )rw   r   r   rd   r:   getr   r   minrh   
differencer   )r   r   rW   r2   lockr   r   r   blenr   r   relax_stackrB   r   s                @r)   rf   rf     s    2 	1A$QqD$DCAGE!H+E>D
RyAz1gRTTXXa66AL)d)T!$Z(  IIK
ABtBx,RL  "Awi!'OO-EBxx0<"3Dq3HH"."3a"7#***VPT@U*VV	 "k ADHHQK 5 %  s#   GGA+GDG%&GGc           	   #     ^ ^^#    Ub  US:X  a  gUS:  a  [        S5      eT R                  5       nT R                  5       nU(       a*  S T R                  R	                  5        5        Sh  vN   O)S T R                  R	                  5        5        Sh  vN   Ub  US:X  a  gU(       aE  [
        R                  " S T R                  R	                  5        5       5      mTR                  SS	9nO7[
        R                  " S
 T R                  R	                  5        5       5      mSnU(       a  U(       d  TR                  5       n[        5       mT R                  R	                  5        H  u  pVU(       aA  S UR	                  5        5       nU H"  u  pU	S:  d  M  TR                  XX4X445        M$     MM  U4S jUR	                  5        5       nU H)  u  pU	S:X  a  XX/v   U	S:  d  M  TR                  XX5        M+     TR                  U5        M     U(       a  TR                  R	                  5        Hc  u  pZU
 Vs/ s H  nTR                  X5      (       d  M  XX/PM      nnU Sh  vN   TR                  U5        TR                  S U 5       5        Me     Ub  US:X  a  gU(       a  [
        R                  nUU 4S jnO[
        R                   nU4S jnU" T5       Vs/ s H  n[#        U5      S:  d  M  UPM     nnU(       a  UR%                  5       n['        [)        U5      5      nTR+                  U5      nS=nnU" UU5       HV  u  nnU(       a  Uv   M  Uc*  [-        U5      nUc  UO[-        UR+                  U5      5      n[/        UUUU5       Sh  vN   MX     UR1                  S U" TR+                  X1-
  5      5       5       5        U(       a  M  gg GNw GNPs  snf  GNs  snf  NV7f)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   n   #    U  H+  u  p[        UR                  US 5      5      S:X  d  M&  U/v   M-     g7f)r/   r7   N)r:   r   r0   s      r)   r4   #chordless_cycles.<locals>.<genexpr>B  s,     N]EAc"&&B-6HA6MCQC]s   %5
5c              3   :   #    U  H  u  pX;   d  M  U/v   M     g 7fr.   r/   r0   s      r)   r4   r   D  s     >]EAagCQC]r6   r7   c              3   N   #    U  H  u  pX;  d  M  U  H  o1U4v   M
     M     g 7fr.   r/   rD   s       r)   r4   r   M  s$     T=%!AKvQSA1vQSv=   %%F)as_viewc              3   N   #    U  H  u  pX;  d  M  U  H  o1U4v   M
     M     g 7fr.   r/   rD   s       r)   r4   r   P  s"     R!+Vr!VrVr   c              3   @   #    U  H  u  pU[        U5      4v   M     g 7fr.   r9   )r1   r2   r<   s      r)   r4   r   j  s     GJ&!CHJs   c              3   R   >#    U  H  u  pUT;   d  M  U[        U5      4v   M     g 7fr.   r9   r;   s      r)   r4   r   o  s#     WJ&!!w,CHJr>   rH   c              3   0   #    U  H  oS S S2   v   M     g 7fNr   r/   )r1   es     r)   r4   r     s     8A$B$s   c              3      >#    [        U R                  U   U R                  U   5       H4  u  p#TR                  X#5      (       a  M  X!U/TR                  X25      4v   M6     g 7fr.   )r   r    succrK   )Cr2   rB   r   Fr   s       r)   stemschordless_cycles.<locals>.stems  sP     q	166!95zz!'')QZZ%555 6s   A A#A#c              3   X   >^#    UU4S j[        U T   S5       5        S h  vN   g  N7f)Nc              3   T   >#    U  H  u  pUTU/TR                  X!5      4v   M     g 7fr.   rJ   )r1   rB   r   r   r2   s      r)   r4   2chordless_cycles.<locals>.stems.<locals>.<genexpr>  s)     XBW$!!QAJJq$45BWs   %(rH   )r   )r   r2   r   s    `r)   r   r     s!     X,qQRtUVBWXXXs   *(*c              3   H   #    U  H  n[        U5      S :  d  M  Uv   M     g7fr[   r9   r\   s     r)   r4   r     s     Q%Bc!fqj!!%Br`   )rL   rM   rP   rN   rO   rQ   rR   to_undirectedrS   copyr   remove_edges_fromrs   r   rK   ra   rp   r:   r   rc   rd   rb   rw   _chordless_cycle_searchrh   )r   rW   r   r   r   rB   rE   rX   r2   rA   Fudigonsseparater   r]   rj   FcFccBccSis_triangler   r=   s   `                    @@r)   r   r     s7    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[[]EAGBHHJG(DA1u++aVaV,<= )  XBHHJW(DAAv f1ua+	 )
 A #( UU[[]EA&(=bAJJq,<fqfbF='888	 # LA$5 33	6 ,,	Y &a[7[CFQJ![J7
NNaMZZ]c#BlNA{;,R0C!"#0B1::a=0QC23QMMM + 	QXajjS.A%BQQ *{ 	O>t >> 8 Ns   A'O8,O#-)O8O&DO8AO8+AO8?O)O)$O8+O.,A:O8&O1=O1BO8O6 ?O8!O8&O8)O81O8c              #   H  #    [        [        5      nUS   nSXBS   '   USS  H  nX    H  nXG==   S-  ss'   M     M     [        XS      5      /nU(       a  US   n	U	 H~  nXF   S:X  d  M  Ub  [        U5      U:  d  M!  X   n
XZ;   a	  X&/-   v   M3  X   nX[;   a  M>  U H  nXG==   S-  ss'   M     UR	                  U5        UR	                  [        U
5      5          O7   UR                  5         XR                  5           H  nXG==   S-  ss'   M     U(       a  M  gg7f)aP  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   r7   NrH   r   )r   intrd   r:   r   r   )r   r   r   rW   r   targetr   r2   r   r   FwBws               r)   r   r     s    ^ #G!WFGG!"XAJ!OJ   !G*E
RyAzQL$8CI<TT<*$B| 
a
  KKNLLb*  IIKxxz]
a
 #% %s   A'D"-D"BD" D"
undirectedT)mutates_inputc           
        ^	^
^^^^^^ U	U
U4S jm
U	U
UUUU4S jm/ m[        [        5      m[        [        5      m	/ mU  H>  nU R                  X5      (       d  M  TR	                  U/5        U R                  X5        M@     [        [        U [        [        U 5      5      5      5      mT H  mU R                  UU4S jU  5       5      n[        R                  " U5      n[        UU4S jS9nU R                  U5      n[        U5      S:  d  Me  [        UTR                  S9nU H  nSTU'   / T	U   SS& M     T" XfU5      nM     T$ )	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                    > TU    (       a6  STU '   TU    (       a&  T" TU    R                  5       5        TU    (       a  M%  ggg)z6Recursively unblock and remove nodes from B[thisnode].FN)r   )thisnoder   _unblockr   s    r)   r   )recursive_simple_cycles.<locals>._unblock/  s?    8 %GHH+8*+ H++ r*   c                 X  > SnT	R                  U 5        STU '   X     H>  nXA:X  a  T
R                  T	S S  5        SnM   TU   (       a  M,  T" XAU5      (       d  M<  SnM@     U(       a	  T" U 5        O*X     H"  nU TU   ;  d  M  TU   R                  U 5        M$     T	R                  5         U$ )NFT)r   r   )r   	startnode	componentr   nextnoder   r   r   circuitr   results        r)   r   (recursive_simple_cycles.<locals>.circuit6  s    H !+H$d1g&X&&8	::!F , X%/1X;.hK&&x0 0 	
r*   c              3   D   >#    U  H  nTU   TT   :  d  M  Uv   M     g 7fr.   r/   )r1   r(   orderingss     r)   r4   *recursive_simple_cycles.<locals>.<genexpr>\  s"     RqtHTNhqk4Qddqs    	 c                 .   > [        U4S jU  5       5      $ )Nc              3   .   >#    U  H
  nTU   v   M     g 7fr.   r/   )r1   nr   s     r)   r4   <recursive_simple_cycles.<locals>.<lambda>.<locals>.<genexpr>`  s     4M"QXa["s   )r   )nsr   s    r)   <lambda>)recursive_simple_cycles.<locals>.<lambda>`  s    4M"4M1Mr*   keyr7   FN)r   boolrq   rK   r   rs   r   zipranger:   rb   rQ   ra   r   __getitem__)r   r2   rb   
strongcompmincompr   r   r(   dummyr   r   r   r   r   r   r   r   s            @@@@@@@@r)   r   r     s!   d, ( D$GDAF
 ::aMM1#MM!  C5Q=)*H::RqRR 55h?
j&MNJJw'	y>AI8+?+?@I! %$
 " I)<E  Mr*   c                    U R                  5       (       a  US;   a  S nOUS:X  a  S nO	US:X  a  S n[        5       n/ nSnU R                  U5       GH  nXt;   a  M  / nU1n	U1n
Sn[        R                  " XU5       H  nW" U5      u  pX;   a  M  UbQ  X:w  aL    UR                  5       nU" U5      S   nU
R                  U5        U(       a  U" US	   5      S   nUU:X  a  OMK  UR                  U5        X;   a  UR                  U5        Un  O(U	R                  U5        U
R                  U5        UnM     U(       a    OFUR                  U	5        GM     [        U5      S
:X  d   e[        R                  R                  S5      e[        U5       H  u  nnW" U5      u  pX:X  d  M    O   UWS $ ! [         a	    / nU1n
 M  f = f)a4
  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                     U S S $ )NrH   r/   edges    r)   tailheadfind_cycle.<locals>.tailhead  s    8Or*   reversec                     U S   U S   4$ )Nr7   r   r/   r   s    r)   r   r     s    7DG##r*   ignorec                 2    U S   S:X  a
  U S   U S   4$ U S S $ )Nr   r   r7   r   rH   r/   r   s    r)   r   r     s,    Bx9$AwQ''8Or*   Nr7   r   r   zNo cycle found.)rM   r   nbunch_iterrQ   edge_dfsr   r   
IndexErrorr   rh   r   r   r:   	exceptionNetworkXNoCycle	enumerate)r   sourceorientationr   exploredr&   
final_node
start_noderr   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(T-B 9&+iik '/{&;A&>$++K8$,U2Y$7$:	9,!  LL#U#!
  & $M <P OOD!o ,t 5zQll**+<==
 U#4d^
 $
 9S &  "(,vs   F33GGweight)
edge_attrsc                 \   ^ ^ [        U U4S j[        R                  " T 5       5       / 5      $ )a  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   Z   >#    U  H   n[        TR                  U5      T5      v   M"     g 7fr.   )_min_cycle_basisrb   )r1   r]   r   r  s     r)   r4   &minimum_cycle_basis.<locals>.<genexpr>6  s&     U:TQ	!**Q-	0	0:Ts   (+)sumrQ   connected_components)r   r  s   ``r)   r   r     s*    R U":Q:QRS:TU
 r*   c                   ^ / n[        [        R                  " U S SS95      nU R                  U-
  U VVs1 s H  u  pEXT4iM
     snn-
  nU Vs/ s H  ow1PM     nnU(       a  UR	                  5       n	[        X	U5      n
UR                  U
 VVs/ s H  u  pEUPM	     snn5        U V^Vs/ s Hs  m[        U4S jU
 5       5      S-  (       aQ  T Vs1 s H  oU	;  d  M
  US S S2   U	;  d  M  UiM     snU	 Vs1 s H  oT;  d  M
  US S S2   T;  d  M  UiM     sn-  OTPMu     nnnU(       a  M  U$ s  snnf s  snf s  snnf s  snf s  snf s  snnf )NF)r  datac              3   P   >#    U  H  oT;   =(       d    US S S2   T;   v   M     g 7fr   r/   )r1   r   orths     r)   r4   #_min_cycle_basis.<locals>.<genexpr>R  s'     G;aI04R4D0;s   #&rH   r   )rq   rQ   minimum_spanning_edgesrr   r   
_min_cycler   r  )r   r  cb
tree_edgesrB   r2   chordsr   set_orthbasecycle_edgesr  r   s              ` r)   r
  r
  ;  sX   	B b//$UKLJWWz!
$C
aV
$CCF $**646H*
||~ &1
		-1-. !
 ! G;GG!K !IDqTMQttWD5HDI"Kdtm1q2wd7J1dKL  ! 	 
 (" I+ %D +
 . JK
sM   D4D:D?
,'E	E 
E.E4E:	E

E
E
E
Ec                    [         R                  " 5       nU R                  USS9 HH  u  pEnXE4U;   d  XT4U;   a  UR                  XES44US4U4/US9  M/  UR                  XE4US4US44/US9  MJ     [         R                  nU  Vs0 s H  oU" X8US4SS9_M     n	n[        XR                  S9n
U
S4n[         R                  " X:USS9nU Vs/ s H  oU ;   a  UOUS   PM     nn[        [        U5      5      n[        5       nU HR  nUU;   a  UR                  U5        M  USSS	2   U;   a  UR                  USSS	2   5        MA  UR                  U5        MT     / nU Hi  nUU;   a$  UR                  U5        UR                  U5        M-  USSS	2   U;   d  M;  UR                  USSS	2   5        UR                  USSS	2   5        Mk     U$ s  snf s  snf )
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).
r7   )r  default)	Gi_weightr  )r   r   r  r   r   Nr   )rQ   rS   rr   add_edges_fromshortest_path_lengthr   r   shortest_pathrq   r	   r   r   r   r   )r   r  r  GirB   r2   wtsplr   liftr   end
min_path_imin_pathedgelistedgesetr   min_edgelists                     r)   r  r  Y  s    
B GGG3b6T>aVt^q6{aVQK8BGvAA'78BG	 4 
!
!CMNOQs2A{CCQDO ((#E!*C!!"3{SJ 0::z!!V1%zH: HX&'HeG<NN1ttWNN1TrT7#KKN  L<"NN1ttW$B$(NN1TrT7#  ? P ;s   GGc                    [         =p[        R                  R                  R                  R
                  n[        R                  R                  R                  R                  nU  HZ  nUS0n[        R                  " X5       H9  u  pxn	Xg   n
X:  a    M/  XL a	  U
S-   Xh'   M  XL nX-   S-   U-
  nX:  d  M3  UnX-
  nM;     M\     U$ )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   r7   rH   )r   rQ   
algorithms	traversalbreadth_first_search	TREE_EDGE
LEVEL_EDGEbfs_labeled_edges)r   r   depth_limit	tree_edge
level_edger   depthrB   r2   labeldudeltalengths                r)   r   r     s    T E''<<FFI((==HHJ A//5KA%B!6 +1u,>"E"$*K 6	 & Lr*   r.   )NN) r   collectionsr   r   	itertoolsr   r   mathr   networkxrQ   networkx.utilsr   r	   __all___dispatchabler
   r   rU   rV   r   rw   re   rf   r   r   r   r   r   r
  r  r   r/   r*   r)   <module>rA     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*   