3
$ßL]w ã               @   sd  d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlmZ ddlZddlZddlZddlZddlZddlZddlZddlZddlmZ ddlZddlZddlmZmZmZmZmZm Z m!Z!m"Z" edƒdd	„ ƒZ#d
d„ Z$G dd„ dƒZ%G dd„ de&ƒZ'G dd„ de(ƒZ)G dd„ de*ƒZ+dd„ Z,dd„ Z-eddd�G dd„ dej.ƒƒZ/eddd�dd„ ƒZ0edd d�d!d"„ ƒZ1d#d$„ Z2d%d&„ Z3edd'd�d(d)„ ƒZ4d¥d,d-„Z5ej6d¦d.d/„ƒZ7d0d1„ Z8d§d3d4„Z9e8fd5d6„Z:edƒd¨d8d9„ƒZ;edƒG d:d;„ d;e&ƒƒZ<ej=ƒ d<d=„ ƒZ>ej?d>ƒZ@i ZAedd?d�d@dA„ ƒZBedƒd©dCdD„ƒZCG dEdF„ dFeDƒZEG dGdH„ dHe&ƒZFdªdIdJ„ZGdKZHedƒdLdM„ ƒZId«dNdO„ZJejKd+fdPdQ„ZLG dRdS„ dSe&ƒZMdTdU„ ZNdVdW„ ZOdXdY„ ZPd¬d[d\„ZQd]d^d_d`daœZRdbdc„ eRjSƒ D ƒZTddde„ ZUdfdg„ ZVdhdi„ ZWdjdk„ ZXdldm„ ZYd­dodp„ZZdqdr„ Z[dsdt„ Z\dudv„ Z]dwdx„ e[e[e\e]dyœZ^dzd{„ Z_d|d}„ Z`d~d„ Zadf f dfd€d�„Zbedƒd‚dƒ„ ƒZcd„ZdedƒG d…d†„ d†e&ƒƒZeej6d‡dˆ„ ƒZfejgehe
jid‰ƒdŠ�fd‹dŒ„Zjd�dŽ„ Zkd�d�„ Zld®d‘d’„Zmd“d”„ Znej6d•d–„ ƒZod¯d—d˜„ZpG d™dš„ dšejqjrƒZsd›dœ„ Ztd�dž„ ZudŸd „ Zvd¡d¢„ Zwd£d¤„ ZxdS )°zî
A collection of utility functions and classes.  Originally, many
(but not all) were from the Python Cookbook -- hence the name cbook.

This module is safe to import from anywhere within matplotlib;
it imports matplotlib only at runtime.
é    N)ÚPath)Ú
WeakMethodé   )Ú
deprecatedÚwarn_deprecatedÚ_rename_parameterÚ_delete_parameterÚ_make_keyword_onlyÚ(_suppress_matplotlib_deprecation_warningÚMatplotlibDeprecationWarningÚmplDeprecationz3.0c             C   sh   t | tƒrdy tjtjd ƒjƒ }|s(d }W n ttt	fk
rH   d }Y nX |d krZt
| ƒS t
| |ƒS | S )Nzaxes.formatter.use_locale)Ú
isinstanceÚbytesÚlocaleÚgetpreferredencodingÚ
matplotlibÚrcParamsÚstripÚ
ValueErrorÚImportErrorÚAttributeErrorÚstr)ÚsZpreferredencoding© r   úA/tmp/pip-install-edjban26/matplotlib/matplotlib/cbook/__init__.pyÚunicode_safe)   s    


r   c             C   s   t jƒ  d S )N)Ú	tracebackÚ	print_exc)Úexcr   r   r   Ú_exception_printerC   s    r   c               @   s0   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
S )Ú
_StrongRefzU
    Wrapper similar to a weakref, but keeping a strong reference to the object.
    c             C   s
   || _ d S )N)Ú_obj)ÚselfÚobjr   r   r   Ú__init__L   s    z_StrongRef.__init__c             C   s   | j S )N)r!   )r"   r   r   r   Ú__call__O   s    z_StrongRef.__call__c             C   s   t |tƒo| j|jkS )N)r   r    r!   )r"   Úotherr   r   r   Ú__eq__R   s    z_StrongRef.__eq__c             C   s
   t | jƒS )N)Úhashr!   )r"   r   r   r   Ú__hash__U   s    z_StrongRef.__hash__N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r$   r%   r'   r)   r   r   r   r   r    G   s
   r    c               @   sL   e Zd ZdZefdd„Zdd„ Zdd„ Zdd	„ Zd
d„ Z	dd„ Z
dd„ ZdS )ÚCallbackRegistrya·  Handle registering and disconnecting for a set of signals and callbacks:

        >>> def oneat(x):
        ...    print('eat', x)
        >>> def ondrink(x):
        ...    print('drink', x)

        >>> from matplotlib.cbook import CallbackRegistry
        >>> callbacks = CallbackRegistry()

        >>> id_eat = callbacks.connect('eat', oneat)
        >>> id_drink = callbacks.connect('drink', ondrink)

        >>> callbacks.process('drink', 123)
        drink 123
        >>> callbacks.process('eat', 456)
        eat 456
        >>> callbacks.process('be merry', 456) # nothing will be called
        >>> callbacks.disconnect(id_eat)
        >>> callbacks.process('eat', 456)      # nothing will be called

    In practice, one should always disconnect all callbacks when they are
    no longer needed to avoid dangling references (and thus memory leaks).
    However, real code in Matplotlib rarely does so, and due to its design,
    it is rather difficult to place this kind of code.  To get around this,
    and prevent this class of memory leaks, we instead store weak references
    to bound methods only, so when the destination object needs to die, the
    CallbackRegistry won't keep it alive.

    Parameters
    ----------
    exception_handler : callable, optional
       If provided must have signature ::

          def handler(exc: Exception) -> None:

       If not None this function will be called with any `Exception`
       subclass raised by the callbacks in `CallbackRegistry.process`.
       The handler may either consume the exception or re-raise.

       The callable must be pickle-able.

       The default handler is ::

          def h(exc):
              traceback.print_exc()
    c             C   s    || _ i | _tjƒ | _i | _d S )N)Úexception_handlerÚ	callbacksÚ	itertoolsÚcountÚ_cid_genÚ_func_cid_map)r"   r/   r   r   r   r$   �   s    
zCallbackRegistry.__init__c             C   s
   d| j iS )Nr/   )r/   )r"   r   r   r   Ú__getstate__�   s    zCallbackRegistry.__getstate__c             C   s   | j f |Ž d S )N)r$   )r"   Ústater   r   r   Ú__setstate__    s    zCallbackRegistry.__setstate__c             C   s�   | j j|i ƒ yt|| jƒ}W n tk
r:   t|ƒ}Y nX || j | krX| j | | S t| jƒ}|| j | |< | jj|i ƒ || j| |< |S )zCRegister *func* to be called when signal *s* is generated.
        )	r4   Ú
setdefaultr   Ú_remove_proxyÚ	TypeErrorr    Únextr3   r0   )r"   r   ÚfuncÚproxyÚcidr   r   r   Úconnect£   s    
zCallbackRegistry.connectc             C   sl   xft | jjƒ ƒD ]T\}}y| j| || = W n tk
r@   Y nX t| j| ƒdkr| j|= | j|= qW d S )Nr   )Úlistr4   Úitemsr0   ÚKeyErrorÚlen)r"   r=   ÚsignalÚproxiesr   r   r   r9   ´   s    zCallbackRegistry._remove_proxyc             C   sŠ   x„t | jjƒ ƒD ]r\}}y
||= W n tk
r8   wY qX xBt | jjƒ ƒD ]0\}}x&t |jƒ ƒD ]\}}||kr`||= q`W qJW dS qW dS )zCDisconnect the callback registered with callback id *cid*.
        N)r@   r0   rA   rB   r4   )r"   r>   Z	eventnameZ	callbackdrD   Z	functionsÚfunctionÚvaluer   r   r   Ú
disconnect¾   s    
zCallbackRegistry.disconnectc             O   s€   xzt | jj|i ƒjƒ ƒD ]`\}}|ƒ }|dk	ry|||Ž W q tk
rv } z| jdk	rd| j|ƒ n‚ W Y dd}~X qX qW dS )z¢
        Process signal *s*.

        All of the functions registered to receive callbacks on *s* will be
        called with ``*args`` and ``**kwargs``.
        N)r@   r0   ÚgetrA   Ú	Exceptionr/   )r"   r   ÚargsÚkwargsr>   Úrefr<   r   r   r   r   ÚprocessÍ   s     
zCallbackRegistry.processN)r*   r+   r,   r-   r   r$   r5   r7   r?   r9   rH   rN   r   r   r   r   r.   Y   s   /
r.   c               @   s6   e Zd ZdZddd„Zdd„ ZeZdd„ Zd	d
„ ZdS )Úsilent_listz±
    override repr when returning a list of matplotlib artists to
    prevent long, meaningless output.  This is meant to be used for a
    homogeneous list of a given type
    Nc             C   s   || _ |d k	r| j|ƒ d S )N)ÚtypeÚextend)r"   rP   Úseqr   r   r   r$   è   s    zsilent_list.__init__c             C   s   dt | ƒ| jf S )Nz<a list of %d %s objects>)rC   rP   )r"   r   r   r   Ú__repr__í   s    zsilent_list.__repr__c             C   s   | j | d d … dœS )N)rP   rR   )rP   )r"   r   r   r   r5   ò   s    zsilent_list.__getstate__c             C   s   |d | _ | j|d ƒ d S )NrP   rR   )rP   rQ   )r"   r6   r   r   r   r7   ö   s    
zsilent_list.__setstate__)N)	r*   r+   r,   r-   r$   rS   Ú__str__r5   r7   r   r   r   r   rO   â   s   
rO   c               @   s   e Zd ZdZdS )ÚIgnoredKeywordWarningze
    A class for issuing warnings about keyword arguments that will be ignored
    by matplotlib
    N)r*   r+   r,   r-   r   r   r   r   rU   û   s   rU   c             G   sF   | }x<|D ]4}|j |dƒ}|dk	r
|dkr0|}q
td| tƒ q
W |S )a	  
    Enforces the priority of a local variable over potentially conflicting
    argument(s) from a kwargs dict. The following possible output values are
    considered in order of priority:

        local_var > kwargs[keys[0]] > ... > kwargs[keys[-1]]

    The first of these whose value is not None will be returned. If all are
    None then None will be returned. Each key in keys will be removed from the
    kwargs dict in place.

    Parameters
    ----------
        local_var : any object
            The local variable (highest priority)

        kwargs : dict
            Dictionary of keyword arguments; modified in place

        keys : str(s)
            Name(s) of keyword arguments to process, in descending order of
            priority

    Returns
    -------
        out : any object
            Either local_var or one of kwargs[key] for key in keys

    Raises
    ------
        IgnoredKeywordWarning
            For each key in keys that is removed from kwargs but not used as
            the output value

    Nz%"%s" keyword argument will be ignored)ÚpopÚ_warn_externalrU   )Z	local_varrL   ÚkeysÚoutÚkeyZ	kwarg_valr   r   r   Úlocal_over_kwdict  s    $

r[   c          
   C   sZ   t | ƒdkrV| d | d   ko&dkn  rV| dd… } xdD ]\}}| j||ƒ} q>W | S )zi
    Remove latex formatting from mathtext.

    Only handles fully math and fully non-math strings.
    é   r   r   ú$ú\timesÚxú\mathdefaultÚ ú\rmú\calú\ttú\itú\Ú{Ú}éÿÿÿÿri   ©r^   r_   ©r`   ra   ©rb   ra   ©rc   ra   ©rd   ra   ©re   ra   ©rf   ra   ©rg   ra   ©rh   ra   )	rj   rk   rl   rm   rn   ro   rp   rq   rr   )rC   Úreplace)r   ZtexÚplainr   r   r   Ú
strip_math3  s    ,        ru   ztypes.SimpleNamespace)Úalternativec               @   s   e Zd ZdZdS )ÚBunchaH  
    Often we want to just collect a bunch of stuff together, naming each
    item of the bunch; a dictionary's OK for that, but a small do- nothing
    class is even handier, and prettier to use.  Whenever you want to
    group a few variables::

      >>> point = Bunch(datum=2, squared=4, coord=12)
      >>> point.datum
    N)r*   r+   r,   r-   r   r   r   r   rw   J  s   
rw   z3.1znp.iterablec             C   s&   yt | ƒ W n tk
r    dS X dS )z return true if *obj* is iterableFT)Úiterr:   )r#   r   r   r   ÚiterableX  s
    ry   z)isinstance(..., collections.abc.Hashable)c             C   s&   yt | ƒ W n tk
r    dS X dS )z#Returns true if *obj* can be hashedFT)r(   r:   )r#   r   r   r   Úis_hashableb  s
    rz   c             C   s   t t| ddƒƒS )zDReturn whether *obj* looks like a file object with a *write* method.ÚwriteN)ÚcallableÚgetattr)r#   r   r   r   Úis_writable_file_likel  s    r~   c             C   s,   y| j dƒ W n tk
r"   dS X dS dS )zf
    Return whether the given writable file-like object requires Unicode to be
    written to it.
    ó    TFN)r{   r:   )r_   r   r   r   Úfile_requires_unicodeq  s
    r€   zisinstance(..., numbers.Number)c             C   s   t | tjtjfƒS )z(return true if *obj* looks like a number)r   ÚnumbersÚNumberÚnpÚnumber)r#   r   r   r   Ú
is_numlike~  s    r…   ÚrFc             C   s°   t | tjƒrtj| ƒ} t | tƒr„| jdƒrD|jddƒ}tj| |ƒ}n:| jdƒrpddl	}|jddƒ}|j
| |ƒ}nt| ||d�}d}nt| d	ƒr˜| }d
}ntdƒ‚|r¬||fS |S )aa  
    Convert a path to an open file handle or pass-through a file-like object.

    Consider using `open_file_cm` instead, as it allows one to properly close
    newly created file objects more easily.

    Parameters
    ----------
    fname : str or PathLike or file-like object
        If `str` or `os.PathLike`, the file is opened using the flags specified
        by *flag* and *encoding*.  If a file-like object, it is passed through.
    flag : str, default 'r'
        Passed as the *mode* argument to `open` when *fname* is `str` or
        `os.PathLike`; ignored if *fname* is file-like.
    return_opened : bool, default False
        If True, return both the file object and a boolean indicating whether
        this was a new file (that the caller needs to close).  If False, return
        only the new file.
    encoding : str or None, default None
        Passed as the *mode* argument to `open` when *fname* is `str` or
        `os.PathLike`; ignored if *fname* is file-like.

    Returns
    -------
    fh : file-like
    opened : bool
        *opened* is only returned if *return_opened* is True.
    z.gzÚUra   z.bz2r   N)ÚencodingTÚseekFz'fname must be a PathLike or file handle)r   ÚosÚPathLikeÚfspathr   Úendswithrs   ÚgzipÚopenÚbz2ÚBZ2FileÚhasattrr   )ÚfnameÚflagZreturn_openedrˆ   Úfhr�   Úopenedr   r   r   Úto_filehandle„  s&    




r—   c          	   c   s8   t | |d|ƒ\}}|r.|� |V  W dQ R X n|V  dS )z;Pass through file objects and context-manage `.PathLike`\s.TN)r—   )Zpath_or_fileÚmoderˆ   r•   r–   r   r   r   Úopen_file_cm¼  s
    r™   c             C   s   t | tƒptj| ƒ S )z;Return whether the given object is a scalar or string like.)r   r   rƒ   ry   )Úvalr   r   r   Úis_scalar_or_stringÇ  s    r›   Tc             C   s˜   t jtjdƒrtjd }ntjjtjƒ dƒ}tjj|| ƒ}|r�tjj| ƒd j	ƒ dkr\d}nd}tjj| ƒ\}}|d	kr„t
j||ƒS t||ƒS n|S d
S )aÿ  
    Return a sample data file.  *fname* is a path relative to the
    `mpl-data/sample_data` directory.  If *asfileobj* is `True`
    return a file object, otherwise just a file path.

    Set the rc parameter examples.directory to the directory where we should
    look, if sample_data files are stored in a location different than
    default (which is 'mpl-data/sample_data` at the same level of 'matplotlib`
    Python module files).

    If the filename ends in .gz, the file is implicitly ungzipped.
    zexamples.directoryZsample_datar   ú.csvú.xrcú.txtr†   Úrbz.gzNri   )rœ   r�   rž   )ÚdictÚ__getitem__r   r   rŠ   ÚpathÚjoinZ_get_data_pathÚsplitextÚlowerrŽ   r�   )r“   Z	asfileobjÚrootr¢   r˜   ÚbaseÚextr   r   r   Úget_sample_dataÌ  s    r©   c             c   s:   x4| D ],}||ƒs|dkr"|V  qt ||ƒE dH  qW dS )a¦  
    Return a generator of flattened nested containers

    For example:

        >>> from matplotlib.cbook import flatten
        >>> l = (('John', ['Hunter']), (1, 23), [[([42, (5, 23)], )]])
        >>> print(list(flatten(l)))
        ['John', 'Hunter', 1, 23, 42, 5, 23]

    By: Composite of Holger Krekel and Luther Blissett
    From: https://code.activestate.com/recipes/121294/
    and Recipe 1.12 in cookbook
    N)Úflatten)rR   ZscalarpÚitemr   r   r   rª   ï  s    
rª   éÿ  c             C   s   t j| |dd� dS )z‡
    make directory *newdir* recursively, and set *mode*.  Equivalent to ::

        > mkdir -p NEWDIR
        > chmod MODE NEWDIR
    T)r˜   Úexist_okN)rŠ   Úmakedirs)Znewdirr˜   r   r   r   Úmkdirs  s    
r¯   c               @   s   e Zd Zdd„ Zdd„ ZdS )ÚGetRealpathAndStatc             C   s
   i | _ d S )N)Ú_cache)r"   r   r   r   r$     s    zGetRealpathAndStat.__init__c             C   s\   | j j|ƒ}|d krXtjj|ƒ}tjdkr0|}ntj|ƒ}|j|j	f}||f}|| j |< |S )NÚwin32)
r±   rI   rŠ   r¢   ÚrealpathÚsysÚplatformÚstatÚst_inoÚst_dev)r"   r¢   Úresultr³   Ústat_keyr¶   r   r   r   r%     s    


zGetRealpathAndStat.__call__N)r*   r+   r,   r$   r%   r   r   r   r   r°     s   r°   c             C   s*   t jj| ƒ}t j|ƒ}|j|jf}||fS )N)rŠ   r¢   r³   r¶   r·   r¸   )r¢   r³   r¶   rº   r   r   r   Úget_realpath_and_stat%  s    
r»   z(?:(?:\n\r?)|^)( *)\Szinspect.cleandocc             C   s|   | sdS t j| ƒ}|dkr| S |jdƒ|jdƒ }|dkr>| S tj|dƒ}|dkrhtjd| ƒ}|t|< |jd| ƒj	ƒ }|S )a¦  
    Remove excess indentation from docstring *s*.

    Discards any leading blank lines, then removes up to n whitespace
    characters from each line, where n is the number of leading
    whitespace characters in the first line. It differs from
    textwrap.dedent in its deletion of leading blank lines and its use
    of the first non-blank line to determine the indentation.

    It is also faster in most cases.
    ra   Nr   r   z

? {0,%d}Ú
)
Ú_find_dedent_regexÚmatchÚendÚstartÚ_dedent_regexrI   ÚreÚcompileÚsubr   )r   r¾   ZnshiftZunindentr¹   r   r   r   Údedent5  s    
rÅ   Ú*c             C   sœ   ddl }ddl}|jdƒ}g }xx|j| ƒD ]j\}}	}
xX|
D ]P}|jj|jj||ƒƒ}|sd|jj|ƒr:x$|D ]}|j||ƒrj|j|ƒ P qjW q:W |s*P q*W |S )zU
    Recursively list files

    from Parmar and Martelli in the Python Cookbook
    r   Nú;)	Úos.pathÚfnmatchÚsplitÚwalkr¢   Únormpathr£   ÚisfileÚappend)r¦   ÚpatternsÚrecurseZreturn_foldersrŠ   rÉ   Zpattern_listÚresultsÚdirnameÚdirsÚfilesÚnameÚfullnameÚpatternr   r   r   Ú	listFiles^  s    




rØ   c               @   s    e Zd ZdZdd„ Zdd„ ZdS )Úmaxdictz›
    A dictionary with a maximum size; this doesn't override all the
    relevant methods to constrain the size, just setitem, so use with
    caution
    c             C   s   t j| ƒ || _g | _d S )N)r    r$   ÚmaxsizeÚ	_killkeys)r"   rÚ   r   r   r   r$   �  s    
zmaxdict.__init__c             C   sH   || kr6t | ƒ| jkr*| | jd = | jd= | jj|ƒ tj| ||ƒ d S )Nr   )rC   rÚ   rÛ   rÎ   r    Ú__setitem__)r"   ÚkÚvr   r   r   rÜ   †  s    zmaxdict.__setitem__N)r*   r+   r,   r-   r$   rÜ   r   r   r   r   rÙ   {  s   rÙ   c               @   sr   e Zd Z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d„ Zdd„ Zdd„ Zdd„ ZdS )ÚStackzb
    Stack of elements with a movable cursor.

    Mimics home/back/forward in a web browser.
    Nc             C   s   | j ƒ  || _d S )N)ÚclearÚ_default)r"   Údefaultr   r   r   r$   –  s    zStack.__init__c             C   s    t | jƒs| jS | j| j S dS )z$Return the current element, or None.N)rC   Ú	_elementsrá   Ú_pos)r"   r   r   r   r%   š  s    
zStack.__call__c             C   s
   t | jƒS )N)rC   rã   )r"   r   r   r   Ú__len__¡  s    zStack.__len__c             C   s
   | j | S )N)rã   )r"   Úindr   r   r   r¡   ¤  s    zStack.__getitem__c             C   s"   t | jd t| jƒd ƒ| _| ƒ S )z9Move the position forward and return the current element.r   )Úminrä   rC   rã   )r"   r   r   r   Úforward§  s    zStack.forwardc             C   s   | j dkr|  j d8  _ | ƒ S )z6Move the position back and return the current element.r   r   )rä   )r"   r   r   r   Úback¬  s    
z
Stack.backc             C   s2   | j d| jd … |g | _ t| j ƒd | _| ƒ S )zs
        Push *o* to the stack at current position.  Discard all later elements.

        *o* is returned.
        Nr   )rã   rä   rC   )r"   Úor   r   r   Úpush²  s    z
Stack.pushc             C   s$   t | jƒsdS | j| jd ƒ | ƒ S )zk
        Push the first element onto the top of the stack.

        The first element is returned.
        Nr   )rC   rã   rë   )r"   r   r   r   Úhome¼  s    
z
Stack.homec             C   s   t | jƒdkS )z"Return whether the stack is empty.r   )rC   rã   )r"   r   r   r   ÚemptyÇ  s    zStack.emptyc             C   s   d| _ g | _dS )zEmpty the stack.r   Nri   )rä   rã   )r"   r   r   r   rà   Ë  s    zStack.clearc             C   st   || j krtdƒ‚| j dd… }| jƒ  g }x*|D ]"}||krJ|j|ƒ q2| j|ƒ q2W x|D ]}| j|ƒ q^W |S )zq
        Raise *o* to the top of the stack.  *o* must be present in the stack.

        *o* is returned.
        zUnknown element oN)rã   r   rà   rÎ   rë   )r"   rê   ÚoldZbubblesÚthisoÚ_r   r   r   ÚbubbleÐ  s    


zStack.bubblec             C   sL   || j krtdƒ‚| j dd… }| jƒ  x|D ]}||kr.| j|ƒ q.W dS )zRemove *o* from the stack.zUnknown element oN)rã   r   rà   rë   )r"   rê   rî   rï   r   r   r   Úremoveä  s    

zStack.remove)N)r*   r+   r,   r-   r$   r%   rå   r¡   rè   ré   rë   rì   rí   rà   rñ   rò   r   r   r   r   rß   �  s   

rß   c             C   s  dd„ }t jƒ }tjdkrD|ddd| ddgd	ƒ}t|d jƒ ƒ}n¼tjdkr||ddd| ddgdƒ}t|d
 jƒ d
 ƒ}n„tjdkr´|ddd| ddgdƒ}t|d
 jƒ d ƒ}nLtjdkrò|dddd| gdƒ}t|jƒ jƒ d jddƒƒ}ntdtj ƒ‚|S )z*Return the memory consumed by the process.c             S   s:   y
t j| ƒS  t jk
r4   td|| d f ƒ‚Y nX d S )Nz;report_memory works on %s only if the '%s' program is foundr   )Ú
subprocessÚcheck_outputÚCalledProcessErrorÚNotImplementedError)ÚcommandÚos_namer   r   r   Úcallñ  s    
zreport_memory.<locals>.callZsunos5Zpsz-pz%dz-oZoszzSun OSr   Úlinuxzrss,szÚLinuxÚdarwinzrss,vszzMac OSr   r²   Ztasklistz/nhz/fiz	pid eq %dÚWindowsr\   ú,ra   z%We don't have a memory monitor for %sri   éþÿÿÿ)	rŠ   Úgetpidr´   rµ   Úintr   rÊ   rs   rö   )Úirù   ÚpidÚlinesZmemr   r   r   Úreport_memoryï  s"    	



r  z0In safezip, len(args[0])=%d but len(args[%d])=%dc              G   s\   t | d ƒ}xBt| dd… ƒD ].\}}t |ƒ|krtt||d t |ƒf ƒ‚qW tt| Ž ƒS )z-make sure *args* are equal len before zippingr   r   N)rC   Ú	enumerater   Ú_safezip_msgr@   Úzip)rK   ZNxr  Úargr   r   r   Úsafezip  s
    r
  c             C   s^   t j| d|d�} | jjs(| j|ƒjdƒ} yt jj| dd�}|jƒ  W n t	k
rX   | S X |S )NT)ZsubokÚcopyÚSF)r  )
rƒ   ÚarrayÚdtypeZisnativeZbyteswapZnewbyteorderÚmaZmasked_invalidZshrink_maskr:   )r_   r  Zxmr   r   r   Úsafe_masked_invalid  s    r  c                s\   ddl ‰ ‡fdd„‰‡ ‡‡‡‡‡fdd„‰x,ˆD ]$}ˆjd|›d�ƒ ˆ||i g ƒ q0W dS )	aY  
    *objects*
        A list of objects to find cycles in.  It is often useful to
        pass in gc.garbage to find the cycles that are preventing some
        objects from being garbage collected.

    *outstream*
        The stream for output.

    *show_progress*
        If True, print the number of objects reached as they are found.
    r   Nc                sî   xÞt | ƒD ]Ò\}}| |d t| ƒ  }ˆ jdt|ƒ ƒ t|tƒrŽxŽ|jƒ D ]<\}}||krnˆ jdj|ƒƒ P ||krLˆ jdj|ƒƒ P qLW nDt|tƒr®ˆ jd|j	|ƒ ƒ n$t|t
ƒrÄˆ jdƒ nˆ jt|ƒƒ ˆ jdƒ q
W ˆ jdƒ d S )	Nr   z	   %s -- z[{!r}]z[key] = {!r}z[%d]z	( tuple )z ->
r¼   )r  rC   r{   rP   r   r    rA   Úformatr@   ÚindexÚtupleÚrepr)r¢   r  Ústepr;   rZ   rš   )Ú	outstreamr   r   Ú
print_path:  s$    


z print_cycles.<locals>.print_pathc                sˆ   ˆrˆj dt|ƒ ƒ d |t| ƒ< ˆ j| ƒ}xV|D ]N}||krHˆ|ƒ q2|ˆks2t|tjƒr`q2q2t|ƒ|kr2ˆ||||| g ƒ q2W d S )Nz%d)r{   rC   ÚidZget_referentsr   ÚtypesÚ	FrameType)r#   rÀ   ÚallÚcurrent_pathZ	referentsZreferent)ÚgcÚobjectsr  r  rÐ   Úshow_progressr   r   rÐ   Q  s    


zprint_cycles.<locals>.recursezExamining: r¼   )r  r{   )r  r  r  r#   r   )r  r  r  r  rÐ   r  r   Úprint_cycles+  s    
r   c               @   sT   e Zd ZdZf f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 )ÚGroupera  
    This class provides a lightweight way to group arbitrary objects
    together into disjoint sets when a full-blown graph data structure
    would be overkill.

    Objects can be joined using :meth:`join`, tested for connectedness
    using :meth:`joined`, and all disjoint sets can be retrieved by
    using the object as an iterator.

    The objects being joined must be hashable and weak-referenceable.

    For example:

        >>> from matplotlib.cbook import Grouper
        >>> class Foo(object):
        ...     def __init__(self, s):
        ...         self.s = s
        ...     def __repr__(self):
        ...         return self.s
        ...
        >>> a, b, c, d, e, f = [Foo(x) for x in 'abcdef']
        >>> grp = Grouper()
        >>> grp.join(a, b)
        >>> grp.join(b, c)
        >>> grp.join(d, e)
        >>> sorted(map(tuple, grp))
        [(a, b, c), (d, e)]
        >>> grp.joined(a, b)
        True
        >>> grp.joined(a, c)
        True
        >>> grp.joined(a, d)
        False

    c             C   s   dd„ |D ƒ| _ d S )Nc             S   s    i | ]}t j|ƒgt j|ƒ“qS r   )ÚweakrefrM   )Ú.0r_   r   r   r   ú
<dictcomp>’  s    z$Grouper.__init__.<locals>.<dictcomp>)Ú_mapping)r"   Úinitr   r   r   r$   ‘  s    zGrouper.__init__c             C   s   t j|ƒ| jkS )N)r"  rM   r%  )r"   r«   r   r   r   Ú__contains__”  s    zGrouper.__contains__c             C   s:   | j }dd„ |D ƒ}x |D ]}|j|ƒ}|j|ƒ qW dS )z/Clean dead weak references from the dictionary.c             S   s   g | ]}|ƒ d kr|‘qS )Nr   )r#  rZ   r   r   r   ú
<listcomp>š  s    z!Grouper.clean.<locals>.<listcomp>N)r%  rV   rò   )r"   ÚmappingZto_droprZ   rš   r   r   r   Úclean—  s
    

zGrouper.cleanc             G   s–   | j }|jtj|ƒtj|ƒgƒ}xh|D ]`}|jtj|ƒtj|ƒgƒ}||k	r&t|ƒt|ƒkrf|| }}|j|ƒ x|D ]}|||< qvW q&W | jƒ  dS )zY
        Join given arguments into the same set.  Accepts one or more arguments.
        N)r%  r8   r"  rM   rI   rC   rQ   r*  )r"   ÚarK   r)  Úset_ar	  Zset_bÚelemr   r   r   r£   Ÿ  s    



zGrouper.joinc             C   s0   | j ƒ  | jjtj|ƒtƒ ƒ| jjtj|ƒƒkS )z7Return whether *a* and *b* are members of the same set.)r*  r%  rI   r"  rM   Úobject)r"   r+  Úbr   r   r   Újoined±  s    zGrouper.joinedc             C   s4   | j ƒ  | jjtj|ƒd ƒ}|r0|jtj|ƒƒ d S )N)r*  r%  rV   r"  rM   rò   )r"   r+  r,  r   r   r   rò   ·  s    zGrouper.removec             c   sB   | j ƒ  dd„ | jjƒ D ƒ}x |jƒ D ]}dd„ |D ƒV  q&W dS )z‰
        Iterate over each of the disjoint sets as a list.

        The iterator is invalid if interleaved with calls to join().
        c             S   s   i | ]}|t |ƒ“qS r   )r  )r#  Úgroupr   r   r   r$  Ä  s    z$Grouper.__iter__.<locals>.<dictcomp>c             S   s   g | ]
}|ƒ ‘qS r   r   )r#  r_   r   r   r   r(  Æ  s    z$Grouper.__iter__.<locals>.<listcomp>N)r*  r%  Úvalues)r"   Zunique_groupsr1  r   r   r   Ú__iter__½  s    zGrouper.__iter__c             C   s2   | j ƒ  | jjtj|ƒtj|ƒgƒ}dd„ |D ƒS )z:Return all of the items joined with *a*, including itself.c             S   s   g | ]
}|ƒ ‘qS r   r   )r#  r_   r   r   r   r(  Ì  s    z(Grouper.get_siblings.<locals>.<listcomp>)r*  r%  rI   r"  rM   )r"   r+  Zsiblingsr   r   r   Úget_siblingsÈ  s    zGrouper.get_siblingsN)r*   r+   r,   r-   r$   r'  r*  r£   r0  rò   r3  r4  r   r   r   r   r!  m  s   #r!  c                st   | j t| ƒdfƒ}tjt| ƒƒ| ‰tjt| ƒd | d ƒ‰ tj‡ ‡fdd„|jD ƒƒj tˆ ƒf| jdd…  ƒS )av  
    Resample an array with ``steps - 1`` points between original point pairs.

    Parameters
    ----------
    a : array, shape (n, ...)
    steps : int

    Returns
    -------
    array, shape ``((n - 1) * steps + 1, ...)``

    Along each column of *a*, ``(steps - 1)`` points are introduced between
    each original values; the values are linearly interpolated.
    r   c                s   g | ]}t jˆ ˆ|ƒ‘qS r   )rƒ   Zinterp)r#  Úfp)r_   Úxpr   r   r(  â  s    z/simple_linear_interpolation.<locals>.<listcomp>Nri   )ÚreshaperC   rƒ   ÚarangeZcolumn_stackÚTÚshape)r+  ÚstepsZfpsr   )r_   r6  r   Úsimple_linear_interpolationÏ  s
    r<  c        
      G   sð  t | ƒsf S t| d ƒr tdƒ‚t | d ƒ}g }dgt | ƒ }xtt| ƒD ]h\}}t|tƒ r¦tj|ƒr¦t |ƒ|kr¦d||< t|tjj	ƒrœ|j
dkr¦tdƒ‚n
tj|ƒ}|j|ƒ qHW g }x–t|ƒD ]Š\}}|| rÂ|j
dkrÞqÂt|tjj	ƒ�r
|jtjj|ƒ ƒ |j}n|}y&tj|ƒ}t|tjƒ�r2|j|ƒ W qÂ tk
�rJ   Y qÂX qÂW t |ƒ�r®tjj|ƒ}|jƒ d }	t |	ƒ|k �r®x,t|ƒD ] \}}|| �rŠ||	 ||< �qŠW x<t|ƒD ]0\}}|| �r¸t|tjj	ƒ�r¸|jƒ ||< �q¸W |S )an  
    Find all masked and/or non-finite points in a set of arguments,
    and return the arguments with only the unmasked points remaining.

    Arguments can be in any of 5 categories:

    1) 1-D masked arrays
    2) 1-D ndarrays
    3) ndarrays with more than one dimension
    4) other non-string iterables
    5) anything else

    The first argument must be in one of the first four categories;
    any argument with a length differing from that of the first
    argument (and hence anything in category 5) then will be
    passed through unchanged.

    Masks are obtained from all arguments of the correct length
    in categories 1, 2, and 4; a point is bad if masked in a masked
    array or if it is a nan or inf.  No attempt is made to
    extract a mask from categories 2, 3, and 4 if :meth:`np.isfinite`
    does not yield a Boolean array.

    All input arguments that are not passed unchanged are returned
    as ndarrays after removing the points or rows corresponding to
    masks in any of the arguments.

    A vastly simpler version of this function was originally
    written as a helper for Axes.scatter().

    r   z!First argument must be a sequenceFTr   zMasked arrays must be 1-D)rC   r›   r   r  r   r   rƒ   ry   r  ÚMaskedArrayÚndimÚasarrayrÎ   ÚgetmaskarrayÚdataÚisfiniteÚndarrayrJ   Úlogical_andÚreduceÚnonzeroÚfilled)
rK   ÚnrecsÚmargsÚseqlistr  r_   ÚmasksZxdÚmaskZigoodr   r   r   Údelete_masked_pointsæ  sR     "







rM  c              G   s4  t | ƒsf S t| d ƒr tdƒ‚t | d ƒ}g }dgt | ƒ }g }x t| ƒD ]”\}}t|ƒsht |ƒ|krt|j|ƒ qLt|tjjƒr”|j	dkr”tdƒ‚tj
|ƒ}|j	dkrÖt|ƒ}d||< tjj|ƒrÖ|jtjj|ƒƒ |j|ƒ qLW t |ƒ�r0tjj|ƒ}x4t|ƒD ](\}}|| �rtjj||d�||< �qW |S )a{  
    Find all masked and/or non-finite points in a set of arguments,
    and return the arguments as masked arrays with a common mask.

    Arguments can be in any of 5 categories:

    1) 1-D masked arrays
    2) 1-D ndarrays
    3) ndarrays with more than one dimension
    4) other non-string iterables
    5) anything else

    The first argument must be in one of the first four categories;
    any argument with a length differing from that of the first
    argument (and hence anything in category 5) then will be
    passed through unchanged.

    Masks are obtained from all arguments of the correct length
    in categories 1, 2, and 4; a point is bad if masked in a masked
    array or if it is a nan or inf.  No attempt is made to
    extract a mask from categories 2 and 4 if :meth:`np.isfinite`
    does not yield a Boolean array.  Category 3 is included to
    support RGB or RGBA ndarrays, which are assumed to have only
    valid values and which are passed through unchanged.

    All input arguments that are not passed unchanged are returned
    as masked arrays if any masked points are found, otherwise as
    ndarrays.

    r   z!First argument must be a sequenceFr   zMasked arrays must be 1-DT)rL  )rC   r›   r   r  rÎ   r   rƒ   r  r=  r>  Ú
asanyarrayr  Z	is_maskedr@  Ú
logical_orrE  r  )rK   rH  rI  rJ  rK  r  r_   rL  r   r   r   Ú_combine_masks3  s4    



rP  ç      ø?c                sÚ  ddd„‰ ‡ fdd„}g }t | dƒ} t| ƒ}|dkr@tjdƒ}nt|ƒ|krTtdƒ‚|}�xztt| |ƒƒD �]f\}	\}
}i }|dk	rŒ||d	< |}|j|ƒ t|
ƒd
k�rtj	g ƒ|d< tj
|d< tj
|d< tj
|d< tj
|d< tj
|d< tj
|d< tj
|d< tj
|d< tj
|d< qjtj|
ƒ}
tj|
ƒ|d< tj|
dddgƒ\}}}|| |d< |d d
k�rf|�rfd}||
||d |ƒ\|d< |d< tj|ƒ�rètj|ƒ�r¾|||d   }|||d   }n(|dk�rÞtj|
ƒ}tj|
ƒ}ntdƒ‚n tj|
|d
 ƒ}tj|
|d ƒ}|
|
|k }t|ƒd
k�s2tj|ƒ|k �r<||d< ntj|ƒ|d< |
|
|k }t|ƒd
k�sttj|ƒ|k�r~||d< ntj|ƒ|d< tj|
|
|d k  |
|
|d k gƒ|d< |||  |d< |d< |d< qjW |S ) aG  
    Returns list of dictionaries of statistics used to draw a series
    of box and whisker plots. The `Returns` section enumerates the
    required keys of the dictionary. Users can skip this function and
    pass a user-defined set of dictionaries to the new `axes.bxp` method
    instead of relying on MPL to do the calculations.

    Parameters
    ----------
    X : array-like
        Data that will be represented in the boxplots. Should have 2 or
        fewer dimensions.

    whis : float, string, or sequence (default = 1.5)
        As a float, determines the reach of the whiskers beyond the
        first and third quartiles. In other words, where IQR is the
        interquartile range (`Q3-Q1`), the upper whisker will extend to last
        datum less than `Q3 + whis*IQR`. Similarly, the lower whisker will
        extend to the first datum greater than `Q1 - whis*IQR`.
        Beyond the whiskers, data are considered outliers
        and are plotted as individual points. This can be set to an
        ascending sequence of percentiles (e.g., [5, 95]) to set the
        whiskers at specific percentiles of the data. Finally, `whis`
        can be the string ``'range'`` to force the whiskers to the
        minimum and maximum of the data. In the edge case that the 25th
        and 75th percentiles are equivalent, `whis` can be automatically
        set to ``'range'`` via the `autorange` option.

    bootstrap : int, optional
        Number of times the confidence intervals around the median
        should be bootstrapped (percentile method).

    labels : array-like, optional
        Labels for each dataset. Length must be compatible with
        dimensions of `X`.

    autorange : bool, optional (False)
        When `True` and the data are distributed such that the 25th and 75th
        percentiles are equal, ``whis`` is set to ``'range'`` such that the
        whisker ends are at the minimum and maximum of the data.

    Returns
    -------
    bxpstats : list of dict
        A list of dictionaries containing the results for each column
        of data. Keys of each dictionary are the following:

        ========   ===================================
        Key        Value Description
        ========   ===================================
        label      tick label for the boxplot
        mean       arithmetic mean value
        med        50th percentile
        q1         first quartile (25th percentile)
        q3         third quartile (75th percentile)
        cilo       lower notch around the median
        cihi       upper notch around the median
        whislo     end of the lower whisker
        whishi     end of the upper whisker
        fliers     outliers
        ========   ===================================

    Notes
    -----
    Non-bootstrapping approach to confidence interval uses Gaussian-
    based asymptotic approximation:

    .. math::

        \mathrm{med} \pm 1.57 \times \frac{\mathrm{iqr}}{\sqrt{N}}

    General approach from:
    McGill, R., Tukey, J.W., and Larsen, W.A. (1978) "Variations of
    Boxplots", The American Statistician, 32:12-16.

    éˆ  c             S   sL   t | ƒ}ddg}tjj|||fd�}| | }tj|ddd�}tj||ƒ}|S )Ng      @g     `X@)Úsizer   T)ÚaxisZoverwrite_input)rC   rƒ   ÚrandomÚrandintÚmedianÚ
percentile)rA  ÚNÚMZpercentilesZbs_indexZbsDataZestimateÚCIr   r   r   Ú_bootstrap_median¾  s    z(boxplot_stats.<locals>._bootstrap_medianc                sb   |d k	r&ˆ | |d�}|d }|d }n4t | ƒ}|d| tj|ƒ  }|d| tj|ƒ  }||fS )N)rY  r   r   g…ëQ¸ù?)rC   rƒ   Úsqrt)rA  ÚmedÚiqrÚ	bootstrapr[  Z	notch_minZ	notch_maxrY  )r\  r   r   Ú_compute_conf_intervalÊ  s    
z-boxplot_stats.<locals>._compute_conf_intervalÚXNz-Dimensions of labels and X must be compatibleÚlabelr   ZfliersÚmeanr^  Úq1Úq3ZciloZcihiZwhisloZwhishié   é2   éK   r_  ÚrangeÚlimitÚlimitsúmin/maxz:whis must be a float, valid string, or list of percentilesr   )rR  )rj  rk  rl  rm  )Ú_reshape_2DrC   r1   Úrepeatr   r  r  rÎ   rƒ   r  Únanr?  rd  rX  ZisscalarZisrealrç   ÚmaxZhstack)rb  Zwhisr`  ÚlabelsZ	autorangera  ZbxpstatsZncolsZ
input_whisÚiir_   rc  Ústatsre  r^  rf  ZlovalZhivalZwiskhiZwisklor   )r\  r   Úboxplot_statso  sv    O

 















 ru  ZsolidZdashedZdashdotZdotted)ú-z--z-.ú:c             C   s   i | ]\}}||“qS r   r   )r#  rÝ   rÞ   r   r   r   r$  @  s    r$  c             C   s’   t j| td�} | jsg S t j| dd… | dd… kƒ\}|d7 }|jƒ }| d rZdg| }| d rp|jt| ƒƒ tt	|ddd… |ddd… ƒƒS )zq
    Return a list of (ind0, ind1) such that mask[ind0:ind1].all() is
    True and we cover all such regions
    )r  Nr   r   r\   ri   ri   )
rƒ   r?  ÚboolrS  rF  ÚtolistrÎ   rC   r@   r  )rL  Úidxr   r   r   Úcontiguous_regionsC  s     
r{  c             C   s4   t | ƒ} | jdƒ| jdƒ }|dko.|d dk}|S )Nr]   z\$r   r\   )r   r2   )r   Zdollar_countZeven_dollarsr   r   r   Úis_math_text]  s    r|  c             C   s0   t | dƒr tjj| tƒjtjƒS tj| tƒS dS )zt
    Convert a sequence to a float array; if input was a masked array, masked
    values are converted to nans.
    rL  N)r’   rƒ   r  r?  ÚfloatrG  rp  )r_   r   r   r   Ú_to_unmasked_float_arrayf  s    
r~  c             C   s\   t | dƒ st| jƒdk r$tj| ƒS y| dd…df  | S  ttfk
rV   tj| ƒS X dS )zy
    Converts a sequence of less than 1 dimension, to an array of 1
    dimension; leaves everything else untouched.
    r:  r   N)r’   rC   r:  rƒ   Ú
atleast_1dÚ
IndexErrorr:   )r_   r   r   r   Ú	_check_1dq  s    
r�  c             C   s€   t jt| t jƒr| jnt j| ƒƒ} t| ƒdkr4g gS | jdkrVt j| d ƒdkrV| gS | jdkrndd„ | D ƒS tdj	|ƒƒ‚dS )	a…  
    Use Fortran ordering to convert ndarrays and lists of iterables to lists of
    1D arrays.

    Lists of iterables are converted by applying `np.asarray` to each of their
    elements.  1D ndarrays are returned in a singleton list containing them.
    2D ndarrays are converted to the list of their *columns*.

    *name* is used to generate the error message for invalid inputs.
    r   r   r\   c             S   s   g | ]}t j|dƒ‘qS )r   ri   )rƒ   r7  )r#  r_   r   r   r   r(  ”  s    z_reshape_2D.<locals>.<listcomp>z"{} must have 2 or fewer dimensionsN)r   r\   )
rƒ   r  r   rC  r9  r?  rC   r>  r   r  )rb  rÕ   r   r   r   rn  €  s    "
rn  éd   c       	      C   s’   g }t | dƒ} x~| D ]v}i }tj|ƒ}tj|ƒ}tj|||ƒ}|||ƒ|d< ||d< tj|ƒ|d< tj|ƒ|d< ||d< ||d< |j|ƒ qW |S )a7  
    Returns a list of dictionaries of data which can be used to draw a series
    of violin plots. See the `Returns` section below to view the required keys
    of the dictionary. Users can skip this function and pass a user-defined set
    of dictionaries to the `axes.vplot` method instead of using MPL to do the
    calculations.

    Parameters
    ----------
    X : array-like
        Sample data that will be used to produce the gaussian kernel density
        estimates. Must have 2 or fewer dimensions.

    method : callable
        The method used to calculate the kernel density estimate for each
        column of data. When called via `method(v, coords)`, it should
        return a vector of the values of the KDE evaluated at the values
        specified in coords.

    points : scalar, default = 100
        Defines the number of points to evaluate each of the gaussian kernel
        density estimates at.

    Returns
    -------

    A list of dictionaries containing the results for each column of data.
    The dictionaries contain at least the following:

        - coords: A list of scalars containing the coordinates this particular
          kernel density estimate was evaluated at.
        - vals: A list of scalars containing the values of the kernel density
          estimate at each of the coordinates given in `coords`.
        - mean: The mean value for this column of data.
        - median: The median value for this column of data.
        - min: The minimum value for this column of data.
        - max: The maximum value for this column of data.
    rb  ÚvalsÚcoordsrd  rW  rç   rq  )rn  rƒ   rç   rq  Zlinspacerd  rW  rÎ   )	rb  ÚmethodZpointsZvpstatsr_   rt  Zmin_valZmax_valr„  r   r   r   Úviolin_stats™  s    )



r†  c             G   sœ   t jdt|ƒ tdt| ƒ d dƒfƒ}| |dddd…f< |dddd…f |dddd…f< ||dd…ddd…f< |dd…ddd…f |dd…ddd…f< |S )a-  
    Convert continuous line to pre-steps.

    Given a set of ``N`` points, convert to ``2N - 1`` points, which when
    connected linearly give a step function which changes values at the
    beginning of the intervals.

    Parameters
    ----------
    x : array
        The x location of the steps. May be empty.

    y1, ..., yp : array
        y arrays to be turned into steps; all must be the same length as ``x``.

    Returns
    -------
    out : array
        The x and y values converted to steps in the same order as the input;
        can be unpacked as ``x_out, y1_out, ..., yp_out``.  If the input is
        length ``N``, each of these arrays will be length ``2N + 1``. For
        ``N=0``, the length will be 0.

    Examples
    --------
    >> x_s, y1_s, y2_s = pts_to_prestep(x, y1, y2)
    r   r\   r   Nrÿ   )rƒ   ÚzerosrC   rq  )r_   rK   r;  r   r   r   Úpts_to_prestepà  s    ( (rˆ  c             G   sœ   t jdt|ƒ tdt| ƒ d dƒfƒ}| |dddd…f< |dddd…f |dddd…f< ||dd…ddd…f< |dd…ddd…f |dd…ddd…f< |S )a(  
    Convert continuous line to post-steps.

    Given a set of ``N`` points convert to ``2N + 1`` points, which when
    connected linearly give a step function which changes values at the end of
    the intervals.

    Parameters
    ----------
    x : array
        The x location of the steps. May be empty.

    y1, ..., yp : array
        y arrays to be turned into steps; all must be the same length as ``x``.

    Returns
    -------
    out : array
        The x and y values converted to steps in the same order as the input;
        can be unpacked as ``x_out, y1_out, ..., yp_out``.  If the input is
        length ``N``, each of these arrays will be length ``2N + 1``. For
        ``N=0``, the length will be 0.

    Examples
    --------
    >> x_s, y1_s, y2_s = pts_to_poststep(x, y1, y2)
    r   r\   r   Nrÿ   )rƒ   r‡  rC   rq  )r_   rK   r;  r   r   r   Úpts_to_poststep  s    ( (r‰  c             G   sÖ   t jdt|ƒ dt| ƒ fƒ}t j| ƒ} | dd… | dd…  d  |dddd…f< |dddd…f< | dd… |ddd…f< | dd… |ddd…f< ||dd…ddd…f< |dd…ddd…f |dd…ddd…f< |S )	aý  
    Convert continuous line to mid-steps.

    Given a set of ``N`` points convert to ``2N`` points which when connected
    linearly give a step function which changes values at the middle of the
    intervals.

    Parameters
    ----------
    x : array
        The x location of the steps. May be empty.

    y1, ..., yp : array
        y arrays to be turned into steps; all must be the same length as
        ``x``.

    Returns
    -------
    out : array
        The x and y values converted to steps in the same order as the input;
        can be unpacked as ``x_out, y1_out, ..., yp_out``.  If the input is
        length ``N``, each of these arrays will be length ``2N``.

    Examples
    --------
    >> x_s, y1_s, y2_s = pts_to_midstep(x, y1, y2)
    r   r\   Nr   ri   ri   ri   ri   )rƒ   r‡  rC   rN  )r_   rK   r;  r   r   r   Úpts_to_midstep*  s    
<(rŠ  c             C   s   | |fS )Nr   )r_   Úyr   r   r   Ú<lambda>P  s    rŒ  )râ   r;  z	steps-prez
steps-postz	steps-midc             C   sD   y| j j| jfS  tk
r>   t| ƒ} tj| jd td�| fS X dS )aÝ  
    A helper function to get the index of an input to plot
    against if x values are not explicitly given.

    Tries to get `y.index` (works if this is a pd.Series), if that
    fails, return np.arange(y.shape[0]).

    This will be extended in the future to deal with more types of
    labeled data.

    Parameters
    ----------
    y : scalar or array-like
        The proposed y-value

    Returns
    -------
    x, y : ndarray
       The x and y values to plot.
    r   )r  N)r  r2  r   r�  rƒ   r8  r:  r}  )r‹  r   r   r   Úindex_ofW  s
    r�  c             C   s@   t | tjjƒr4y| d S  tk
r*   Y nX tdƒ‚tt| ƒƒS )Nr   z/matplotlib does not support generators as input)r   ÚcollectionsÚabcÚIteratorr:   ÚRuntimeErrorr;   rx   )r#   r   r   r   Úsafe_first_elements  s    r’  c             C   s   t | tjjƒrt| ƒS | S )z Converts dictview object to list)r   rŽ  r�  ÚMappingViewr@   )rA  r   r   r   Úsanitize_sequenceƒ  s    r”  c                s”  |dkrt ƒ }t | ƒ} t ƒ ‰xÚ|jƒ D ]Î\}}g }g }x@|D ]8}	y|j| j|	ƒƒ |j|	ƒ W q< tk
rr   Y q<X q<W ||kr´y|j| j|ƒƒ |j|ƒ W n tk
r²   Y nX |r&|d ˆ|< t|ƒdkr&tdd|›d|›d|d ›d�d� q&W ˆj| ƒ ‡fd	d
„|D ƒ}
|
�r*tdj	|
d�ƒ‚‡fdd
„|D ƒ}
|
�rRtdj	|
d�ƒ‚|dk	�r�||™‰ ‡ fdd
„ˆD ƒ}
|
�r�tdj	|
||d�ƒ‚ˆS )aR  Helper function to normalize kwarg inputs

    The order they are resolved are:

     1. aliasing
     2. required
     3. forbidden
     4. allowed

    This order means that only the canonical names need appear in
    `allowed`, `forbidden`, `required`

    Parameters
    ----------

    alias_mapping, dict, optional
        A mapping between a canonical name to a list of
        aliases, in order of precedence from lowest to highest.

        If the canonical value is not in the list it is assumed to have
        the highest priority.

    required : iterable, optional
        A tuple of fields that must be in kwargs.

    forbidden : iterable, optional
        A list of keys which may not be in kwargs

    allowed : tuple, optional
        A tuple of allowed fields.  If this not None, then raise if
        `kw` contains any keys not in the union of `required`
        and `allowed`.  To allow only the required fields pass in
        ``()`` for `allowed`

    Raises
    ------
    TypeError
        To match what python raises if invalid args/kwargs are passed to
        a callable.

    Nr   z3.1zSaw kwargs z which are all aliases for z.  Kept value from zU.  Passing multiple aliases for the same property will raise a TypeError %(removal)s.)Úmessagec                s   g | ]}|ˆ kr|‘qS r   r   )r#  rÝ   )Úretr   r   r(  à  s    z$normalize_kwargs.<locals>.<listcomp>z,The required keys {keys!r} are not in kwargs)rX   c                s   g | ]}|ˆ kr|‘qS r   r   )r#  rÝ   )r–  r   r   r(  å  s    z)The forbidden keys {keys!r} are in kwargsc                s   g | ]}|ˆ kr|‘qS r   r   )r#  rÝ   )Úallowed_setr   r   r(  ì  s    zXkwargs contains {keys!r} which are not in the required {req!r} or allowed {allow!r} keys)rX   ÚreqZallowri   ri   )
r    rA   rÎ   rV   rB   rC   r   Úupdater:   r  )ÚkwZalias_mappingÚrequiredÚ	forbiddenÚallowedÚ	canonicalZ
alias_listÚtmpÚseenr+  Z	fail_keysr   )r—  r–  r   Únormalize_kwargs‰  sR    ,

&



r¡  c             C   s    y| j S  tk
r   |S X d S )N)rÕ   r   )r‹  Údefault_namer   r   r   Ú	get_labelö  s    r£  zêLOCKERROR: matplotlib is trying to acquire the lock
    {!r}
and has failed.  This maybe due to any other process holding this
lock.  If you are sure no other matplotlib process is running try
removing these folders and trying again.
c               @   s<   e Zd ZdZdZG dd„ deƒZdd„ Zdd„ Zd	d
„ Z	dS )ÚLockeda<  
    Context manager to handle locks.

    Based on code from conda.

    (c) 2012-2013 Continuum Analytics, Inc. / https://www.continuum.io/
    All Rights Reserved

    conda is distributed under the terms of the BSD 3-clause license.
    Consult LICENSE_CONDA or https://opensource.org/licenses/BSD-3-Clause.
    z.matplotlib_lockc               @   s   e Zd ZdS )zLocked.TimeoutErrorN)r*   r+   r,   r   r   r   r   ÚTimeoutError  s   r¥  c             C   sT   || _ dttjƒ ƒ | _tj j| j | j| j ƒ| _tj j| j | jd ƒ| _d| _	d S )Nrv  z-*T)
r¢   r   rŠ   r   r¿   r£   ÚLOCKFNÚ	lock_pathr×   rò   )r"   r¢   r   r   r   r$     s
    zLocked.__init__c             C   s–   d}d}xV|rHt j | jƒ}|rD|d j| jƒ rDtj|ƒ |d8 }q
P q
W tj| jƒ}| j|ƒ‚|sŒyt	j
| jƒ W q’ tk
rˆ   Y q’X nd| _d S )Nrh  gš™™™™™¹?r   r   F)Úglobr×   r�   r¿   ÚtimeÚsleepÚ_lockstrr  r¥  rŠ   r®   r§  ÚOSErrorrò   )r"   ÚretriesÚ	sleeptimerÔ   Úerr_strr   r   r   Ú	__enter__   s     


zLocked.__enter__c             C   sD   | j r@x8| j| jfD ](}ytj|ƒ W q tk
r:   Y qX qW d S )N)rò   r§  r¢   rŠ   Úrmdirr¬  )r"   Úexc_typeÚ	exc_valuer   r¢   r   r   r   Ú__exit__6  s    zLocked.__exit__N)
r*   r+   r,   r-   r¦  r‘  r¥  r$   r°  r´  r   r   r   r   r¤    s   r¤  c             c   s–   t | ƒ} | j| jd ƒ}d}d}xZt|ƒD ]@}y|jdƒ� P W dQ R X W q* tk
rh   tj|ƒ Y q*X q*W tdj	|ƒƒ‚z
dV  W d|j
ƒ  X dS )af  
    Context manager for locking a path.

    Usage::

        with _lock_path(path):
            ...

    Another thread or process that attempts to lock the same path will wait
    until this context manager is exited.

    The lock is implemented by creating a temporary file in the parent
    directory, so that directory must exist and be writable.
    z.matplotlib-lockrh  gš™™™™™¹?ÚxbNzÛLock error: Matplotlib failed to acquire the following lock file:
    {}
This maybe due to another process holding this lock file.  If you are sure no
other Matplotlib process is running, remove this file and try again.)r   Z	with_namerÕ   rj  r�   ÚFileExistsErrorr©  rª  r¥  r  Úunlink)r¢   r§  r­  r®  rð   r   r   r   Ú
_lock_path?  s     
r¸  Zzorder)rZ   c             C   s   |t | ƒƒS )zýGet the topmost artist of a list.

    In case of a tie, return the *last* of the tied artists, as it will be
    drawn on top of the others. `max` returns the first maximum in case of
    ties, so we need to iterate over the list in reverse order.
    )Úreversed)ZartistsZ_cached_maxr   r   r   Ú_topmost_artistf  s    	rº  c             C   s   t | tƒo| |kS )zÿReturn whether *obj* is a string equal to string *s*.

    This helper solely exists to handle the case where *obj* is a numpy array,
    because in such cases, a naive ``obj == s`` would yield an array, which
    cannot be used in a boolean context.
    )r   r   )r#   r   r   r   r   Ú
_str_equalr  s    r»  c             C   s   t | tƒo| jƒ |kS )a  Return whether *obj* is a string equal, when lowercased, to string *s*.

    This helper solely exists to handle the case where *obj* is a numpy array,
    because in such cases, a naive ``obj == s`` would yield an array, which
    cannot be used in a boolean context.
    )r   r   r¥   )r#   r   r   r   r   Ú_str_lower_equal|  s    r¼  c       	         sÎ   ˆ dkrt jt| ƒS ‡ fdd„}x�| jƒ D ]„\}}d}xddD ]\}|| tˆ ƒkr<d}xB|D ]:}||| ƒ}|| |_dj|| ƒ|_tˆ || |ƒ qZW q<W |s*t	d	j|ƒƒ‚q*W t
ˆ d
ƒrÄtdƒ‚| ˆ _ˆ S )aR  Class decorator for defining property aliases.

    Use as ::

        @cbook._define_aliases({"property": ["alias", ...], ...})
        class C: ...

    For each property, if the corresponding ``get_property`` is defined in the
    class so far, an alias named ``get_alias`` will be defined; the same will
    be done for setters.  If neither the getter nor the setter exists, an
    exception will be raised.

    The alias map is stored as the ``_alias_map`` attribute on the class and
    can be used by `~.normalize_kwargs` (which assumes that higher priority
    aliases come last).
    Nc                s    t jtˆˆ ƒƒ‡ fdd„ƒ}|S )Nc                s   t | ˆ ƒ||ŽS )N)r}   )r"   rK   rL   )rÕ   r   r   r…  ›  s    z3_define_aliases.<locals>.make_alias.<locals>.method)Ú	functoolsÚwrapsr}   )rÕ   r…  )Úcls)rÕ   r   Ú
make_aliasš  s    z#_define_aliases.<locals>.make_aliasFÚget_Úset_TzAlias for `{}`.z)Neither getter nor setter exists for {!r}Ú
_alias_mapz$Parent class already defines aliases)rÁ  rÂ  )r½  ÚpartialÚ_define_aliasesrA   Úvarsr*   r  r-   Úsetattrr   r’   rö   rÃ  )	Zalias_dr¿  rÀ  ÚpropÚaliasesÚexistsÚprefixÚaliasr…  r   )r¿  r   rÅ  †  s(    



rÅ  c             C   sP   t jdd… }t jddd… }t j| d|f | |df | d|f | |df fƒS )a]  
    Get the elements on the perimeter of ``arr``,

    Parameters
    ----------
    arr : ndarray, shape (M, N)
        The input array

    Returns
    -------
    perimeter : ndarray, shape (2*(M - 1) + 2*(N - 1),)
        The elements on the perimeter of the array::

            [arr[0,0] ... arr[0,-1] ... arr[-1, -1] ... arr[-1,0] ...]

    Examples
    --------
    >>> i, j = np.ogrid[:3,:4]
    >>> a = i*10 + j
    >>> a
    array([[ 0,  1,  2,  3],
           [10, 11, 12, 13],
           [20, 21, 22, 23]])
    >>> _array_perimeter(a)
    array([ 0,  1,  2,  3, 13, 23, 22, 21, 20, 10])
    r   r   ri   ri   ri   ri   ri   )rƒ   Zs_Zconcatenate)Zarrrè   Zbackwardr   r   r   Ú_array_perimeterµ  s    


rÍ  c             +   s€   t ƒ ‰‡ ‡fdd„|D ƒ}z,x |jƒ D ]\}}tˆ ||ƒ q&W dV  W dx0|D ](\}}|ˆkrjtˆ |ƒ qNtˆ ||ƒ qNW X dS )zMTemporarily set some attributes; restore original state at context exit.
    c                s   g | ]}|t ˆ |ˆƒf‘qS r   )r}   )r#  Úattr)r#   Úsentinelr   r   r(  á  s    z_setattr_cm.<locals>.<listcomp>N)r.  rA   rÇ  Údelattr)r#   rL   ZorigsrÎ  rš   Úorigr   )r#   rÏ  r   Ú_setattr_cmÜ  s    
rÒ  c             C   sV   t jƒ }x:tjdƒD ],}|dkr"P tjd|jjddƒƒs:P |j}qW t	j
| ||ƒ dS )a6  
    `warnings.warn` wrapper that sets *stacklevel* to "outside Matplotlib".

    The original emitter of the warning can be obtained by patching this
    function back to `warnings.warn`, i.e. ``cbook._warn_external =
    warnings.warn`` (or ``functools.partial(warnings.warn, stacklevel=2)``,
    etc.).
    r   Nz"\A(matplotlib|mpl_toolkits)(\Z|\.)r*   ra   )r´   Ú	_getframer1   r2   rÂ   r¾   Ú	f_globalsrI   Úf_backÚwarningsÚwarn)r•  ÚcategoryÚframeÚ
stacklevelr   r   r   rW   î  s    	
rW   c               @   s<   e Zd Zdd„ Zdd„ Zdd„ Zdd„ Zd	d
„ Zdd„ ZdS )Ú_OrderedSetc             C   s   t jƒ | _d S )N)rŽ  ÚOrderedDictÚ_od)r"   r   r   r   r$     s    z_OrderedSet.__init__c             C   s
   || j kS )N)rÝ  )r"   rZ   r   r   r   r'    s    z_OrderedSet.__contains__c             C   s
   t | jƒS )N)rx   rÝ  )r"   r   r   r   r3    s    z_OrderedSet.__iter__c             C   s
   t | jƒS )N)rC   rÝ  )r"   r   r   r   rå     s    z_OrderedSet.__len__c             C   s   | j j|d ƒ d | j |< d S )N)rÝ  rV   )r"   rZ   r   r   r   Úadd  s    z_OrderedSet.addc             C   s   | j j|d ƒ d S )N)rÝ  rV   )r"   rZ   r   r   r   Údiscard  s    z_OrderedSet.discardN)	r*   r+   r,   r$   r'  r3  rå   rÞ  rß  r   r   r   r   rÛ    s   rÛ  c             C   s’   t j| tjdkrddddgn
ddddgdd�}|ddd
…f }|d }|dk}x>t j|dƒD ].}|| jtƒd	 || d  ||  ||< q\W |S )zS
    Convert a premultiplied ARGB32 buffer to an unmultiplied RGBA8888 buffer.
    Úlittler\   r   r   é   )rT  .Néÿ   ri   ri   ).ri   ri   )rƒ   Útaker´   Ú	byteorderZrollaxisZastyper  )ÚbufZrgbaZrgbÚalpharL  Zchannelr   r   r   Ú._premultiplied_argb32_to_unmultiplied_rgba8888  s    (rç  c             C   s¢   t jdkrDtj| ddddgdd�}|ddd…f }|ddd…f }n8tj| ddddgdd�}|ddd…f }|ddd…f }|jƒ d	kržtj||d	 |d
d� |S )zS
    Convert an unmultiplied RGBA8888 buffer to a premultiplied ARGB32 buffer.
    rà  r\   r   r   rá  )rT  .Nrâ  Zunsafe)rY   Zcastingri   ri   )r´   rä  rƒ   rã  rç   Úmultiply)Zrgba8888Zargb32Zrgb24Zalpha8r   r   r   Ú._unmultiplied_rgba8888_to_premultiplied_argb32/  s    
ré  c             K   s‚   |j dt| ƒƒ tj| ftjtjdœ|—Ž}|jr`tdt| ƒ› d|jjdƒ› d|j	jdƒ› �ƒ‚|j d|jƒ |j d|j	ƒ |jS )	aj  
    Run *command*, returning its stdout output if it succeeds.

    If it fails (exits with nonzero return code), raise an exception whose text
    includes the failed command and captured stdout and stderr output.

    Regardless of the return code, the command is logged at DEBUG level on
    *logger*.  In case of success, the output is likewise logged.
    z%s)ÚstdoutÚstderrzThe command
    z,
failed and generated the following output:
zutf-8z
and the following error:
z
stdout:
%sz
stderr:
%s)
Údebugr   ró   ÚrunÚPIPEÚ
returncoder‘  rê  Údecoderë  )r÷   ÚloggerrL   Úprocr   r   r   Ú_check_and_log_subprocessC  s    
,ró  c              K   s6   x0| j ƒ D ]$\}}t|tjƒr
td|›d�ƒ‚q
W dS )zl
    If any value in *kwargs* is a `np.matrix`, raise a TypeError with the key
    name in its message.
    z	Argument z cannot be a np.matrixN)rA   r   rƒ   Zmatrixr:   )rL   rÝ   rÞ   r   r   r   Ú_check_not_matrix]  s    rô  c          	   K   s@   x:|j ƒ D ].\}}|| kr
tdj||djtt| ƒƒƒƒ‚q
W dS )zç
    For each *key, value* pair in *kwargs*, check that *value* is in *values*;
    if not, raise an appropriate ValueError.

    Examples
    --------
    >>> cbook._check_in_list(["foo", "bar"], arg=arg, other_arg=other_arg)
    z9{!r} is not a valid value for {}; supported values are {}z, N)rA   r   r  r£   Úmapr  )r2  rL   rÝ   rÞ   r   r   r   Ú_check_in_listg  s
    	rö  )r†   FN)r†   N)T)r¬   )rÆ   r   r   )r   )F)rQ  NNF)r‚  )N)N)yr-   rŽ  Úcollections.abcÚ
contextlibr½  r¨  rŽ   r1   r   r�   ÚoperatorrŠ   Zpathlibr   rÂ   ró   r´   r©  r   r  rÖ  r"  r   Znumpyrƒ   r   Údeprecationr   r   r   r   r	   r
   r   r   r   r   r    r.  r.   r@   rO   ÚUserWarningrU   r[   ru   ÚSimpleNamespacerw   ry   rz   r~   r€   r…   r—   Úcontextmanagerr™   r›   r©   rª   r¯   r°   Ú	lru_cacher»   rÃ   r½   rÁ   rÅ   rØ   r    rÙ   rß   r  r  r
  r  rê  r   r!  r<  rM  rP  ru  Z	ls_mapperrA   Zls_mapper_rr{  r|  r~  r�  rn  r†  rˆ  r‰  rŠ  ZSTEP_LOOKUP_MAPr�  r’  r”  r¡  r£  r«  r¤  r¸  rÄ  rq  Ú
attrgetterrº  r»  r¼  rÅ  rÍ  rÒ  rW   r�  Ú
MutableSetrÛ  rç  ré  ró  rô  rö  r   r   r   r   Ú<module>   sÚ   ( 
0



8

#
)`


BbM< 
 P	
G&$&l7)



/'

