B
    Nô`W.  ã               @   s  d Z ddlmZ ddlmZ ddlZddlZddlZddlmZm	Z	 ddl
Zdd„ Zdd	„ Zd
d„ Zd1dd„Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zd2dd„Zd3dd„Zd4dd„Zdd„ Zd d!„ Zd"d#„ Zd5d%d&„Zd'd(„ Zd)d*„ Zd6d+d,„ZG d-d.„ d.ƒZd7d/d0„Z dS )8a  
Miscellaneous Helpers for NetworkX.

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

>>> import networkx
>>> networkx.utils.is_list_of_ints([1, 2, 3])
True
>>> networkx.utils.is_list_of_ints([1, 2, "spam"])
False
é    )Údefaultdict)ÚdequeN)ÚteeÚchainc             C   s   d}t  |t¡ t| tƒS )zCheck if obj is string.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   ú7/tmp/pip-unpacked-wheel-fc63gmtm/networkx/utils/misc.pyÚis_string_like   s    r   c             C   s*   t | dƒrdS yt| ƒ W n
   dS dS )z: Return True if obj is iterable with a well-defined len().Ú__iter__TF)ÚhasattrÚlen)r   r   r   r   Úiterable&   s    
r   c               c   s   dE dH  dS )z$ Return a generator with no members r   Nr   r   r   r   r   Úempty_generator1   s    r   c             C   s^   t | ƒrt| ƒr| S |dkr g }x2| D ]*}t |ƒr:t|ƒrF| |¡ q&t||ƒ q&W |  |¡S )z@ Return flattened version of (possibly nested) iterable object. N)r   r   ÚappendÚflattenÚ	__class__)r   ÚresultÚitemr   r   r   r   6   s    
r   c          	   C   sì   t | tƒstg }x`| D ]X}d|› �}yt|ƒ}W n  tk
rN   t |¡d‚Y nX ||krbt |¡‚| |¡ qW |S xrt| ƒD ]f\}}d|› �}t |tƒrœq~yt|ƒ}W n  tk
rÈ   t |¡d‚Y nX ||krÜt |¡‚|| |< q~W | 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NetworkXErrorr   Ú	enumerate)Úsequencer   ÚiÚerrmsgÚiiZindxr   r   r   Úmake_list_of_intsD   s0    	






r#   c             C   s.   t | tƒsdS x| D ]}t |tƒsdS qW dS )z( Return True if list is a list of ints. FT)r	   r   r   )Zintlistr    r   r   r   Úis_list_of_intsh   s    


r$   c             C   s   d}t  |t¡ t| ƒS )z'Returns the string representation of t.zCmake_str is deprecated and will be removed in 3.0. Use str instead.)r   r   r   r
   )Úxr   r   r   r   Úmake_strr   s    r&   c               C   s   t t ¡ ƒS )z Generate a unique node label.)r
   ÚuuidZuuid1r   r   r   r   Úgenerate_unique_nodey   s    r(   c             C   sD   ddl m} dgdgdgddddgd	œ}|tj | g }||ƒ d
S )z“Opens `filename` using system's default program.

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

    r   )ÚcallÚopenzxdg-openzcmd.exez/CÚstartÚ )ÚdarwinÚlinuxZlinux2Úwin32N)Ú
subprocessr)   ÚsysÚplatform)Úfilenamer)   ZcmdsÚcmdr   r   r   Údefault_opener~   s    	r5   c          	   C   s.   y
t | |ƒS  ttfk
r(   t| |ƒS X 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   Údict_to_numpy_array“   s    
r<   c          
   C   sÊ   ddl }|dkrVt|  ¡ ƒ}x"|  ¡ D ]\}}| | ¡ ¡ q&W tt|tt|ƒƒƒƒ}t|ƒ}| 	||f¡}xX| ¡ D ]L\}}	xB| ¡ D ]6\}
}y| | |
 ||	|f< W qˆ t
k
r¼   Y qˆX qˆW qvW |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)r:   r;   r=   ÚsÚkÚvÚnÚaÚk1r    Zk2Újr   r   r   r6   ž   s    r6   c             C   sr   ddl }|dkr2t|  ¡ ƒ}tt|tt|ƒƒƒƒ}t|ƒ}| |¡}x(| ¡ D ]\}}|| }| | ||< qNW |S )zTConvert a dictionary of numbers to a 1d numpy array
    with optional mapping.

    r   N)	r=   r>   r?   rB   rC   rD   r   rE   r@   )r:   r;   r=   rG   rJ   rK   rL   r    r   r   r   r9   µ   s    
r9   c             C   s$   t | dƒpt | dƒ}t| ƒ| ko"|S )zMReturns True if and only if the given object is an iterator
    object.

    Ú__next__Únext)r   Úiter)r   Zhas_next_attrr   r   r   Úis_iteratorÇ   s    rQ   c             C   s   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::

        >>> arbitrary_element({3, 2, 1})
        1
        >>> arbitrary_element("hello")
        'h'

    This function raises a :exc:`ValueError` if `iterable` is an
    iterator (because the current implementation of this function would
    consume an element from the iterator)::

        >>> iterator = iter([1, 2, 3])
        >>> arbitrary_element(iterator)
        Traceback (most recent call last):
            ...
        ValueError: cannot return an arbitrary item from an iterator

    z0cannot return an arbitrary item from an iterator)rQ   r   rO   rP   )r   r   r   r   Úarbitrary_elementÐ   s    rR   c             C   s   t | dd� dS )zConsume the iterator entirely.r   )ÚmaxlenN)r   )Úiteratorr   r   r   Úconsumeí   s    rU   Fc             C   s:   t | ƒ\}}t|dƒ}|dkr0t|t||fƒƒS t||ƒS )z&s -> (s0, s1), (s1, s2), (s2, s3), ...NT)r   rO   rC   r   )r   ZcyclicrK   ÚbÚfirstr   r   r   Úpairwiseô   s
    
rX   c             C   s4   t tƒ}x"|  ¡ D ]\}}||  |¡ qW 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.

    For example::

        >>> 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: {'d', 'e'}}

    )r   r>   r@   ÚaddrB   )Zmany_to_oneZone_to_manyrI   rH   r   r   r   Úgroupsý   s    rZ   c             C   s    t | ttfƒs| S ttt| ƒƒS )z»Converts lists to tuples.

    For example::

        >>> from networkx.utils import to_tuple
        >>> a_list = [1, 2, [1, 4]]
        >>> to_tuple(a_list)
        (1, 2, (1, 4))

    )r	   Útupler   ÚmapÚto_tuple)r%   r   r   r   r]     s    r]   c             C   sb   ddl }| dks| |jkr$|jjjS t| |jjƒr6| S t| tƒrL|j | ¡S | › d�}t|ƒ‚dS )a£  Returns a numpy.random.RandomState instance depending on input.

    Parameters
    ----------
    random_state : int or RandomState instance or None  optional (default=None)
        If int, return a numpy.random.RandomState instance set with seed=int.
        if numpy.random.RandomState instance, return it.
        if None or numpy.random, return the global random number generator used
        by numpy.random.
    r   Nz? cannot be used to generate a numpy.random.RandomState instance)r=   ÚrandomÚmtrandÚ_randr	   ÚRandomStater   r   )Úrandom_stateÚnpr   r   r   r   Úcreate_random_state$  s    


rd   c               @   s’   e Zd Zyddd„ZW n$ ek
r:   dZe ee¡ Y nX 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 )ÚPythonRandomInterfaceNc             C   s&   dd l }|d kr|jjj| _|| _d S )Nr   )r=   r^   r_   r`   Ú_rng)ÚselfÚrngr=   r   r   r   Ú__init__@  s    zPythonRandomInterface.__init__z.numpy not found, only random.random available.c             C   s
   | j  ¡ S )N)rf   Úrandom_sample)rg   r   r   r   r^   K  s    zPythonRandomInterface.randomc             C   s   ||| | j  ¡   S )N)rf   rj   )rg   rK   rV   r   r   r   ÚuniformN  s    zPythonRandomInterface.uniformc             C   s   | j  ||¡S )N)rf   Úrandint)rg   rK   rV   r   r   r   Ú	randrangeQ  s    zPythonRandomInterface.randrangec             C   s   || j  dt|ƒ¡ S )Nr   )rf   rl   r   )rg   Úseqr   r   r   ÚchoiceT  s    zPythonRandomInterface.choicec             C   s   | j  ||¡S )N)rf   Únormal)rg   ÚmuÚsigmar   r   r   ÚgaussW  s    zPythonRandomInterface.gaussc             C   s   | j  |¡S )N)rf   Úshuffle)rg   rn   r   r   r   rt   Z  s    zPythonRandomInterface.shufflec             C   s   | j jt|ƒ|fdd�S )NF)ÚsizeÚreplace)rf   ro   r   )rg   rn   rH   r   r   r   Úsample`  s    zPythonRandomInterface.samplec             C   s   | j  ||d ¡S )Né   )rf   rl   )rg   rK   rV   r   r   r   rl   c  s    zPythonRandomInterface.randintc             C   s   | j  d| ¡S )Nrx   )rf   Zexponential)rg   Zscaler   r   r   Úexpovariateg  s    z!PythonRandomInterface.expovariatec             C   s   | j  |¡S )N)rf   Zpareto)rg   Úshaper   r   r   Úparetovariatek  s    z#PythonRandomInterface.paretovariate)N)N)Ú__name__Ú
__module__Ú__qualname__ri   ÚImportErrorr   r   r   ÚImportWarningr^   rk   rm   ro   rs   rt   rw   rl   ry   r{   r   r   r   r   re   =  s   
re   c             C   s¶   ddl }yHddl}| |j kr*t|j jjƒS t| |j jƒr@t| ƒS t| tƒrN| S W n tk
rd   Y nX | dksv| |k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 instance, return it wrapped in
        PythonRandomInterface
        if a PythonRandomInterface instance, return it
    r   Nz4 cannot be used to generate a random.Random instance)r^   r=   re   r_   r`   r	   ra   r   Ú_instÚRandomr   r   )rb   r^   rc   r   r   r   r   Úcreate_py_random_statez  s&    




rƒ   )N)N)N)N)F)N)N)!Ú__doc__Úcollectionsr   r   r   r1   r'   Ú	itertoolsr   r   Znetworkxr   r   r   r   r   r#   r$   r&   r(   r5   r<   r6   r9   rQ   rR   rU   rX   rZ   r]   rd   re   rƒ   r   r   r   r   Ú<module>   s8   

$



	
	
=