U
    f»{jHA  ã                   @   sŽ  d Z ddl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
Z
ddlmZ ddlZddlmZmZmZ ddlmZ e
 d¡Zd	e_G d
d„ de
jƒZeƒ Ze e¡ ededef d�Zeedœdd„ZeG dd„ dƒƒZed0dd„ƒZd1dd„Z dd„ Z!G dd„ deƒZ"G dd„ de#ƒZ$ej%dd „ ƒZ&G d!d"„ d"e#ƒZ'e (d#¡Z)e*dd$fd%d&„Z+d'd(„ Z,d2d)d*„Z-ej%d3d,d-„ƒZ.d.d/„ Z/dS )4zSome utility functions.é    N)ÚFunctionMaker)ÚStringIO)ÚAnyÚCallableÚTypeVaré   )Úfill_docÚmneFc                   @   s   e Zd Zdd„ Zdd„ ZdS )Ú_FrameFilterc                 C   s
   d| _ d S )Nr   ©Ú
add_frames©Úself© r   úQ/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/utils/_logging.pyÚ__init__   s    z_FrameFilter.__init__c                 C   s®   d|_ | jrªtd| j ƒdd … d d d… }t|ƒrª|d d  d¡|d< t|ƒdkrvd|d  |d< d	|d  |d< t|dd… dƒD ]\}}d
| ||< qˆd |¡|_ dS )NÚUnknowné   éÿÿÿÿz :é   r   u   â”Œr   u   â””u   â”œÚ
T)Ú
frame_infor   Ú_frame_infoÚlenÚljustÚ	enumerateÚjoin)r   Úrecordr   ÚiiÚinfor   r   r   Úfilter!   s     z_FrameFilter.filterN)Ú__name__Ú
__module__Ú__qualname__r   r    r   r   r   r   r
      s   r
   Ú_FuncT.)Úbound)ÚfunctionÚreturnc                 C   sp   zt | ƒ W n tk
r    Y nX d}tt| d�}t| dddd| jƒ}t| | j| jd�}|j||fddi|—ŽS )a…  Verbose decorator to allow functions to override log-level.

    Parameters
    ----------
    function : callable
        Function to be decorated by setting the verbosity level.

    Returns
    -------
    dec : callable
        The decorated function.

    See Also
    --------
    set_log_level
    set_config

    Notes
    -----
    This decorator is used to set the verbose level during a function or method
    call, such as :func:`mne.compute_covariance`. The `verbose` keyword
    argument can be 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL', True (an
    alias for 'INFO'), or False (an alias for 'WARNING'). To set the global
    verbosity level for all functions, use :func:`mne.set_log_level`.

    This function also serves as a docstring filler.

    Examples
    --------
    You can use the ``verbose`` argument to set the verbose level on the fly::

        >>> import mne
        >>> cov = mne.compute_raw_covariance(raw, verbose='WARNING')  # doctest: +SKIP
        >>> cov = mne.compute_raw_covariance(raw, verbose='INFO')  # doctest: +SKIP
        Using up to 49 segments
        Number of samples used : 5880
        [done]
    aµ  def %(name)s(%(signature)s):

    try:
        do_level_change = verbose is not None
    except (NameError, UnboundLocalError):
        raise RuntimeError('Function/method %%s does not accept verbose '
                           'parameter' %% (_function_,)) from None
    if do_level_change:
        with _use_log_level_(verbose):
            return _function_(%(shortsignature)s)
    else:
        return _function_(%(shortsignature)s))Z_use_log_level_Z
_function_N)Ú__wrapped__r#   Ú__globals__Z	addsourceT)	r   Ú	TypeErrorÚdictÚuse_log_levelr   r"   r#   r)   Úmake)r&   ÚbodyZevaldictÚfmÚattrsr   r   r   Úverbose;   s    ) ÿÿr1   c                   @   s.   e Zd ZdZddœdd„Zdd„ Zdd	„ ZdS )
r,   a  Context manager for logging level.

    Parameters
    ----------
    %(verbose)s
    %(add_frames)s

    See Also
    --------
    mne.verbose

    Notes
    -----
    See the :ref:`logging documentation <tut-logging>` for details.

    Examples
    --------
    >>> from mne import use_log_level
    >>> from mne.utils import logger
    >>> with use_log_level(False):
    ...     # Most MNE logger messages are "info" level, False makes them not
    ...     # print:
    ...     logger.info('This message will not be printed')
    >>> with use_log_level(True):
    ...     # Using verbose=True in functions, methods, or this context manager
    ...     # will ensure they are printed
    ...     logger.info('This message will be printed!')
    This message will be printed!
    Nr   c                C   s   || _ || _tj| _d S ©N)Ú_levelÚ_add_framesÚ_filterr   Ú_old_frames)r   r1   r   r   r   r   r   Ÿ   s    zuse_log_level.__init__c                 C   s   t | jd| jd�| _d S )NT)Úreturn_old_levelr   )Úset_log_levelr3   r4   Ú
_old_levelr   r   r   r   Ú	__enter__¤   s
      ÿzuse_log_level.__enter__c                 G   s&   | j d k	r| jnd }t| j|d� d S )Nr   )r4   r6   r8   r9   )r   Úargsr   r   r   r   Ú__exit__¨   s    zuse_log_level.__exit__©r!   r"   r#   Ú__doc__r   r:   r<   r   r   r   r   r,      s   r,   c           
      C   s  ddl m} ddlm}m} || tttdfdƒ | dkrD|ddƒ} nt| tƒr`| dkr\d} nd	} t| tƒr¤|  	¡ } t
tjtjtjtjtjd
�}|d| |dƒ ||  } tj}| |kr¼t | ¡ |dk	�rt|ƒt_|rØdnd}|d7 }t |¡}tjD ]}	|	 |¡ qô|�r|S dS )aÓ  Set the logging level.

    Parameters
    ----------
    verbose : bool, str, int, or None
        The verbosity of messages to print. If a str, it can be either DEBUG,
        INFO, WARNING, ERROR, or CRITICAL. Note that these are for
        convenience and are equivalent to passing in logging.DEBUG, etc.
        For bool, True is the same as 'INFO', False is the same as 'WARNING'.
        If None, the environment variable MNE_LOGGING_LEVEL is read, and if
        it doesn't exist, defaults to INFO.
    return_old_level : bool
        If True, return the old verbosity level.
    %(add_frames)s

    Returns
    -------
    old_level : int
        The old level. Only returned if ``return_old_level`` is True.
    r   )Ú
get_config)Ú_check_optionÚ_validate_typeNr1   ZMNE_LOGGING_LEVELÚINFOTÚWARNING)ÚDEBUGrB   rC   ÚERRORÚCRITICALz(when a string)z%(frame_info)s Ú ú%(message)s)Úconfigr?   Úcheckr@   rA   ÚboolÚstrÚintÚ
isinstanceÚupperr+   ÚloggingrD   rB   rC   rE   rF   ÚloggerÚlevelÚsetLevelr5   r   Ú	FormatterÚhandlersÚsetFormatter)
r1   r7   r   r?   r@   rA   Zlogging_typesZold_verboseÚfmtÚhandlerr   r   r   r8   ­   s:    


 þ




r8   rH   c                 C   s|   t tƒ | dk	rRt | ¡r6|dkr6tjdtdd� d}|r>dnd}tj| |d�}nt 	t
ƒ ¡}| t |¡¡ t |¡ dS )	aÄ  Set the log to print to a file.

    Parameters
    ----------
    fname : str, or None
        Filename of the log to print to. If None, stdout is used.
        To suppress log outputs, use set_log_level('WARN').
    output_format : str
        Format of the output messages. See the following for examples:

            https://docs.python.org/dev/howto/logging.html

        e.g., "%(asctime)s - %(levelname)s - %(message)s".
    overwrite : bool | None
        Overwrite the log file (if it exists). Otherwise, statements
        will be appended to the log (default). None is the same as False,
        but additionally raises a warning to notify the user that log
        entries will be appended.
    NzbLog entries will be appended to the file. Use overwrite=False to avoid this message in the future.é   )Ú
stacklevelFÚwÚa)Úmode)Ú_remove_close_handlersrQ   ÚopÚisfileÚwarningsÚwarnÚRuntimeWarningrP   ÚFileHandlerÚStreamHandlerÚ
WrapStdOutrV   rT   Ú
addHandler)ÚfnameZoutput_formatÚ	overwriter]   Zlhr   r   r   Úset_log_fileá   s     þrj   c                 C   sD   t | jƒD ]4}t|tjtjfƒr
t|tjƒr4| ¡  |  |¡ q
d S r2   )ÚlistrU   rN   rP   rd   re   ÚcloseÚremoveHandler)rQ   Úhr   r   r   r^     s
    r^   c                       s"   e Zd ZdZd‡ fdd„	Z‡  ZS )ÚClosingStringIOz&StringIO that closes after getvalue().Tc                    s   t ƒ  ¡ }|r|  ¡  |S )zGet the value.)ÚsuperÚgetvaluerl   )r   rl   Úout©Ú	__class__r   r   rq     s    
zClosingStringIO.getvalue)T)r!   r"   r#   r>   rq   Ú__classcell__r   r   rs   r   ro     s   ro   c                   @   s*   e Zd ZdZd	dd„Zdd„ Zdd„ ZdS )
Úcatch_loggingzyStore logging.

    This will remove all other logging handlers, and return the handler to
    stdout when complete.
    Nc                 C   s
   || _ d S r2   )r1   )r   r1   r   r   r   r   '  s    zcatch_logging.__init__c                 C   sv   | j d k	rt| j ƒ| _n
t ¡ | _tƒ | _t | j¡| _	| j	 
t d¡¡ d| j	_ttƒ t | j	¡ | j ¡  | jS )NrH   T)r1   r,   Ú_ctxÚ
contextlibÚnullcontextro   Ú_datarP   re   Ú_lhrV   rT   Ú_mne_file_liker^   rQ   rg   r:   r   r   r   r   r:   *  s    


zcatch_logging.__enter__c                 G   s$   | j j|Ž  t | j¡ td ƒ d S r2   )rw   r<   rQ   rm   r{   rj   )r   r;   r   r   r   r<   8  s    zcatch_logging.__exit__)Nr=   r   r   r   r   rv      s   
rv   c               	   c   s,   t jdd��} t  d¡ | V  W 5 Q R X d S )NT)r   Úalways)ra   Úcatch_warningsÚsimplefilter)r[   r   r   r   Ú_record_warnings>  s    
r€   c                   @   s   e Zd ZdZdd„ ZdS )rf   z‹Dynamically wrap to sys.stdout.

    This makes packages that monkey-patch sys.stdout (e.g.doctest,
    sphinx-gallery) work properly.
    c                 C   s(   t tj|ƒrttj|ƒS td| ƒ‚d S )Nz$'file' object has not attribute '%s')ÚhasattrÚsysÚstdoutÚgetattrÚAttributeError)r   Únamer   r   r   Ú__getattr__N  s    zWrapStdOut.__getattr__N)r!   r"   r#   r>   r‡   r   r   r   r   rf   G  s   rf   z^<decorator-gen-[0-9]+>$)r	   c                    sÜ   dd„ |D ƒ}dd„ |D ƒ}d}t jtjkr´t ¡ }|r”|jj‰ |j}t	 
ˆ ¡sŒt‡ fdd„|D ƒƒsvdˆ kr”dˆ kr”t t ˆ ¡¡d	krŒq”|j}q4~t | |ˆ ||tƒ  d
i ¡¡ tdd„ t jD ƒƒsÎtjrØt  | ¡ dS )a  Emit a warning with trace outside the mne namespace.

    This function takes arguments like warnings.warn, and sends messages
    using both ``warnings.warn`` and ``logger.warn``. Warnings can be
    generated deep within nested function calls. In order to provide a
    more helpful warning, this function traverses the stack until it
    reaches a frame outside the ``mne`` namespace that caused the error.

    Parameters
    ----------
    message : str
        Warning message.
    category : instance of Warning
        The warning class. Defaults to ``RuntimeWarning``.
    module : str
        The name of the module emitting the warning.
    ignore_namespaces : list of str
        Namespaces to ignore when traversing the stack.

        .. versionadded:: 0.24
    c                 S   s   g | ]}t  |¡‘qS r   )Ú	importlibÚimport_module©Ú.0Únsr   r   r   Ú
<listcomp>q  s     zwarn.<locals>.<listcomp>c                 S   s   g | ]}t  |j¡‘qS r   )r_   ÚdirnameÚ__file__rŠ   r   r   r   r�   r  s     Nc                 3   s   | ]}ˆ   |¡V  qd S r2   )Ú
startswith)r‹   Úrd©rh   r   r   Ú	<genexpr>}  s     zwarn.<locals>.<genexpr>ZunittestÚcaseZtestsÚ__warningregistry__c                 s   s&   | ]}t |tjƒpt|d dƒV  qdS )r|   FN)rN   rP   rd   r„   )r‹   rn   r   r   r   r“   Ž  s   þÿ)rQ   rR   rP   ÚWARNÚinspectÚcurrentframeÚf_codeÚco_filenameÚf_linenoÚ_verbose_dec_reÚsearchÚanyr_   ÚbasenamerŽ   Úf_backra   Úwarn_explicitÚglobalsÚgetrU   r5   r   Úwarning)ÚmessageÚcategoryÚmoduleZignore_namespacesZ	root_dirsÚframeÚlinenor   r’   r   rb   Z  sB    
ÿÿþ    þþþrb   c                  C   sH   t  ¡ jj} t | jj¡r | j} t  | ¡j}|dkr8dn
|d  	¡ }|S )z)Get the call line from within a function.NÚunknownr   )
r—   r˜   r    rœ   r�   r™   rš   ÚgetframeinfoÚcode_contextÚstrip)r¨   Úcontextr   r   r   Ú_get_call_line”  s    r¯   c                    st   t  |dkrdn|¡‰‡ fdd„| jD ƒ}‡fdd„| jD ƒ}dd„ tt||ƒƒD ƒ}t|ƒD ]}| j |¡ q^dS )a€  Remove particular records from ``warn_record``.

    This helper takes a list of :class:`warnings.WarningMessage` objects,
    and remove those matching category and/or text.

    Parameters
    ----------
    category: WarningMessage type | None
       class of the message to filter out

    match : str | None
        text or regex that matches the error message to filter out
    Nz.*c                    s"   g | ]}ˆ d k	r|j ˆ knd‘qS )NT©r¦   ©r‹   r[   r°   r   r   r�   ­  s   ÿz'filter_out_warnings.<locals>.<listcomp>c                    s"   g | ]}ˆ   |jjd  ¡dk	‘qS )r   N)Úmatchr¥   r;   r±   )Úregexpr   r   r�   ¯  s   ÿc                 S   s    g | ]\}\}}|r|r|‘qS r   r   )r‹   ÚindÚcÚmr   r   r   r�   ±  s    
 ÿ)ÚreÚcompileZ_listr   ÚzipÚreversedÚpop)Zwarn_recordr¦   r²   Zis_categoryZis_matchr´   Úir   )r¦   r³   r   Úfilter_out_warningsž  s    
ÿ
ÿr½   rG   c                 c   s~   t j}tƒ }|t _z
dV  W 5 |t _d}| ¡  d¡D ]@}| ¡ sP|rP|d7 }q6t|ƒD ]}t d¡ qXt | | ¡ q6X dS )zæWrap stdout writes to logger.info, with an optional indent prefix.

    Parameters
    ----------
    indent : str
        The indentation to add.
    cull_newlines : bool
        If True, cull any new/blank lines at the end.
    r   r   r   N)	r‚   rƒ   ro   rq   Úsplitr­   ÚrangerQ   r   )ÚindentZcull_newlinesZorig_stdoutZmy_outZpending_newlinesÚlineÚ_r   r   r   Úwrapped_stdout¸  s    
rÃ   c              	   C   s¬   t  ¡ }zšzv|j}tƒ }t| ƒD ]V}z|jd }W n tk
rF   Y nX | | d¡› d|j	› �¡ |j}|d kr  qxq |W W ¢$S  t
k
rž   dg Y W ¢S X W 5 ~X d S )Nr!   zmne.ú:rª   )r—   r˜   r    rk   r¿   Ú	f_globalsÚKeyErrorÚappendÚlstripr›   Ú	Exception)Únr¨   ÚinfosrÂ   r†   r   r   r   r   Ô  s"    
r   )NFN)NrH   N)NN)rG   F)0r>   rx   Ú	decoratorr   rˆ   r—   Úior   r·   r‚   rP   Úos.pathÚpathr_   ra   Útypingr   r   r   Údocsr   Ú	getLoggerrQ   Ú	propagateÚFilterr
   r5   Ú	addFilterr$   r1   r,   r8   rj   r^   ro   Úobjectrv   Úcontextmanagerr€   rf   r¸   rœ   rc   rb   r¯   r½   rÃ   r   r   r   r   r   Ú<module>   sN   

D-3
+	

ÿ
:

