U
    f»{j¡ ã                
   @   st  d Z ddlmZ ddlmZ ddlZddlmZ ddl	m
Z
mZ dd	lmZ dd
lmZ ddlmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0m1Z1m2Z2m3Z3m4Z4 ddl5m6Z6m7Z7 ddl8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z? dRdd„Z@dSdd„ZAdTdd„ZBdddddœdd„ZCdUd!d"„ZDd#d$„ ZEdVd%d&„ZFdWd'd(„ZGd)d*„ ZHdXd+d,„ZIedYd.d/„ƒZJedZd0d1„ƒZKed[d2d3„ƒZLG d4d5„ d5e7e+eeƒZMeG d6d7„ d7eMƒƒZNeG d8d9„ d9eMeƒƒZOd\d;d<„ZPd=d>„ ZQd?d@„ ZRdAdB„ ZSd]dCdD„ZTdEdF„ ZUed^ddGœdHdI„ƒZVdJdK„ ZWd_dLdM„ZXdNdO„ ZYd`dPdQ„ZZdS )az‚A module which implements the time-frequency estimation.

Morlet code inspired by Matlab code from Sheraz Khan & Brainstorm & SPM
é    ©Údeepcopy)ÚpartialNé   )Údpss_windowsé   )ÚrescaleÚ_check_baseline)Únext_fast_len)Úparallel_func)ÚloggerÚverboseÚ
_time_maskÚ
_freq_maskÚcheck_fnameÚ
sizeof_fmtÚGetEpochsMixinÚ	TimeMixinÚ_prepare_read_metadataÚfill_docÚ_prepare_write_metadataÚ_check_event_idÚ_gen_eventsÚ	SizeMixinÚ_is_numericÚ_check_optionÚ_validate_typeÚ_check_combineÚ_check_pandas_installedÚ_check_pandas_index_argumentsÚ_check_time_formatÚ_convert_timesÚ_build_data_frameÚwarnÚ_import_h5io_funcs)ÚUpdateChannelsMixin)Ú_merge_ch_dataÚ_pair_grad_sensors)Ú	pick_infoÚ_picks_to_idxÚchannel_typeÚ
_pick_instÚ_get_channel_types)ÚInfoÚContainsMixin)Úfigure_nobarÚplt_showÚ_setup_cmapÚ_connection_lineÚ_prepare_joint_axesÚ_setup_vmin_vmaxÚ_set_title_multiple_electrodesç      @Fc                 C   sz  t ƒ }t |¡}t |¡}t |dk¡r0tdƒ‚|jdkrP|jt|ƒkrPtdƒ‚t|ƒD �]\}}t|ƒdkrx|| }n|d }|dkrœ|dtj	 |  }	n|dtj	 |  }	t 
dd|	 d	|  ¡}
tj|
ddd
…  |
dd… f }
t dtj	 | |
 ¡}t |
d  d|	d   ¡}|�rDt dtj	| |	 d  ¡}||8 }|| }|t d¡tj | ¡ ¡  }| |¡ qX|S )a¼  Compute Morlet wavelets for the given frequency range.

    Parameters
    ----------
    sfreq : float
        The sampling Frequency.
    freqs : array
        Frequency range of interest (1 x Frequencies).
    n_cycles : float | array of float, default 7.0
        Number of cycles. Fixed number or one per frequency.
    sigma : float, default None
        It controls the width of the wavelet ie its temporal
        resolution. If sigma is None the temporal resolution
        is adapted with the frequency like for all wavelet transform.
        The higher the frequency the shorter is the wavelet.
        If sigma is fixed the temporal resolution is fixed
        like for the short time Fourier transform and the number
        of oscillations increases with the frequency.
    zero_mean : bool, default False
        Make sure the wavelet has a mean of zero.

    Returns
    -------
    Ws : list of array
        The wavelets time series.
    r   ú2all frequencies in 'freqs' must be greater than 0.r   ú7n_cycles should be fixed or defined for each frequency.Nç       @ç        g      @ç      ð?éÿÿÿÿù               @r   éþÿÿÿç      à?)ÚlistÚnpÚ
atleast_1dÚarrayÚanyÚ
ValueErrorÚsizeÚlenÚ	enumerateÚpiÚarangeZr_ÚexpÚsqrtÚlinalgÚnormÚravelÚappend)ÚsfreqÚfreqsÚn_cyclesÚsigmaÚ	zero_meanÚWsÚkÚfÚthis_n_cyclesZsigma_tÚtÚoscillationZgaussian_enveloppeÚreal_offsetÚW© r^   úU/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/time_frequency/tfr.pyÚmorlet(   s2    


"r`   ç      @c                 C   sf  t ƒ }t |¡}t |dk¡r&tdƒ‚|dk r6tdƒ‚tt |d ¡ƒ}t |¡}|jdkrr|jt	|ƒkrrtdƒ‚t
|ƒD ]æ}t ƒ }t|ƒD ]È\}	}
t	|ƒdkrª||	 }n|d }|t|
ƒ }t d|d|  ¡}t d	tj |
 ||d   ¡}t|jd |d |ƒ\}}|||  }|�r,| ¡ }||8 }|t d
¡tj | ¡ ¡  }| |¡ qŒ| |¡ qz|S )aï  Compute DPSS tapers for the given frequency range.

    Parameters
    ----------
    sfreq : float
        The sampling frequency.
    freqs : ndarray, shape (n_freqs,)
        The frequencies in Hz.
    n_cycles : float | ndarray, shape (n_freqs,), default 7.
        The number of cycles globally or for each frequency.
    time_bandwidth : float, default 4.0
        Time x Bandwidth product.
        The number of good tapers (low-bias) is chosen automatically based on
        this to equal floor(time_bandwidth - 1).
        Default is 4.0, giving 3 good tapers.
    zero_mean : bool | None, , default False
        Make sure the wavelet has a mean of zero.

    Returns
    -------
    Ws : list of array
        The wavelets time series.
    r   r7   r9   z/time_bandwidth should be >= 2.0 for good tapersr   r8   r:   r;   r=   r?   )r@   rA   rC   rD   rE   ÚintÚfloorrB   rF   rG   ÚrangerH   ÚfloatrJ   rK   rI   r   ÚshapeÚmeanrL   rM   rN   rO   rP   )rQ   rR   rS   Útime_bandwidthrU   rV   Zn_tapsÚmZWmrW   rX   rY   Zt_winrZ   r[   ZtapersZconcZWkr\   r^   r^   r_   Ú
_make_dpssg   s<    


 ÿrj   Tc                 C   sj   |j d }tdd„ | D ƒƒ}||krRd|› d|› d�}|rR|rJt|tƒ nt|ƒ‚|| d }t|ƒ}|S )Nr<   c                 s   s   | ]}|j V  qd S ©N)rF   )Ú.0Úwr^   r^   r_   Ú	<genexpr>±   s     z_get_nfft.<locals>.<genexpr>zAt least one of the wavelets (z) is longer than the signal (z6). Consider using a longer signal or shorter wavelets.r   )rf   Úmaxr#   ÚUserWarningrE   r
   )ZwaveletsÚXÚuse_fftÚcheckÚn_timesÚmax_sizeÚmsgÚnfftr^   r^   r_   Ú	_get_nfft¯   s    
rx   Úsame©ÚfsizeÚmodeÚdecimrr   c                c   sö  ddl m}m} td|dddgƒ t|ƒ}t | ¡} | j\}}	| dd…|f jd }
t|ƒ}|r”tj	||ftj
d	�}t|ƒD ]\}}|||ƒ||< q|tj||
ftj
d	�}| D �]B}|rÀ|||ƒ}t|ƒD �]\}}|rú||||  ƒd|	|j d … }ntj|||d
�}|dk�rrtt|j|	 ƒƒd }|	| d }t||j || |j ƒ}|�r`t||ƒ}|| |||f< qÈ|dk�rÄ|�sÄ|jd d }t|ƒ|jd  }|||… }|| ||dd…f< qÈ|�rÔt||	ƒ}|| ||dd…f< qÈ|V  q¬dS )a,  Compute cwt with fft based convolutions or temporal convolutions.

    Parameters
    ----------
    X : array of shape (n_signals, n_times)
        The data.
    Ws : list of array
        Wavelets time series.
    fsize : int
        FFT length.
    mode : {'full', 'valid', 'same'}
        See numpy.convolve.
    decim : int | slice, default 1
        To reduce memory usage, decimation factor after time-frequency
        decomposition.
        If `int`, returns tfr[..., ::decim].
        If `slice`, returns tfr[..., decim].

        .. note:: Decimation may create aliasing artifacts.

    use_fft : bool, default True
        Use the FFT for convolutions or not.

    Returns
    -------
    out : array, shape (n_signals, n_freqs, n_time_decim)
        The time-frequency transform of the signals.
    r   )ÚfftÚifftr|   ry   ZvalidÚfullNr   ©Údtype)r|   r   )Z	scipy.fftr~   r   r   Ú_check_decimrA   Úasarrayrf   rG   ÚemptyÚ
complex128rH   ÚzerosrF   Zconvolverb   ÚabsÚsliceÚstepÚ	_centered)rq   rV   r{   r|   r}   rr   r~   r   Ú_rt   Zn_times_outÚn_freqsZfft_WsÚir]   ÚtfrÚxZfft_xÚiiÚretÚszÚoffsetZ
this_sliceÚstartÚendr^   r^   r_   Ú_cwt_genÀ   sJ    



$

ÿ

r—   r;   Úcomplexc              
      sT  t  | ¡} | jdkr$td| jf ƒ‚t||ˆ|||ˆˆˆƒ	\}}}}}‰tˆƒ‰||d k ¡ rxtd|d | ¡ f ƒ‚ˆdkr˜t	||||d�}|g‰ nˆdkr²t
|||||d�‰ tˆ d	 d	 ƒ| jd
 krÔtdƒ‚t|ƒ}tˆ ƒ}| dd…dd…ˆf j\}}}ˆdk�rt j}nˆdk�r$t j}dˆk�s8dˆk�rLt  |||f|¡}n@ˆdk�rxˆdk�rxt  |||||f|¡}nt  ||||f|¡}tdd„ ˆ D ƒtƒ ƒ}t|| ˆƒ tt|
ƒ\}‰}
|‡ ‡‡‡‡‡fdd„|  dd	d
¡D ƒƒ}t|ƒD ]\}}|||< �qðdˆk�rPdˆk�rPˆdk�r@ˆdk�r@| d
d	ddd¡}n| dd	d
d¡}|S )a®
  Compute time-frequency transforms.

    Parameters
    ----------
    epoch_data : array of shape (n_epochs, n_channels, n_times)
        The epochs.
    freqs : array-like of floats, shape (n_freqs)
        The frequencies.
    sfreq : float | int, default 1.0
        Sampling frequency of the data.
    method : 'multitaper' | 'morlet', default 'morlet'
        The time-frequency method. 'morlet' convolves a Morlet wavelet.
        'multitaper' uses complex exponentials windowed with multiple DPSS
        tapers.
    n_cycles : float | array of float, default 7.0
        Number of cycles in the wavelet. Fixed number
        or one per frequency.
    zero_mean : bool | None, default None
        None means True for method='multitaper' and False for method='morlet'.
        If True, make sure the wavelets have a mean of zero.
    time_bandwidth : float, default None
        If None and method=multitaper, will be set to 4.0 (3 tapers).
        Time x (Full) Bandwidth product. Only applies if
        method == 'multitaper'. The number of good tapers (low-bias) is
        chosen automatically based on this to equal floor(time_bandwidth - 1).
    use_fft : bool, default True
        Use the FFT for convolutions or not.
    decim : int | slice, default 1
        To reduce memory usage, decimation factor after time-frequency
        decomposition.
        If `int`, returns tfr[..., ::decim].
        If `slice`, returns tfr[..., decim].

        .. note::
            Decimation may create aliasing artifacts, yet decimation
            is done after the convolutions.

    output : str, default 'complex'

        * 'complex' : single trial complex.
        * 'power' : single trial power.
        * 'phase' : single trial phase.
        * 'avg_power' : average of single trial power.
        * 'itc' : inter-trial coherence.
        * 'avg_power_itc' : average of single trial power and inter-trial
          coherence across trials.

    %(n_jobs)s
        The number of epochs to process at the same time. The parallelization
        is implemented across channels.
    %(verbose)s

    Returns
    -------
    out : array
        Time frequency transform of epoch_data. If output is in ['complex',
        'phase', 'power'], then shape of ``out`` is ``(n_epochs, n_chans,
        n_freqs, n_times)``, else it is ``(n_chans, n_freqs, n_times)``.
        However, using multitaper method and output ``'complex'`` or
        ``'phase'`` results in shape of ``out`` being ``(n_epochs, n_chans,
        n_tapers, n_freqs, n_times)``. If output is ``'avg_power_itc'``, the
        real values in the ``output`` contain average power' and the imaginary
        values contain the ITC: ``out = avg_power + i * itc``.
    é   z@epoch_data must be of shape (n_epochs, n_chans, n_times), got %sr9   zKCannot compute freq above Nyquist freq of the data (%0.1f Hz), got %0.1f Hzr`   )rS   rU   Ú
multitaper)rS   rh   rU   r   r   z`At least one of the wavelets is longer than the signal. Use a longer signal or shorter wavelets.N)ÚpowerÚphaseÚ	avg_powerÚitc©r˜   Úavg_power_itcÚavg_rž   ©r˜   rœ   c                 S   s   g | ]}t |ƒ‘qS r^   ©r@   )rl   r]   r^   r^   r_   Ú
<listcomp>‰  s     z _compute_tfr.<locals>.<listcomp>c              	   3   s"   | ]}ˆ|ˆ ˆˆd ˆˆƒV  qdS )ry   Nr^   )rl   Zchannel©rV   r}   ÚmethodZmy_cwtÚoutputrr   r^   r_   rn   Ž  s   ÿz_compute_tfr.<locals>.<genexpr>r   é   )rA   r„   ÚndimrE   rf   Ú_check_tfr_paramrƒ   rD   ro   r`   rj   rG   Úfloat64r†   r…   Úsumr@   rx   r   Ú_time_frequency_loopZ	transposerH   )Ú
epoch_datarR   rQ   r¦   rS   rU   rh   rr   r}   r§   Ún_jobsr   r]   r�   Ún_tapersÚn_epochsZn_chansrt   r‚   ÚoutZall_WsÚparallelÚtfrsZchannel_idxr�   r^   r¥   r_   Ú_compute_tfr  sh    E

ÿ   ÿÿþ ÿ

þrµ   c	           	   	   C   sà  t | ttjfƒs tdt| ƒ ƒ‚tj| td�} | jdkrLtdt 	| j
¡ ƒ‚t |ttfƒsjtdt|ƒ ƒ‚t|ƒ}|dkr‚|dkn|}t |tƒs tdt|ƒ ƒ‚t | ¡} t |ttfƒrÂt|ƒ}nXt |ttjfƒ�r
t 	|¡}t|ƒt| ƒk�rtd	t| ƒt|ƒf ƒ‚ntd
t|ƒ ƒ‚|dk�r8|dk	�r8tdƒ‚n |dk�rX|dk�rPdnt|ƒ}t |tƒ�sttdt|ƒ ƒ‚t |tƒ�rŒtdd|ƒ}t |tƒ�s¨tdt|ƒ ƒ‚td|ddddddgƒ td|ddgƒ | |||||fS )z;Aux. function to _compute_tfr to check the params validity.z,freqs must be an array-like, got %s instead.r�   r   z2freqs must be of shape (n_freqs,), got %s instead.z0sfreq must be a float or an int, got %s instead.Nrš   z1zero_mean should be of type bool, got %s. insteadzUn_cycles must be a float or an array of length %i frequencies, got %i cycles instead.z5n_cycles must be a float or an array, got %s instead.r`   z3time_bandwidth only applies to "multitaper" method.ra   z*use_fft must be a boolean, got %s instead.z4decim must be an integer or a slice, got %s instead.r§   r˜   r›   rœ   r    r�   rž   r¦   )Ú
isinstancer@   rA   ÚndarrayrE   Útyper„   re   r©   rC   rf   rb   ÚboolrG   r‰   r   )	rR   rQ   r¦   rU   rS   rh   rr   r}   r§   r^   r^   r_   rª   Ÿ  sl    ÿ

ÿÿ
ÿ


þÿ

ÿÿÿ  ÿrª   c              	   C   sP  t j}|dkrt j}t|ƒ}t|ƒ}| dd…|f j\}	}
t|d ƒ}d|ksVd|krjt j||
f|d�}n<|dkr’|dkr’t j||	||
f|d�}nt j|	||
f|d�}t|ƒD �]b\}}t|| |d	d
�}t	| |||||d�}d|krøt j||
ft jd�}t|ƒD ]Ü\}}|dk�r"|| 
¡  j}n`|dk�r8t  |¡}nJ|dk�rbt  |¡}||| 7 }|d }n |dk�r‚||t  |¡ 7 }�q d|k�s–d|k�r ||7 }n:|dk�rÊ|dk�rÊ|||f  |7  < n||  |7  < �q |dk�rü|dt  |¡ 7 }q®|dkr®|t  |¡7 }q®d|k�s(d|k�r0||	 }|dk�rL|dk�rL|| }|S )aÙ  Aux. function to _compute_tfr.

    Loops time-frequency transform across wavelets and epochs.

    Parameters
    ----------
    X : array, shape (n_epochs, n_times)
        The epochs data of a single channel.
    Ws : list, shape (n_tapers, n_wavelets, n_times)
        The wavelets.
    output : str

        * 'complex' : single trial complex.
        * 'power' : single trial power.
        * 'phase' : single trial phase.
        * 'avg_power' : average of single trial power.
        * 'itc' : inter-trial coherence.
        * 'avg_power_itc' : average of single trial power and inter-trial
          coherence across trials.

    use_fft : bool
        Use the FFT for convolutions or not.
    mode : {'full', 'valid', 'same'}
        See numpy.convolve.
    decim : slice
        The decimation slice: e.g. power[:, decim]
    method : str | None
        Used only for multitapering to create tapers dimension in the output
        if ``output in ['complex', 'phase']``.
    rŸ   Nr   r¡   rž   r�   r¢   rš   F)rs   rz   )r›   r�   rœ   r    r   y              ð?r   )rA   r«   r†   rƒ   rG   rf   r‡   rH   rx   r—   ÚconjÚrealZanglerˆ   )rq   rV   r§   rr   r|   r}   r¦   r‚   r°   r±   rt   r�   r´   Z	taper_idxr]   rw   ÚcoefsZplfZ	epoch_idxr�   Ztfr_absr^   r^   r_   r­   ß  sh    !ÿ     ÿ







r­   c                 C   s   t || |ƒ}t| |||||ƒS )a  Compute time freq decomposition with continuous wavelet transform.

    Parameters
    ----------
    X : array, shape (n_signals, n_times)
        The signals.
    Ws : list of array
        Wavelets time series.
    use_fft : bool
        Use FFT for convolutions. Defaults to True.
    mode : 'same' | 'valid' | 'full'
        Convention for convolution. 'full' is currently not implemented with
        ``use_fft=False``. Defaults to ``'same'``.
    decim : int | slice
        To reduce memory usage, decimation factor after time-frequency
        decomposition.
        If `int`, returns tfr[..., ::decim].
        If `slice`, returns tfr[..., decim].

        .. note:: Decimation may create aliasing artifacts.

        Defaults to 1.

    Returns
    -------
    tfr : array, shape (n_signals, n_freqs, n_times)
        The time-frequency decompositions.

    See Also
    --------
    mne.time_frequency.tfr_morlet : Compute time-frequency decomposition
                                    with Morlet wavelets.
    )rx   Ú
_cwt_array)rq   rV   rr   r|   r}   rw   r^   r^   r_   ÚcwtC  s    "r¾   c                 C   sj   t |ƒ}t| |||||d�}| d d …|f j\}}tj|t|ƒ|ftjd�}	t|ƒD ]\}
}||	|
< qT|	S )Nrz   r�   )rƒ   r—   rf   rA   r…   rG   r†   rH   )rq   rV   rw   r|   r}   rr   r¼   Z	n_signalsrt   r´   rW   r�   r^   r^   r_   r½   i  s         ÿ
r½   c                 K   s°  ddl m}	 t|ƒ}t||ƒ}
|j ¡ }t||
|dd�\}}
~|rb|dkrRtdƒ‚|r\d}q~d}n|d krnd	n|}|r~td
ƒ‚t|
||d f| ||dœ|—Ž}|j	|  ¡ }| 
¡ � |d  |j  < W 5 Q R X |�r4|rì|j|j }}n|}t|
ƒ}t|||||d|  d�}|�r¬|t|||||d|  d�f}nx|}t||	ƒ�rxt|jƒ}t|jƒ}t|jƒ}t|jƒ}t|jƒ}nd  } } } }}t||||d|  |||||d�
}|S )Nr   ©Ú
BaseEpochsr   ©Úaxisr˜   z&output must be "power" if average=Truer    r�   r›   z9Inter-trial coherence is not supported with average=FalserQ   )r¦   r§   r}   z%s-power©r¦   z%s-itc)r¦   ÚeventsÚevent_idÚ	selectionÚdrop_logÚmetadata)ÚepochsrÀ   rƒ   Ú	_get_dataÚinfoÚcopyÚ_prepare_picksrE   rµ   ÚtimesZ_unlockrŠ   r»   ÚimagrG   Ú
AverageTFRr¶   r   Ú	_metadatarÄ   rÅ   rÆ   rÇ   Ú	EpochsTFR)r¦   ÚinstrR   r}   Ú
return_itcÚpicksÚaverager§   Ú
tfr_paramsrÀ   ÚdatarË   r²   rÎ   r›   rž   ÚnaveÚmetaZevsZev_idrÆ   rÇ   r^   r^   r_   Ú_tfr_auxv  sh    

 ÿÿ
ÿÿ




   þrÛ   r›   c                 C   s*   t |||||
d�}td| |||||	f|ŽS )aœ  Compute Time-Frequency Representation (TFR) using Morlet wavelets.

    Same computation as `~mne.time_frequency.tfr_array_morlet`, but
    operates on `~mne.Epochs` objects instead of
    :class:`NumPy arrays <numpy.ndarray>`.

    Parameters
    ----------
    inst : Epochs | Evoked
        The epochs or evoked object.
    freqs : ndarray, shape (n_freqs,)
        The frequencies in Hz.
    n_cycles : float | ndarray, shape (n_freqs,)
        The number of cycles globally or for each frequency.
    use_fft : bool, default False
        The fft based convolution or not.
    return_itc : bool, default True
        Return inter-trial coherence (ITC) as well as averaged power.
        Must be ``False`` for evoked data.
    decim : int | slice, default 1
        To reduce memory usage, decimation factor after time-frequency
        decomposition.
        If `int`, returns tfr[..., ::decim].
        If `slice`, returns tfr[..., decim].

        .. note:: Decimation may create aliasing artifacts.
    %(n_jobs)s
    picks : array-like of int | None, default None
        The indices of the channels to decompose. If None, all available
        good data channels are decomposed.
    zero_mean : bool, default True
        Make sure the wavelet has a mean of zero.

        .. versionadded:: 0.13.0
    %(average_tfr)s
    output : str
        Can be "power" (default) or "complex". If "complex", then
        average must be False.

        .. versionadded:: 0.15.0
    %(verbose)s

    Returns
    -------
    power : AverageTFR | EpochsTFR
        The averaged or single-trial power.
    itc : AverageTFR | EpochsTFR
        The inter-trial coherence (ITC). Only returned if return_itc
        is True.

    See Also
    --------
    mne.time_frequency.tfr_array_morlet
    mne.time_frequency.tfr_multitaper
    mne.time_frequency.tfr_array_multitaper
    mne.time_frequency.tfr_stockwell
    mne.time_frequency.tfr_array_stockwell
    )rS   r¯   rr   rU   r§   r`   ©ÚdictrÛ   )rÓ   rR   rS   rr   rÔ   r}   r¯   rÕ   rU   rÖ   r§   r   r×   r^   r^   r_   Ú
tfr_morlet²  s    > ÿÿÿrÞ   c
           
      C   s    t | ||d||d|||||	d�S )a5	  Compute Time-Frequency Representation (TFR) using Morlet wavelets.

    Same computation as `~mne.time_frequency.tfr_morlet`, but operates on
    :class:`NumPy arrays <numpy.ndarray>` instead of `~mne.Epochs` objects.

    Parameters
    ----------
    epoch_data : array of shape (n_epochs, n_channels, n_times)
        The epochs.
    sfreq : float | int
        Sampling frequency of the data.
    freqs : array-like of float, shape (n_freqs,)
        The frequencies.
    n_cycles : float | array of float, default 7.0
        Number of cycles in the Morlet wavelet. Fixed number or one per
        frequency.
    zero_mean : bool | False
        If True, make sure the wavelets have a mean of zero. default False.
    use_fft : bool
        Use the FFT for convolutions or not. default True.
    decim : int | slice
        To reduce memory usage, decimation factor after time-frequency
        decomposition. default 1
        If `int`, returns tfr[..., ::decim].
        If `slice`, returns tfr[..., decim].

        .. note::
            Decimation may create aliasing artifacts, yet decimation
            is done after the convolutions.
    output : str, default 'complex'

        * 'complex' : single trial complex.
        * 'power' : single trial power.
        * 'phase' : single trial phase.
        * 'avg_power' : average of single trial power.
        * 'itc' : inter-trial coherence.
        * 'avg_power_itc' : average of single trial power and inter-trial
          coherence across trials.
    %(n_jobs)s
        The number of epochs to process at the same time. The parallelization
        is implemented across channels. Default 1.
    %(verbose)s

    Returns
    -------
    out : array
        Time frequency transform of epoch_data. If output is in ['complex',
        'phase', 'power'], then shape of out is (n_epochs, n_chans, n_freqs,
        n_times), else it is (n_chans, n_freqs, n_times). If output is
        'avg_power_itc', the real values code for 'avg_power' and the
        imaginary values code for the 'itc': out = avg_power + i * itc.

    See Also
    --------
    mne.time_frequency.tfr_morlet
    mne.time_frequency.tfr_multitaper
    mne.time_frequency.tfr_array_multitaper
    mne.time_frequency.tfr_stockwell
    mne.time_frequency.tfr_array_stockwell

    Notes
    -----
    .. versionadded:: 0.14.0
    r`   N)r®   rR   rQ   r¦   rS   rU   rh   rr   r}   r§   r¯   r   )rµ   )
r®   rQ   rR   rS   rU   rr   r}   r§   r¯   r   r^   r^   r_   Útfr_array_morletö  s    D      ürß   c                 C   s*   t |||d|d�}td| |||||	f|ŽS )aQ  Compute Time-Frequency Representation (TFR) using DPSS tapers.

    Same computation as `~mne.time_frequency.tfr_array_multitaper`, but
    operates on `~mne.Epochs` objects instead of
    :class:`NumPy arrays <numpy.ndarray>`.

    Parameters
    ----------
    inst : Epochs | Evoked
        The epochs or evoked object.
    freqs : ndarray, shape (n_freqs,)
        The frequencies in Hz.
    n_cycles : float | ndarray, shape (n_freqs,)
        The number of cycles globally or for each frequency.
        The time-window length is thus T = n_cycles / freq.
    time_bandwidth : float, (optional), default 4.0 (n_tapers=3)
        Time x (Full) Bandwidth product. Should be >= 2.0.
        Choose this along with n_cycles to get desired frequency resolution.
        The number of good tapers (least leakage from far away frequencies)
        is chosen automatically based on this to floor(time_bandwidth - 1).
        E.g., With freq = 20 Hz and n_cycles = 10, we get time = 0.5 s.
        If time_bandwidth = 4., then frequency smoothing is (4 / time) = 8 Hz.
    use_fft : bool, default True
        The fft based convolution or not.
    return_itc : bool, default True
        Return inter-trial coherence (ITC) as well as averaged (or
        single-trial) power.
    decim : int | slice, default 1
        To reduce memory usage, decimation factor after time-frequency
        decomposition.
        If `int`, returns tfr[..., ::decim].
        If `slice`, returns tfr[..., decim].

        .. note:: Decimation may create aliasing artifacts.
    %(n_jobs)s
    %(picks_good_data)s
    %(average_tfr)s
    %(verbose)s

    Returns
    -------
    power : AverageTFR | EpochsTFR
        The averaged or single-trial power.
    itc : AverageTFR | EpochsTFR
        The inter-trial coherence (ITC). Only returned if return_itc
        is True.

    See Also
    --------
    mne.time_frequency.tfr_array_multitaper
    mne.time_frequency.tfr_stockwell
    mne.time_frequency.tfr_array_stockwell
    mne.time_frequency.tfr_morlet
    mne.time_frequency.tfr_array_morlet

    Notes
    -----
    .. versionadded:: 0.9.0
    T)rS   r¯   rr   rU   rh   rš   rÜ   )rÓ   rR   rS   rh   rr   rÔ   r}   r¯   rÕ   rÖ   r   r×   r^   r^   r_   Útfr_multitaperA  s    ? ÿÿÿrà   c                       s’   e Zd ZdZdd„ Zedd„ ƒZejdd„ ƒZedd„ ƒZe	d‡ fdd„	ƒZ
dd„ Zeddd„ƒZedd	dœdd„ƒZedd	dœdd„ƒZ‡  ZS )Ú_BaseTFRzBase TFR class.c                 C   s
   d | _ d S rk   )Úbaseline©Úselfr^   r^   r_   Ú__init__‹  s    z_BaseTFR.__init__c                 C   s   | j S rk   ©Ú_datarã   r^   r^   r_   rØ   Ž  s    z_BaseTFR.datac                 C   s
   || _ d S rk   ræ   )rä   rØ   r^   r^   r_   rØ   ’  s    c                 C   s
   | j d S )zChannel names.Úch_names©rË   rã   r^   r^   r_   rè   –  s    z_BaseTFR.ch_namesNTc                    s„   t ƒ j|||d� |dk	s"|dk	r<t| j| jd ||d�}ntdƒ}| j| | _t|tjƒrjt 	|¡d }| j
d|dd…f | _
| S )a\  Crop data to a given time interval in place.

        Parameters
        ----------
        tmin : float | None
            Start time of selection in seconds.
        tmax : float | None
            End time of selection in seconds.
        fmin : float | None
            Lowest frequency of selection in Hz.

            .. versionadded:: 0.18.0
        fmax : float | None
            Highest frequency of selection in Hz.

            .. versionadded:: 0.18.0
        %(include_tmax)s

        Returns
        -------
        inst : instance of AverageTFR
            The modified instance.
        )ÚtminÚtmaxÚinclude_tmaxNrQ   )rQ   ÚfminÚfmaxr   .)ÚsuperÚcropr   rR   rË   r‰   r¶   rA   r·   Úwhererç   )rä   rê   rë   rí   rî   rì   Z	freq_mask©Ú	__class__r^   r_   rð   ›  s     ÿz_BaseTFR.cropc                 C   s   t | ƒS )zªReturn a copy of the instance.

        Returns
        -------
        copy : instance of EpochsTFR | instance of AverageTFR
            A copy of the instance.
        r   rã   r^   r^   r_   rÌ   Å  s    z_BaseTFR.copyrg   c                 C   s4   t || j| jd d�| _t| j| j| j|dd� | S )a©  Baseline correct the data.

        Parameters
        ----------
        baseline : array-like, shape (2,)
            The time interval to apply rescaling / baseline correction.
            If None do not apply it. If baseline is (a, b)
            the interval is between "a (s)" and "b (s)".
            If a is None the beginning of the data is used
            and if b is None then b is set to the end of the interval.
            If baseline is equal to (None, None) all the time
            interval is used.
        mode : 'mean' | 'ratio' | 'logratio' | 'percent' | 'zscore' | 'zlogratio'
            Perform baseline correction by

            - subtracting the mean of baseline values ('mean')
            - dividing by the mean of baseline values ('ratio')
            - dividing by the mean of baseline values and taking the log
              ('logratio')
            - subtracting the mean of baseline values followed by dividing by
              the mean of baseline values ('percent')
            - subtracting the mean of baseline values and dividing by the
              standard deviation of baseline values ('zscore')
            - dividing by the mean of baseline values, taking the log, and
              dividing by the standard deviation of log baseline values
              ('zlogratio')
        %(verbose)s

        Returns
        -------
        inst : instance of AverageTFR
            The modified instance.
        rQ   )rÎ   rQ   F©rÌ   )r	   rÎ   rË   râ   r   rØ   )rä   râ   r|   r   r^   r^   r_   Úapply_baselineÏ  s
    #ÿz_BaseTFR.apply_baselineF©r   c                C   s   t || |d� dS )a
  Save TFR object to hdf5 file.

        Parameters
        ----------
        fname : str
            The file name, which should end with ``-tfr.h5``.
        %(overwrite)s
        %(verbose)s

        See Also
        --------
        read_tfrs, write_tfrs
        )Ú	overwriteN)Ú
write_tfrs)rä   Úfnamer÷   r   r^   r^   r_   Úsave÷  s    z_BaseTFR.savec             	      sê  t ƒ }ddg}t| tƒr&| ddg¡ ddg}t||ƒ}t||ƒ}| j}	t| j|ddd	�}t| tƒr„| j	d
d
…|d
d
…d
d
…f }
n| j	t
j|f }
|
j\}}}}t
 |
dd¡}
|
 || | |¡}
tƒ ‰ t
 |	|| ¡}	t| |	|ƒ}	ˆ  d|	f¡ | j}t
 t
 ||¡|¡}ˆ  d|f¡ t| tƒ�r’ˆ  dt
 | j|| ¡f¡ dd„ | j ¡ D ƒ‰‡fdd„| jd
d
…df D ƒ}ˆ  dt
 ||| ¡f¡ t‡ fdd„ˆ D ƒƒ�s®t‚t| tƒ�rÈddddg}nddg}t| |
||ˆ ||d�}|S )aË  Export data in tabular structure as a pandas DataFrame.

        Channels are converted to columns in the DataFrame. By default,
        additional columns ``'time'``, ``'freq'``, ``'epoch'``, and
        ``'condition'`` (epoch event description) are added, unless ``index``
        is not ``None`` (in which case the columns specified in ``index`` will
        be used to form the DataFrame's index instead). ``'epoch'``, and
        ``'condition'`` are not supported for ``AverageTFR``.

        Parameters
        ----------
        %(picks_all)s
        %(index_df_epo)s
            Valid string values are ``'time'``, ``'freq'``, ``'epoch'``, and
            ``'condition'`` for ``EpochsTFR`` and ``'time'`` and ``'freq'``
            for ``AverageTFR``.
            Defaults to ``None``.
        %(long_format_df_epo)s
        %(time_format_df)s

            .. versionadded:: 0.23
        %(verbose)s

        Returns
        -------
        %(df_return)s
        ÚtimeÚfreqÚepochÚ	conditionÚmsÚ	timedeltaÚallr^   ©ÚexcludeNr   r<   c                 S   s   i | ]\}}||“qS r^   r^   ©rl   rW   Úvr^   r^   r_   Ú
<dictcomp>E  s      z*_BaseTFR.to_data_frame.<locals>.<dictcomp>c                    s   g | ]}ˆ | ‘qS r^   r^   ©rl   rW   )Úrev_event_idr^   r_   r¤   F  s     z*_BaseTFR.to_data_frame.<locals>.<listcomp>r   c                 3   s"   | ]}t |ƒt ˆ d  ƒkV  qdS ©r   N©rG   )rl   Zmdx)Úmindexr^   r_   rn   I  s     z)_BaseTFR.to_data_frame.<locals>.<genexpr>)Údefault_index)r   r¶   rÒ   Úextendr   r    rÎ   r)   rË   rØ   rA   Únewaxisrf   ZmoveaxisZreshaper@   Ztiler!   rP   rR   ÚrepeatrÆ   rÅ   ÚitemsrÄ   r  ÚAssertionErrorr"   )rä   rÕ   ÚindexZlong_formatÚtime_formatr   ÚpdZvalid_index_argsZvalid_time_formatsrÎ   rØ   r±   Ún_picksr�   rt   rR   Ú
conditionsr  Zdfr^   )r  r  r_   Úto_data_frame  sN    



 ÿ ÿÿz_BaseTFR.to_data_frame)NNNNT)rg   N)F)NNFN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rå   ÚpropertyrØ   Úsetterrè   r   rð   rÌ   r   rõ   rú   r  Ú__classcell__r^   r^   rò   r_   rá   ˆ  s.   


  ÿ)
'  ÿÿrá   c                       sb  e Zd ZdZed6‡ fdd„	ƒZeddddddddddddddddd	ddd
ddg ddfdd„ƒZeddddddddddddddddd	ddd
dddddeƒ dddfdd„ƒZedddddddddddddddd	dg dddfdd„ƒZ	ed7dd„ƒZ
ed8dd„ƒZed9d d!„ƒZd"d#„ Zd$d%„ Zd&d'„ Zd(d)„ Zd*d+„ Zd,d-„ Zd.d/„ Zd0d1„ Zd2d3„ Zd4d5„ Z‡  ZS ):rÐ   aá  Container for Time-Frequency data.

    Can for example store induced power at sensor level or inter-trial
    coherence.

    Parameters
    ----------
    %(info_not_none)s
    data : ndarray, shape (n_channels, n_freqs, n_times)
        The data.
    times : ndarray, shape (n_times,)
        The time values in seconds.
    freqs : ndarray, shape (n_freqs,)
        The frequencies in Hz.
    nave : int
        The number of averaged TFRs.
    comment : str | None, default None
        Comment on the data, e.g., the experimental condition.
    method : str | None, default None
        Comment on the method used to compute the data, e.g., morlet wavelet.
    %(verbose)s

    Attributes
    ----------
    %(info_not_none)s
    ch_names : list
        The names of the channels.
    nave : int
        Number of averaged epochs.
    data : ndarray, shape (n_channels, n_freqs, n_times)
        The data array.
    times : ndarray, shape (n_times,)
        The time values in seconds.
    freqs : ndarray, shape (n_freqs,)
        The frequencies in Hz.
    comment : str
        Comment on dataset. Can be the condition.
    method : str | None, default None
        Comment on the method used to compute the data, e.g., morlet wavelet.
    Nc	                    sî   t ƒ  ¡  || _|jdkr(td|j ƒ‚|j\}	}
}|	t|d ƒkr\td|	t|d ƒf ƒ‚|
t|ƒkr|td|
t|ƒf ƒ‚|t|ƒkrœtd|t|ƒf ƒ‚|| _|  t	j
|td�¡ | j ¡ | _t	j
|td�| _|| _|| _|| _d| _d S )	Nr™   zdata should be 3d. Got %d.Úchsú8Number of channels and data size don't match (%d != %d).ú;Number of frequencies and data size don't match (%d != %d).ú5Number of times and data size don't match (%d != %d).r�   T)rï   rå   rË   r©   rE   rf   rG   rØ   Ú
_set_timesrA   rC   re   rÎ   rÌ   Ú
_raw_timesrR   rÙ   Úcommentr¦   Úpreload)rä   rË   rØ   rÎ   rR   rÙ   r%  r¦   r   Ú
n_channelsr�   rt   rò   r^   r_   rå     s2    

ÿ
ÿ
ÿzAverageTFR.__init__rg   ÚRdBu_rFTÚautoZGreysçš™™™™™¹?c                 C   s<   | j |||||||||	|
|||||||||||||||d�S )aq  Plot TFRs as a two-dimensional image(s).

        Parameters
        ----------
        %(picks_good_data)s
        baseline : None (default) or tuple, shape (2,)
            The time interval to apply baseline correction.
            If None do not apply it. If baseline is (a, b)
            the interval is between "a (s)" and "b (s)".
            If a is None the beginning of the data is used
            and if b is None then b is set to the end of the interval.
            If baseline is equal to (None, None) all the time
            interval is used.
        mode : 'mean' | 'ratio' | 'logratio' | 'percent' | 'zscore' | 'zlogratio'
            Perform baseline correction by

            - subtracting the mean of baseline values ('mean') (default)
            - dividing by the mean of baseline values ('ratio')
            - dividing by the mean of baseline values and taking the log
              ('logratio')
            - subtracting the mean of baseline values followed by dividing by
              the mean of baseline values ('percent')
            - subtracting the mean of baseline values and dividing by the
              standard deviation of baseline values ('zscore')
            - dividing by the mean of baseline values, taking the log, and
              dividing by the standard deviation of log baseline values
              ('zlogratio')

        tmin : None | float
            The first time instant to display. If None the first time point
            available is used. Defaults to None.
        tmax : None | float
            The last time instant to display. If None the last time point
            available is used. Defaults to None.
        fmin : None | float
            The first frequency to display. If None the first frequency
            available is used. Defaults to None.
        fmax : None | float
            The last frequency to display. If None the last frequency
            available is used. Defaults to None.
        vmin : float | None
            The minimum value an the color scale. If vmin is None, the data
            minimum value is used. Defaults to None.
        vmax : float | None
            The maximum value an the color scale. If vmax is None, the data
            maximum value is used. Defaults to None.
        cmap : matplotlib colormap | 'interactive' | (colormap, bool)
            The colormap to use. If tuple, the first value indicates the
            colormap to use and the second value is a boolean defining
            interactivity. In interactive mode the colors are adjustable by
            clicking and dragging the colorbar with left and right mouse
            button. Left mouse button moves the scale up and down and right
            mouse button adjusts the range. Hitting space bar resets the range.
            Up and down arrows can be used to change the colormap. If
            'interactive', translates to ('RdBu_r', True). Defaults to
            'RdBu_r'.

            .. warning:: Interactive mode works smoothly only for a small
                amount of images.

        dB : bool
            If True, 10*log10 is applied to the data to get dB.
            Defaults to False.
        colorbar : bool
            If true, colorbar will be added to the plot. Defaults to True.
        show : bool
            Call pyplot.show() at the end. Defaults to True.
        title : str | 'auto' | None
            String for ``title``. Defaults to None (blank/no title). If
            'auto', and ``combine`` is None, the title for each figure
            will be the channel name. If 'auto' and ``combine`` is not None,
            ``title`` states how many channels were combined into that figure
            and the method that was used for ``combine``. If str, that String
            will be the title for each figure.
        axes : instance of Axes | list | None
            The axes to plot to. If list, the list must be a list of Axes of
            the same length as ``picks``. If instance of Axes, there must be
            only one channel plotted. If ``combine`` is not None, ``axes``
            must either be an instance of Axes, or a list of length 1.
        layout : Layout | None
            Layout instance specifying sensor positions. Used for interactive
            plotting of topographies on rectangle selection. If possible, the
            correct layout is inferred from the data.
        yscale : 'auto' (default) | 'linear' | 'log'
            The scale of y (frequency) axis. 'linear' gives linear y axis,
            'log' leads to log-spaced y axis and 'auto' detects if frequencies
            are log-spaced and only then sets the y axis to 'log'.

            .. versionadded:: 0.14.0
        mask : ndarray | None
            An array of booleans of the same shape as the data. Entries of the
            data that correspond to False in the mask are plotted
            transparently. Useful for, e.g., masking for statistical
            significance.

            .. versionadded:: 0.16.0
        mask_style : None | 'both' | 'contour' | 'mask'
            If ``mask`` is not None: if ``'contour'``, a contour line is drawn
            around the masked areas (``True`` in ``mask``). If ``'mask'``,
            entries not ``True`` in ``mask`` are shown transparently. If
            ``'both'``, both a contour and transparency are used.
            If ``None``, defaults to ``'both'`` if ``mask`` is not None, and is
            ignored otherwise.

             .. versionadded:: 0.17
        mask_cmap : matplotlib colormap | (colormap, bool) | 'interactive'
            The colormap chosen for masked parts of the image (see below), if
            ``mask`` is not ``None``. If None, ``cmap`` is reused. Defaults to
            ``'Greys'``. Not interactive. Otherwise, as ``cmap``.

             .. versionadded:: 0.17
        mask_alpha : float
            A float between 0 and 1. If ``mask`` is not None, this sets the
            alpha level (degree of transparency) for the masked-out segments.
            I.e., if 0, masked-out segments are not visible at all.
            Defaults to 0.1.

            .. versionadded:: 0.16.0
        combine : 'mean' | 'rms' | None
            Type of aggregation to perform across selected channels. If
            None, plot one figure per selected channel.
        exclude : list of str | 'bads'
            Channels names to exclude from being shown. If 'bads', the
            bad channels are excluded. Defaults to an empty list.
        %(cnorm)s

            .. versionadded:: 0.24
        %(verbose)s

        Returns
        -------
        figs : list of instances of matplotlib.figure.Figure
            A list of figures containing the time-frequency power.
        )rÕ   râ   r|   rê   rë   rí   rî   ÚvminÚvmaxÚcmapÚdBÚcolorbarÚshowÚtitleÚaxesÚlayoutÚyscaleÚmaskÚ
mask_styleÚ	mask_cmapÚ
mask_alphaÚcombiner  Úcnormr   )Ú_plot)rä   rÕ   râ   r|   rê   rë   rí   rî   r+  r,  r-  r.  r/  r0  r1  r2  r3  r4  r5  r6  r7  r8  r9  r  r:  r   r^   r^   r_   Úplot™  s2     
               ùzAverageTFR.plotg      Ð?c           )         s|  ddl m‰  ddlm} t| |||||||	|||||ƒ}~|j} |dkrRt|jƒnd}!|dkrn| jddd�} n2|d	kr�t	 
| d jddd�¡} n|dk	r td
ƒ‚|jddg \}}|	dkrÈt	 | ¡ ¡ }	|dkràt	 | ¡ ¡  }t|
ƒ}
t|tƒ�st|t	jƒ�rdd„ |D ƒ}"nXt|ˆ jƒ�r2dd„ |fD ƒ}"n8|dk�rb‡ fdd„t|!ƒD ƒ}#dd„ |#D ƒ}"ntdƒ‚t|"ƒ|!k�r€tdƒ‚t|!ƒD ]Ü}$|"|$ d }%|"|$ d }&t|j|
|dd„ | ¡ D ƒd�}'||&d||||	|'d| |$|$d … |jdd||
||||||d� |dk�rTt|jd ƒdk�s*|dk�r:|jd |$ }(ntd||jd d|d�}(n|}(|% |(¡ �qˆt|ƒ dd„ |"D ƒS )zfPlot TFRs as a two-dimensional image(s).

        See self.plot() for parameters description.
        r   Nr   )Ú_imshow_tfrr   rg   T)rÂ   ÚkeepdimsÚrmsz"combine must be None, mean or rms.r<   c                 S   s   g | ]}|  ¡ |f‘qS r^   ©Z
get_figure©rl   Úaxr^   r^   r_   r¤   ^  s     z$AverageTFR._plot.<locals>.<listcomp>c                 S   s   g | ]}|  ¡ |f‘qS r^   r@  rA  r^   r^   r_   r¤   `  s     c                    s   g | ]}ˆ   ¡ ‘qS r^   )Zfigure)rl   rŽ   ©Úpltr^   r_   r¤   b  s     c                 S   s   g | ]}||  d ¡f‘qS )éo   )Úadd_subplot)rl   Úfigr^   r^   r_   r¤   c  s     z1axes must be None, plt.Axes, or list of plt.Axes.z.There must be an axes for each picked channel.c                 S   s   i | ]\}}|d kr||“qS )>   r,  r-  r2  r+  r^   r  r^   r^   r_   r  p  s    ÿ z$AverageTFR._plot.<locals>.<dictcomp>)r-  Úsource_plot_jointÚtopomap_argsúTime (s)úFrequency (Hz))Zylimr�   rü   Úx_labelÚy_labelr/  r-  r4  r5  r6  r7  r8  r:  r)  rè   )r  Úch_typec                 S   s   g | ]\}}|‘qS r^   r^   )rl   rG  rB  r^   r^   r_   r¤   …  s     )Úmatplotlib.pyplotÚpyplotÚviz.topor=  Ú_preproc_tfr_instancerØ   rG   rè   rg   rA   rL   rE   rÎ   rˆ   ro   r1   r¶   r@   r·   ZAxesrd   ÚRuntimeErrorr   Ú	_onselectr  rR   rË   r5   Úsuptitler0   ))rä   rÕ   râ   r|   rê   rë   rí   rî   r+  r,  r-  r.  r/  r0  r1  r2  r3  r4  r5  r6  r7  r8  r9  r  rÌ   rH  rI  rN  r:  r   r=  r�   rØ   r  Zfigs_and_axesÚfigsÚidxrG  rB  Úonselect_callbackÚsubtitler^   rC  r_   r;  /  s®               þ
  þ               û
   þzAverageTFR._plotc           C         s  ddl m}m}m}m} ddlm} tdd„ |||fD ƒƒ}t| |||d�‰~t	ˆj
dd	�}t|ƒd
k�rt 
d¡ tƒ }|D ]ˆ‰‡‡fdd„tˆj
d ƒD ƒ}tˆ|ddd�}tt	|j
dd	�ƒd
krÎtdƒ‚| |j|d|||||||	|
|||d|||d||d�¡ q~|S | ¡ } tˆ|ƒ}t|ƒ}!|dk�r6tƒ }dd„ | ¡ D ƒ}"| dd¡|"d< | dd¡|"d< | |"d< t|!ƒ\‰ ‰}#}$t|ƒ}|dk�r˜tƒ }ˆjf d|||||||	|
||dd|ˆ||ddd|"| dœ|—Žd ‰ ˆj ¡ ˆj ¡  }}ˆj ¡ ˆj ¡  }}| ¡ D ]v\}%}&||%  k�r.|k�sBn dt|%ƒ d }'n0||&  k�rZ|k�sn dt|&ƒ d }'n�qt d|' d ƒ‚�qg g g g f\}(})}*}+t! "d d„ |D ƒ¡},|,dd…df  #¡ }-t$|,|- ƒD �]ø\}.\}%}&||%|&f }/|/d! \}0}1|0dk�rˆjt! %t! &ˆj|% ¡¡ }%|1dk�r@ˆjt! %t! &ˆj|& ¡¡ }&|0dk�rb|1dk�rbd"|%|&f }2nd#|%|0|&|1f }2|%|0 }|%|0 }|&|1 }|&|1 }ˆj'}3| d$¡}4| d%k�rüt(ˆj
dd&�}|ˆj
|ddd… |4d'�}5|�pÜd(}6t)|3| | g |6d)�\}3}7~~6n|ˆj
d|4ƒ\}5}7~4|* |5¡ t*|3ˆjˆj|||||||	|
dˆj
d* ƒ\}3}8}9}7}7|+ t! &|3¡ ¡ ¡ |( |2¡ |) |3¡ ˆjt! &ˆjt! +|8g¡ ¡ %¡  }:ˆjt! &ˆjt! +|9g¡ ¡ %¡  };|:|;f|,|.< �qÎt|+ƒ}<| d+|< ¡ |"d+< }	| d,|<¡ |"d,< }
||	|
|"d ƒ\}=}>|>|"d< t,|#|(|)|*ƒD ]>\}?}}3}5|? -|¡ ||3j.d-d.�|5f|d |?dd/œ|"—Ž �q&|�r°dd0l/m0}@ |j1|?j2d |$d1�}A|=dk�r¢|@j3d2d3�}=|=|A_4|A 5¡  |j6d4d5d6|dk	�rÈd7nd8d9� ‡ ‡fd:d„t,|,|#ƒD ƒ}Bˆ j7 8|B¡ t9|ƒ ˆ S );aÊ  Plot TFRs as a two-dimensional image with topomaps.

        Parameters
        ----------
        timefreqs : None | list of tuple | dict of tuple
            The time-frequency point(s) for which topomaps will be plotted.
            See Notes.
        %(picks_good_data)s
        baseline : None (default) or tuple of length 2
            The time interval to apply baseline correction.
            If None do not apply it. If baseline is (a, b)
            the interval is between "a (s)" and "b (s)".
            If a is None, the beginning of the data is used.
            If b is None, then b is set to the end of the interval.
            If baseline is equal to (None, None), the  entire time
            interval is used.
        mode : None | str
            If str, must be one of 'ratio', 'zscore', 'mean', 'percent',
            'logratio' and 'zlogratio'.
            Do baseline correction with ratio (power is divided by mean
            power during baseline) or zscore (power is divided by standard
            deviation of power during baseline after subtracting the mean,
            power = [power - mean(power_baseline)] / std(power_baseline)),
            mean simply subtracts the mean power, percent is the same as
            applying ratio then mean, logratio is the same as mean but then
            rendered in log-scale, zlogratio is the same as zscore but data
            is rendered in log-scale first.
            If None no baseline correction is applied.
        tmin : None | float
            The first time instant to display. If None the first time point
            available is used.
        tmax : None | float
            The last time instant to display. If None the last time point
            available is used.
        fmin : None | float
            The first frequency to display. If None the first frequency
            available is used.
        fmax : None | float
            The last frequency to display. If None the last frequency
            available is used.
        vmin : float | None
            The minimum value of the color scale for the image (for
            topomaps, see ``topomap_args``). If vmin is None, the data
            absolute minimum value is used.
        vmax : float | None
            The maximum value of the color scale for the image (for
            topomaps, see ``topomap_args``). If vmax is None, the data
            absolute maximum value is used.
        cmap : matplotlib colormap
            The colormap to use.
        dB : bool
            If True, 10*log10 is applied to the data to get dB.
        colorbar : bool
            If true, colorbar will be added to the plot (relating to the
            topomaps). For user defined axes, the colorbar cannot be drawn.
            Defaults to True.
        show : bool
            Call pyplot.show() at the end.
        title : str | None
            String for title. Defaults to None (blank/no title).
        yscale : 'auto' (default) | 'linear' | 'log'
            The scale of y (frequency) axis. 'linear' gives linear y axis,
            'log' leads to log-spaced y axis and 'auto' detects if frequencies
            are log-spaced and only then sets the y axis to 'log'.
        combine : 'mean' | 'rms'
            Type of aggregation to perform across selected channels.
        exclude : list of str | 'bads'
            Channels names to exclude from being shown. If 'bads', the
            bad channels are excluded. Defaults to an empty list, i.e., ``[]``.
        topomap_args : None | dict
            A dict of ``kwargs`` that are forwarded to
            :func:`mne.viz.plot_topomap` to style the topomaps. ``axes`` and
            ``show`` are ignored. If ``times`` is not in this dict, automatic
            peak detection is used. Beyond that, if ``None``, no customizable
            arguments will be passed.
            Defaults to ``None``.
        image_args : None | dict
            A dict of ``kwargs`` that are forwarded to :meth:`AverageTFR.plot`
            to style the image. ``axes`` and ``show`` are ignored. Beyond that,
            if ``None``, no customizable arguments will be passed.
            Defaults to ``None``.
        %(verbose)s

        Returns
        -------
        fig : matplotlib.figure.Figure
            The figure containing the topography.

        Notes
        -----
        ``timefreqs`` has three different modes: tuples, dicts, and auto.
        For (list of) tuple(s) mode, each tuple defines a pair
        (time, frequency) in s and Hz on the TFR plot. For example, to
        look at 10 Hz activity 1 second into the epoch and 3 Hz activity
        300 msec into the epoch, ::

            timefreqs=((1, 10), (.3, 3))

        If provided as a dictionary, (time, frequency) tuples are keys and
        (time_window, frequency_window) tuples are the values - indicating the
        width of the windows (centered on the time and frequency indicated by
        the key) to be averaged over. For example, ::

            timefreqs={(1, 10): (0.1, 2)}

        would translate into a window that spans 0.95 to 1.05 seconds, as
        well as 9 to 11 Hz. If None, a single topomap will be plotted at the
        absolute peak across the time-frequency representation.

        .. versionadded:: 0.16.0
        r   )Ú_set_contour_locatorÚplot_topomapÚ_get_pos_outlinesÚ_find_topomap_coordsr   Nc                 s   s   | ]}|d k	V  qd S rk   r^   )rl   Úvarr^   r^   r_   rn   
  s     z(AverageTFR.plot_joint.<locals>.<genexpr>rô   T)Úuniquer   z?Multiple channel types selected, returning one figure per type.c                    s    g | ]}t ˆ j|ƒˆkr|‘qS r^   )r*   rË   )rl   rW  )r�   Ú	this_typer^   r_   r¤     s    ÿz)AverageTFR.plot_joint.<locals>.<listcomp>ZnchanzsPossibly infinite loop due to channel selection problem. This should never happen! Please check your channel types.F)Ú	timefreqsrÕ   râ   r|   rê   rë   rí   rî   r+  r,  r-  r.  r/  r0  r1  r4  r9  r  rI  r   c                 S   s   i | ]\}}|d kr||“qS ))r2  r0  r/  r^   r  r^   r^   r_   r  0  s    ÿ z)AverageTFR.plot_joint.<locals>.<dictcomp>ÚoutlinesZskirtÚcontoursé   rN  )rÕ   râ   r|   rê   rë   rí   rî   r+  r,  r-  r.  r/  r0  r1  r2  r4  r9  r  rÌ   rH  rI  rN  ztime point (z s)zfrequency (z Hz)z
Requested z< exceeds the rangeof the data. Choose different `timefreqs`.c                 S   s   g | ]}t  |¡‘qS r^   )rA   rC   )rl   Úkeysr^   r^   r_   r¤   d  s     r9   z(%.2f s,
%.1f Hz)u!   (%.1f Â± %.1f s,
%.1f Â± %.1f Hz)ÚsphereÚgrad)Útopomap_coords)rÕ   rf  r?  rÃ   rQ   r+  r,  )r<   r>   rÁ   )r-  r2  r0  )Úticker)Zcaxé   )Znbinsg¸…ëQ¸¾?gš™™™™™í?gìQ¸…ëÁ?r;   g333333ó?)ÚleftÚrightÚbottomÚtopc              
      s(   g | ] \\}}}t |ˆ ˆ||d d�‘qS )Z	transData)ÚyZy_source_transform)r2   )rl   Ztime_Zfreq_Zmap_ax_)rG  Útf_axr^   r_   r¤   ¹  s   
þÿ):Úviz.topomaprZ  r[  r\  r]  rO  rP  rD   r+   r,   rË   rG   r   r@   rd   rS  rP   Ú
plot_jointÚpopÚ_get_timefreqsrÝ   r  Úgetr3   r1   r;  rÎ   ro   ÚminrR   re  ÚstrrE   rA   rC   ZargsortrH   Zargminrˆ   rØ   r'   r&   Ú_preproc_tfrZmedianÚzipÚ	set_titlerg   Z
matplotlibri  r/  ZimagesZMaxNLocatorÚlocatorZupdate_ticksZsubplots_adjustÚlinesr  r0   )Crä   ra  rÕ   râ   r|   rê   rë   rí   rî   r+  r,  r-  r.  r/  r0  r1  r4  r9  r  rI  Z
image_argsr   rZ  r[  r\  r]  rD  rÌ   Zch_typesrV  Z
type_picksZtf_rN  Zn_timefreqsZtopomap_args_passZmap_axZcbar_axrû   rü   Zerror_valueÚtitlesZall_dataZall_posZvlimsZtimefreqs_arrayÚorderr‘   ÚavgZtime_half_rangeZfreq_half_rangeZsub_map_titlerØ   rf  Úposr¦   rŒ   rÎ   rR   Znew_tÚnew_fZmax_limr{  rc  rB  ri  Zcbarr|  r^   )rG  rp  r�   r`  r_   rr  ‡  sn   v
ÿ             ùÿ	


                úúú


ÿÿ

  ÿ
ÿ

           þ

""  ÿ
  ÿþ


ÿþzAverageTFR.plot_jointc	                    sŒ  ddl m}	m}
m} t|j|j ƒdk s<t|j|j ƒdk r@dS tt|j	|j	ƒdƒ‰tt
|j	|j	ƒdƒ‰tt|j|jƒdƒ‰tt
|j|jƒdƒ‰ t| j‡fdd„d�‰t| j‡fd	d„d�‰t| j‡fd
d„d�‰t| j‡ fdd„d�‰ ˆˆksúˆˆ k�rt d¡ dS tƒ }d| k�r"| d¡ d| k�r6| d¡ d| k�rxtt| jddd�ƒdk�rf| d¡ nt|ƒdk�rxdS tƒ }|jd ˆˆˆˆ ¡dd� |�r<| d¡}t| j| j| jˆˆˆˆ ddddd| jd ƒd }| d¡ d¡}t |¡ 
¡ }|
|| jf| ||d |ddœ|—Ž\}}||||ddd� | ¡  nLt|ƒD ]B\}}| dt|ƒ|d ¡}|	| |ˆˆˆˆ ||d|dd|d� �qDdS )z+Handle rubber band selector in channel tfr.r   )Úplot_tfr_topomapr[  Ú_add_colorbarr*  Nrj  c                    s   t | ˆ  ƒS rk   ©rˆ   ©r�   )rê   r^   r_   Ú<lambda>Í  ó    z&AverageTFR._onselect.<locals>.<lambda>)Úkeyc                    s   t | ˆ  ƒS rk   r„  r…  )rë   r^   r_   r†  Î  r‡  c                    s   t | ˆ  ƒS rk   r„  r…  )rí   r^   r_   r†  Ï  r‡  c                    s   t | ˆ  ƒS rk   r„  r…  )rî   r^   r_   r†  Ð  r‡  zFThe selected area is too small. Select a larger time-frequency window.ZeegÚmagrg  F)rh  Zraise_errorr   z*{:.2f} s - {:.2f} s, {:.2f} Hz - {:.2f} Hzg{®Gáz¤?)ro  rE  rQ   r<   )r+  r,  r-  r2  r0  ZAU)r1  Úpadr   )rN  rê   rë   rí   rî   râ   r|   r-  r1  r+  r,  r2  )rq  r‚  r[  rƒ  rˆ   r�   ro  Úroundrv  Zxdataro   ZydatarÎ   rR   r   rË   r@   rP   rG   r'   r/   rU  ÚformatrF  rx  rØ   rg   rA   r0  rH   )rä   ZeclickZereleaserâ   r|   r-  rH  rI  r   r‚  r[  rƒ  ÚtypesrG  rB  rØ   r,  ZimrŒ   rW  rN  r^   )rî   rí   rë   rê   r_   rT  Á  s     (






ÿÿ   ÿÿ
           þþ  ÿþ


      ýzAverageTFR._onselectç=
×£p=î?ÚnonerW   rm   c           $      C   s  ddl m}m}m} ddlm} | j ¡ }| j}| j	}| j
}t|||dd�\}}~t|||||||||||	||d ƒ\}}}}}	|
dkržddlm} || j
ƒ}
t| j||d	�} t|||||d
f| d�}!t||||| d�}"||||"|!|
|||	||||dd||d
d
d�}#||#|ƒ t|ƒ |#S )ar  Plot TFRs in a topography with images.

        Parameters
        ----------
        %(picks_good_data)s
        baseline : None (default) or tuple of length 2
            The time interval to apply baseline correction.
            If None do not apply it. If baseline is (a, b)
            the interval is between "a (s)" and "b (s)".
            If a is None the beginning of the data is used
            and if b is None then b is set to the end of the interval.
            If baseline is equal to (None, None) all the time
            interval is used.
        mode : 'mean' | 'ratio' | 'logratio' | 'percent' | 'zscore' | 'zlogratio'
            Perform baseline correction by

            - subtracting the mean of baseline values ('mean')
            - dividing by the mean of baseline values ('ratio')
            - dividing by the mean of baseline values and taking the log
              ('logratio')
            - subtracting the mean of baseline values followed by dividing by
              the mean of baseline values ('percent')
            - subtracting the mean of baseline values and dividing by the
              standard deviation of baseline values ('zscore')
            - dividing by the mean of baseline values, taking the log, and
              dividing by the standard deviation of log baseline values
              ('zlogratio')

        tmin : None | float
            The first time instant to display. If None the first time point
            available is used.
        tmax : None | float
            The last time instant to display. If None the last time point
            available is used.
        fmin : None | float
            The first frequency to display. If None the first frequency
            available is used.
        fmax : None | float
            The last frequency to display. If None the last frequency
            available is used.
        vmin : float | None
            The minimum value of the color scale. If vmin is None, the data
            minimum value is used.
        vmax : float | None
            The maximum value of the color scale. If vmax is None, the data
            maximum value is used.
        layout : Layout | None
            Layout instance specifying sensor positions. If possible, the
            correct layout is inferred from the data.
        cmap : matplotlib colormap | str
            The colormap to use. Defaults to 'RdBu_r'.
        title : str
            Title of the figure.
        dB : bool
            If True, 10*log10 is applied to the data to get dB.
        colorbar : bool
            If true, colorbar will be added to the plot.
        layout_scale : float
            Scaling factor for adjusting the relative size of the layout
            on the canvas.
        show : bool
            Call pyplot.show() at the end.
        border : str
            Matplotlib borders style to be used for each sensor plot.
        fig_facecolor : color
            The figure face color. Defaults to black.
        fig_background : None | array
            A background image for the figure. This must be a valid input to
            `matplotlib.pyplot.imshow`. Defaults to None.
        font_color : color
            The color of tick labels in the colorbar. Defaults to white.
        yscale : 'auto' (default) | 'linear' | 'log'
            The scale of y (frequency) axis. 'linear' gives linear y axis,
            'log' leads to log-spaced y axis and 'auto' detects if frequencies
            are log-spaced and only then sets the y axis to 'log'.
        %(verbose)s

        Returns
        -------
        fig : matplotlib.figure.Figure
            The figure containing the topography.
        r   )r=  Ú
_plot_topoÚ_imshow_tfr_unified)Úadd_background_imager   rÁ   rQ   N)Úfind_layout)râ   r|   T)r�   rü   r4  r-  Úonselect)r�   rü   r-  r”  rJ  rK  )rË   rÎ   Z	show_funcZ
click_funcr3  r/  r+  r,  r-  Úlayout_scaler1  ÚborderrL  rM  Úfig_facecolorÚ
font_colorZunifiedZimg)rQ  r=  r�  r‘  Úvizr’  rÎ   rÌ   rR   rØ   rË   rÍ   rx  Zmner“  r   rT  r0   )$rä   rÕ   râ   r|   rê   rë   rí   rî   r+  r,  r3  r-  r1  r.  r/  r•  r0  r–  r—  Zfig_backgroundr˜  r4  r   r=  r�  r‘  r’  rÎ   rR   rØ   rË   r“  rX  Z	click_funZimshowrG  r^   r^   r_   Ú	plot_topoú  sd    Y
     ÿÿ
ÿ
 ÿ
ÿ         ú
zAverageTFR.plot_topoé@   r   ú%1.1eÚheadrd  c                 C   sD   ddl m} || |||||||||	|
|||||||||||||d�S )a§  Plot topographic maps of time-frequency intervals of TFR data.

        Parameters
        ----------
        tmin : None | float
            The first time instant to display. If None the first time point
            available is used.
        tmax : None | float
            The last time instant to display. If None the last time point
            available is used.
        fmin : None | float
            The first frequency to display. If None the first frequency
            available is used.
        fmax : None | float
            The last frequency to display. If None the last frequency
            available is used.
        ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg' | None
            The channel type to plot. For 'grad', the gradiometers are
            collected in pairs and the RMS for each pair is plotted.
            If None, then first available channel type from order given
            above is used. Defaults to None.
        baseline : tuple or list of length 2
            The time interval to apply rescaling / baseline correction.
            If None do not apply it. If baseline is (a, b)
            the interval is between "a (s)" and "b (s)".
            If a is None the beginning of the data is used
            and if b is None then b is set to the end of the interval.
            If baseline is equal to (None, None) all the time
            interval is used.
        mode : 'mean' | 'ratio' | 'logratio' | 'percent' | 'zscore' | 'zlogratio'
            Perform baseline correction by

            - subtracting the mean of baseline values ('mean')
            - dividing by the mean of baseline values ('ratio')
            - dividing by the mean of baseline values and taking the log
              ('logratio')
            - subtracting the mean of baseline values followed by dividing by
              the mean of baseline values ('percent')
            - subtracting the mean of baseline values and dividing by the
              standard deviation of baseline values ('zscore')
            - dividing by the mean of baseline values, taking the log, and
              dividing by the standard deviation of log baseline values
              ('zlogratio')
        vmin : float | callable | None
            The value specifying the lower bound of the color range. If None,
            and vmax is None, -vmax is used. Else np.min(data) or in case
            data contains only positive values 0. If callable, the output
            equals vmin(data). Defaults to None.
        vmax : float | callable | None
            The value specifying the upper bound of the color range. If None,
            the maximum value is used. If callable, the output equals
            vmax(data). Defaults to None.
        cmap : matplotlib colormap | (colormap, bool) | 'interactive' | None
            Colormap to use. If tuple, the first value indicates the colormap
            to use and the second value is a boolean defining interactivity. In
            interactive mode the colors are adjustable by clicking and dragging
            the colorbar with left and right mouse button. Left mouse button
            moves the scale up and down and right mouse button adjusts the
            range. Hitting space bar resets the range. Up and down arrows can
            be used to change the colormap. If None (default), 'Reds' is used
            for all positive data, otherwise defaults to 'RdBu_r'. If
            'interactive', translates to (None, True).
        sensors : bool | str
            Add markers for sensor locations to the plot. Accepts matplotlib
            plot format string (e.g., 'r+' for red plusses). If True, a circle
            will be used (via .add_artist). Defaults to True.
        colorbar : bool
            Plot a colorbar.
        unit : dict | str | None
            The unit of the channel type used for colorbar label. If
            scale is None the unit is automatically determined.
        res : int
            The resolution of the topomap image (n pixels along each side).
        size : float
            Side length per topomap in inches.
        cbar_fmt : str
            String format for colorbar values.
        show_names : bool | callable
            If True, show channel names on top of the map. If a callable is
            passed, channel names will be formatted using the callable; e.g.,
            to delete the prefix 'MEG ' from all channel names, pass the
            function lambda x: x.replace('MEG ', ''). If ``mask`` is not None,
            only significant sensors will be shown.
        title : str | None
            Title. If None (default), no title is displayed.
        axes : instance of Axes | None
            The axes to plot to. If None the axes is defined automatically.
        show : bool
            Call pyplot.show() at the end.
        %(outlines_topomap)s
        contours : int | array of float
            The number of contour lines to draw. If 0, no contours will be
            drawn. When an integer, matplotlib ticker locator is used to find
            suitable values for the contour thresholds (may sometimes be
            inaccurate, use array for accuracy). If an array, the values
            represent the levels for the contours. If colorbar=True, the ticks
            in colorbar correspond to the contour levels. Defaults to 6.
        %(sphere_topomap_auto)s

        Returns
        -------
        fig : matplotlib.figure.Figure
            The figure containing the topography.
        r   )r‚  )rê   rë   rí   rî   rN  râ   r|   r+  r,  r-  Úsensorsr/  ÚunitÚresrF   Úcbar_fmtÚ
show_namesr1  r2  r0  rb  rc  rf  )r™  r‚  )rä   rê   rë   rí   rî   rN  râ   r|   r+  r,  r-  rž  r/  rŸ  r   rF   r¡  r¢  r1  r2  r0  rb  rc  rf  r‚  r^   r^   r_   r[  x  s.    p
            øzAverageTFR.plot_topomapc                 C   s0   t  |j| jk¡st‚t  |j| jk¡s,t‚dS )z<Check that self and tfr have the same time-frequency ranges.N)rA   r  rÎ   r  rR   ©rä   r�   r^   r^   r_   Ú_check_compató  s    zAverageTFR._check_compatc                 C   s&   |   |¡ |  ¡ }| j|j7  _|S )zAdd instances.©r¤  rÌ   rØ   ©rä   r�   r²   r^   r^   r_   Ú__add__ø  s    
zAverageTFR.__add__c                 C   s   |   |¡ |  j|j7  _| S rk   ©r¤  rØ   r£  r^   r^   r_   Ú__iadd__ÿ  s    
zAverageTFR.__iadd__c                 C   s&   |   |¡ |  ¡ }| j|j8  _|S )zSubtract instances.r¥  r¦  r^   r^   r_   Ú__sub__  s    
zAverageTFR.__sub__c                 C   s   |   |¡ |  j|j8  _| S rk   r¨  r£  r^   r^   r_   Ú__isub__  s    
zAverageTFR.__isub__c                 C   s   |   ¡ }|| }|S )zDivide instances.rô   ©rä   Úar²   r^   r^   r_   Ú__truediv__  s    zAverageTFR.__truediv__c                 C   s   |  j |  _ | S rk   ©rØ   ©rä   r­  r^   r^   r_   Ú__itruediv__  s    zAverageTFR.__itruediv__c                 C   s   |   ¡ }||9 }|S )zMultiply source instances.rô   r¬  r^   r^   r_   Ú__mul__  s    zAverageTFR.__mul__c                 C   s   |  j |9  _ | S rk   r¯  r°  r^   r^   r_   Ú__imul__   s    zAverageTFR.__imul__c                 C   sr   d| j d | j d f }|d| jd | jd f 7 }|d| j 7 }|d| jjd  7 }|dt| jƒf 7 }d| S )	Nútime : [%f, %f]r   r<   ú, freq : [%f, %f]z, nave : %dú, channels : %dú, ~%sz<AverageTFR | %s>)rÎ   rR   rÙ   rØ   rf   r   Ú_size©rä   Úsr^   r^   r_   Ú__repr__$  s    zAverageTFR.__repr__)NNN)NNNFNN)NNrg   NNNNNNNr(  NFTrŽ  Tr�  rW   Nrm   r)  N)NNNNNNrg   NNNTTNr›  r   rœ  FNNTr�  rd  N)r  r  r  r  r   rå   r<  rÝ   r;  rr  rT  rš  r   r[  r¤  r§  r©  rª  r«  r®  r±  r²  r³  r»  r  r^   r^   rò   r_   rÐ   T  s  )    ÿ                û                   ùW             û  ;       þ8                                û}                                 úzrÐ   c                	       sL   e Zd ZdZed‡ fdd„	ƒZedd„ ƒZdd„ Zd	d
„ Z	ddd„Z
‡  ZS )rÒ   að  Container for Time-Frequency data on epochs.

    Can for example store induced power at sensor level.

    Parameters
    ----------
    %(info_not_none)s
    data : ndarray, shape (n_epochs, n_channels, n_freqs, n_times)
        The data.
    times : ndarray, shape (n_times,)
        The time values in seconds.
    freqs : ndarray, shape (n_freqs,)
        The frequencies in Hz.
    comment : str | None, default None
        Comment on the data, e.g., the experimental condition.
    method : str | None, default None
        Comment on the method used to compute the data, e.g., morlet wavelet.
    events : ndarray, shape (n_events, 3) | None
        The events as stored in the Epochs class. If None (default), all event
        values are set to 1 and event time-samples are set to range(n_epochs).
    event_id : dict | None
        Example: dict(auditory=1, visual=3). They keys can be used to access
        associated events. If None, all events will be used and a dict is
        created with string integer names corresponding to the event id
        integers.
    selection : iterable | None
        Iterable of indices of selected epochs. If ``None``, will be
        automatically generated, corresponding to all non-zero events.

        .. versionadded:: 0.23
    drop_log : tuple | None
        Tuple of tuple of strings indicating which epochs have been marked to
        be ignored.

        .. versionadded:: 0.23
    metadata : instance of pandas.DataFrame | None
        A :class:`pandas.DataFrame` containing pertinent information for each
        trial. See :class:`mne.Epochs` for further details.
    %(verbose)s

    Attributes
    ----------
    %(info_not_none)s
    ch_names : list
        The names of the channels.
    data : ndarray, shape (n_epochs, n_channels, n_freqs, n_times)
        The data array.
    times : ndarray, shape (n_times,)
        The time values in seconds.
    freqs : ndarray, shape (n_freqs,)
        The frequencies in Hz.
    comment : string
        Comment on dataset. Can be the condition.
    method : str | None, default None
        Comment on the method used to compute the data, e.g., morlet wavelet.
    events : ndarray, shape (n_events, 3) | None
        Array containing sample information as event_id
    event_id : dict | None
        Names of conditions correspond to event_ids
    selection : array
        List of indices of selected events (not dropped or ignored etc.). For
        example, if the original event array had 4 events and the second event
        has been dropped, this attribute would be np.array([0, 2, 3]).
    drop_log : tuple of tuple
        A tuple of the same length as the event array used to initialize the
        ``EpochsTFR`` object. If the i-th original event is still part of the
        selection, drop_log[i] will be an empty tuple; otherwise it will be
        a tuple of the reasons the event is not longer in the selection, e.g.:

        - ``'IGNORED'``
            If it isn't part of the current subset defined by the user
        - ``'NO_DATA'`` or ``'TOO_SHORT'``
            If epoch didn't contain enough data names of channels that
            exceeded the amplitude threshold
        - ``'EQUALIZED_COUNTS'``
            See :meth:`~mne.Epochs.equalize_event_counts`
        - ``'USER'``
            For user-defined reasons (see :meth:`~mne.Epochs.drop`).

    metadata : pandas.DataFrame, shape (n_events, n_cols) | None
        DataFrame containing pertinent information for each trial
    Notes
    -----
    .. versionadded:: 0.13.0
    Nc                    sÖ  t ƒ  ¡  || _|jdkr(td|j ƒ‚|j\}}}}|t|d ƒkr^td|t|d ƒf ƒ‚|t|ƒkr~td|t|ƒf ƒ‚|t|ƒkržtd|t|ƒf ƒ‚|d kr¶t|ƒ}t|ƒ}ˆ d krÐt|ƒ}t 	|¡‰ |
d k�rt
t|ƒt
ˆ ƒd ƒ}t‡ fdd	„t|ƒD ƒƒ}
n|
}
tˆ ƒt|ƒk�s&t‚t|
ƒt|ƒk�s<t‚tˆ ƒtd
d	„ |
D ƒƒk�s\t‚t||ƒ}|| _|  tj|td�¡ | j ¡ | _d| _tj|td�| _|| _|| _ˆ | _|
| _|| _|| _d| _|| _ d S )Nr¨   zdata should be 4d. Got %d.r  r   r!  r"  r   c                 3   s   | ]}|ˆ krd ndV  qdS )r^   )ZIGNOREDNr^   r  ©rÆ   r^   r_   rn      s   ÿz%EpochsTFR.__init__.<locals>.<genexpr>c                 s   s   | ]}t |ƒd kV  qdS r	  r
  )rl   Údlr^   r^   r_   rn   ©  s     r�   T)!rï   rå   rË   r©   rE   rf   rG   r   rA   rJ   ro   Útuplerd   r  r¬   r   rØ   r#  rC   re   rÎ   rÌ   r$  Z_decimrR   rÄ   rÅ   rÆ   rÇ   r%  r¦   r&  rÈ   )rä   rË   rØ   rÎ   rR   r%  r¦   rÄ   rÅ   rÆ   rÇ   rÈ   r   r±   r'  r�   rt   Zn_epochs_prerejectionrò   r¼  r_   rå   …  s`    

ÿ
ÿ
ÿ

þ
ÿ
zEpochsTFR.__init__c                 C   s   t ƒ S rk   r£   rã   r^   r^   r_   Ú_detrend_picks¹  s    zEpochsTFR._detrend_picksc                 C   sx   d| j d | j d f }|d| jd | jd f 7 }|d| jjd  7 }|d| jjd  7 }|dt| jƒf 7 }d	| S )
Nr´  r   r<   rµ  z, epochs : %dr¶  r   r·  z<EpochsTFR | %s>)rÎ   rR   rØ   rf   r   r¸  r¹  r^   r^   r_   r»  ½  s    zEpochsTFR.__repr__c                 C   s   |   ¡ }t | j¡|_|S )zTake the absolute value.)rÌ   rA   rˆ   rØ   )rä   rÉ   r^   r^   r_   Ú__abs__Å  s    zEpochsTFR.__abs__rg   rÉ   Fc                 C   sj  t d|dƒ tdd| jjd d�| }t||d�}|| jƒ}| jj\}}}	}
| j| j }}|dkrxtj	| jdd	�}d}	n|d
kr”tj	| jdd	�}d}
|dkr®| j
jdd… }n|||	|
f}tj||d�}|j|krêtd|j› d|› d�ƒ‚|dk�rt| j ¡ |||| jjd | j| jd�S |�rLt| j ¡ |||| j| j| j| j| jd�	S || _|  |¡ || _| S dS )a­  Average the data across epochs.

        Parameters
        ----------
        method : str | callable
            How to combine the data. If "mean"/"median", the mean/median
            are returned. Otherwise, must be a callable which, when passed
            an array of shape (n_epochs, n_channels, n_freqs, n_time)
            returns an array of shape (n_channels, n_freqs, n_time).
            Note that due to file type limitations, the kind for all
            these will be "average".
        dim : 'epochs' | 'freqs' | 'times'
            The dimension along which to combine the data.
        copy : bool
            Whether to return a copy of the modified instance,
            or modify in place. Ignored when ``dim='epochs'``
            because a new instance must be returned.

        Returns
        -------
        ave : instance of AverageTFR | EpochsTFR
            The averaged data.

        Notes
        -----
        Passing in ``np.median`` is considered unsafe when there is complex
        data because NumPy doesn't compute the marginal median. Numpy currently
        sorts the complex values by real part and return whatever value is
        computed. Use with caution. We use the marginal median in the
        complex case (i.e. the median of each component separately) if
        one passes in ``median``. See a discussion in scipy:

        https://github.com/scipy/scipy/pull/12676#issuecomment-783370228
        Údim)rÉ   rR   rÎ   r   r   r   )r|   rÂ   rR   T)r>  rÎ   rÉ   NrÁ   z5You passed a function that resulted in data of shape z, but it should be Ú.)rË   rØ   rÎ   rR   rÙ   r¦   r%  )	rË   rØ   rÎ   rR   r¦   r%  rÈ   rÄ   rÅ   )r   rÝ   rØ   r©   r   rf   rR   rÎ   rA   rg   rç   Zexpand_dimsrS  rÐ   rË   rÌ   r¦   r%  rÒ   rÈ   rÄ   rÅ   r#  )rä   r¦   rÁ  rÌ   rÂ   ÚfuncrØ   r±   r'  r�   rt   rR   rÎ   Zexpected_shaper^   r^   r_   rÖ   Ë  sT    #

ÿ
 
 ý    ý
zEpochsTFR.average)NNNNNNNN)rg   rÉ   F)r  r  r  r  r   rå   r  r¿  r»  rÀ  rÖ   r  r^   r^   rò   r_   rÒ   -  s   V           þ3
rÒ   rÙ   c                 C   st  | d   ¡ }t|tƒrh|dkr&tdƒ‚|dkrRt dd„ | D ƒt¡}|| ¡  }ndt| ƒ gt| ƒ }t |t¡}|j	dksŒ|j
t| ƒkr”td	ƒ‚|j}| dd
… D ]R}|j|ksÈttd||f ƒƒ‚t t |j|j ¡¡dk s¦ttd||f ƒƒ‚q¦tt|jd ƒjdd„ | dd
… D ƒŽ ƒ}||jd< tdd„ t|| ƒD ƒƒ|_ttdtdd„ t|| ƒD ƒƒ ƒdƒ|_|S )a  Merge AverageTFR data by weighted addition.

    Create a new AverageTFR instance, using a combination of the supplied
    instances as its data. By default, the mean (weighted by trials) is used.
    Subtraction can be performed by passing negative weights (e.g., [1, -1]).
    Data must have the same channels and the same time instants.

    Parameters
    ----------
    all_tfr : list of AverageTFR
        The tfr datasets.
    weights : list of float | str
        The weights to apply to the data of each AverageTFR instance.
        Can also be ``'nave'`` to weight according to tfr.nave,
        or ``'equal'`` to use equal weighting (each weighted as ``1/N``).

    Returns
    -------
    tfr : AverageTFR
        The new TFR data.

    Notes
    -----
    .. versionadded:: 0.11.0
    r   )rÙ   Úequalz5Weights must be a list of float, or "nave" or "equal"rÙ   c                 S   s   g | ]
}|j ‘qS r^   ©rÙ   )rl   Úer^   r^   r_   r¤   ;	  s     zcombine_tfr.<locals>.<listcomp>r;   r   z(Weights must be the same size as all_tfrNz*%s and %s do not contain the same channelsgH¯¼šò×z>z/%s and %s do not contain the same time instantsÚbadsc                 s   s   | ]}|j d  V  qdS )rÇ  Nré   )rl   Út_r^   r^   r_   rn   M	  s   ÿzcombine_tfr.<locals>.<genexpr>c                 s   s   | ]\}}||j  V  qd S rk   r¯  )rl   rm   rÈ  r^   r^   r_   rn   R	  s     c                 s   s    | ]\}}|d  |j  V  qdS )r   NrÅ  )rl   rm   rÆ  r^   r^   r_   rn   S	  s   ÿ)rÌ   r¶   rw  rE   rA   rC   re   r¬   rG   r©   rF   rè   r  ro   rˆ   rÎ   r@   ÚsetrË   Úunionry  rØ   rb   rÙ   )Zall_tfrÚweightsr�   rè   rÈ  rÇ  r^   r^   r_   Úcombine_tfr	  s@    
þÿÿ
ÿ

ÿ
ÿrÌ  c                 C   sb   ddl m} ddlm} t| ||fƒs.tdƒ‚t| |ƒrB|  ¡ }n|rNtdƒ‚| jt	j
  ¡ }|S )z>Get data from Epochs or Evoked instance as epochs x ch x time.r   r¿   )ÚEvokedzinst must be Epochs or Evokedz(return_itc must be False for evoked data)rÉ   rÀ   ZevokedrÍ  r¶   Ú	TypeErrorÚget_datarE   rØ   rA   r  rÌ   )rÓ   rÔ   rÀ   rÍ  rØ   r^   r^   r_   rÊ   [	  s    

rÊ   c                 C   sD   t | |dd�}t| |ƒ} tdƒg|j }|||< |t|ƒ }| |fS )zPrepare the picks.rÇ  r  N)r)   r(   r‰   r©   r¾  )rË   rØ   rÕ   rÂ   Úslr^   r^   r_   rÍ   j	  s    
rÍ   c                    sR   t  |¡}t  | j¡}|| d ‰ˆ| ‰ ‡ ‡fdd„ttˆ ƒƒD ƒ}| t|ƒ S )zAux Function to center data.r   c                    s   g | ]}t ˆ| ˆ | ƒ‘qS r^   )r‰   r  ©ZendindZstartindr^   r_   r¤   {	  s     z_centered.<locals>.<listcomp>)rA   r„   rC   rf   rd   rG   r¾  )ZarrZnewsizeÚcurrsizeZmyslicer^   rÑ  r_   r‹   t	  s    
r‹   c                 C   s0  |dkr|dk	}t | ||||d�} t | ¡r@t | |  ¡  j¡} d\}}t t||||d�¡d }|dk	rr|d }|dk	r†|d d }|||… }d\}}t t||||d�¡d }|dk	rÄ|d }|dk	rØ|d d }|||… }| dd…||…||…f } |�rdt | ¡ } t	| |	|
ƒ\}	}
| |||	|
fS )	z(Aux Function to prepare tfr computation.Nrô   )NN)rQ   r   r<   r   é   )
r   rA   ZiscomplexobjrL   rº   r»   rñ   r   Úlog10r4   )rØ   rÎ   rR   rê   rë   rí   rî   r|   râ   r+  r,  r.  rQ   rÌ   ZitminZitmaxrW  ZifminZifmaxr^   r^   r_   rx  	  s0    
rx  c                 C   sH   t | dtfdƒ t| tƒs*tddt| ƒƒ} | jdkrDt| j| jdƒ} | S )z*Aux function checking the decim parameter.zint-liker}   Nr   )r   r‰   r¶   rb   rŠ   r•   Ústop)r}   r^   r^   r_   rƒ   §	  s    

rƒ   rö   c          
      C   sp   t ƒ \}}g }t|ttfƒs"|g}t|ƒD ].\}}|jdkr@|n|j}	| t||	d�¡ q*|| ||ddd� dS )a  Write a TFR dataset to hdf5.

    Parameters
    ----------
    fname : str
        The file name, which should end with ``-tfr.h5``.
    tfr : AverageTFR | list of AverageTFR | EpochsTFR
        The TFR dataset, or list of TFR datasets, to save in one file.
        Note. If .comment is not None, a name will be generated on the fly,
        based on the order in which the TFR objects are passed.
    %(overwrite)s
    %(verbose)s

    See Also
    --------
    read_tfrs

    Notes
    -----
    .. versionadded:: 0.9.0
    N)rþ   Ú	mnepythonÚreplace)r÷   r1  Úslash)r$   r¶   r@   r¾  rH   r%  rP   Ú_prepare_write_tfr)
rù   r�   r÷   r   rŒ   Z
write_hdf5r²   r‘   Ztfr_r%  r^   r^   r_   rø   µ	  s    

ÿrø   c                 C   s~   t | j| j| j| j| j| jd�}t| dƒr6| j|d< n@t| dƒrv| j	|d< | j
|d< | j|d< | j|d< t| jƒ|d< ||fS )zAux function.)rÎ   rR   rØ   rË   r%  r¦   rÙ   rÄ   rÅ   rÆ   rÇ   rÈ   )rÝ   rÎ   rR   rØ   rË   r%  r¦   ÚhasattrrÙ   rÄ   rÅ   rÆ   rÇ   r   rÈ   )r�   rþ   Ú
attributesr^   r^   r_   rÙ  ×	  s      ÿ





rÙ  c                    s  t | ddƒ tƒ \}}t d|  ¡ || ddd�}|D ]<\}}t|d ƒ|d< |d  ¡  d|kr6t|d ƒ|d< q6d	|k}|d
k	rÔ|s�tdƒ‚t|ƒ}||krÄdd„ |D ƒ}	t	d 
|d |	¡¡ƒ‚tf || Ž}
n*|rÜtnt‰ ‡ fdd„tt|Ž ƒd D ƒ}
|
S )a4  Read TFR datasets from hdf5 file.

    Parameters
    ----------
    fname : str
        The file name, which should end with -tfr.h5 .
    condition : int or str | list of int or str | None
        The condition to load. If None, all conditions will be returned.
        Defaults to None.

    Returns
    -------
    tfr : AverageTFR | list of AverageTFR | EpochsTFR
        Depending on ``condition`` either the TFR object or a list of multiple
        TFR objects.

    See Also
    --------
    write_tfrs

    Notes
    -----
    .. versionadded:: 0.9.0
    r�   )z-tfr.h5z_tfr.h5zReading %s ...rÖ  r×  )r1  rØ  rË   rÈ   rÙ   Nz/condition not supported when reading EpochsTFR.c                 S   s   g | ]}d | ‘qS )z%sr^   r  r^   r^   r_   r¤   
  s     zread_tfrs.<locals>.<listcomp>zBCannot find condition ("{}") in this file. The file contains "{}""z or c                    s   g | ]}ˆ f |Ž‘qS r^   r^   )rl   Úd©rÓ   r^   r_   r¤   
  s     r   )r   r$   r   rË   r-   Z_check_consistencyr   ÚNotImplementedErrorrÝ   rE   rŒ  ÚjoinrÐ   rÒ   r@   ry  )rù   rþ   Z	read_hdf5rŒ   Ztfr_datarW   r�   Z
is_averageZtfr_dictre  r²   r^   rÝ  r_   Ú	read_tfrsæ	  s0    
 þrà  c                    sÆ  d}t ˆtƒrZˆ ¡ D ]>\}}||fD ],}t|ƒdksHtdd„ |D ƒƒr&t||ƒ‚q&q�nVˆdk	ràtˆdƒsvt|ˆƒ‚tˆƒdkr tdd„ ˆD ƒƒr tˆƒg‰n>ˆD ]8}t|dƒrÒt|ƒdkrÒtdd„ |D ƒƒrÒq¤t||ƒ‚q¤nÐd	d
l	m
} tdˆ jjd d fƒ}|ˆ j|dd�}|d	 jd	k�rXt ˆ j ¡ ˆ jj¡\}	}
}ˆ j|
 ˆ j| fg‰nX‡ fdd„t|d |d ƒD ƒ}t |¡}ˆ j|d |  }ˆ j|d |  }||fg‰‡fdd„ˆD ƒ‰ˆS )z1Find and/or setup timefreqs for `tfr.plot_joint`.z{Supplied `timefreqs` are somehow malformed. Please supply None, a list of tuple pairs, or a dict of such tuple pairs, not: r   c                 s   s   | ]}t |ƒ V  qd S rk   ©r   ©rl   Únr^   r^   r_   rn   $
  s     z!_get_timefreqs.<locals>.<genexpr>NÚ__len__c                 s   s   | ]}t |ƒV  qd S rk   rá  )rl   r  r^   r^   r_   rn   )
  s     c                 s   s   | ]}t |ƒV  qd S rk   rá  râ  r^   r^   r_   rn   .
  s     r   )Ú	argrelmaxr   é   )r~  rÂ   c                    s    g | ]\}}ˆ j d ||f ‘qS ©r   r¯  )rl   rX   rZ   ©r�   r^   r_   r¤   =
  s     z"_get_timefreqs.<locals>.<listcomp>c                    s8   i | ]0}t |ƒtˆ tƒr&t ˆ | ¡nt d d g¡“qS rç  )r¾  r¶   rÝ   rA   r„   rC   r  )ra  r^   r_   r  E
  s   ÿ z"_get_timefreqs.<locals>.<dictcomp>)r¶   rÝ   r  rG   rD   rE   rÚ  r  r¾  Zscipy.signalrå  ro   rØ   rf   rF   rA   Zunravel_indexZargmaxrÎ   rR   ry  )r�   ra  Ztimefreq_error_msgrW   r  Úitemrå  r~  Z	peaks_idxrŒ   Zp_tZp_fZpeaksZpeakmax_idxZpeakmax_timeZpeakmax_freqr^   )r�   ra  r_   rt  
  sF    ÿ


ÿ
ÿ


þrt  c                    sÒ   |rˆ   ¡ nˆ ‰ |dkrdn|}tˆ j|dd�}‡ fdd„|D ƒ}ˆ  |¡ |dkrl‡ fdd„ˆ jd D ƒ}|dk	r~ˆ  |¡ tˆ jˆ jˆ j|||||	|
|||ˆ jd dd	�\}}}}}ˆ  	|¡ |ˆ _|ˆ _ˆ S )
z7Baseline and truncate (times and freqs) a TFR instance.NrÇ  r  c                    s   g | ]}ˆ j d  | ‘qS ©rè   ré   )rl   Úpickrè  r^   r_   r¤   S
  s     z)_preproc_tfr_instance.<locals>.<listcomp>c                    s   g | ]}|ˆ j d  kr|‘qS rê  ré   )rl   Úchrè  r^   r_   r¤   W
  s    ÿrQ   Frô   )
rÌ   r)   rË   Zpick_channelsZdrop_channelsrx  rØ   rÎ   rR   r#  )r�   rÕ   rê   rë   rí   rî   r+  r,  r.  r|   râ   r  rÌ   Z
pick_namesrØ   rÎ   rR   rŒ   r^   rè  r_   rR  L
  s:    

            þ
rR  )r6   NF)r6   ra   F)TT)
r;   r`   r6   NNTr   r˜   NN)N)Try   r   )N)	FTr   NNTTr›   N)r6   FTr   r˜   NN)ra   TTr   NNTN)rÙ   )N)F)N)T)[r  rÌ   r   Ú	functoolsr   ÚnumpyrA   rš   r   râ   r   r	   Úfilterr
   r³   r   Úutilsr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   Zchannels.channelsr%   Zchannels.layoutr&   r'   Zio.pickr(   r)   r*   r+   r,   Zio.meas_infor-   r.   Z	viz.utilsr/   r0   r1   r2   r3   r4   r5   r`   rj   rx   r—   rµ   rª   r­   r¾   r½   rÛ   rÞ   rß   rà   rá   rÐ   rÒ   rÌ  rÊ   rÍ   r‹   rx  rƒ   rø   rÙ  rà  rt  rR  r^   r^   r^   r_   Ú<module>   s¶   l$
?
H
R              ý
 A ÿ
d
& ÿ
<           þC           þJ             þF M       _ n
@
 ÿ
(!
52 ÿ