U
    f»{jL2  ã                   @   sZ  d Z ddlm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	m
Z
mZ ddlm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 dd
lmZ ddlmZmZmZ d4dd„Zd5dd„Zdd„ Z G dd„ dƒZ!G dd„ de"ƒZ#dd„ Z$dd„ Z%ed6d d!„ƒZ&ed7d#d$„ƒZ'd8d&d'„Z(d(d)„ Z)d*d+„ Z*d,d-„ Z+d.d/„ Z,d9d0d1„Z-d2d3„ Z.dS ):z%Some miscellaneous utility functions.é    )ÚcontextmanagerN)Úlog)ÚQueueÚEmpty)Ú	Formatter)ÚThreadé   )Ú_check_optionÚ_validate_type)Ú	_get_argsé   )ÚloggerÚverboseÚwarnÚ Úsc                 C   s,   t | ttjfƒr| nt| ƒ}|dkr(|S |S )z#Determine if plural should be used.r   )Ú
isinstanceÚintÚnpZgenericÚlen)ÚxZnon_plÚplZlen_x© r   úM/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/utils/misc.pyÚ_pl   s    r   éÿÿÿÿú> c                 C   s\   t  ¡ \}}}t t |¡| |… ¡}d |¡ d¡t ||¡ }d| d|  |¡ }|S )zExplain an exception.r   Ú
ú:
)ÚsysÚexc_infoÚ	tracebackÚformat_listÚ
extract_tbÚjoinÚsplitÚformat_exception_only)ÚstartÚstopÚprefixÚetypeÚvalueÚtbÚstringr   r   r   Ú_explain_exception!   s    
ÿr.   c                    s6   t |  ¡ ƒ‰ t dd„ ˆ D ƒ¡}‡ fdd„|D ƒ‰ ˆ S )zSort and return keys of dict.c                 S   s   g | ]}t |ƒ‘qS r   ©Ústr)Ú.0Úkr   r   r   Ú
<listcomp>/   s     z_sort_keys.<locals>.<listcomp>c                    s   g | ]}ˆ | ‘qS r   r   )r1   Úii©Úkeysr   r   r3   0   s     )Úlistr6   r   Zargsort)r   Úidxr   r5   r   Ú
_sort_keys,   s    r9   c                   @   s"   e Zd ZdZdd„ Zddd„ZdS )	Ú_DefaultEventParserzParse none standard events.c                 C   s   t ƒ | _d S ©N)ÚdictÚ	event_ids)Úselfr   r   r   Ú__init__7   s    z_DefaultEventParser.__init__r   c                 C   s(   || j kr|t| j ƒ | j |< | j | S r;   )r=   r   )r>   ÚdescriptionÚoffsetr   r   r   Ú__call__:   s    
z_DefaultEventParser.__call__N)r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r?   rB   r   r   r   r   r:   4   s   r:   c                   @   s   e Zd ZdZdd„ ZdS )Ú_FormatDictzHelp pformat() work properly.c                 C   s   d| d S )NÚ{Ú}r   )r>   Úkeyr   r   r   Ú__missing__D   s    z_FormatDict.__missing__N)rC   rD   rE   rF   rK   r   r   r   r   rG   A   s   rG   c                 K   s   t ƒ }t|ƒ}| | d|¡S )zqFormat a template string partially.

    Examples
    --------
    >>> pformat("{a}_{b}", a='x')
    'x_{b}'
    r   )r   rG   Úvformat)ÚtempÚfmtÚ	formatterÚmappingr   r   r   ÚpformatH   s    rQ   c                 C   s    t | jdƒD ]}| |¡ qd S )Nó    )ÚiterÚreadlineÚput)ÚoutÚqueueÚliner   r   r   Ú_enqueue_outputU   s    rY   Fc                 O   s¦  d}d}t ƒ }t ƒ }t| f|ž|Ž��}	|	j��  |	j�î tt|	j|fd�}
tt|	j|fd�}d|
_d|_|
 ¡  | ¡  |	 ¡ dk	}z|j	dd�}W n t
k
r®   Y qÎY q†X | d¡}t |¡ ||7 }q†z|j	dd�}W n t
k
rø   Y �qY qÎX | d¡}t |¡ ||7 }qÎ|rz�q"qzW 5 Q R X W 5 Q R X W 5 Q R X ||f}|�r\||	jf }nF|	j�r¢t|ƒ tjj}dt|ƒk�r”t |	j| |¡‚nt |	j| ¡‚|S )	a–  Run command using subprocess.Popen.

    Run command and wait for command to complete. If the return code was zero
    then return, otherwise raise CalledProcessError.
    By default, this will also add stdout= and stderr=subproces.PIPE
    to the call to Popen to suppress printing to the terminal.

    Parameters
    ----------
    command : list of str | str
        Command to run as subprocess (see subprocess.Popen documentation).
    return_code : bool
        If True, return the return code instead of raising an error if it's
        non-zero.

        .. versionadded:: 0.20
    %(verbose)s
    *args, **kwargs : arguments
        Additional arguments to pass to subprocess.Popen.

    Returns
    -------
    stdout : str
        Stdout returned by the process.
    stderr : str
        Stderr returned by the process.
    code : int
        The return code, only returned if ``return_code == True``.
    r   )ÚtargetÚargsTNg{®Gáz„?)Útimeoutzutf-8Úoutput)r   Úrunning_subprocessÚstdoutÚstderrr   rY   Údaemonr'   ÚpollÚgetr   Údecoder   ÚinfoÚwarningÚ
returncodeÚprintÚ
subprocessÚCalledProcessErrorr?   r   )ÚcommandZreturn_coder   r[   ÚkwargsZall_outZall_errZout_qZerr_qÚpZout_tZerr_tZdo_breakrV   Úerrr]   Zerr_funr   r   r   Úrun_subprocessZ   sL    &






$ro   Úwaitc              	   o   sJ  t |tdƒ td|ddddgƒ dtjgdtjgfD ]\}}||kr4tj||< q4| dt	j
¡}td	d
„ |d  t	j¡D ƒƒr„tdƒ t| tƒr”| }n"dd„ | D ƒ} d dd
„ | D ƒ¡}t d| ¡ ztj| f|ž|Ž}	W nH tk
�r"   t| tƒ�r|  ¡ d }
n| d }
t d|
 ¡ ‚ Y nX z
|	V  W 5 t|	|ƒƒ  |	 ¡  X dS )a¶  Context manager to do something with a command running via Popen.

    Parameters
    ----------
    command : list of str | str
        Command to run as subprocess (see :class:`python:subprocess.Popen`).
    after : str
        Can be:

        - "wait" to use :meth:`~python:subprocess.Popen.wait`
        - "communicate" to use :meth:`~python.subprocess.Popen.communicate`
        - "terminate" to use :meth:`~python:subprocess.Popen.terminate`
        - "kill" to use :meth:`~python:subprocess.Popen.kill`

    %(verbose)s
    *args, **kwargs : arguments
        Additional arguments to pass to subprocess.Popen.

    Returns
    -------
    p : instance of Popen
        The process.
    Úafterrp   Ú	terminateÚkillÚcommunicater`   r_   Úenvc                 s   s   | ]}|  d ¡V  qdS )ú~N)Ú
startswith)r1   rm   r   r   r   Ú	<genexpr>Ó   s     z%running_subprocess.<locals>.<genexpr>ÚPATHzÔYour PATH environment variable contains at least one path starting with a tilde ("~") character. Such paths are not interpreted correctly from within Python. It is recommended that you use "$HOME" instead of "~".c                 S   s   g | ]}t |ƒ‘qS r   r/   ©r1   r   r   r   r   r3   Û   s     z&running_subprocess.<locals>.<listcomp>ú c                 s   s   | ]
}|V  qd S r;   r   rz   r   r   r   rx   Ü   s     zRunning subprocess: %sr   zCommand not found: %sN)r
   r0   r	   r   r`   r_   ri   ÚPIPErc   ÚosÚenvironÚanyr%   Úpathsepr   r   r$   r   re   ÚPopenÚ	ExceptionÚerrorÚgetattrrp   )rk   rq   r   r[   rl   ZstdxxxZ
sys_stdxxxru   Zcommand_strrm   Úcommand_namer   r   r   r^   ±   s2    

r^   Tc                 C   sd   g }| D ]V}d|kr$|r$|  dd¡}d|kr>|r>| d¡d }| d¡rT|dd… }| |¡ q|S )aÒ  Remove white-space on topo matching.

    This function handles different naming
    conventions for old VS new VectorView systems (`remove_whitespace`).
    Also it allows to remove system specific parts in CTF channel names
    (`before_dash`).

    Usage
    -----
    # for new VectorView (only inside layout)
    ch_names = _clean_names(epochs.ch_names, remove_whitespace=True)

    # for CTF
    ch_names = _clean_names(epochs.ch_names, before_dash=True)

    r{   r   ú-r   Ú_vNéþÿÿÿ)Úreplacer%   ÚendswithÚappend)ÚnamesZremove_whitespaceZbefore_dashÚcleanedÚnamer   r   r   Ú_clean_namesî   s    
r�   c                  C   s€   t  ¡ } zFtdƒD ]
}| j} q| jj}t |d¡s:W ¢dS t  | ¡\}}}}W 5 ~ X tƒ }|D ]}|| ||< q^| 	dd¡ |S )z>Return all arguments (except self) and values of read_raw_xxx.é   z
*/mne/io/*Nr>   )
ÚinspectÚcurrentframeÚrangeÚf_backÚf_codeÚco_filenameÚfnmatchÚgetargvaluesr<   Úpop)ÚframeÚ_Úfnamer[   ÚvaluesÚparamsÚargr   r   r   Ú_get_argvalues  s    r    c                 C   s”   ddddddg}dddd	d	d	g}| dkrxt tt| d
ƒƒt|ƒd ƒ}t| ƒd
|  }|| }|| }d| }| ||¡S | dkr„dS | dkr�dS dS )zÏTurn number of bytes into human-readable str.

    Parameters
    ----------
    num : int
        The number of bytes.

    Returns
    -------
    size : str
        The size in human-readable format.
    ÚbytesÚkBÚMBÚGBÚTBÚPBr   r   r   i   z{0:.%sf} {1}z0 bytesz1 byteN)Úminr   r   r   ÚfloatÚformat)ÚnumZunitsZdecimalsÚexponentZquotientÚunitZnum_decimalsÚformat_stringr   r   r   Ú
sizeof_fmt#  s    r®   c                    s   t ‡ fdd„dD ƒƒS )Nc                 3   s   | ]}t tˆ |d ƒƒV  qd S r;   )Úcallabler„   )r1   rŽ   ©Úobjr   r   rx   F  s     z_file_like.<locals>.<genexpr>)ÚreadÚseek)Úallr°   r   r°   r   Ú
_file_like?  s    rµ   c                 C   s(   | j }|j}|dkr|jS |d |j S )NÚbuiltinsÚ.)Ú	__class__rD   rE   )r±   ÚklassÚmoduler   r   r   Ú	_fullnameI  s
    r»   c              
   C   s  d}d}t ƒ }t ¡  t ¡ }|D �]ž}zt|| ƒ}W n tk
rN   d}Y nX |�rÀ| jdkrx| dt|dd ƒ› �¡ t 	|¡}d}	|D �]$}
|
|k	�r®|
t
ƒ k	�r®|
tƒ k	�r®t |
¡�s®t|
t tfƒ�r,dt|
ƒ› �}t 	|
¡}dd	„ |D ƒ}d
 ttdd	„ |D ƒƒƒ¡}|dt|ƒ› d|› �7 }~n^t|
ƒd d…  dd¡}| d¡�rŠz"|dt|
jƒd d… › d�7 }W n tk
�rˆ   Y nX t|
ƒ}| |› d|› �¡ |	d7 }	~
qŠ~||	dk7 }~q"~t ¡  |dk�s td|› d| j› d|› d�d |¡ ƒ‚d S )NTr   FZBrainzBrain._cleaned = Z_cleanedzlen=c                 s   s   | ]}t |ƒV  qd S r;   )r»   ©r1   r   r   r   r   rx   j  s     z'_assert_no_instances.<locals>.<genexpr>ú/c                 s   s   | ]}|d k	r|V  qd S r;   r   r¼   r   r   r   rx   k  s     z, z referrers: éd   r   r{   z	<cell at z (ú)z: r   z @ r   )r7   ÚgcZcollectZget_objectsr   r‚   rC   r‹   r„   Zget_referrersÚglobalsÚlocalsr‘   Úisframer<   r   r$   ÚsortedÚsetÚreprr‰   rw   Úcell_contentsr»   ÚAssertionError)ÚclsÚwhenZ__tracebackhide__ÚnÚrefZobjsr±   ÚcheckZrrÚcountÚrÚrepZr_ÚtypesrŽ   r   r   r   Ú_assert_no_instancesQ  sd    


ÿ


ÿþý
ÿ"rÒ   c                 C   sL   zddl m} || ƒ |¡W S  tk
rF   ddlm} || |ƒ Y S X dS )ah  Return a full system path to a package resource (AKA a file).

    Parameters
    ----------
    submodule : str
        An import-style module or submodule name
        (e.g., "mne.datasets.testing").
    filename : str
        The file whose full path you want.

    Returns
    -------
    path : str
        The full system path to the requested file.
    r   )Úfiles)Úresource_filenameN)Úimportlib.resourcesrÓ   ÚjoinpathÚImportErrorÚpkg_resourcesrÔ   )Ú	submoduleÚfilenamerÓ   rÔ   r   r   r   Ú_resource_pathƒ  s    rÛ   )r   r   )r   Nr   )FN)rp   N)FT)r   )/rF   Ú
contextlibr   r—   rÀ   r‘   Úmathr   r}   rW   r   r   r-   r   ri   r   Ú	threadingr   r!   Únumpyr   Úutilsr	   r
   Úfixesr   Z_loggingr   r   r   r   r.   r9   r:   r<   rG   rQ   rY   ro   r^   r�   r    r®   rµ   r»   rÒ   rÛ   r   r   r   r   Ú<module>   sD   

V<


2