U
    f»{j³¼  ã                   @   sè  d dl Zd dlZd dlZddlmZmZmZ ddl	m
Z
mZ ddl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mZmZ dd	lmZ g g d
dfdd„ZG dd„ deƒZdd„ Z dd„ Z!dd„ Z"dd„ Z#ed ej$ddddddfddœdd„ƒZ%ed d ej$ddddddf	ddœdd„ƒZ&ed ej$dddddd
dddfddœdd„ƒZ'ed d ej$dddddd
dddfddœdd „ƒZ(ed2ddœd"d#„ƒZ)ed3ddœd$d%„ƒZ*d4d&d'„Z+d5d(d)„Z,ed6ddœd*d+„ƒZ-d,d-„ Z.d.d/„ Z/d7d0d1„Z0dS )8é    Né   )Ú
_cwt_arrayÚmorletÚ	_get_nffté   )Úpick_channelsÚ_picks_to_idx)ÚloggerÚverboseÚwarnÚcopy_function_doc_to_method_docÚProgressBarÚ_check_fnameÚ_import_h5io_funcs©Úplot_csd)Ú_compute_mt_paramsÚ_mt_spectraÚ_csd_from_mtÚ_psd_from_mt_adaptive)Úparallel_funcFTc           
         sŒ   |rˆ   ¡ ‰ tˆ j|||d�}g }ˆ jjD ]6}t|ƒ}||dd…f dd…|f }| t|ƒ¡ q*‡ fdd„|D ƒ}	t 	|¡jˆ _|	ˆ _ˆ S )am  Pick channels from cross-spectral density matrix.

    Parameters
    ----------
    csd : instance of CrossSpectralDensity
        The CSD object to select the channels from.
    include : list of str
        List of channels to include (if empty, include all available).
    exclude : list of str
        Channels to exclude (if empty, do not exclude any).
    ordered : bool
        If True (default False), ensure that the order of the channels in the
        modified instance matches the order of ``include``.

        .. versionadded:: 0.20.0
    copy : bool
        If True (the default), return a copy of the CSD matrix with the
        modified channels. If False, channels are modified in-place.

        .. versionadded:: 0.20.0

    Returns
    -------
    res : instance of CrossSpectralDensity
        Cross-spectral density restricted to selected channels.
    )ÚincludeÚexcludeÚorderedNc                    s   g | ]}ˆ j | ‘qS © )Úch_names©Ú.0Úi©Úcsdr   úU/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/time_frequency/csd.pyÚ
<listcomp><   s     z%pick_channels_csd.<locals>.<listcomp>)
Úcopyr   r   Ú_dataÚTÚ_vector_to_sym_matÚappendÚ_sym_mat_to_vectorÚnpÚarray)
r    r   r   r   r#   ÚselÚdataÚvecÚmatr   r   r   r!   Úpick_channels_csd   s    
ÿr/   c                   @   sÂ   e Zd ZdZd*dd„Zedd„ ƒZedd„ ƒZd	d
„ Zdd„ Z	d+dd„Z
d,dd„Zdd„ Zd-dd„Zd.dd„Zeeƒd/dd„ƒZdd„ Zdd „ Zd!d"„ Zeddd#œd$d%„ƒZd&d'„ Zd0d(d)„ZdS )1ÚCrossSpectralDensityaZ  Cross-spectral density.

    Given a list of time series, the CSD matrix denotes for each pair of time
    series, the cross-spectral density. This matrix is symmetric and internally
    stored as a vector.

    This object can store multiple CSD matrices: one for each frequency.
    Use ``.get_data(freq)`` to obtain an CSD matrix as an ndarray.

    Parameters
    ----------
    data : ndarray, shape ((n_channels**2 + n_channels) // 2, n_frequencies)
        For each frequency, the cross-spectral density matrix in vector format.
    ch_names : list of str
        List of string names for each channel.
    frequencies : float | list of float | list of list of float
        Frequency or frequencies for which the CSD matrix was calculated. When
        averaging across frequencies (see the :func:`CrossSpectralDensity.mean`
        function), this will be a list of lists that contains for each
        frequency bin, the frequencies that were averaged. Frequencies should
        always be sorted.
    n_fft : int
        The number of FFT points or samples that have been used in the
        computation of this CSD.
    tmin : float | None
        Start of the time window for which CSD was calculated in seconds. Can
        be ``None`` (the default) to indicate no timing information is
        available.
    tmax : float | None
        End of the time window for which CSD was calculated in seconds. Can be
        ``None`` (the default) to indicate no timing information is available.
    projs : list of Projection | None
        List of projectors to apply to timeseries data when using this CSD
        object to compute a DICS beamformer. Defaults to ``None``, which means
        no projectors will be applied.

    See Also
    --------
    csd_fourier
    csd_multitaper
    csd_morlet
    csd_array_fourier
    csd_array_multitaper
    csd_array_morlet
    Nc                 C   sÜ   t  |¡}|jdkr(|d d …t jf }n|jdkr:tdƒ‚|| _t|ƒtt|ƒƒkr\tdƒ‚t|ƒ| _	|| _
|| _t|tjƒr„|g}t|ƒ|jd kr°tdt|ƒ|jd f ƒ‚|| _|| _|d krÌg | _nt |¡| _d S )Nr   r   z)`data` should be either a 1D or 2D array.zNNumber of ch_names does not match the number of time series in the CSD matrix.z]Number of frequencies does not match the number of CSD matrices in the data array (%d != %d).)r)   ÚasarrayÚndimÚnewaxisÚ
ValueErrorr$   ÚlenÚ_n_dims_from_triuÚlistr   ÚtminÚtmaxÚ
isinstanceÚnumbersÚNumberÚshapeÚfrequenciesÚn_fftÚprojsÚcpÚdeepcopy)Úselfr,   r   r>   r?   r8   r9   r@   r   r   r!   Ú__init__r   s,    



þzCrossSpectralDensity.__init__c                 C   s
   t | jƒS )z1Number of time series defined in this CSD object.)r5   r   ©rC   r   r   r!   Ú
n_channels�   s    zCrossSpectralDensity.n_channelsc                 C   s   t | jd tjƒ S )z>Whether the CSD matrix represents a sum (or average) of freqs.r   )r:   r>   r;   r<   rE   r   r   r!   Ú_is_sum•   s    zCrossSpectralDensity._is_sumc                 C   s
   t | jƒS )z„Return number of frequencies.

        Returns
        -------
        n_freqs : int
            The number of frequencies.
        )r5   r>   rE   r   r   r!   Ú__len__œ   s    zCrossSpectralDensity.__len__c              	   C   s²   g }| j D ]^}t|tjƒr*| t|ƒ¡ q
t|ƒdkrJ| t|d ƒ¡ q
| d t 	|¡t 
|¡¡¡ q
d |¡d }| jd k	rž| jd k	ržd | j| j¡}nd}d | j||¡S )	Nr   r   z{}-{}z, z Hz.z
{} to {} sÚunknownz?<CrossSpectralDensity | n_channels={}, time={}, frequencies={}>)r>   r:   r;   r<   r'   Ústrr5   Úformatr)   ÚminÚmaxÚjoinr8   r9   rF   )rC   Z	freq_strsÚfZfreq_strZtime_strr   r   r!   Ú__repr__¦   s"    
   þÿzCrossSpectralDensity.__repr__c              	      sš  ˆ j rtdƒ‚|dkr8|dkr8ˆ jd g}ˆ jd g}n\t|tjƒrJ|g}t|tjƒr\|g}|dkrxˆ jd gt|ƒ }|dkr”ˆ jd gt|ƒ }tdd„ t||ƒD ƒƒr´t	dƒ‚‡ fdd	„|D ƒ}‡ fd
d	„|D ƒ}t|ƒt|ƒkrðt	dƒ‚t|ƒ}t
jˆ jjd |fˆ jjd�}g }tt||ƒƒD ]L\}\}	}
ˆ jdd…|	|
…f jdd�|dd…|f< | ˆ j|	|
… ¡ �q(t|ˆ jˆ jˆ j|ˆ jˆ jd�}|S )aæ  Calculate the sum CSD in the given frequency range(s).

        If the exact given frequencies are not available, the nearest
        frequencies will be chosen.

        Parameters
        ----------
        fmin : float | list of float | None
            Lower bound of the frequency range in Hertz. Defaults to the lowest
            frequency available. When a list of frequencies is given, these are
            used as the lower bounds (inclusive) of frequency bins and the sum
            is taken for each bin.
        fmax : float | list of float | None
            Upper bound of the frequency range in Hertz. Defaults to the
            highest frequency available. When a list of frequencies is given,
            these are used as the upper bounds (inclusive) of frequency bins
            and the sum is taken for each bin.

        Returns
        -------
        csd : instance of CrossSpectralDensity
            The CSD matrix, summed across the given frequency range(s).
        zDThis CSD matrix already represents a mean or sum across frequencies.Nr   éÿÿÿÿc                 s   s   | ]\}}||kV  qd S ©Nr   )r   Zfmin_Zfmax_r   r   r!   Ú	<genexpr>æ   s     z+CrossSpectralDensity.sum.<locals>.<genexpr>zASome lower bounds are higher than the corresponding upper bounds.c                    s   g | ]}ˆ   |¡‘qS r   ©Ú_get_frequency_index©r   rO   rE   r   r!   r"   ë   s     z,CrossSpectralDensity.sum.<locals>.<listcomp>c                    s   g | ]}ˆ   |¡d  ‘qS )r   rT   rV   rE   r   r!   r"   ì   s     z5The length of fmin does not match the length of fmax.©Údtyper   ©Zaxis©r,   r   r8   r9   r>   r?   r@   )rG   ÚRuntimeErrorr>   r:   r;   r<   r5   ÚanyÚzipr4   r)   Úzerosr$   r=   rX   Ú	enumerateÚsumr'   r0   r   r8   r9   r?   r@   )rC   ÚfminÚfmaxZ	fmin_indsZ	fmax_indsZn_binsZnew_dataZnew_frequenciesr   Zmin_indZmax_indZcsd_outr   rE   r!   r`   ¼   sF    ÿ*  ýzCrossSpectralDensity.sumc                 C   sB   |   ||¡}t|jƒD ]&\}}|jdd…|f  t|ƒ  < q|S )a€  Calculate the mean CSD in the given frequency range(s).

        Parameters
        ----------
        fmin : float | list of float | None
            Lower bound of the frequency range in Hertz. Defaults to the lowest
            frequency available. When a list of frequencies is given, these are
            used as the lower bounds (inclusive) of frequency bins and the mean
            is taken for each bin.
        fmax : float | list of float | None
            Upper bound of the frequency range in Hertz. Defaults to the
            highest frequency available. When a list of frequencies is given,
            these are used as the upper bounds (inclusive) of frequency bins
            and the mean is taken for each bin.

        Returns
        -------
        csd : instance of CrossSpectralDensity
            The CSD matrix, averaged across the given frequency range(s).
        N)r`   r_   r>   r$   r5   )rC   ra   rb   r    r   rO   r   r   r!   Úmean  s     zCrossSpectralDensity.meanc                 C   sN   | j rtdƒ‚t t | j¡| ¡}t |¡}|| }|dkrJtd| ƒ‚|S )aº  Find the index of the given frequency in ``self.frequencies``.

        If the exact given frequency is not available, the nearest frequencies
        will be chosen, up to a difference of 1 Hertz.

        Parameters
        ----------
        freq : float
            The frequency to find the index for

        Returns
        -------
        index : int
            The index of the frequency nearest to the requested frequency.
        zYThis CSD object represents a mean across frequencies. Cannot select a specific frequency.r   zFrequency %f is not available.)rG   r4   r)   Úabsr1   r>   ÚargminÚ
IndexError)rC   ÚfreqZdistanceÚindexZmin_distr   r   r!   rU     s    
z)CrossSpectralDensity._get_frequency_indexc                 C   sD   |dkr|dkrt dƒ‚n"|dk	r<|dk	r2t dƒ‚|  |¡}| | S )aŸ  Get a CrossSpectralDensity object with only the given frequency.

        Parameters
        ----------
        freq : float | None
            Return the CSD matrix for a specific frequency. Only available
            when no averaging across frequencies has been done.
        index : int | None
            Return the CSD matrix for the frequency or frequency-bin with the
            given index.

        Returns
        -------
        csd : instance of CrossSpectralDensity
            A CSD object containing a single CSD matrix that corresponds to the
            requested frequency or frequency-bin.

        See Also
        --------
        get_data
        NzKUse either the "freq" or "index" parameter to select the desired frequency.ú*Cannot specify both a frequency and index.)r4   rU   )rC   rg   rh   r   r   r!   Úpick_frequency7  s    

z#CrossSpectralDensity.pick_frequencyFc                 C   s–   |dkr.|dkr.| j jd dkr(tdƒ‚d}n"|dk	rP|dk	rFtdƒ‚|  |¡}t| j dd…|f ƒ}|rŽddlm} ||| jg | j| j	d�S |S dS )	aL  Get the CSD matrix for a given frequency as NumPy array.

        If there is only one matrix defined in the CSD object, calling this
        method without any parameters will return it. If multiple matrices are
        defined, use either the ``frequency`` or ``index`` parameter to select
        one.

        Parameters
        ----------
        frequency : float | None
            Return the CSD matrix for a specific frequency. Only available when
            no averaging across frequencies has been done.
        index : int | None
            Return the CSD matrix for the frequency or frequency-bin with the
            given index.
        as_cov : bool
            Whether to return the data as a numpy array (`False`, the default),
            or pack it in a :class:`mne.Covariance` object (`True`).

            .. versionadded:: 0.20

        Returns
        -------
        csd : ndarray, shape (n_channels, n_channels) | instance of Covariance
            The CSD matrix corresponding to the requested frequency.

        See Also
        --------
        pick_frequency
        Nr   z^Specify either the frequency or index of the frequency bin for which to obtain the CSD matrix.r   ri   r   )Ú
Covariance)Zbadsr@   Znfree)
r$   r=   r4   rU   r&   Zcovrk   r   r@   r?   )rC   Z	frequencyrh   Zas_covr,   rk   r   r   r!   Úget_dataY  s    
ÿzCrossSpectralDensity.get_datar    TÚviridisc              	   C   s   t | ||||||d�S )N)ÚinfoÚmodeÚcolorbarÚcmapÚn_colsÚshowr   )rC   rn   ro   rp   rq   rr   rs   r   r   r!   ÚplotŒ  s
    
  ÿzCrossSpectralDensity.plotc                    sd   ddl m‰  |d | _|d | _|d | _|d | _|d | _|d | _‡ fd	d
„|d D ƒ| _d S )Nr   ©Ú
Projectionr,   r8   r9   r   r>   r?   c                    s   g | ]}ˆ f |Ž‘qS r   r   )r   Úprojru   r   r!   r"   ›  s     z5CrossSpectralDensity.__setstate__.<locals>.<listcomp>r@   )	rw   rv   r$   r8   r9   r   r>   r?   r@   )rC   Ústater   ru   r!   Ú__setstate__’  s    





z!CrossSpectralDensity.__setstate__c              	   C   s$   t | j| j| j| j| j| j| jd�S )N)r,   r8   r9   r   r>   r?   r@   )Údictr$   r8   r9   r   r>   r?   r@   rE   r   r   r!   Ú__getstate__�  s    ùz!CrossSpectralDensity.__getstate__c              	   C   s>   t | jdd…|f | j| j| jt | j¡|  ¡ | j	| j
d�S )a   Subselect frequencies.

        Parameters
        ----------
        sel : ndarray
            Array of frequency indices to subselect.

        Returns
        -------
        csd : instance of CrossSpectralDensity
            A new CSD instance with the subset of frequencies.
        NrZ   )r0   r$   r   r8   r9   r)   Z
atleast_1dr>   Útolistr?   r@   )rC   r+   r   r   r!   Ú__getitem__¨  s      ûz CrossSpectralDensity.__getitem__)Ú	overwriter
   c                C   s@   t ƒ \}}| d¡s|d7 }t||d�}|||  ¡ ddd� dS )aÁ  Save the CSD to an HDF5 file.

        Parameters
        ----------
        fname : str
            The name of the file to save the CSD to. The extension '.h5' will
            be appended if the given filename doesn't have it already.
        %(overwrite)s

            .. versionadded:: 1.0
        %(verbose)s

            .. versionadded:: 1.0

        See Also
        --------
        read_csd : For reading CSD objects from a file.
        ú.h5)r~   TÚconpy)r~   ÚtitleN)r   Úendswithr   r{   )rC   Úfnamer~   r
   Ú_Z
write_hdf5r   r   r!   Úsave½  s    

ÿzCrossSpectralDensity.savec                 C   s
   t  | ¡S )z«Return copy of the CrossSpectralDensity object.

        Returns
        -------
        copy : instance of CrossSpectralDensity
            A copy of the object.
        )rA   rB   rE   r   r   r!   r#   Ù  s    zCrossSpectralDensity.copyc                 C   s   t | |g |dd�S )a?  Pick channels from this cross-spectral density matrix.

        Parameters
        ----------
        ch_names : list of str
            List of channels to keep. All other channels are dropped.
        ordered : bool
            If True (default False), ensure that the order of the channels
            matches the order of ``ch_names``.

        Returns
        -------
        csd : instance of CrossSpectralDensity.
            The modified cross-spectral density object.

        Notes
        -----
        Operates in-place.

        .. versionadded:: 0.20.0
        F)r   r   r   r#   )r/   )rC   r   r   r   r   r!   r   ã  s     ÿz"CrossSpectralDensity.pick_channels)NNN)NN)NN)NN)NNF)Nr    Trm   NT)F)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rD   ÚpropertyrF   rG   rH   rP   r`   rc   rU   rj   rl   r   r   rt   ry   r{   r}   r
   r…   r#   r   r   r   r   r!   r0   C   s8   .    ÿ




E

"
3    ÿ
r0   c                 C   s   t t t | d ¡¡ƒd S )a  Compute matrix dims from number of elements in the upper triangle.

    Parameters
    ----------
    n : int
        Number of elements in the upper triangle of the symmetric matrix.

    Returns
    -------
    dim : int
        The dimensions of the symmetric matrix.
    r   r   )Úintr)   ÚceilÚsqrt)Únr   r   r!   r6   ý  s    r6   c                 C   s’   t t| ƒƒ}tj||f| jdd…  | jd�}| |t |¡< |t |d¡ ¡  }t 	|jtj
¡rx|t |¡  d  < n|t |¡  d  < |S )a†  Convert vector to a symmetric matrix.

    The upper triangle of the matrix (including the diagonal) will be filled
    with the values of the vector.

    Parameters
    ----------
    vec : list or 1d-array
        The vector to convert to a symmetric matrix.

    Returns
    -------
    mat : 2d-array
        The symmetric matrix.

    See Also
    --------
    _sym_mat_to_vector
    r   NrW   r   )r6   r5   r)   r^   r=   rX   Ztriu_indicesZrollaxisÚconjZ
issubdtypeÚintegerZdiag_indices)r-   Údimr.   r   r   r!   r&     s    "r&   c                 C   s   | t  | ¡ S )a¬  Convert a symmetric matrix to a vector.

    The upper triangle of the matrix (including the diagonal) will be used
    as the values of the vector.

    Parameters
    ----------
    mat : 2d-array
        The symmetric matrix to convert to a vector

    Returns
    -------
    vec : 1d-array
        A vector consisting of the values of the upper triangle of the matrix.

    See Also
    --------
    _vector_to_sym_mat
    )r)   Ztriu_indices_from)r.   r   r   r!   r(   3  s    r(   c                 C   s2   t ƒ \}}|  d¡s| d7 } || dd�}tf |ŽS )a¼  Read a CrossSpectralDensity object from an HDF5 file.

    Parameters
    ----------
    fname : str
        The name of the file to read the CSD from. The extension '.h5' will be
        appended if the given filename doesn't have it already.

    Returns
    -------
    csd : instance of CrossSpectralDensity
        The CSD that was stored in the file.

    See Also
    --------
    CrossSpectralDensity.save : For saving CSD objects.
    r   r€   )r�   )r   r‚   r0   )rƒ   Z	read_hdf5r„   Zcsd_dictr   r   r!   Úread_csdJ  s
    

r’   ©r
   c	          
      C   sB   t | ||||ƒ\} }t|  ¡ | jd | j||||| j||||	d�S )a³  Estimate cross-spectral density from an array using short-time fourier.

    Parameters
    ----------
    epochs : instance of Epochs
        The epochs to compute the CSD for.
    fmin : float
        Minimum frequency of interest, in Hertz.
    fmax : float | np.inf
        Maximum frequency of interest, in Hertz.
    tmin : float | None
        Minimum time instant to consider, in seconds. If ``None`` start at
        first sample.
    tmax : float | None
        Maximum time instant to consider, in seconds. If ``None`` end at last
        sample.
    %(picks_good_data_noref)s
    n_fft : int | None
        Length of the FFT. If ``None``, the exact number of samples between
        ``tmin`` and ``tmax`` will be used.
    projs : list of Projection | None
        List of projectors to store in the CSD object. Defaults to ``None``,
        which means the projectors defined in the Epochs object will by copied.
    %(n_jobs)s
    %(verbose)s

    Returns
    -------
    csd : instance of CrossSpectralDensity
        The computed cross-spectral density.

    See Also
    --------
    csd_array_fourier
    csd_array_morlet
    csd_array_multitaper
    csd_morlet
    csd_multitaper
    Úsfreq)r”   Út0ra   rb   r8   r9   r   r?   r@   Ún_jobsr
   )Ú_prepare_csdÚcsd_array_fourierrl   rn   r8   r   )
Úepochsra   rb   r8   r9   Úpicksr?   r@   r–   r
   r   r   r!   Úcsd_fourierd  s    *       ýr›   c                C   s   ddl m} t| ||||||ƒ\} }}}}}|dkr8dnt ||d ¡}|dkrTdnt ||d ¡}| dd…dd…||…f } |||… }t|ƒ}|dkrž|n|}||d| ƒ}||k||k @ }|| }t|ƒdkrÜtdƒ‚t| ||t||||g|||	|
|d�
S )a-  Estimate cross-spectral density from an array using short-time fourier.

    Parameters
    ----------
    X : array-like, shape (n_epochs, n_channels, n_times)
        The time series data consisting of n_epochs separate observations
        of signals with n_channels time-series of length n_times.
    sfreq : float
        Sampling frequency of observations.
    t0 : float
        Time of the first sample relative to the onset of the epoch, in
        seconds. Defaults to 0.
    fmin : float
        Minimum frequency of interest, in Hertz.
    fmax : float | np.inf
        Maximum frequency of interest, in Hertz.
    tmin : float | None
        Minimum time instant to consider, in seconds. If ``None`` start at
        first sample.
    tmax : float | None
        Maximum time instant to consider, in seconds. If ``None`` end at last
        sample.
    ch_names : list of str | None
        A name for each time series. If ``None`` (the default), the series will
        be named 'SERIES###'.
    n_fft : int | None
        Length of the FFT. If ``None``, the exact number of samples between
        ``tmin`` and ``tmax`` will be used.
    projs : list of Projection | None
        List of projectors to store in the CSD object. Defaults to ``None``,
        which means no projectors are stored.
    %(n_jobs)s
    %(verbose)s

    Returns
    -------
    csd : instance of CrossSpectralDensity
        The computed cross-spectral density.

    See Also
    --------
    csd_array_morlet
    csd_array_multitaper
    csd_fourier
    csd_morlet
    csd_multitaper
    r   ©ÚrfftfreqNç»½×Ùß|Û=ç      ð?ú„No discrete fourier transform results within the given frequency window. Please widen either the frequency window or the time window©Úparamsr?   r   r@   r–   r
   )	Ú	scipy.fftr�   Ú_prepare_csd_arrayr)   Úsearchsortedr5   r4   Ú_execute_csd_functionÚ_csd_fourier)ÚXr”   r•   ra   rb   r8   r9   r   r?   r@   r–   r
   r�   ÚtimesÚtstartÚtstopÚn_timesÚorig_frequenciesÚ	freq_maskr>   r   r   r!   r˜   •  s:    3      ÿ

   ýr˜   c                C   sH   t | ||||
ƒ\} }
t|  ¡ | jd | j||||| j||||	|
||d�S )aÙ  Estimate cross-spectral density from epochs using a multitaper method.

    Parameters
    ----------
    epochs : instance of Epochs
        The epochs to compute the CSD for.
    fmin : float | None
        Minimum frequency of interest, in Hertz.
    fmax : float | np.inf
        Maximum frequency of interest, in Hertz.
    tmin : float
        Minimum time instant to consider, in seconds. If ``None`` start at
        first sample.
    tmax : float | None
        Maximum time instant to consider, in seconds. If ``None`` end at last
        sample.
    %(picks_good_data_noref)s
    n_fft : int | None
        Length of the FFT. If ``None``, the exact number of samples between
        ``tmin`` and ``tmax`` will be used.
    bandwidth : float | None
        The bandwidth of the multitaper windowing function in Hz.
    adaptive : bool
        Use adaptive weights to combine the tapered spectra into PSD.
    low_bias : bool
        Only use tapers with more than 90%% spectral concentration within
        bandwidth.
    projs : list of Projection | None
        List of projectors to store in the CSD object. Defaults to ``None``,
        which means the projectors defined in the Epochs object will by copied.
    %(n_jobs)s
    %(verbose)s

    Returns
    -------
    csd : instance of CrossSpectralDensity
        The computed cross-spectral density.

    See Also
    --------
    csd_array_fourier
    csd_array_morlet
    csd_array_multitaper
    csd_fourier
    csd_morlet
    r”   )r”   r•   ra   rb   r8   r9   r   r?   Ú	bandwidthÚadaptiveÚlow_biasr@   r–   r
   )r—   Úcsd_array_multitaperrl   rn   r8   r   )r™   ra   rb   r8   r9   rš   r?   r¯   r°   r±   r@   r–   r
   r   r   r!   Úcsd_multitaperæ  s     2        ûr³   c                C   s  ddl m} t| ||||||ƒ\} }}}}}|dkr8dnt ||d ¡}|dkrTdnt ||d ¡}| dd…dd…||…f } |||… }t|ƒ}|dkrž|n|}t|||	||
ƒ\}}}||d| ƒ}||k||k @ }|| }t|ƒdkròtdƒ‚t| ||t	|||||||
g|||||d�
S )aU  Estimate cross-spectral density from an array using a multitaper method.

    Parameters
    ----------
    X : array-like, shape (n_epochs, n_channels, n_times)
        The time series data consisting of n_epochs separate observations
        of signals with n_channels time-series of length n_times.
    sfreq : float
        Sampling frequency of observations.
    t0 : float
        Time of the first sample relative to the onset of the epoch, in
        seconds. Defaults to 0.
    fmin : float
        Minimum frequency of interest, in Hertz.
    fmax : float | np.inf
        Maximum frequency of interest, in Hertz.
    tmin : float | None
        Minimum time instant to consider, in seconds. If ``None`` start at
        first sample.
    tmax : float | None
        Maximum time instant to consider, in seconds. If ``None`` end at last
        sample.
    ch_names : list of str | None
        A name for each time series. If ``None`` (the default), the series will
        be named 'SERIES###'.
    n_fft : int | None
        Length of the FFT. If ``None``, the exact number of samples between
        ``tmin`` and ``tmax`` will be used.
    bandwidth : float | None
        The bandwidth of the multitaper windowing function in Hz.
    adaptive : bool
        Use adaptive weights to combine the tapered spectra into PSD.
    low_bias : bool
        Only use tapers with more than 90%% spectral concentration within
        bandwidth.
    projs : list of Projection | None
        List of projectors to store in the CSD object. Defaults to ``None``,
        which means no projectors are stored.
    %(n_jobs)s
    %(verbose)s

    Returns
    -------
    csd : instance of CrossSpectralDensity
        The computed cross-spectral density.

    See Also
    --------
    csd_array_fourier
    csd_array_morlet
    csd_fourier
    csd_morlet
    csd_multitaper
    r   rœ   Nrž   rŸ   r    r¡   )
r£   r�   r¤   r)   r¥   r5   r   r4   r¦   Ú_csd_multitaper)r¨   r”   r•   ra   rb   r8   r9   r   r?   r¯   r°   r±   r@   r–   r
   r�   r©   rª   r«   r¬   Ú
window_funÚeigvalsZmt_adaptiver­   r®   r>   r   r   r!   r²   !  sF    ;      ÿÿ
  ÿ   ür²   é   c
                C   sD   t | ||||ƒ\} }t|  ¡ | jd || j||| j|||||	|
d�S )aó  Estimate cross-spectral density from epochs using Morlet wavelets.

    Parameters
    ----------
    epochs : instance of Epochs
        The epochs to compute the CSD for.
    frequencies : list of float
        The frequencies of interest, in Hertz.
    tmin : float | None
        Minimum time instant to consider, in seconds. If ``None`` start at
        first sample.
    tmax : float | None
        Maximum time instant to consider, in seconds. If ``None`` end at last
        sample.
    %(picks_good_data_noref)s
    n_cycles : float | list of float | None
        Number of cycles to use when constructing Morlet wavelets. Fixed number
        or one per frequency. Defaults to 7.
    use_fft : bool
        Whether to use FFT-based convolution to compute the wavelet transform.
        Defaults to True.
    decim : int | slice
        To reduce memory usage, decimation factor during time-frequency
        decomposition. Defaults to 1 (no decimation).

        If `int`, uses tfr[..., ::decim].
        If `slice`, uses tfr[..., decim].

    projs : list of Projection | None
        List of projectors to store in the CSD object. Defaults to ``None``,
        which means the projectors defined in the Epochs object will be copied.
    %(n_jobs)s
    %(verbose)s

    Returns
    -------
    csd : instance of CrossSpectralDensity
        The computed cross-spectral density.

    See Also
    --------
    csd_array_fourier
    csd_array_morlet
    csd_array_multitaper
    csd_fourier
    csd_multitaper
    r”   )r”   r>   r•   r8   r9   r   Ún_cyclesÚuse_fftÚdecimr@   r–   r
   )r—   Úcsd_array_morletrl   rn   r8   r   )r™   r>   r8   r9   rš   r¸   r¹   rº   r@   r–   r
   r   r   r!   Ú
csd_morlet}  s    3       ür¼   c                C   s6  t | ||||ƒ\} }}}}}t|ƒ}t|||ƒ}t|t |¡ ƒd }d }}|dk	rpt ||¡}td|| ƒ}|dk	r’t ||¡}t||| ƒ}| dd…dd…||…f } |||… }|dkrÄdnt ||d ¡}|dkràdnt ||d ¡}t||ƒ}|| }t	|| |ƒ}t
| ||t||||||	gd||
||d�
S )a‘  Estimate cross-spectral density from an array using Morlet wavelets.

    Parameters
    ----------
    X : array-like, shape (n_epochs, n_channels, n_times)
        The time series data consisting of n_epochs separate observations
        of signals with n_channels time-series of length n_times.
    sfreq : float
        Sampling frequency of observations.
    frequencies : list of float
        The frequencies of interest, in Hertz.
    t0 : float
        Time of the first sample relative to the onset of the epoch, in
        seconds. Defaults to 0.
    tmin : float | None
        Minimum time instant to consider, in seconds. If ``None`` start at
        first sample.
    tmax : float | None
        Maximum time instant to consider, in seconds. If ``None`` end at last
        sample.
    ch_names : list of str | None
        A name for each time series. If ``None`` (the default), the series will
        be named 'SERIES###'.
    n_cycles : float | list of float | None
        Number of cycles to use when constructing Morlet wavelets. Fixed number
        or one per frequency. Defaults to 7.
    use_fft : bool
        Whether to use FFT-based convolution to compute the wavelet transform.
        Defaults to True.
    decim : int | slice
        To reduce memory usage, decimation factor during time-frequency
        decomposition. Defaults to 1 (no decimation).

        If `int`, uses tfr[..., ::decim].
        If `slice`, uses tfr[..., decim].

    projs : list of Projection | None
        List of projectors to store in the CSD object. Defaults to ``None``,
        which means the projectors defined in the Epochs object will be copied.
    %(n_jobs)s
    %(verbose)s

    Returns
    -------
    csd : instance of CrossSpectralDensity
        The computed cross-spectral density.

    See Also
    --------
    csd_array_fourier
    csd_array_multitaper
    csd_fourier
    csd_morlet
    csd_multitaper
    r   Nr   rž   r   r¡   )r¤   r5   r   r)   re   r¥   rM   rL   Úslicer   r¦   Ú_csd_morlet)r¨   r”   r>   r•   r8   r9   r   r¸   r¹   rº   r@   r–   r
   r©   r„   r¬   ÚwaveletsZwave_lengthrª   r«   Z
csd_tstartZ	csd_tstopZ
csd_tsliceÚnfftr   r   r!   r»   ¸  s:    ;

 ÿ   ür»   c                 C   sÒ   | j d | j d  }|dk	r6|| j d | k r6tdƒ‚|dk	rX|| j d | krXtdƒ‚|dk	rx|dk	rx||k rxtdƒ‚| jdkr˜| jd d	k r˜td
ƒ t| j|ddd�}|  ¡  |¡} |dkrÊ| jd }| |fS )z…Do some checking and preprocessing of common csd_* parameters.

    See the csd_* functions for documentation of the parameters.
    r   r   Nú7tmin should be larger than the smallest data time pointrQ   ú7tmax should be smaller than the largest data time pointútmax must be larger than tminZhighpassgš™™™™™¹?zhEpochs are not baseline corrected or enough highpass filtered. Cross-spectral density may be inaccurate.r,   F)Zwith_ref_megr@   )r©   r4   Zbaselinern   r   r   r#   Úpick)r™   r8   r9   rš   r@   Útstepr   r   r!   r—     s    
r—   c           
      C   sÔ   t j| td�} | jdkr tdƒ‚| jd }d| }t  |¡| | }	|dkrT|	 ¡ }|dkrd|	 ¡ }||krttdƒ‚||	d | k rŒtd	ƒ‚||	d
 | kr¤tdƒ‚|dk	rÄ|dk	rÄ||krÄtdƒ‚| |	||||fS )z“Do some checking and preprocessing of common csd_r=array_* parameters.

    See the csd_array_* functions for documentation of the parameters.
    rW   é   z*X must be n_epochs x n_channels x n_times.r   rŸ   NrÃ   r   rÁ   rQ   rÂ   zfmax must be larger than fmin)	r)   r1   Úfloatr2   r4   r=   ZarangerM   rL   )
r¨   r”   r•   r8   r9   ra   rb   r¬   rÅ   r©   r   r   r!   r¤   1  s&    

r¤   c	             	      s
  | j \}
}}t d¡ t|ƒ}tj||d  d |ftjd�}t|||	d�\}‰ }tt 	|
t
|ƒ ¡ƒ}tt|ƒdd�D ]F}| || |d | … }|‡ ‡fdd	„|D ƒƒ}|tj|d
d�7 }qx||
 }t d¡ |dkrìdd„ t|ƒD ƒ}t|||d
 |d |||d�S )aå  Estimate cross-spectral density with a given function.

    This function will apply the given CSD function in parallel across epochs.

    Parameters
    ----------
    X : array-like, shape (n_epochs, n_channels, n_times)
        The time series data consisting of n_epochs separate observations
        of signals with n_channels time-series of length n_times.
    times : float
        Timestamps for each sample.
    frequencies : list of float
        The frequencies of interest for which the CSD is going to be computed.
    csd_function : function
        Function that performs the actual CSD computation
    params : list
        List of parameters to pass the CSD function.
    n_fft : int
        Number of FFT points. This is stored in the CSD object.
    ch_names : list of str | None
        A name for each time series. If ``None`` (the default), the series will
        be named 'SERIES###'.
    projs : list of Projection | None
        List of projectors to store in the CSD object. Defaults to ``None``,
        which means the projectors defined in the Epochs object will be copied.
    %(n_jobs)s
    %(verbose)s

    Returns
    -------
    csd : instance of CrossSpectralDensity
        The computed cross-spectral density.
    z/Computing cross-spectral density from epochs...r   r   rW   r“   zCSD epoch blocks)Zmesgc                 3   s   | ]}ˆ |fˆžŽ V  qd S rR   r   )r   Z
this_epoch©Zmy_csdr¢   r   r!   rS   ‰  s   ÿz(_execute_csd_function.<locals>.<genexpr>r   rY   z[done]Nc                 S   s   g | ]}d |d  ‘qS )z
SERIES%03dr   r   r   r   r   r!   r"   “  s     z)_execute_csd_function.<locals>.<listcomp>rQ   )r   r8   r9   r>   r?   r@   )r=   r	   rn   r5   r)   r^   Z
complex128r   r‹   rŒ   rÇ   r   Úranger`   r0   )r¨   r©   r>   Zcsd_functionr¢   r?   r   r@   r–   r
   Zn_epochsrF   r„   Zn_freqsZ	csds_meanÚparallelZn_blocksr   Zepoch_blockÚcsdsr   rÈ   r!   r¦   S  s8    %
ÿ  ÿÿ
  þr¦   c           
         s  t | t |¡||ƒ\}}t dg¡dd…tjtjtjf }|dd…dd…|f }|dd…tjdd…dd…f }t |d|jd ddg¡}tj|ddddgd�}tj|ddddgd�}	t||||	ƒ‰ t ‡ fdd	„t	ˆ jd
 ƒD ƒ¡j
‰ ˆ | ‰ ˆ d9 ‰ ˆ | ‰ ˆ S )a  Compute cross spectral density (CSD) using short-time fourier transform.

    Computes the CSD for a single epoch of data.

    Parameters
    ----------
    X : ndarray, shape (n_channels, n_times)
        The time series data consisting of n_channels time-series of length
        n_times.
    sfreq : float
        The sampling frequency of the data in Hertz.
    n_times : int
        Number of time samples
    freq_mask : ndarray
        Which frequencies to use.
    n_fft : int
        Length of the FFT.
    rŸ   Nr   r   r   rÆ   ©Zaxesc                    s&   g | ]}t ˆ d d …d d …|f ƒ‘qS rR   ©r(   r   ©rË   r   r!   r"   ½  s   ÿz _csd_fourier.<locals>.<listcomp>rQ   gUUUUUU@)r   r)   Zhanningr*   r3   Útiler=   Ú	transposer   rÉ   r%   )
r¨   r”   r¬   r®   r?   Úx_mtr„   ÚweightsÚy_mtÚ	weights_yr   rÎ   r!   r§   š  s    "ÿ
r§   c                    s<  t | |||ƒ\}}	|rdt|||dd�\}	}
|
dd…tjdd…dd…f }
t |
d|jd ddg¡}
n t |¡tjtjdd…tjf }
|dd…dd…|f }|dd…tjdd…dd…f }t |d|jd ddg¡}tj|ddddgd�}tj|
ddddgd�}t|||
|ƒ‰ t 	‡ fd	d
„t
ˆ jd ƒD ƒ¡j‰ ˆ | ‰ ˆ S )a+  Compute cross spectral density (CSD) using multitaper module.

    Computes the CSD for a single epoch of data.

    Parameters
    ----------
    X : ndarray, shape (n_channels, n_times)
        The time series data consisting of n_channels time-series of length
        n_times.
    sfreq : float
        The sampling frequency of the data in Hertz.
    n_times : int
        Number of time samples
    window_fun : ndarray
        Window function(s) of length n_times. This corresponds to first output
        of `dpss_windows`.
    eigvals : ndarray | float
        Eigenvalues associated with window functions.
    freq_mask : ndarray
        Which frequencies to use.
    n_fft : int
        Length of the FFT.
    adaptive : bool
        Use adaptive weights to combine the tapered spectra into PSD.
    T)Zreturn_weightsNr   r   r   rÆ   rÌ   c                    s&   g | ]}t ˆ d d …d d …|f ƒ‘qS rR   rÍ   r   rÎ   r   r!   r"   þ  s   ÿz#_csd_multitaper.<locals>.<listcomp>rQ   )r   r   r)   r3   rÏ   r=   r�   rÐ   r   r*   rÉ   r%   )r¨   r”   r¬   rµ   r¶   r®   r?   r°   rÑ   r„   rÒ   rÓ   rÔ   r   rÎ   r!   r´   Ë  s&    ÿ
 ÿ
r´   c                    sÄ   t | ||d||d�‰ |dk	r†|jdkr*dn|j| }|jdkrBdn|j| }|jdkrZdn|j| }	t|||	ƒ}ˆ dd…dd…|f ‰ t ˆ ¡‰| jd }
t ‡ ‡fdd„t	|
ƒD ƒ¡}|| }|S )a‚  Compute cross spectral density (CSD) using the given Morlet wavelets.

    Computes the CSD for a single epoch of data.

    Parameters
    ----------
    data : ndarray, shape (n_channels, n_times)
        The time series data consisting of n_channels time-series of length
        n_times.
    sfreq : float
        The sampling frequency of the data in Hertz.
    wavelets : list of ndarray
        The Morlet wavelets for which to compute the CSD's. These have been
        created by the `mne.time_frequency.tfr.morlet` function.
    nfft : int
        The number of FFT points.
    tslice : slice | None
        The desired time samples to compute the CSD over. If None, defaults to
        including all time samples.
    use_fft : bool
        Whether to use FFT-based convolution to compute the wavelet transform.
        Defaults to True.
    decim : int | slice
        To reduce memory usage, decimation factor during time-frequency
        decomposition. Defaults to 1 (no decimation).
        Only used in 'cwt_morlet' mode.

        If `int`, uses tfr[..., ::decim].
        If `slice`, uses tfr[..., decim].

    Returns
    -------
    csd : ndarray, shape ((n_channels**2 + n_channels) / 2 , n_wavelets)
        For each wavelet, the upper triangle of the cross spectral density
        matrix.

    See Also
    --------
    _vector_to_sym_mat : For converting the CSD to a full matrix.
    Zsame)ro   r¹   rº   Nr   c                    s,   g | ]$}t jˆ |g ˆ|d …  dd�‘qS )Nr   rY   )r)   rc   r   ©ZpsdsZ	psds_conjr   r!   r"   @  s   ÿz_csd_morlet.<locals>.<listcomp>)
r   ÚstartÚstopÚstepr½   r)   r�   r=   ZvstackrÉ   )r,   r”   r¿   rÀ   Ztslicer¹   rº   rª   r«   rÅ   rF   rË   r   rÕ   r!   r¾     s     +ÿ

ÿr¾   )NNNr·   Tr   NN)	r   NNNr·   Tr   NN)NNNN)NN)NNN)NTr   )1r#   rA   r;   Únumpyr)   Ztfrr   r   r   Zio.pickr   r   Úutilsr	   r
   r   r   r   r   r   Zviz.miscr   Ztime_frequency.multitaperr   r   r   r   rÊ   r   r/   Úobjectr0   r6   r&   r(   r’   Úinfr›   r˜   r³   r²   r¼   r»   r—   r¤   r¦   r§   r´   r¾   r   r   r   r!   Ú<module>   s¾   $,   =&  ÿÿ0
   þþP
     þþ:
     ýý[          ÿþ:           þþ\

"     ÿþF1<  ÿ