o
    ˷eT                     @   s   d Z ddlmZ ddlZddlmZmZ g dZededddd	Z	ed
dd Z
ed
dd ZdddZededdddZdd ZdddZdd ZdS )zL
========================
Cycle finding algorithms
========================
    )defaultdictN)not_implemented_forpairwise)cycle_basissimple_cyclesrecursive_simple_cycles
find_cycleminimum_cycle_basisdirected
multigraphc                 C   s  t |  }g }|r|du r| }|g}||i}|t  i}|r| }|| }| | D ]R}	|	|vrA|||	< ||	 |h||	< q,|	|krL||g q,|	|vr~||	 }
|	|g}|| }||
vrm|| || }||
vs`|| || ||	 | q,|s |t |8 }d}|s
|S )ae  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])
    >>> print(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
    N)setnodespopappendadd)Grootgnodescyclesstackpredusedzzusednbrpncyclep r   Q/var/www/ideatree/venv/lib/python3.10/site-packages/networkx/algorithms/cycles.pyr      sF   ,




r   
undirectedc                 c   s   dd }t | |  }dd t|D }|D ]}|||r+|gV  ||| q|r| }||}| }|g}t }	t }
|		| t
t}|t|| fg}|r|d \}}|r| }||kru|dd V  |
| n||	vr|| ||t|| f |
| |		| qV|s||
v r|||	| n|| D ]}||| vr|| 	| q|  |  |sX||}|dd t|D  |s.dS dS )	aw  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 is a nonrecursive, iterator/generator version of Johnson's
    algorithm [1]_.  There may be better algorithms for some cases [2]_ [3]_.

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

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

    Examples
    --------
    >>> edges = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)]
    >>> G = nx.DiGraph(edges)
    >>> 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
    -----
    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
    .. [2] Enumerating the cycles of a digraph: a new preprocessing strategy.
       G. Loizou and P. Thanish, Information Sciences, v. 27, 163-182, 1982.
    .. [3] 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.

    See Also
    --------
    cycle_basis
    c                 S   sJ   | h}|r#|  }||v r|| |||  ||   |sd S d S N)r   removeupdateclear)thisnodeblockedBr   noder   r   r   _unblock   s   
zsimple_cycles.<locals>._unblockc                 S   s   g | ]
}t |d kr|qS )   len.0sccr   r   r   
<listcomp>       z!simple_cycles.<locals>.<listcomp>Nc                 s   s     | ]}t |d kr|V  qdS )r*   Nr+   r-   r   r   r   	<genexpr>       z simple_cycles.<locals>.<genexpr>)typeedgesnxstrongly_connected_componentshas_edgeremove_edger   subgraphr   r   r   listr#   r   discardextend)r   r)   subGsccsvr/   sccG	startnodepathr&   closedr'   r   r%   nbrsnextnoder   Hr   r   r   r   b   sZ   <





r   c           	         s   fdd fddg t tt t g | D ]}| ||r5|g | || q!tt| tt	| D ]G| 
fdd| D }t|}t|fddd	}| 
|}t	|d
krt|jd	}|D ]}d|< g  | dd< qu|||}qC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                    s<   |  rd| <  |  r |      |  sdS dS dS )z6Recursively unblock and remove nodes from B[thisnode].FN)r   )r%   )r'   r)   r&   r   r   r)     s   z)recursive_simple_cycles.<locals>._unblockc                    s   d} |  d| < ||  D ]}||kr! d d   d}q| s-|||r-d}q|r5|  n||  D ]}|  | vrH |  |  q9  |S )NFT)r   r   )r%   rC   	componentrE   rG   )r'   r)   r&   circuitrD   resultr   r   rJ     s&   

z(recursive_simple_cycles.<locals>.circuitc                 3   s$    | ]} |   kr|V  qd S r!   r   r.   r(   )orderingsr   r   r3   >  s   " z*recursive_simple_cycles.<locals>.<genexpr>c                    s   t  fdd| D S )Nc                 3   s    | ]} | V  qd S r!   r   r.   nrM   r   r   r3   B  s    z<recursive_simple_cycles.<locals>.<lambda>.<locals>.<genexpr>)min)nsrQ   r   r   <lambda>B      z)recursive_simple_cycles.<locals>.<lambda>keyr*   FN)r   boolr<   r9   r   r:   dictzipranger,   r;   r7   r8   rR   __getitem__)	r   rA   r;   
strongcompmincomprI   rC   r(   dummyr   )r'   r)   r&   rJ   rM   rD   rK   rN   r   r      s2   0

r   c              
   C   s  |   r|dv rdd }n|dkrdd }n|dkrdd }t }g }d}| |D ]}||v r1q*g }|h}	|h}
d}t| ||D ]d}||\}}||v rOqB|dur||kr	 z| }W n tyl   g }|h}
Y nw ||d
 }|
| |r||d d
 }||krnqX|| ||
v r|	| |} n|	
| |

| |}qB|r n||	 q*t|dksJ tjdt|D ]\}}||\}}||kr nq||d S )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                 S   s   | d d S )N   r   edger   r   r   tailhead  s   zfind_cycle.<locals>.tailheadreversec                 S   s   | d | d fS )Nr*   r   r   rb   r   r   r   rd     s   ignorec                 S   s(   | d dkr| d | d fS | d d S )Nr2   re   r*   r   ra   r   rb   r   r   r   rd     s   NTr*   r2   r   zNo cycle found.)is_directedr   nbunch_iterr7   edge_dfsr   
IndexErrorr"   r   r>   r   r#   r,   	exceptionNetworkXNoCycle	enumerate)r   sourceorientationrd   exploredr   
final_node
start_noder6   seenactive_nodesprevious_headrc   tailheadpopped_edgepopped_head	last_headir   r   r   r   N  sn   C






r   c                    s    t  fddt D g S )al  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])
    >>> print([sorted(c) for c in nx.minimum_cycle_basis(G)])
    [[0, 1, 2, 3], [0, 3, 4, 5]]

    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   s     | ]}t  |V  qd S r!   )_min_cycle_basisr;   )r.   cr   weightr   r   r3     r4   z&minimum_cycle_basis.<locals>.<genexpr>)sumr7   connected_componentsr~   r   r~   r   r	     s   (r	   c                    s   g }t tj| d ddfdd|  D }t|}dd |D }t|D ]0}t| || |d|t t j	  ||   fdd||d d  D ||d d < q&|S )	NF)r   datac                    s   g | ]
}| vrt |qS r   	frozenset)r.   e)spanning_tree_edgesr   r   r0   !  r1   z$_min_cycle_basis.<locals>.<listcomp>c                 S   s   g | ]}|hqS r   r   )r.   rc   r   r   r   r0   %  s    r   c                    s(   g | ]}t |@ d  r| A n|qS )ra   r+   )r.   orth)base	new_cycler   r   r0   -  s    r*   )
r<   r7   minimum_spanning_edgesr6   r,   r[   
_min_cycler   r   union)compr   cb
edges_exclNset_orthkr   )r   r   r   r   r|     s   r|   c                    sB  t  }dd t|  D }dd | D t|| jddD ]?\}}}|| || }}	||d}
t||f|v rP|j	||	 f| |	fg|
d q"|j	||	f| |	 fg|
d q"t
t j||d  fddtD }t||jd	}| }t j|||d
d}fdd|D }t|}fdd|D S )zf
    Computes the minimum weight cycle in G,
    orthogonal to the vector orth as per [p. 338, 1]
    c                 S      i | ]\}}||qS r   r   )r.   idxr(   r   r   r   
<dictcomp>;  rU   z_min_cycle.<locals>.<dictcomp>c                 S   r   r   r   )r.   r(   r   r   r   r   r   <  rU   T)r   r*   r   c                    s   i | ]}| | |  qS r   r   rO   )all_shortest_pathlensnnodesr   r   r   O  s    rV   r   )rn   targetr   c                    s    g | ]}| k r
|n|  qS r   r   rL   )r   r   r   r0   Y  s     z_min_cycle.<locals>.<listcomp>c                    s$   h | ]\}}t  |  | fqS r   r   )r.   urA   )	idx_nodesr   r   	<setcomp>]  s   $ z_min_cycle.<locals>.<setcomp>)r7   Graphrm   r   itemsr,   r6   getr   add_edges_fromrY   shortest_path_lengthr[   rR   shortest_path_path_to_cycle)r   r   r   T	nodes_idxr   rA   r   uidxvidxedge_wcross_paths_w_lensstartendmin_pathmin_path_nodesmcycle_prunedr   )r   r   r   r   r   4  s0   r   c                 C   s"   t  }t| D ]}||hN }q|S )za
    Removes the edges from path that occur even number of times.
    Returns a set of edges
    )r   r   )rD   r6   rc   r   r   r   r   `  s   r   r!   )NN)__doc__collectionsr   networkxr7   networkx.utilsr   r   __all__r   r   r   r   r	   r|   r   r   r   r   r   r   <module>   s(    	K
~

l  ,
,