a
    Oˆc¦O  ã                   @   sL  d Z ddlZddlZddlZddlmZmZ ddlmZm	Z	m
Z
 ddlmZmZ ddlZg d¢Zdd„ Zd	d
„ Zdd„ Zd<dd„Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zd=dd„Zd>dd„Zd?dd„Zd@dd „ZdAd!d"„Zd#d$„ Zd%d&„ Z d'd(„ Z!dBd*d+„Z"d,d-„ Z#d.d/„ Z$dCd0d1„Z%G d2d3„ d3ƒZ&dDd4d5„Z'd6d7„ Z(d8d9„ Z)d:d;„ Z*dS )Ea  
Miscellaneous Helpers for NetworkX.

These are not imported into the base networkx namespace but
can be accessed, for example, as

>>> import networkx
>>> networkx.utils.make_list_of_ints({1, 2, 3})
[1, 2, 3]
>>> networkx.utils.arbitrary_element({5, 1, 7})  # doctest: +SKIP
1
é    N)ÚdefaultdictÚdeque)ÚIterableÚIteratorÚSized)ÚchainÚtee)Úis_string_likeÚiterableÚempty_generatorÚflattenÚmake_list_of_intsÚis_list_of_intsÚmake_strÚgenerate_unique_nodeÚdefault_openerÚdict_to_numpy_arrayÚdict_to_numpy_array1Údict_to_numpy_array2Úis_iteratorÚarbitrary_elementÚconsumeÚpairwiseÚgroupsÚto_tupleÚcreate_random_stateÚcreate_py_random_stateÚPythonRandomInterfaceÚnodes_equalÚedges_equalÚgraphs_equalc                 C   s   d}t  |t¡ t| tƒS )zvCheck if obj is string.

    .. deprecated:: 2.6
        This is deprecated and will be removed in NetworkX v3.0.
    zYis_string_like is deprecated and will be removed in 3.0.Use isinstance(obj, str) instead.)ÚwarningsÚwarnÚDeprecationWarningÚ
isinstanceÚstr©ÚobjÚmsg© r)   úV/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/networkx/utils/misc.pyr	   8   s    ÿr	   c                 C   s>   d}t  |t¡ t| dƒrdS zt| ƒ W n   Y dS 0 dS )z˜Return True if obj is iterable with a well-defined len().

    .. deprecated:: 2.6
        This is deprecated and will be removed in NetworkX v3.0.
    z�iterable is deprecated and will be removed in 3.0.Use isinstance(obj, (collections.abc.Iterable, collections.abc.Sized)) instead.Ú__iter__TF)r!   r"   r#   ÚhasattrÚlenr&   r)   r)   r*   r
   F   s    ÿ
r
   c                   C   s   t  dt¡ dd„ dD ƒS )zAReturn a generator with no members.

    .. deprecated:: 2.6
    z:empty_generator is deprecated and will be removed in v3.0.c                 s   s   | ]
}|V  qd S ©Nr)   )Ú.0Úir)   r)   r*   Ú	<genexpr>b   ó    z"empty_generator.<locals>.<genexpr>r)   )r!   r"   r#   r)   r)   r)   r*   r   Z   s    ÿr   c                 C   sh   t | ttfƒrt | tƒr| S |du r(g }| D ]2}t |ttfƒrHt |tƒrT| |¡ q,t||ƒ q,t|ƒS )z>Return flattened version of (possibly nested) iterable object.N)r$   r   r   r%   Úappendr   Útuple)r'   ÚresultÚitemr)   r)   r*   r   e   s    r   c              	   C   sà   t | tƒsng }| D ]V}d|› �}zt|ƒ}W n tyJ   t |¡d‚Y n0 ||kr^t |¡‚| |¡ q|S t| ƒD ]d\}}d|› �}t |tƒr”qvzt|ƒ}W n ty¾   t |¡d‚Y n0 ||krÒt |¡‚|| |< qv| S )a*  Return list of ints from sequence of integral numbers.

    All elements of the sequence must satisfy int(element) == element
    or a ValueError is raised. Sequence is iterated through once.

    If sequence is a list, the non-int values are replaced with ints.
    So, no new list is created
    zsequence is not all integers: N)r$   ÚlistÚintÚ
ValueErrorÚnxZNetworkXErrorr3   Ú	enumerate)Úsequencer5   r0   ÚerrmsgÚiiZindxr)   r)   r*   r   s   s0    	






r   c                 C   s@   d}t j|tdd� t| tƒs"dS | D ]}t|tƒs& dS q&dS )z…Return True if list is a list of ints.

    .. deprecated:: 2.6
        This is deprecated and will be removed in NetworkX v3.0.
    zhis_list_of_ints is deprecated and will be removed in 3.0.See also: ``networkx.utils.make_list_of_ints.``é   ©Ú
stacklevelFT)r!   r"   r#   r$   r7   r8   )Zintlistr(   r0   r)   r)   r*   r   —   s    ÿ

r   c                 C   s   d}t  |t¡ t| ƒS )z†Returns the string representation of t.

    .. deprecated:: 2.6
        This is deprecated and will be removed in NetworkX v3.0.
    zCmake_str is deprecated and will be removed in 3.0. Use str instead.)r!   r"   r#   r%   )Úxr(   r)   r)   r*   r   ª   s    r   c                  C   s   d} t  | t¡ tt ¡ ƒS )z|Generate a unique node label.

    .. deprecated:: 2.6
        This is deprecated and will be removed in NetworkX v3.0.
    zVgenerate_unique_node is deprecated and will be removed in 3.0. Use uuid.uuid4 instead.)r!   r"   r#   r%   ÚuuidÚuuid4)r(   r)   r)   r*   r   µ   s    r   c                 C   sL   t  dt¡ ddlm} dgdgdgg d¢dœ}|tj | g }||ƒ dS )	aŠ  Opens `filename` using system's default program.

    .. deprecated:: 2.6
       default_opener is deprecated and will be removed in version 3.0.
       Consider an image processing library to open images, such as Pillow::

           from PIL import Image
           Image.open(filename).show()

    Parameters
    ----------
    filename : str
        The path of the file to be opened.

    zAdefault_opener is deprecated and will be removed in version 3.0. r   )ÚcallÚopenzxdg-open)zcmd.exez/CÚstartÚ )ÚdarwinÚlinuxZlinux2Úwin32N)r!   r"   r#   Ú
subprocessrE   ÚsysÚplatform)ÚfilenamerE   ZcmdsÚcmdr)   r)   r*   r   À   s    þür   c              	   C   s2   zt | |ƒW S  ttfy,   t| |ƒ Y S 0 dS )zPConvert a dictionary of dictionaries to a numpy array
    with optional mapping.N)Ú_dict_to_numpy_array2ÚAttributeErrorÚ	TypeErrorÚ_dict_to_numpy_array1)ÚdÚmappingr)   r)   r*   r   à   s    r   c                 C   s   d}t j|tdd� t| |ƒS )zÚConvert a dict of dicts to a 2d numpy array with optional mapping.

    .. deprecated:: 2.8

       dict_to_numpy_array2 is deprecated and will be removed in networkx 3.0.
       Use `dict_to_numpy_array` instead.
    zhdict_to_numpy_array2 is deprecated and will be removed in networkx 3.0.
Use dict_to_numpy_array instead.r?   r@   )r!   r"   r#   rQ   ©rU   rV   r(   r)   r)   r*   r   ë   s    	ÿr   c              
   C   s¼   ddl }|du rRt|  ¡ ƒ}|  ¡ D ]\}}| | ¡ ¡ q$tt|tt|ƒƒƒƒ}t|ƒ}| 	||f¡}| ¡ D ]F\}}	| ¡ D ]4\}
}z| | |
 ||	|f< W q€ t
y²   Y q€0 q€qp|S )zYConvert a dictionary of dictionaries to a 2d numpy array
    with optional mapping.

    r   N)ÚnumpyÚsetÚkeysÚitemsÚupdateÚdictÚzipÚranger-   ÚzerosÚKeyError)rU   rV   ÚnpÚsÚkÚvÚnÚaÚk1r0   Zk2Újr)   r)   r*   rQ   ü   s    
rQ   c                 C   s   d}t j|tdd� t| |ƒS )zÚConvert a dict of numbers to a 1d numpy array with optional mapping.

    .. deprecated:: 2.8

       dict_to_numpy_array1 is deprecated and will be removed in networkx 3.0.
       Use dict_to_numpy_array instead.
    zhdict_to_numpy_array1 is deprecated and will be removed in networkx 3.0.
Use dict_to_numpy_array instead.r?   r@   )r!   r"   r#   rT   rW   r)   r)   r*   r     s    	ÿr   c                 C   sn   ddl }|du r2t|  ¡ ƒ}tt|tt|ƒƒƒƒ}t|ƒ}| |¡}| ¡ D ]\}}|| }| | ||< qL|S )zJConvert a dictionary of numbers to a 1d numpy array with optional mapping.r   N)	rX   rY   rZ   r]   r^   r_   r-   r`   r[   )rU   rV   rb   rc   rf   rg   rh   r0   r)   r)   r*   rT   $  s    
rT   c                 C   s8   d}t j|tdd� t| dƒp&t| dƒ}t| ƒ| u o6|S )z°Returns True if and only if the given object is an iterator object.

    .. deprecated:: 2.6.0
        Deprecated in favor of ``isinstance(obj, collections.abc.Iterator)``
    zxis_iterator is deprecated and will be removed in version 3.0. Use ``isinstance(obj, collections.abc.Iterator)`` instead.r?   r@   Ú__next__Únext)r!   r"   r#   r,   Úiter)r'   r(   Zhas_next_attrr)   r)   r*   r   3  s
    ÿr   c                 C   s   t | tƒrtdƒ‚tt| ƒƒS )aË  Returns an arbitrary element of `iterable` without removing it.

    This is most useful for "peeking" at an arbitrary element of a set,
    but can be used for any list, dictionary, etc., as well.

    Parameters
    ----------
    iterable : `abc.collections.Iterable` instance
        Any object that implements ``__iter__``, e.g. set, dict, list, tuple,
        etc.

    Returns
    -------
    The object that results from ``next(iter(iterable))``

    Raises
    ------
    ValueError
        If `iterable` is an iterator (because the current implementation of
        this function would consume an element from the iterator).

    Examples
    --------
    Arbitrary elements from common Iterable objects:

    >>> nx.utils.arbitrary_element([1, 2, 3])  # list
    1
    >>> nx.utils.arbitrary_element((1, 2, 3))  # tuple
    1
    >>> nx.utils.arbitrary_element({1, 2, 3})  # set
    1
    >>> d = {k: v for k, v in zip([1, 2, 3], [3, 2, 1])}
    >>> nx.utils.arbitrary_element(d)  # dict_keys
    1
    >>> nx.utils.arbitrary_element(d.values())   # dict values
    3

    `str` is also an Iterable:

    >>> nx.utils.arbitrary_element("hello")
    'h'

    :exc:`ValueError` is raised if `iterable` is an iterator:

    >>> iterator = iter([1, 2, 3])  # Iterator, *not* Iterable
    >>> nx.utils.arbitrary_element(iterator)
    Traceback (most recent call last):
        ...
    ValueError: cannot return an arbitrary item from an iterator

    Notes
    -----
    This function does not return a *random* element. If `iterable` is
    ordered, sequential calls will return the same value::

        >>> l = [1, 2, 3]
        >>> nx.utils.arbitrary_element(l)
        1
        >>> nx.utils.arbitrary_element(l)
        1

    z0cannot return an arbitrary item from an iterator)r$   r   r9   rk   rl   )r
   r)   r)   r*   r   B  s    ?
r   c                 C   s$   d}t j|tdd� t| dd� dS )z}Consume the iterator entirely.

    .. deprecated:: 2.6
        This is deprecated and will be removed in NetworkX v3.0.
    zpconsume is deprecated and will be removed in version 3.0. Use ``collections.deque(iterator, maxlen=0)`` instead.r?   r@   r   )ÚmaxlenN)r!   r"   r#   r   )Úiteratorr(   r)   r)   r*   r   ˆ  s    ÿr   Fc                 C   s:   t | ƒ\}}t|dƒ}|du r0t|t||fƒƒS t||ƒS )z&s -> (s0, s1), (s1, s2), (s2, s3), ...NT)r   rk   r^   r   )r
   Zcyclicrg   ÚbÚfirstr)   r)   r*   r   ˜  s
    
r   c                 C   s0   t tƒ}|  ¡ D ]\}}||  |¡ qt|ƒS )aÿ  Converts a many-to-one mapping into a one-to-many mapping.

    `many_to_one` must be a dictionary whose keys and values are all
    :term:`hashable`.

    The return value is a dictionary mapping values from `many_to_one`
    to sets of keys from `many_to_one` that have that value.

    Examples
    --------
    >>> from networkx.utils import groups
    >>> many_to_one = {"a": 1, "b": 1, "c": 2, "d": 3, "e": 3}
    >>> groups(many_to_one)  # doctest: +SKIP
    {1: {'a', 'b'}, 2: {'c'}, 3: {'e', 'd'}}
    )r   rY   r[   Úaddr]   )Zmany_to_oneZone_to_manyre   rd   r)   r)   r*   r   ¡  s    r   c                 C   s0   t jdtdd� t| ttfƒs"| S ttt| ƒƒS )a  Converts lists to tuples.

    .. deprecated:: 2.8

       to_tuple is deprecated and will be removed in NetworkX 3.0.

    Examples
    --------
    >>> from networkx.utils import to_tuple
    >>> a_list = [1, 2, [1, 4]]
    >>> to_tuple(a_list)
    (1, 2, (1, 4))
    z;to_tuple is deprecated and will be removed in NetworkX 3.0.r?   r@   )r!   r"   r#   r$   r4   r7   Úmapr   )rB   r)   r)   r*   r   ·  s    ýr   c                 C   st   ddl }| du s| |ju r$|jjjS t| |jjƒr6| S t| tƒrL|j | ¡S t| |jjƒr^| S | › d�}t|ƒ‚dS )a  Returns a numpy.random.RandomState or numpy.random.Generator instance
    depending on input.

    Parameters
    ----------
    random_state : int or NumPy RandomState or Generator instance, optional (default=None)
        If int, return a numpy.random.RandomState instance set with seed=int.
        if `numpy.random.RandomState` instance, return it.
        if `numpy.random.Generator` instance, return it.
        if None or numpy.random, return the global random number generator used
        by numpy.random.
    r   NzW cannot be used to create a numpy.random.RandomState or
numpy.random.Generator instance)	rX   ÚrandomÚmtrandÚ_randr$   ÚRandomStater8   Ú	Generatorr9   )Úrandom_staterb   r(   r)   r)   r*   r   Ð  s    

ÿr   c                   @   sh   e Zd Zddd„Zdd„ Zdd„ Zddd	„Zd
d„ Zdd„ Zdd„ Z	dd„ Z
dd„ Zdd„ Zdd„ ZdS )r   Nc                 C   sP   zdd l }W n" ty.   d}t |t¡ Y n0 |d u rF|jjj| _n|| _d S )Nr   z.numpy not found, only random.random available.)	rX   ÚImportErrorr!   r"   ÚImportWarningrs   rt   ru   Ú_rng)ÚselfÚrngrb   r(   r)   r)   r*   Ú__init__ï  s    zPythonRandomInterface.__init__c                 C   s
   | j  ¡ S r.   ©r{   rs   )r|   r)   r)   r*   rs   û  s    zPythonRandomInterface.randomc                 C   s   ||| | j  ¡   S r.   r   )r|   rg   ro   r)   r)   r*   Úuniformþ  s    zPythonRandomInterface.uniformc                 C   s4   dd l }t| j|jjƒr&| j ||¡S | j ||¡S ©Nr   ©rX   r$   r{   rs   rw   ÚintegersÚrandint©r|   rg   ro   rb   r)   r)   r*   Ú	randrange  s    zPythonRandomInterface.randrangec                 C   sF   dd l }t| j|jjƒr,| j dt|ƒ¡}n| j dt|ƒ¡}|| S r�   )rX   r$   r{   rs   rw   rƒ   r-   r„   )r|   Úseqrb   Úidxr)   r)   r*   Úchoice
  s
    zPythonRandomInterface.choicec                 C   s   | j  ||¡S r.   )r{   Únormal)r|   ÚmuÚsigmar)   r)   r*   Úgauss  s    zPythonRandomInterface.gaussc                 C   s   | j  |¡S r.   )r{   Úshuffle)r|   r‡   r)   r)   r*   rŽ     s    zPythonRandomInterface.shufflec                 C   s   | j jt|ƒ|fdd�S )NF)ÚsizeÚreplace)r{   r‰   r7   )r|   r‡   rd   r)   r)   r*   Úsample  s    zPythonRandomInterface.samplec                 C   s<   dd l }t| j|jjƒr*| j ||d ¡S | j ||d ¡S )Nr   é   r‚   r…   r)   r)   r*   r„     s    zPythonRandomInterface.randintc                 C   s   | j  d| ¡S )Nr’   )r{   Zexponential)r|   Zscaler)   r)   r*   Úexpovariate'  s    z!PythonRandomInterface.expovariatec                 C   s   | j  |¡S r.   )r{   Zpareto)r|   Úshaper)   r)   r*   Úparetovariate+  s    z#PythonRandomInterface.paretovariate)N)N)Ú__name__Ú
__module__Ú__qualname__r~   rs   r€   r†   r‰   r�   rŽ   r‘   r„   r“   r•   r)   r)   r)   r*   r   î  s   

		r   c                 C   sÂ   ddl }zVddl}| |j u r,t|j jjƒW S t| |j j|j jfƒrLt| ƒW S t| tƒr\| W S W n typ   Y n0 | du s‚| |u rˆ|j	S t| |j
ƒr˜| S t| tƒr¬| 
| ¡S | › d�}t|ƒ‚dS )a«  Returns a random.Random instance depending on input.

    Parameters
    ----------
    random_state : int or random number generator or None (default=None)
        If int, return a random.Random instance set with seed=int.
        if random.Random instance, return it.
        if None or the `random` package, return the global random number
        generator used by `random`.
        if np.random package, return the global numpy random number
        generator wrapped in a PythonRandomInterface class.
        if np.random.RandomState or np.random.Generator instance, return it
        wrapped in PythonRandomInterface
        if a PythonRandomInterface instance, return it
    r   Nz4 cannot be used to generate a random.Random instance)rs   rX   r   rt   ru   r$   rv   rw   ry   Ú_instÚRandomr8   r9   )rx   rs   rb   r(   r)   r)   r*   r   :  s&    






r   c              	   C   sX   t | ƒ}t |ƒ}zt|ƒ}t|ƒ}W n* ttfyN   t |¡}t |¡}Y n0 ||kS )aU  Check if nodes are equal.

    Equality here means equal as Python objects.
    Node data must match if included.
    The order of nodes is not relevant.

    Parameters
    ----------
    nodes1, nodes2 : iterables of nodes, or (node, datadict) tuples

    Returns
    -------
    bool
        True if nodes are equal, False otherwise.
    )r7   r]   r9   rS   Úfromkeys)Znodes1Znodes2Znlist1Znlist2Úd1Úd2r)   r)   r*   r   b  s    
r   c                 C   sŠ  ddl m} |tƒ}|tƒ}d}t| ƒD ]\\}}|d |d  }}|dd… g}	||| v rl|| | |	 }	|	|| |< |	|| |< q(d}
t|ƒD ]\\}
}|d |d  }}|dd… g}	||| v rÖ|| | |	 }	|	|| |< |	|| |< q’||
k� rþdS | ¡ D ]~\}}| ¡ D ]j\}}||v�r0  dS ||| v�rF  dS || | }|D ]&}	| |	¡| |	¡k�rV   dS �qV�q�qdS )aÕ  Check if edges are equal.

    Equality here means equal as Python objects.
    Edge data must match if included.
    The order of the edges is not relevant.

    Parameters
    ----------
    edges1, edges2 : iterables of with u, v nodes as
        edge tuples (u, v), or
        edge tuples with data dicts (u, v, d), or
        edge tuples with keys and data dicts (u, v, k, d)

    Returns
    -------
    bool
        True if edges are equal, False otherwise.
    r   )r   r’   r?   NFT)Úcollectionsr   r]   r;   r[   Úcount)Zedges1Zedges2r   rœ   r�   Zc1ÚeÚure   ÚdataÚc2rf   ZnbrdictZnbrZdatalistZ
d2datalistr)   r)   r*   r   }  s@    

r   c                 C   s$   | j |j ko"| j|jko"| j|jkS )a  Check if graphs are equal.

    Equality here means equal as Python objects (not isomorphism).
    Node, edge and graph data must match.

    Parameters
    ----------
    graph1, graph2 : graph

    Returns
    -------
    bool
        True if graphs are equal, False otherwise.
    )ZadjÚnodesÚgraph)Zgraph1Zgraph2r)   r)   r*   r    ´  s
    
ÿ
ýr    )N)N)N)N)N)N)F)N)N)+Ú__doc__rM   rC   r!   rž   r   r   Úcollections.abcr   r   r   Ú	itertoolsr   r   Znetworkxr:   Ú__all__r	   r
   r   r   r   r   r   r   r   r   r   rQ   r   rT   r   r   r   r   r   r   r   r   r   r   r   r    r)   r)   r)   r*   Ú<module>   sD   !
$ 




F
	
L
(7