U
    f»{j6 ã                   @   s  d dl mZ d dlZd dlmZ d dlZddlm	Z	m
Z
mZ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 ddlmZmZ dd	l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)m*Z* ddl+m,Z, ddlm-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3 ddlm4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z: ddl;m<Z< ddl=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZN ddlOmPZP ddlQmRZRmSZSmTZTmUZUmVZV dd„ ZWdd„ ZXeKG dd„ deYƒƒZZe@d_dd„ƒZ[e@d`dd „ƒZ\d!d"„ Z]e@dad(d)„ƒZ^dbd+d,„Z_e@dcd.d/„ƒZ`d0d1„ Zad2d3„ Zbd4d5„ Zcddd6d7„Zdd8d9„ Zeded:d;„ZfG d<d=„ d=eRƒZgG d>d?„ d?eRƒZhe@d&dd@œdAdB„ƒZidCdD„ ZjdEdF„ Zke@dfdHdI„ƒZle@dgdJdK„ƒZme@dhdNdO„ƒZndidPdQ„Zoe@djdSdT„ƒZpe@dkdUdV„ƒZqe@dldWdX„ƒZrdYdZ„ Zse@dmdd\œd]d^„ƒZtdS )né    ©ÚdeepcopyN)Úlogé   )Ú_INTERPOLATION_DEFAULTÚ_EXTRAPOLATE_DEFAULTÚ_BORDER_DEFAULTÚDEFAULTS)Ústart_and_end_file)Úmake_projectorÚ_proj_equalÚactivate_projÚ_check_projsÚ_needs_eeg_average_ref_projÚ_has_eeg_average_ref_projÚ
_read_projÚ_write_proj)Ú	fiff_openÚRawArray)Ú
pick_typesÚpick_channels_covÚpick_channelsÚ	pick_infoÚ_picks_by_typeÚ_pick_data_channelsÚ_picks_to_idxÚ_DATA_CH_TYPES_SPLIT)ÚFIFF)Ú_read_bad_channelsÚcreate_info)Úfind_tag)Údir_tree_find)Ústart_blockÚ	end_blockÚ	write_intÚwrite_name_listÚwrite_doubleÚwrite_float_matrixÚwrite_string)Ú_handle_default)ÚEpochs)Úmake_fixed_length_events)ÚEvokedArray)Úcompute_rank)Úcheck_fnameÚloggerÚverboseÚcheck_versionÚ
_time_maskÚwarnÚcopy_function_doc_to_method_docÚ_plÚ_undo_scaling_covÚ_scaled_arrayÚ_validate_typeÚ_check_optionÚeighÚfill_docÚ_on_missingÚ_check_on_missingÚ_check_fname)Úviz)ÚBaseEstimatorÚEmpiricalCovarianceÚ_logdetÚempirical_covarianceÚlog_likelihoodc                 C   sL   | j |j krtdƒ‚dd„ | d D ƒ}dd„ | d D ƒ}||krHtdƒ‚d S )Nz6Both Covariance do not have the same list of channels.c                 S   s   g | ]}t |ƒ‘qS © ©Ústr©Ú.0ÚcrE   rE   úF/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/cov.pyÚ
<listcomp>3   s     z'_check_covs_algebra.<locals>.<listcomp>Úprojsc                 S   s   g | ]}t |ƒ‘qS rE   rF   rH   rE   rE   rK   rL   4   s     z=Both Covariance do not have the same list of SSP projections.)Úch_namesÚ
ValueError)Zcov1Zcov2Zprojs1Zprojs2rE   rE   rK   Ú_check_covs_algebra/   s    rP   c                 C   sh   t | j||| jd d�}|dk	r2t |¡d d nd}|dk	rTt |¡d d d nd}t||dƒ}|S )zGet the slice.Úsfreq)rQ   Nr   éÿÿÿÿr   )r2   ÚtimesÚinfoÚnpÚwhereÚslice)ÚepochsÚtminÚtmaxÚmaskZtstartÚtendÚtslicerE   rE   rK   Ú_get_tslice:   s
    "r^   c                   @   s  e Zd ZdZed*ddœdd„ƒZedd„ ƒZedd	„ ƒZed
d„ ƒZ	edddœdd„ƒZ
dd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zeeejjƒg dd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d$d%edededdfd&d'„ƒZd+d(d)„ZdS ),Ú
Covarianceaf  Noise covariance matrix.

    .. warning:: This class should not be instantiated directly, but
                 instead should be created using a covariance reading or
                 computation function.

    Parameters
    ----------
    data : array-like
        The data.
    names : list of str
        Channel names.
    bads : list of str
        Bad channels.
    projs : list
        Projection vectors.
    nfree : int
        Degrees of freedom.
    eig : array-like | None
        Eigenvalues.
    eigvec : array-like | None
        Eigenvectors.
    method : str | None
        The method used to compute the covariance.
    loglik : float
        The log likelihood.
    %(verbose)s

    Attributes
    ----------
    data : array of shape (n_channels, n_channels)
        The covariance.
    ch_names : list of str
        List of channels' names.
    nfree : int
        Number of degrees of freedom i.e. number of time points used.
    dim : int
        The number of channels ``n_channels``.

    See Also
    --------
    compute_covariance
    compute_raw_covariance
    make_ad_hoc_cov
    read_cov
    N©r0   c
                C   sZ   |j dk}t|ƒ}| j|t|ƒ|||||||tjd�
 |dk	rF|| d< |	dk	rV|	| d< dS )zInit of covariance.r   )
ÚdataÚdimÚnamesÚbadsÚnfreeÚeigÚeigvecÚdiagrM   ÚkindNÚmethodÚloglik)Úndimr   ÚupdateÚlenr   ÚFIFFV_MNE_NOISE_COV)Úselfra   rc   rd   rM   re   rf   rg   rj   rk   r0   rh   rE   rE   rK   Ú__init__t   s    
    þzCovariance.__init__c                 C   s   | d S )z'Numpy array of Noise covariance matrix.ra   rE   ©rp   rE   rE   rK   ra   ‚   s    zCovariance.datac                 C   s   | d S )zChannel names.rc   rE   rr   rE   rE   rK   rN   ‡   s    zCovariance.ch_namesc                 C   s   | d S )zNumber of degrees of freedom.re   rE   rr   rE   rE   rK   re   Œ   s    zCovariance.nfreeF©Ú	overwriter0   c             	   C   s:   t |ddƒ t||d�}t|ƒ�}t|| ƒ W 5 Q R X dS )zÓSave covariance matrix in a FIF file.

        Parameters
        ----------
        fname : str
            Output filename.
        %(overwrite)s

            .. versionadded:: 1.0
        %(verbose)s
        Ú
covariance©z-cov.fifz-cov.fif.gzz_cov.fifz_cov.fif.gz)Úfnamert   N)r.   r>   r
   Ú
_write_cov)rp   rw   rt   r0   ÚfidrE   rE   rK   Úsave‘   s    
zCovariance.savec                 C   s   t | ƒS )z‰Copy the Covariance object.

        Returns
        -------
        cov : instance of Covariance
            The copied object.
        r   rr   rE   rE   rK   Úcopy¤   s    zCovariance.copyc                 C   s:   | d r| S d| d< t  | d ¡| d< d| d< d| d< | S )aJ  Set covariance to be processed as being diagonal.

        Returns
        -------
        cov : dict
            The covariance.

        Notes
        -----
        This function allows creation of inverse operators
        equivalent to using the old "--diagnoise" mne option.

        This function operates in place.
        rh   Tra   Nrf   rg   )rU   rh   rr   rE   rE   rK   Úas_diag®   s    zCovariance.as_diagc                 C   s$   | d r d| d< |   ¡  d| d< | S )Nrh   F)r|   rr   rE   rE   rK   Ú
_as_squareÅ   s
    zCovariance._as_squarec                 C   sJ   | d | j jdkkr,td| j j| d f ƒ‚| d r@t | j ¡S | j  ¡ S )Nrh   r   zOCovariance attributes inconsistent, got data with dimensionality %d but diag=%s)ra   rl   ÚRuntimeErrorrU   rh   r{   rr   rE   rE   rK   Ú_get_squareÍ   s    þÿzCovariance._get_squarec                 C   sJ   | j jdkrd| j j }nd| j j }|d| j 7 }|d| j  7 }d| S )Né   zsize : %s x %szdiagonal : %sz, n_samples : %sz, data : %sz<Covariance | %s>)ra   rl   ÚshapeÚsizere   )rp   ÚsrE   rE   rK   Ú__repr__Õ   s    zCovariance.__repr__c                 C   s|   t | |ƒ | ¡ }|d |d  | d | d   | d |d   |d< |d  | d 7  < tt|d ƒ | d ¡ƒ|d< |S )ú@Add Covariance taking into account number of degrees of freedom.ra   re   rd   )rP   r{   ÚlistÚsetÚunion)rp   ÚcovZthis_covrE   rE   rK   Ú__add__Þ   s    
ÿþzCovariance.__add__c                 C   s|   t | |ƒ | d | d  |d |d   | d |d   | d dd…< | d  |d 7  < tt| d ƒ |d ¡ƒ| d< | S )r…   ra   re   Nrd   )rP   r†   r‡   rˆ   )rp   r‰   rE   rE   rK   Ú__iadd__ë   s    
ÿþzCovariance.__iadd__Tc              
   C   s   t j | |||||||¡S ©N)r?   ÚmiscÚplot_cov)rp   rT   ÚexcludeÚcolorbarÚprojZshow_svdÚshowr0   rE   rE   rK   Úplot÷   s     ÿzCovariance.ploté@   r   z%3.1fÚheadé   c                  C   sì   ddl m} ||| dd�\}}}}tt |¡dd…tjf |ƒ}|dk	rptt||ƒ|ƒ}|	dkrdd}	|dkrpd}|	dkrŽdd	„ td
  ¡ D ƒ}	|dkr¬dd	„ td  ¡ D ƒ}|j	dg||||||||	|
|||||||||||||||dd�S )a.  Plot a topomap of the covariance diagonal.

        Parameters
        ----------
        %(info_not_none)s
        %(ch_type_topomap)s
        %(vmin_vmax_topomap)s
        %(cmap_topomap)s
        %(sensors_topomap)s
        %(colorbar_topomap)s
        %(scalings_topomap)s
        %(units_topomap)s
        %(res_topomap)s
        %(size_topomap)s
        %(cbar_fmt_topomap)s
        %(proj_plot)s
        %(show)s
        %(show_names_topomap)s
        %(title_none)s
        %(mask_topomap)s
        %(mask_params_topomap)s
        %(outlines_topomap)s
        %(contours_topomap)s
        %(image_interp_topomap)s
        %(axes_topomap)s
        %(extrapolate_topomap)s
        %(sphere_topomap_auto)s
        %(border_topomap)s
        noise_cov : instance of Covariance | None
            If not None, whiten the instance with ``noise_cov`` before
            plotting.
        %(verbose)s

        Returns
        -------
        fig : instance of Figure
            The matplotlib figure.

        Notes
        -----
        .. versionadded:: 0.21
        r   )Ú_index_info_covrE   ©r�   NZAUç      ð?c                 S   s   i | ]\}}|d |› d�“qS )ú(u   )Â²rE   ©rI   ÚkÚvrE   rE   rK   Ú
<dictcomp>>  s      z+Covariance.plot_topomap.<locals>.<dictcomp>Úunitsc                 S   s   i | ]\}}||| “qS rE   rE   r›   rE   rE   rK   rž   @  s      Úscalingsr   Ú )rS   Úch_typeÚvminÚvmaxÚcmapÚsensorsr�   r    rŸ   Úresr‚   Úcbar_fmtr‘   r’   Ú
show_namesÚtitler[   Úmask_paramsÚoutlinesÚcontoursÚimage_interpÚaxesÚextrapolateÚsphereÚborderÚtime_format)
Zviz.miscr—   r,   rU   rh   ÚnewaxisÚwhiten_evokedr	   ÚitemsÚplot_topomap) rp   rT   r¢   r£   r¤   r¥   r¦   r�   r    rŸ   r§   r‚   r¨   r‘   r’   r©   rª   r[   r«   r¬   r­   r®   r¯   r°   r±   r²   Ú	noise_covr0   r—   ÚCÚ_ÚevokedrE   rE   rK   r·   þ   sR    4                  øzCovariance.plot_topomapc                 C   s   t | |g |dd�S )a  Pick channels from this covariance 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
        -------
        cov : instance of Covariance.
            The modified covariance matrix.

        Notes
        -----
        Operates in-place.

        .. versionadded:: 0.20.0
        F)r�   Úorderedr{   )r   )rp   rN   r¼   rE   rE   rK   r   K  s    
ÿzCovariance.pick_channels)NNNN)F)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r0   rq   Úpropertyra   rN   re   rz   r{   r|   r}   r   r„   rŠ   r‹   r4   r?   r�   rŽ   r“   r   r   r   r·   r   rE   rE   rE   rK   r_   C   sr   /    ÿÿ



	
 ÿ                øLr_   c              
   C   sb   t | ddƒ t| ddd�} t| ƒdd… \}}|�&}tf t||tjdd�ŽW  5 Q R £ S Q R X dS )	aƒ  Read a noise covariance from a FIF file.

    Parameters
    ----------
    fname : str
        The name of file containing the covariance matrix. It should end with
        -cov.fif or -cov.fif.gz.
    %(verbose)s

    Returns
    -------
    cov : Covariance
        The noise covariance matrix.

    See Also
    --------
    write_cov, compute_covariance, compute_raw_covariance
    ru   rv   TÚread)rw   Z
must_existrt   Nr€   )Úlimited)r.   r>   r   r_   Ú	_read_covr   ro   )rw   r0   ÚfÚtreery   rE   rE   rK   Úread_covh  s    ÿrÇ   c           
         s    t ˆ dddd�}td|ƒ}t t|ƒ¡}tdd|d |d |d	 fƒD ],\}}}t ˆ ||d
�}|| |t ||¡< qF‡ fdd„|D ƒ}	t||	ˆ d ˆ d dd�S )uª  Create an ad hoc noise covariance.

    Parameters
    ----------
    %(info_not_none)s
    std : dict of float | None
        Standard_deviation of the diagonal elements. If dict, keys should be
        ``'grad'`` for gradiometers, ``'mag'`` for magnetometers and ``'eeg'``
        for EEG channels. If None, default values will be used (see Notes).
    %(verbose)s

    Returns
    -------
    cov : instance of Covariance
        The ad hoc diagonal noise covariance for the M/EEG data channels.

    Notes
    -----
    The default noise values are 5 fT/cm, 20 fT, and 0.2 ÂµV for gradiometers,
    magnetometers, and EEG channels respectively.

    .. versionadded:: 0.9.0
    TrE   )ÚmegÚeegr�   Z	noise_std)ÚgradÚmagF)FFTrÊ   rË   rÉ   )rÈ   rÉ   c                    s   g | ]}ˆ d  | ‘qS ©rN   rE   )rI   Úpick©rT   rE   rK   rL   ©  s     z#make_ad_hoc_cov.<locals>.<listcomp>rd   rM   r   ©re   )r   r)   rU   Úzerosrn   ÚzipÚsearchsortedr_   )
rT   Zstdr0   Úpicksra   rÈ   rÉ   ÚvalZthese_picksrN   rE   rÎ   rK   Úmake_ad_hoc_covˆ  s    
ÿrÕ   c                 C   s<   d|d  d }| dkr t dƒ‚| |k r8td|| f ƒ dS )z?Check to see if there are enough samples for reliable cov calc.é
   r   r€   r   z1No samples found to compute the covariance matrixzOToo few samples (required : %d got : %d), covariance estimate may be unreliableN)rO   r3   )Ú	n_samplesÚn_chanZn_samples_minrE   rE   rK   Ú_check_n_samples­  s    ÿrÙ   çš™™™™™É?Ú	empiricalé   FTc                    sl  |dkrdnt |ƒ}dˆjd  }|dkr8ˆjd | nt |ƒ}|dkrP|| nt |ƒ}|| }tˆd|||ƒ}t dt|ƒt|ƒf ¡ |dkrºt ˆjd ¡}t 	|t
ˆjd	d
�¡}ntdƒ}tˆj|ƒ}tˆ|dd|d|||d	d	d	|d�}|dkrüd}t|tƒ�r
|dk�r
|| }d}d}d}|D ]>}|| }||jdd�7 }|t ||j¡7 }||jd 7 }�q*t|t|ƒƒ ||dd…df |ddd…f |  8 }||d  }t d| ¡ t d¡ ‡fdd„|D ƒ‰ ‡ fdd„ˆjd D ƒ}t|ˆ |ˆjd |d d�S ~~| ¡  |jjdd�jdd�}| j|tjdd…tjf 8  _d|_t|d|||	|
|||d�	S )aÀ  Estimate noise covariance matrix from a continuous segment of raw data.

    It is typically useful to estimate a noise covariance from empty room
    data or time intervals before starting the stimulation.

    .. note:: To estimate the noise covariance from epoched data, use
              :func:`mne.compute_covariance` instead.

    Parameters
    ----------
    raw : instance of Raw
        Raw data.
    tmin : float
        Beginning of time interval in seconds. Defaults to 0.
    tmax : float | None (default None)
        End of time interval in seconds. If None (default), use the end of the
        recording.
    tstep : float (default 0.2)
        Length of data chunks for artifact rejection in seconds.
        Can also be None to use a single epoch of (tmax - tmin)
        duration. This can use a lot of memory for large ``Raw``
        instances.
    reject : dict | None (default None)
        Rejection parameters based on peak-to-peak amplitude.
        Valid keys are 'grad' | 'mag' | 'eeg' | 'eog' | 'ecg'.
        If reject is None then no rejection is done. Example::

            reject = dict(grad=4000e-13, # T / m (gradiometers)
                          mag=4e-12, # T (magnetometers)
                          eeg=40e-6, # V (EEG channels)
                          eog=250e-6 # V (EOG channels)
                          )

    flat : dict | None (default None)
        Rejection parameters based on flatness of signal.
        Valid keys are 'grad' | 'mag' | 'eeg' | 'eog' | 'ecg', and values
        are floats that set the minimum acceptable peak-to-peak amplitude.
        If flat is None then no rejection is done.
    %(picks_good_data_noref)s
    method : str | list | None (default 'empirical')
        The method used for covariance estimation.
        See :func:`mne.compute_covariance`.

        .. versionadded:: 0.12
    method_params : dict | None (default None)
        Additional parameters to the estimation procedure.
        See :func:`mne.compute_covariance`.

        .. versionadded:: 0.12
    cv : int | sklearn.model_selection object (default 3)
        The cross validation method. Defaults to 3, which will
        internally trigger by default :class:`sklearn.model_selection.KFold`
        with 3 splits.

        .. versionadded:: 0.12
    scalings : dict | None (default None)
        Defaults to ``dict(mag=1e15, grad=1e13, eeg=1e6)``.
        These defaults will scale magnetometers and gradiometers
        at the same unit.

        .. versionadded:: 0.12
    %(n_jobs)s

        .. versionadded:: 0.12
    return_estimators : bool (default False)
        Whether to return all estimators or the best. Only considered if
        method equals 'auto' or is a list of str. Defaults to False.

        .. versionadded:: 0.12
    %(reject_by_annotation_epochs)s

        .. versionadded:: 0.14
    %(rank_none)s

        .. versionadded:: 0.17

        .. versionadded:: 0.18
           Support for 'info' mode.
    %(verbose)s

    Returns
    -------
    cov : instance of Covariance | list
        The computed covariance. If method equals 'auto' or is a list of str
        and return_estimators equals True, a list of covariance estimators is
        returned (sorted by log-likelihood, from high to low, i.e. from best
        to worst).

    See Also
    --------
    compute_covariance : Estimate noise covariance matrix from epoched data.

    Notes
    -----
    This function will:

    1. Partition the data into evenly spaced, equal-length epochs.
    2. Load them into memory.
    3. Subtract the mean across all time points and epochs for each channel.
    4. Process the :class:`Epochs` by :func:`compute_covariance`.

    This will produce a slightly different result compared to using
    :func:`make_fixed_length_events`, :class:`Epochs`, and
    :func:`compute_covariance` directly, since that would (with the recommended
    baseline correction) subtract the mean across time *for each epoch*
    (instead of across epochs) for each channel.
    Nç        r™   rQ   rR   r   zUsing up to %s segment%sZnchanF©Zwith_ref_megr   )ÚbaselinerÓ   ÚrejectÚflatr0   Zpreloadr‘   Úreject_by_annotationrÛ   ©ZaxisúNumber of samples used : %dú[done]c                    s   g | ]}ˆ j d  | ‘qS rÌ   rÎ   ©rI   rœ   )ÚrawrE   rK   rL   P  s     z*compute_raw_covariance.<locals>.<listcomp>c                    s   g | ]}|ˆ kr|‘qS rE   rE   )rI   ÚbrÌ   rE   rK   rL   Q  s      rd   rM   rÏ   )NNT)Úkeep_sample_meanrj   Úmethod_paramsÚcvr    Ún_jobsÚreturn_estimatorsÚrank)ÚfloatrT   rS   r+   r/   rn   r5   rU   ÚarangeZin1dr   rW   r   r*   Ú
isinstancerG   ÚsumÚdotÚTr�   rÙ   r_   Z	load_dataÚ_dataÚmeanr´   rß   Úcompute_covariance)rç   rY   rZ   Ztsteprà   rá   rÓ   rj   rê   rë   r    rì   rí   râ   rî   r0   ÚdtZtstep_m1ÚeventsZ	pick_maskrX   ra   r×   ÚmuZraw_segmentrd   Zch_meansrE   )rN   rç   rK   Úcompute_raw_covariance·  sv    q ÿ    ý(
ÿ   ürû   rj   c              
      s  d‰ dddœdddœdddœdddœddddœt  ddd	¡dddœd
did
didœ}tD ]}d|d |< qXt|tƒrî| ¡ D ]8\}}	||kr¢td|d |¡f ƒ‚||  || ¡ q|| 	di ¡ 	dd¡}
d|
  krÞdksîn td|
f ƒ‚d}| dk�rdg} n | dk�r$|�r$d}ddddg} t| t
tfƒ�s:| g} t‡ fdd„| D ƒƒ�sftdj|| ˆ d�ƒ‚t|tƒ�r||dk�s¸|�r’|  |  d¡¡ | D ] }|dk�r–td||f ƒ‚�q–|�st| ƒdk�sÖd| k�rätd|f ƒ‚| ¡ D ]$\}}| 	dd¡dk�rìtd ƒ‚�qì| |fS )!z/Check that method and method_params are usable.)	ÚautorÛ   Údiagonal_fixedÚledoit_wolfÚoasÚshrunkÚpcaÚfactor_analysisÚ	shrinkageFT©Ústore_precisionÚassume_centeredçš™™™™™¹?)r  r  r  éüÿÿÿr   é   Úiter_n_componentsN)rÛ   rý   rþ   rÿ   r  r   r  r  rý   zkey (%s) must be "%s"z" or "r  r   z)shrinkage must be between 0 and 1, got %srÛ   rü   r   r  c                 3   s   | ]}|ˆ kV  qd S rŒ   rE   ræ   ©Úaccepted_methodsrE   rK   Ú	<genexpr>�  s     z'_check_method_params.<locals>.<genexpr>zoInvalid {name} ({method}). Accepted values (individually or in a list) are any of "{accepted_methods}" or None.)Únamerj   r  Úfull)r  r  z8%s can so far only be used with rank="full", got rank=%rz=`keep_sample_mean=False` is only supportedwith %s="empirical"r  z=`assume_centered` must be True if `keep_sample_mean` is False)rU   Zlogspacer   rñ   Údictr¶   rO   Újoinrm   Úgetr†   ÚtupleÚallÚformatrG   ÚpopÚindexrn   )rj   rê   ré   r  Ú
allow_autorî   Ú_method_paramsr¢   ÚkeyÚvaluesr  Zwas_autoÚmethod_Úpr�   rE   r  rK   Ú_check_method_paramsd  s|    ÿ ÿö
ÿÿ
  þÿ
ÿ
ÿr  Úraisec           +         sà  t |ƒ}t||ˆ|d�\}}~dd„ ‰ tˆtƒs:ˆ ˆƒ‰nt‡ fdd„ˆD ƒg ƒ‰t‡fdd„ˆD ƒƒrptdƒ ˆd	 jd
 }t|dƒ t	ˆƒD ]j\}}|j 
¡  |dk|jd
 dkksÚ|dk	r�t |d |jd
 d ¡s�d|||jd
 f }t||dƒ q�ˆd	 jd }|dk�r€ˆd	 jd }ˆdd… D ]P}|jˆd	 jk�rLtdƒ‚t|jd |ƒD ]\}}t||ƒ�s\tdƒ‚�q\�q.t|ƒ}ˆd	 j}ˆdd… D ]2}|jd |k�rºtdƒ‚|j|k�ržtdƒ‚�qžtˆd	 jƒ}t dd„ |D ƒ¡‰t ˆ¡‰‡fdd„ˆD ƒ}ˆd	 j}ˆ�sôtˆƒ}d	g| }tj|tjd�}tj|tjd�}t	ˆƒD ]j\}}t|||ƒ‰|D ]N}|ˆˆf }ˆ�s˜||  |7  < ||  |jd 7  < ||  d7  < �qr�qZ|| } t | |d  ¡}!dd„ t||ƒD ƒ}t|ˆƒ}tˆd	 ||ƒ‰‡‡fdd„ˆD ƒ‰t tˆƒ¡‰t|ƒ}tˆƒdk�rTt ˆd	¡‰nˆd	 ‰t ˆ¡‰ˆjd }"t|"tˆƒƒ ˆj ‰t!ˆ|||||	d|||d�
}#ˆdk�rÞ|#d d  }$|$|"d 9 }$|D ]}%|$|%8 }$�qÆ|$|! }$tƒ }&|# "¡ D ]H\}'}(t#|( $d ¡||d ||"d d!�}$|$j%f d"|'i|(—Ž |& &|$¡ �qìt' d#|" ¡ |&jd$d%„ dd&� t|&ƒdk�rÊd'g}|&D ] })| &d(|)d" |)d) f ¡ �qnt' d* (|¡¡ |
�r¬|&}*n|&d	 }*t' d+ )|*d" ¡¡ n|&d	 }*t' d,¡ |*S )-a¸  Estimate noise covariance matrix from epochs.

    The noise covariance is typically estimated on pre-stimulus periods
    when the stimulus onset is defined from events.

    If the covariance is computed for multiple event types (events
    with different IDs), the following two options can be used and combined:

        1. either an Epochs object for each event type is created and
           a list of Epochs is passed to this function.
        2. an Epochs object is created for multiple events and passed
           to this function.

    .. note:: To estimate the noise covariance from non-epoched raw data, such
              as an empty-room recording, use
              :func:`mne.compute_raw_covariance` instead.

    Parameters
    ----------
    epochs : instance of Epochs, or list of Epochs
        The epochs.
    keep_sample_mean : bool (default True)
        If False, the average response over epochs is computed for
        each event type and subtracted during the covariance
        computation. This is useful if the evoked response from a
        previous stimulus extends into the baseline period of the next.
        Note. This option is only implemented for method='empirical'.
    tmin : float | None (default None)
        Start time for baseline. If None start at first sample.
    tmax : float | None (default None)
        End time for baseline. If None end at last sample.
    projs : list of Projection | None (default None)
        List of projectors to use in covariance calculation, or None
        to indicate that the projectors from the epochs should be
        inherited. If None, then projectors from all epochs must match.
    method : str | list | None (default 'empirical')
        The method used for covariance estimation. If 'empirical' (default),
        the sample covariance will be computed. A list can be passed to
        perform estimates using multiple methods.
        If 'auto' or a list of methods, the best estimator will be determined
        based on log-likelihood and cross-validation on unseen data as
        described in :footcite:`EngemannGramfort2015`. Valid methods are
        'empirical', 'diagonal_fixed', 'shrunk', 'oas', 'ledoit_wolf',
        'factor_analysis', 'shrinkage', and 'pca' (see Notes). If ``'auto'``,
        it expands to::

             ['shrunk', 'diagonal_fixed', 'empirical', 'factor_analysis']

        ``'factor_analysis'`` is removed when ``rank`` is not 'full'.
        The ``'auto'`` mode is not recommended if there are many
        segments of data, since computation can take a long time.

        .. versionadded:: 0.9.0
    method_params : dict | None (default None)
        Additional parameters to the estimation procedure. Only considered if
        method is not None. Keys must correspond to the value(s) of ``method``.
        If None (default), expands to the following (with the addition of
        ``{'store_precision': False, 'assume_centered': True} for all methods
        except ``'factor_analysis'`` and ``'pca'``)::

            {'diagonal_fixed': {'grad': 0.1, 'mag': 0.1, 'eeg': 0.1, ...},
             'shrinkage': {'shrikage': 0.1},
             'shrunk': {'shrinkage': np.logspace(-4, 0, 30)},
             'pca': {'iter_n_components': None},
             'factor_analysis': {'iter_n_components': None}}

    cv : int | sklearn.model_selection object (default 3)
        The cross validation method. Defaults to 3, which will
        internally trigger by default :class:`sklearn.model_selection.KFold`
        with 3 splits.
    scalings : dict | None (default None)
        Defaults to ``dict(mag=1e15, grad=1e13, eeg=1e6)``.
        These defaults will scale data to roughly the same order of
        magnitude.
    %(n_jobs)s
    return_estimators : bool (default False)
        Whether to return all estimators or the best. Only considered if
        method equals 'auto' or is a list of str. Defaults to False.
    on_mismatch : str
        What to do when the MEG<->Head transformations do not match between
        epochs. If "raise" (default) an error is raised, if "warn" then a
        warning is emitted, if "ignore" then nothing is printed. Having
        mismatched transforms can in some cases lead to unexpected or
        unstable results in covariance calculation, e.g. when data
        have been processed with Maxwell filtering but not transformed
        to the same head position.
    %(rank_none)s

        .. versionadded:: 0.17

        .. versionadded:: 0.18
           Support for 'info' mode.
    %(verbose)s

    Returns
    -------
    cov : instance of Covariance | list
        The computed covariance. If method equals 'auto' or is a list of str
        and return_estimators equals True, a list of covariance estimators is
        returned (sorted by log-likelihood, from high to low, i.e. from best
        to worst).

    See Also
    --------
    compute_raw_covariance : Estimate noise covariance from raw data, such as
        empty-room recordings.

    Notes
    -----
    Baseline correction or sufficient high-passing should be used
    when creating the :class:`Epochs` to ensure that the data are zero mean,
    otherwise the computed covariance matrix will be inaccurate.

    Valid ``method`` strings are:

    * ``'empirical'``
        The empirical or sample covariance (default)
    * ``'diagonal_fixed'``
        A diagonal regularization based on channel types as in
        :func:`mne.cov.regularize`.
    * ``'shrinkage'``
        Fixed shrinkage.

      .. versionadded:: 0.16
    * ``'ledoit_wolf'``
        The Ledoit-Wolf estimator, which uses an
        empirical formula for the optimal shrinkage value
        :footcite:`LedoitWolf2004`.
    * ``'oas'``
        The OAS estimator :footcite:`ChenEtAl2010`, which uses a different
        empricial formula for the optimal shrinkage value.

      .. versionadded:: 0.16
    * ``'shrunk'``
        Like 'ledoit_wolf', but with cross-validation
        for optimal alpha.
    * ``'pca'``
        Probabilistic PCA with low rank :footcite:`TippingBishop1999`.
    * ``'factor_analysis'``
        Factor analysis with low rank :footcite:`Barber2012`.

    ``'ledoit_wolf'`` and ``'pca'`` are similar to ``'shrunk'`` and
    ``'factor_analysis'``, respectively, except that they use
    cross validation (which is useful when samples are correlated, which
    is often the case for M/EEG data). The former two are not included in
    the ``'auto'`` mode to avoid redundancy.

    For multiple event types, it is also possible to create a
    single :class:`Epochs` object with events obtained using
    :func:`mne.merge_events`. However, the resulting covariance matrix
    will only be correct if ``keep_sample_mean is True``.

    The covariance can be unstable if the number of samples is small.
    In that case it is common to regularize the covariance estimate.
    The ``method`` parameter allows to regularize the covariance in an
    automated way. It also allows to select between different alternative
    estimation algorithms which themselves achieve regularization.
    Details are described in :footcite:`EngemannGramfort2015`.

    For more information on the advanced estimation methods, see
    :ref:`the sklearn manual <sklearn:covariance>`.

    References
    ----------
    .. footbibliography::
    )rî   c                    s.   t ˆ jƒdkr$‡ fdd„ˆ jD ƒ‰ nˆ g‰ ˆ S )Nr   c                    s   g | ]}ˆ | ‘qS rE   rE   ræ   ©rX   rE   rK   rL   ]  s     z>compute_covariance.<locals>._unpack_epochs.<locals>.<listcomp>©rn   Zevent_idr   rE   r   rK   Ú_unpack_epochs[  s    z*compute_covariance.<locals>._unpack_epochsc                    s   g | ]}ˆ |ƒ‘qS rE   rE   )rI   Úepoch)r"  rE   rK   rL   e  s     z&compute_covariance.<locals>.<listcomp>c                 3   s*   | ]"}|j d ko |jd dk o ˆ V  qd S )NZhighpassç      à?)rß   rT   )rI   Úepochs_t)ré   rE   rK   r  h  s   ÿz%compute_covariance.<locals>.<genexpr>zFEpochs are not baseline corrected, covariance matrix may be inaccurater   Z
dev_head_tÚon_mismatchNZtranszGMEG<->Head transform mismatch between epochs[0]:
%s

and epochs[%s]:
%srd   rM   r   z+Epochs must agree on the use of projectionsz Epochs must have same projectorsz"Epochs must have same bad channelsz#Epochs must have same channel namesc                 S   s   g | ]\}}|‘qS rE   rE   )rI   rº   rè   rE   rE   rK   rL   Ž  s     c                    s   g | ]}ˆ d  j | ‘qS ©r   rÌ   ræ   r   rE   rK   rL   �  s     ©Údtypec                 S   s&   g | ]\}}d | t  ||j¡ ‘qS )r™   )rU   ró   rô   )rI   Zn_epochrö   rE   rE   rK   rL   ¦  s     c                    s    g | ]}|j ˆ d �dˆf ‘qS ))rÓ   .)Úget_data)rI   Úee)Ú
picks_meegr]   rE   rK   rL   «  s     rR   T©	rj   rê   rT   rë   rì   Ú
stop_earlyÚ
picks_listr    rî   FrÛ   ra   rÏ   rj   rä   c                 S   s   | d S )Nrk   rE   )rJ   rE   rE   rK   Ú<lambda>Ð  ó    z$compute_covariance.<locals>.<lambda>)r  Úreversez1log-likelihood on unseen data (descending order):z	%s: %0.3frk   z
   zselecting best estimator: {}rå   )*Ú_check_scalings_userr  rñ   r†   rò   Úanyr3   rT   r=   Ú	enumerateÚ_check_consistencyrU   Zallcloser<   r‘   rO   rÑ   r   r   rN   r   ZconcatenateÚsortrn   rÐ   Zint64r^   r�   r   rð   ZhstackrÙ   rô   Ú_compute_covariance_autor¶   r_   r  rm   Úappendr/   r  r  )+rX   ré   rY   rZ   rM   rj   rê   rë   r    rì   rí   r&  rî   r0   r  ÚorigÚeir#  Úmsgrd   r%  Zproj_aZproj_brN   r/  rT   Zn_epoch_typesZ	data_meanr×   Zn_epochsÚiiÚeZn_samples_epochZ
norm_constZn_samples_totZcov_datar‰   Zmean_covÚcovsZthis_methodra   rJ   ÚoutrE   )r"  rX   ré   r,  r]   rK   r÷   ¦  sô     .   ÿ


ÿ

ÿ
ÿþþ




ÿ


       ý
ÿ
r÷   c                 C   sb   t | tƒr0|  ¡ D ]\}}td|dddgƒ qn$| d k	rTt | tjƒsTtdt| ƒ ƒ‚td| ƒ} | S )Nzthe keys in `scalings`rË   rÊ   rÉ   z1scalings must be a dict, ndarray, or None, got %sr    )	rñ   r  r¶   r9   rU   ZndarrayÚ	TypeErrorÚtyper)   )r    rœ   r�   rE   rE   rK   r3  ã  s    
ÿ
r3  c                 C   sJ   t  t|ƒ¡t  ||   ¡ j||  ¡ }t|ƒ\} }| ¡ j}| |fS )z3Compute the subspace from a subset of eigenvectors.)rU   Úeyern   ró   Úconjrô   r:   )rf   rg   r[   ÚPrE   rE   rK   Ú_eigvec_subspaceî  s    ,
rF  c
           /   
      s„  |	}
t t| j|ddd�|	||ƒ}	t| j||ƒ��J t | j| ¡}t|||	ddd�\}}}|| }t | |j¡} t |¡d ‰ ‡ fdd„|D ƒ}tˆ ƒt|ƒkr¨t	|ˆ ƒn|}t
 d	t|ƒ|jd f ¡ tƒ }d
}tdƒ}|�st|ƒdksú|d dk�rtd|f ƒ‚|D �]’}|  ¡ }t|ƒ�r*|jn|}t
 || ¡  ¡ || }i }|dk�r‚tf |Ž}| |¡ | ||j|f¡ ~�n|dk�rÀtf d|i|—Ž}| |¡ | ||j|f¡ ~�nÔ|dk�rRddlm} g }|f |Ž}|D ]2\}}| |dd…|f ¡ | ||j|f¡ �qètf d|i|—Ž}| |¡ | ||j|f¡ ~~�nB|dk�räddlm}  g }| f |Ž}!|D ]2\}}|! |dd…|f ¡ | ||!j|f¡ �qztf d|i|—Ž}| |¡ | ||j|f¡ ~!~�n°|dk�rtf |Ž}| |¡ | ||j|f¡ ~�nz|dk�rèddlm}" ddlm }# | !d¡}$d|$ig}%g }|"|#f |Ž|%|d�}&|D ]4\}}|& |dd…|f ¡ | ||&j"j#|f¡ �qldd„ t$|ƒD ƒ}tf d|i|—Ž}| |¡ | ||j|f¡ ~$~n¬|dk�r:|
dk�s t%‚t&||||||d�\}'}|' |¡ | |'|' '¡ |f¡ ~'nZ|dk�rŒ|
dk�sRt%‚t&||||||d�\}(}|( |¡ | |(|( '¡ |f¡ ~(ntdƒ‚t
 d ¡ �qt|ƒdk�rºt
 d!¡ t(ƒ })t)|ƒD ]¬\}*\}+},}-t|ƒdk�rôt*| |+||ƒ}.nd}.t |jt |,|¡¡},|,| jd | jd d  9 },t+|,||ƒ ||* }t|ƒ�rN|jn|}t(|.|,|+d"�|)|< |)|  ,|-¡ �qÈW 5 Q R X |)S )#zCompute covariance auto mode.NF)r{   r0   T)Úproj_subspaceÚdo_compute_rankr   c                    s    g | ]\}}|t  ˆ |¡f‘qS rE   )rU   rÒ   )rI   r  rÓ   ©ÚusedrE   rK   rL     s   ÿz,_compute_covariance_auto.<locals>.<listcomp>z Reducing data rank from %s -> %szEstimating covariance using %sZsklearnr   rÛ   zCscikit-learn is not installed, `method` must be `empirical`, got %srý   rT   rþ   )Ú
LedoitWolfr  rÿ   )ÚOASr   )ÚGridSearchCV)ÚShrunkCovariance)rë   c                 S   s   g | ]}|d  ‘qS r'  rE   rH   rE   rE   rK   rL   Q  s     r  r  )rì   rê   rë   r.  r  z1Oh no! Your estimator does not have a .fit methodzDone.z4Using cross-validation to select the best estimator.)rk   ra   Ú	estimator)-r-   r   rô   r7   rU   ró   Ú_smart_eighrV   rn   r   r/   rT   r�   r†   r1   rO   r{   Úcallabler½   ÚupperrA   Úfitr9  Úcovariance_Ú_RegCovarianceÚsklearn.covariancerK  Z
shrinkage_Ú_ShrunkCovariancerL  Úsklearn.model_selectionrM  rN  r  Zbest_estimator_r  rÑ   ÚAssertionErrorÚ_auto_low_rank_modelZget_covariancer  r5  Ú
_cross_valr6   rm   )/ra   rj   rT   rê   rë   r    rì   r.  r/  rî   Z	orig_rankr¹   rº   rg   r[   Zsub_picks_listZsub_infoZestimator_cov_infor<  Z
ok_sklearnr  Zdata_r  ÚmpÚ_infoÚestrK  Z
shrinkagesZlwr¢   rÓ   ÚscrL  rÿ   rM  rN  r  Ztuned_parametersÚgsr  Úfar@  r;  rO  r‰   Úruntime_infork   rE   rI  rK   r8  ÷  s     ÿ
ÿ
ÿÿ ÿ


















 ÿÿ


    þ


    þ


ÿr8  c                 C   s^   |   ¡ }|j\}}d|t ||¡ jdd� }|d|tdtj ƒ t|ƒ  8 }t |¡}|S )z@Compute the Gaussian log likelihood of X under the model in est.g      à¿r   rã   r$  ç       @)	Úget_precisionr�   rU   ró   rò   r   ÚpirB   rö   )r^  ÚXÚyÚ	precisionr×   Z
n_featuresZlog_liker@  rE   rE   rK   Ú_gaussian_loglik_scorer…  s    
"
ri  c              	   C   s$   ddl m} t ||| ||td�¡S )zCompute cross validation.r   )Úcross_val_score)rë   rì   Zscoring)rX  rj  rU   rö   ri  )ra   r^  rë   rì   rj  rE   rE   rK   r[  �  s    ÿr[  c              	   C   sê  t |ƒ}| d¡}|dkr.t d| jd d¡}ddlm}m}	 |dkrL|	}
n|dksXt‚|}
|
f |Ž}
d|
_	tj
|tjd	�}| tj¡ ttt |ƒƒƒ}|| jd kr¼td
|| jd f ƒ t|ƒD ]Ê\}}||
_	zt| |
||d�}W n tk
�r   tj}Y nX t |¡�s|dk�r*t d¡  �q�t d||f ¡ |tj k�rR|||< |dkrÄt t ||d |… ¡dk ¡rÄ|rÄt d¡  �q�qÄt |¡ ¡ �r¨tdƒ‚t |¡}||  }|
_	t d| ¡ t |¡|||dœ}|
|fS )zCompute latent variable models.r
  Né   r   r   )ÚPCAÚFactorAnalysisr  r  r(  zDYou are trying to estimate %i components on matrix with %i features.)ra   r^  rë   rì   z4... infinite values encountered. stopping estimationz... rank: %i - loglik: %0.3frÜ   z early stopping parameter search.zkOh no! Could not estimate covariance because all scores were NaN. Please contact the MNE-Python developers.z... best model at rank = %i)ZranksÚscoresÚbestrë   )r   r  rU   rð   r�   Zsklearn.decompositionrl  rm  rY  Zn_componentsZ
empty_likeÚfloat64ÚfillÚnanÚmaxr†   r3   r5  r[  rO   ÚinfÚisinfr/   rT   r  ÚdiffÚisnanr~   Z	nanargmaxÚarray)ra   Úmoderì   rê   rë   r.  r0   r
  rl  rm  r^  rn  Zmax_nr=  ÚnÚscoreZi_scorero  rb  rE   rE   rK   rZ  —  sX    

ÿ
,

ýrZ  c                   @   s4   e Zd ZdZddd„Zdd„ Zdd	d
„Zdd„ ZdS )rU  ú
Aux class.r  Fc                 C   sd   || _ || _|| _|| _|| _|| _|| _|| _|| _|	| _	|
| _
|| _|| _|| _|| _|| _d S rŒ   )rT   rÊ   rË   rÉ   ÚseegÚdbsÚecogÚhboÚhbrÚfnirs_cw_amplitudeÚfnirs_fd_ac_amplitudeÚfnirs_fd_phaseÚfnirs_odÚcsdr  r  )rp   rT   rÊ   rË   rÉ   r}  r  r€  r�  r‚  rƒ  r„  r…  r†  r~  r  r  rE   rE   rK   rq   Ø  s     z_RegCovariance.__init__c                 C   sª   t | j| jd�| _| j |¡j| _d| j| jj  | _t| j| jd | jd | jd t	| jƒd�}t
|| jdd| j| j| j| j| j| j| j| jdd	�}|j | j_| _| S )
z<Fit covariance model with classical diagonal regularization.r  r$  rN   rd   rM   )ra   rc   rd   rM   re   Fr  )r‘   r�   rÊ   rË   rÉ   r  r}  r~  r€  r�  rî   )rA   r  r  Ú
estimator_rS  rT  rô   r_   rT   rn   Ú
regularizerÊ   rË   rÉ   r  r}  r~  r€  r�  ra   )rp   rf  Zcov_rE   rE   rK   rS  ð  s<    þ  ý         üz_RegCovariance.fitNc                 C   s   | j j||d�S )ú7Delegate call to modified EmpiricalCovariance instance.)rg  )r‡  r{  )rp   ÚX_testrg  rE   rE   rK   r{    s    z_RegCovariance.scorec                 C   s
   | j  ¡ S )r‰  ©r‡  rd  rr   rE   rE   rK   rd    s    z_RegCovariance.get_precision)r  r  r  r  r  r  r  r  r  r  r  r  r  FF)N©r½   r¾   r¿   rÀ   rq   rS  r{  rd  rE   rE   rE   rK   rU  Õ  s"                      ü

rU  c                   @   s4   e Zd ZdZddd„Zdd„ Zddd	„Zd
d„ ZdS )rW  r|  r  c                 C   s   || _ || _|| _d S rŒ   )r  r  r  )rp   r  r  r  rE   rE   rK   rq     s    z_ShrunkCovariance.__init__c                 C   s°  ddl m} t| j| jd�| _| j |¡j}t| j	t
tfƒsVd| j	t t|ƒ¡fg}n| j	}tj|td�}t |d¡D ]R\}}|d |d  }}	|d |d f}
d|
krvd|t ||	¡< d|t |	|¡< qv|| _|D ]2\}}}|t ||¡ }|||d	�|t ||¡< qÔt |d¡D ]t\}}|d
 |d
  }}|d |d  }}	t d| d|  ¡}|t ||	¡  |9  < |t |	|¡  |9  < �qt |¡�ržd||< | | j_| _| S )z:Fit covariance model with oracle shrinkage regularization.r   )Úshrunk_covariancer  r  r(  r€   rÉ   T©r  r   r™   rÝ   )rV  r�  rA   r  r  r‡  rS  rT  rñ   r  r†   r  rU   rð   rn   Z
zeros_likeÚboolÚittÚcombinationsÚix_Úzero_cross_cov_Úsqrtr4  )rp   rf  r�  r‰   r  Zzero_cross_covÚarè   Zpicks_iZpicks_jZch_r¢   rJ   rÓ   Zsub_covZshrinkage_iZshrinkage_jZc_ijrE   rE   rK   rS    s@    þÿz_ShrunkCovariance.fitNc                 C   s>   t || jj dd�}t | j¡r*d|| j< t|| j ¡ ƒ}|S )ú2Delegate to modified EmpiricalCovariance instance.T)r  rÝ   )rC   r‡  Z	location_rU   r4  r“  rD   rd  )rp   rŠ  rg  Ztest_covr§   rE   rE   rK   r{  D  s    ÿ
z_ShrunkCovariance.scorec                 C   s
   | j  ¡ S )r–  r‹  rr   rE   rE   rK   rd  N  s    z_ShrunkCovariance.get_precision)r  )NrŒ  rE   rE   rE   rK   rW    s    ÿ
-

rW  rs   c                C   s   |j | ||d� dS )aA  Write a noise covariance matrix.

    Parameters
    ----------
    fname : str
        The name of the file. It should end with -cov.fif or -cov.fif.gz.
    cov : Covariance
        The noise covariance matrix.
    %(overwrite)s

        .. versionadded:: 1.0
    %(verbose)s

    See Also
    --------
    read_cov
    rs   N)rz   )rw   r‰   rt   r0   rE   rE   rK   Ú	write_covV  s    r—  c                    s.   t ˆ jƒdkr$‡ fdd„ˆ jD ƒ‰ nˆ g‰ ˆ S )zAux Function.r   c                    s   g | ]}ˆ | ‘qS rE   rE   ræ   r   rE   rK   rL   r  s     z"_unpack_epochs.<locals>.<listcomp>r!  r   rE   r   rK   r"  o  s    r"  c                 C   s€   t | dd�\}}| ¡ j}t t|ƒt¡}d|d| …< d|d| …< t d||rVdndf ¡ |rv|d| …  	¡ }|||fS )	z*Get whitener params for a set of channels.T)Zoverwrite_arÝ   NFz-    Setting small %s eigenvalues to zero (%s)z	using PCAzwithout PCA)
r:   rD  rô   rU   Úonesrn   r�  r/   rT   r{   )ÚAr  r¢   rî   rf   rg   r[   rE   rE   rK   Ú_get_ch_whitenery  s    
ÿrš  Úignorec                 C   s  t ƒ }t ƒ }|dkr|d n|}|D ],}	|	| jkrF| | j |	¡¡ q$| |	¡ q$t|ƒrftd| ƒ‚|  ¡ t ||¡ }
t	|t
|d |ƒƒ}|d | d  }t|
|t | d ƒt| d ƒ| d |  dd¡|  dd¡d	�} t| ||||||d
�\}}}| j||d� | S )aK  Prepare noise covariance matrix.

    Parameters
    ----------
    noise_cov : instance of Covariance
        The noise covariance to process.
    %(info_not_none)s (Used to get channel types and bad channels).
    ch_names : list | None
        The channel names to be considered. Can be None to use
        ``info['ch_names']``.
    %(rank_none)s

        .. versionadded:: 0.18
           Support for 'info' mode.
    scalings : dict | None
        Data will be rescaled before rank estimation to improve accuracy.
        If dict, it will override the following dict (default if None)::

            dict(mag=1e12, grad=1e11, eeg=1e5)
    %(on_rank_mismatch)s
    %(verbose)s

    Returns
    -------
    cov : instance of Covariance
        A copy of the covariance with the good channels subselected
        and parameters updated.
    NrN   z0Not all channels present in noise covariance:
%srM   rd   re   rj   rk   )ra   rc   rd   rM   re   rj   rk   ©Úon_rank_mismatch)rf   rg   )r†   rN   r9  r  rn   r~   r   rU   r’  r   r   r_   r   r  rP  rm   )r¸   rT   rN   rî   r    r�  r0   Znoise_cov_idxÚmissingrJ   r¹   rM   rf   rg   rº   rE   rE   rK   Úprepare_noise_cov‹  s:     
ÿ  

 

ü ÿrŸ  c
                    sh  t d|ƒ}|dkrˆ d n|}|dkr.ˆ d n|}ˆ d |krVtˆ ‡ fdd„|D ƒƒ‰ ˆ d |ksft‚t|ƒ}
t||ƒ\}}}t| tƒr�| d } |dkr¼t d	| ¡ t	 
|t	 
| |j¡¡} t| |g |dƒ}|rât|||ˆ |d
�}| jdk�r| jd | jd k�st‚|�rDt| ¡ ƒ| jd k�rDt	 |
¡t	 |
¡t	 |
t¡fS | jt	jk�rVtnt}t	 |
|¡}t	 |
|
f|¡}t	 |
t¡}tˆ ddg d�D ]Ê\}}t|ƒdk�r¬�q’| t	 ||¡ }||k�rÚ|dk�rÚ|d }n|| }t|d| ¡ |ƒ\}}}|�rt|||ƒ\}}|||  ||< |t	 ||¡< ||< |dk�r’tˆ ƒ�r’t|ƒ�s’t dƒ �q’|||fS )z@Compute eigh of C taking into account rank and ch_type scalings.Úscalings_cov_rankNrM   rN   c                    s   g | ]}ˆ d    |¡‘qS rÌ   )r  rH   rÎ   rE   rK   rL   Ï  s     z_smart_eigh.<locals>.<listcomp>ra   r   z5    Created an SSP operator (subspace dimension = %d)rœ  r€   r   TF)Úmeg_combinedÚref_megr�   ©rË   rÊ   rÈ   rÉ   z­No average EEG reference present in info["projs"], covariance may be adversely affected. Consider recomputing covariance using with an average eeg reference projector added.)!r)   r   rY  rn   r   rñ   r_   r/   rT   rU   ró   rô   r-   rl   r�   rò   r  r˜  rC  r�  r)  Zcomplex_Úcomplexrï   rÐ   r   r’  rš  rR  rF  r   r   r3   )r¹   rT   rî   r    rM   rN   rG  rH  r�  r0   rØ   r‘   Úncomprº   r¸   r)  rf   rg   r[   r¢   rÓ   Úthis_CZ	this_rankr>  ZevÚmrE   rÎ   rK   rP  Æ  sd    

ÿ    ÿ& ÿ
$ÿrP  r  rd   c           /         sÂ  ddl m} |  ¡ } | ¡  td|ƒ}t|||||	|
|||||d�}|dkrTtdƒ‚|dkrl|d | d  }dd	„ tD ƒ}|d
kr†dnd}| tt	|||dd�ƒ¡ t
| dg ¡ƒdkrì|d
krì||krØtd||f ƒ‚t d¡ ||d< n|j||d� |d
k�rt| |||ƒ}|d ‰tƒ }| ¡ D ] \}}‡fdd„|D ƒ||< �q(t| ˆ|d�}|j‰ dd	„ |D ƒ}tˆ ƒD ]D\}}|D ](}||| k�r€||  |¡  �qt�q€td| ƒ‚�qt|d }t
|ƒttt
| ¡ ƒƒk�sât‚|�r |d |d  } t| ƒ} |D �]’}| ¡ }!|| }"t
|"ƒdk�r,�q|| }#|#dk�rPt d|! ¡ �qt d|!|#f ¡ |t |"|"¡ }$t |$jd ¡}%‡ fdd„|"D ƒ}&|d
k�rò|�r&t| |&ƒ\}'}(})|(dk�r&|  |'¡d dd…d|( …f }%t d|!|(f ¡ n4t!|d |&ƒ}*t"||*ƒ}+t#|$|+|ƒ\})},}-|,|- j$}%t %|%j$t %|$|%¡¡}$t &t '|$¡¡}.|$j(ddt
|$ƒd …  |#|. 7  < t %|%t %|$|%j$¡¡}$|$|t |"|"¡< �qt!| jˆ|d �}"|| d t |"|"¡< | S )!aˆ
  Regularize noise covariance matrix.

    This method works by adding a constant to the diagonal for each
    channel type separately. Special care is taken to keep the
    rank of the data constant.

    .. note:: This function is kept for reasons of backward-compatibility.
              Please consider explicitly using the ``method`` parameter in
              :func:`mne.compute_covariance` to directly combine estimation
              with regularization in a data-driven fashion. See the `faq
              <http://mne.tools/dev/overview/faq.html#how-should-i-regularize-the-covariance-matrix>`_
              for more information.

    Parameters
    ----------
    cov : Covariance
        The noise covariance matrix.
    %(info_not_none)s (Used to get channel types and bad channels).
    mag : float (default 0.1)
        Regularization factor for MEG magnetometers.
    grad : float (default 0.1)
        Regularization factor for MEG gradiometers. Must be the same as
        ``mag`` if data have been processed with SSS.
    eeg : float (default 0.1)
        Regularization factor for EEG.
    exclude : list | 'bads' (default 'bads')
        List of channels to mark as bad. If 'bads', bads channels
        are extracted from both info['bads'] and cov['bads'].
    proj : bool (default True)
        Apply projections to keep rank of data.
    seeg : float (default 0.1)
        Regularization factor for sEEG signals.
    ecog : float (default 0.1)
        Regularization factor for ECoG signals.
    hbo : float (default 0.1)
        Regularization factor for HBO signals.
    hbr : float (default 0.1)
        Regularization factor for HBR signals.
    fnirs_cw_amplitude : float (default 0.1)
        Regularization factor for fNIRS CW raw signals.
    fnirs_fd_ac_amplitude : float (default 0.1)
        Regularization factor for fNIRS FD AC raw signals.
    fnirs_fd_phase : float (default 0.1)
        Regularization factor for fNIRS raw phase signals.
    fnirs_od : float (default 0.1)
        Regularization factor for fNIRS optical density signals.
    csd : float (default 0.1)
        Regularization factor for EEG-CSD signals.
    dbs : float (default 0.1)
        Regularization factor for DBS signals.
    %(rank_none)s

        .. versionadded:: 0.17

        .. versionadded:: 0.18
           Support for 'info' mode.
    scalings : dict | None
        Data will be rescaled before rank estimation to improve accuracy.
        See :func:`mne.compute_covariance`.

        .. versionadded:: 0.17
    %(verbose)s

    Returns
    -------
    reg_cov : Covariance
        The regularized covariance matrix.

    See Also
    --------
    mne.compute_covariance
    r   )Úlinalgr   )rÉ   r}  r~  r  r€  r�  r‚  rƒ  r„  r…  r†  Nz+exclude must be a list of strings or "bads"rd   c                 S   s   i | ]
}|g “qS rE   rE   ©rI   r¢   rE   rE   rK   rž   b  s      zregularize.<locals>.<dictcomp>r  rü   F)r¡  r�   r¢  rÈ   zlOn data where magnetometers and gradiometers are dependent (e.g., SSSed data), mag (%s) must equal grad (%s)z!Regularizing MEG channels jointlyr£  rN   c                    s   g | ]}ˆ | ‘qS rE   rE   )rI   Úi)Úinfo_ch_namesrE   rK   rL   u  s     zregularize.<locals>.<listcomp>)Úincluder�   c                 S   s   i | ]
}|g “qS rE   rE   r©  rE   rE   rK   rž   }  s      zchannel %s is unknown typera   rM   rÝ   z    %s regularization : Nonez    %s regularization : %sc                    s   g | ]}ˆ | ‘qS rE   rE   ræ   rÌ   rE   rK   rL   ›  s     z3    Created an SSP operator for %s (dimension = %d)r   r˜   ))Úscipyr¨  r{   r6  r)   r  rO   r   rm   r   rn   r  r/   rT   r-   r¶   r   rN   r5  r9  Ú	Exceptionrò   Úmapr  rY  r   rR  rU   r’  rC  r�   r   Zsvdr   r   rP  rô   ró   rö   rh   rá   )/r‰   rT   rË   rÊ   rÉ   r�   r‘   r}  r  r€  r�  r‚  rƒ  r„  r…  r†  r~  rî   r    r0   r¨  ÚregsZ
picks_dictr¡  Zch_names_by_typer¢   Z
picks_typeZcov_goodZidx_covrª  Úchr¹   rM   ÚdescÚidxÚregr¦  ÚUZthis_ch_namesrE  r¥  rº   Z
this_picksZ	this_inforg   r[   ÚsigmarE   )rN   r«  rK   rˆ    s¨    N
  ý   ÿ
þ



 



 ÿ

$rˆ  c           	      C   sÒ   t |tddfƒ |dkrd}nDt|tƒsbt|ƒ}|dk	rJtdt|ƒf ƒ‚tt|ddd�d�}d	}t||d
d|d�\}}|dkr’t| j	d ddƒn|}t
|ƒ}tddƒ}t| j|||ddd|||d�
| d }|S )a  Compute a regularized covariance from data using sklearn.

    This is a convenience wrapper for mne.decoding functions, which
    adopted a slightly different covariance API.

    Returns
    -------
    cov : ndarray, shape (n_channels, n_channels)
        The covariance matrix.
    ÚnumericNrÛ   z6If reg is a float, method_params must be None (got %s)TF)r  r  r  rŽ  r  r´  )r  r  rî   éþÿÿÿg     @�@rË   r   r-  ra   )r8   rG   rñ   rï   rO   rB  r  r  r   r�   r   r)   r8  rô   )	ra   r´  rê   rT   rî   rj   r/  r    r‰   rE   rE   rK   Ú_regularized_covariance¹  sT    
ÿ  ÿ
    ÿ

      üüür¹  r3   c
                    sÐ  t |ttfdƒ d}
||
kr,td|
|f ƒ‚ˆ dkrRd| krDtdƒ‚t| d ƒ}n6tˆ |dd	�}‡ fd
d„|D ƒ}~t| ˆ ||||d�} t|ƒ}|t| d ƒks¤t‚| d  	¡ }|dk}d|| < | d j
jdkrÚtj}ntj}t |df|¡}dt || ¡ ||df< || d  }t |¡| d  ¡ j }| ¡ }t d|| d | f ¡ |dk�rt|| }|dd…|f }n0|dk�r¤t | d  ¡ j|¡}t || d ¡}||f}|�r¼||f7 }|�rÌ||f7 }|S )a�  Compute whitening matrix.

    Parameters
    ----------
    noise_cov : Covariance
        The noise covariance.
    %(info)s Can be None if ``noise_cov`` has already been
        prepared with :func:`prepare_noise_cov`.
    %(picks_good_data_noref)s
    %(rank_none)s

        .. versionadded:: 0.18
           Support for 'info' mode.
    scalings : dict | None
        The rescaling method to be applied. See documentation of
        ``prepare_noise_cov`` for details.
    return_rank : bool
        If True, return the rank used to compute the whitener.

        .. versionadded:: 0.15
    pca : bool | str
        Space to project the data into. Options:

        :data:`python:True`
            Whitener will be shape (n_nonzero, n_channels).
        ``'white'``
            Whitener will be shape (n_channels, n_channels), potentially rank
            deficient, and have the first ``n_channels - n_nonzero`` rows and
            columns set to zero.
        :data:`python:False` (default)
            Whitener will be shape (n_channels, n_channels), potentially rank
            deficient, and rotated back to the space of the original data.

        .. versionadded:: 0.18
    return_colorer : bool
        If True, return the colorer as well.
    %(on_rank_mismatch)s
    %(verbose)s

    Returns
    -------
    W : ndarray, shape (n_channels, n_channels) or (n_nonzero, n_channels)
        The whitening matrix.
    ch_names : list
        The channel names.
    rank : int
        Rank reduction of the whitener. Returned only if return_rank is True.
    colorer : ndarray, shape (n_channels, n_channels) or (n_channels, n_nonzero)
        The coloring matrix.
    Úspace)TÚwhiteFzspace must be one of %s, got %sNrf   zWinfo can only be None if the noise cov has already been prepared with prepare_noise_covrc   FrÞ   c                    s   g | ]}ˆ d  | ‘qS rÌ   rE   ræ   rÎ   rE   rK   rL   !  s     z$compute_whitener.<locals>.<listcomp>rœ  r   rÝ   rg   rJ   r   r™   zd    Created the whitener using a noise covariance matrix with rank %d (%d small eigenvalues omitted)rb   T)r8   rG   r�  rO   r   r   rŸ  rn   rY  r{   r)  ri   rU   Z
complex128rp  rÐ   r”  rD  rô   rò   r/   rT   ró   )r¸   rT   rÓ   rî   r    Zreturn_rankr  Zreturn_colorerr�  r0   Z_valid_pcasrN   rØ   rf   Znzeror)  ÚWr¹   Zn_nzeror@  rE   rÎ   rK   Úcompute_whitenerÞ  sb    7ÿ    þ
þ



r½  c           	      C   s`   |   ¡ } t| j|ƒ}|r | ¡ }t|| j|||d�\}}t | j¡t || j	| ¡ | j	|< | S )aS  Whiten evoked data using given noise covariance.

    Parameters
    ----------
    evoked : instance of Evoked
        The evoked data.
    noise_cov : instance of Covariance
        The noise covariance.
    %(picks_good_data)s
    diag : bool (default False)
        If True, whiten using only the diagonal of the covariance.
    %(rank_none)s

        .. versionadded:: 0.18
           Support for 'info' mode.
    scalings : dict | None (default None)
        To achieve reliable rank estimation on multiple sensors,
        sensors have to be rescaled. This parameter controls the
        rescaling. If dict, it will override the
        following default dict (default if None):

            dict(mag=1e12, grad=1e11, eeg=1e5)
    %(verbose)s

    Returns
    -------
    evoked_white : instance of Evoked
        The whitened evoked data.
    )rÓ   rî   r    )
r{   r   rT   r|   r½  rU   r”  Znaveró   ra   )	r»   r¸   rÓ   rh   rî   r    r0   r¼  rº   rE   rE   rK   rµ   N  s     
 ÿ
$rµ   c                 C   s6  ddl m} t|tjƒ}t|ƒdkr,tdƒ‚tt|ƒƒD �]è}t| || tj	ƒ}|dk	r8t
|jƒ|kr8|| }	t| |	tjƒ}|dkrŒtdƒ‚t
|jƒ}
t| |	tjƒ}|dkr²d}n
t
|jƒ}t| |	tjƒ}|dkrØd}n|j}t| |	tjƒ}|dkrúd}n
|jd }t| |	tjƒ}|dk�r"g }n"|j d¡}t|ƒ|
k�rDtdƒ‚t| |	tjƒ}|dk�ržt| |	tjƒ}|dk�r~td	ƒ‚n|j}d
}t d|
|
|f ¡ nœ| |j¡�s|j}t |
|
f¡}||t t |
|
f¡¡dk< ||j }|jdd|
d …  d  < d}t d|
|
|f ¡ nd}|j}t d|
|
|f ¡ t| |	tjƒ}t| |	tjƒ}|dk	�rx|dk	�rx|j}|j}nd}d}t| |	ƒ}t | |	dƒ}|
t|ƒk�s¨t!‚|j"|�r¶dndk�sÂt!‚t#|||
|||||||d�
}|dk	�rð||d< |dk	�r||d< |�r|d= |d= |d= |  S q8t d| ¡ dS )zRead a noise covariance matrix.r   )ÚsparsezNo covariance matrices foundNz%Covariance matrix dimension not foundrR   ú:z:Number of names does not match covariance matrix dimensionzNo covariance matrix data foundTz2    %d x %d diagonal covariance (kind = %d) found.r   rc  Fz.    %d x %d full covariance (kind = %d) found.z0    %d x %d sparse covariance (kind = %d) found.r€   )
ri   rh   rb   rc   ra   rM   rd   re   rf   rg   rk   rj   ri   rb   rh   z:    Did not find the desired covariance matrix (kind = %d))$r­  r¾  r!   r   ÚFIFFB_MNE_COVrn   rO   Úranger    ÚFIFF_MNE_COV_KINDÚintra   ÚFIFF_MNE_COV_DIMÚFIFF_MNE_COV_NFREEÚFIFF_MNE_COV_METHODÚFIFF_MNE_COV_SCOREÚFIFF_MNE_ROW_NAMESÚsplitÚFIFF_MNE_COVÚFIFF_MNE_COV_DIAGr/   rT   ÚissparserU   rÐ   Útrilr˜  rô   rá   ÚFIFF_MNE_COV_EIGENVALUESÚFIFF_MNE_COV_EIGENVECTORSr   r   rY  rl   r  )ry   ÚnodeZcov_kindrÃ   r0   r¾  r?  r  ÚtagÚthisrb   re   rj   r{  rc   ra   rh   ÚvalsZtag1Ztag2rf   rg   rM   rd   r‰   rE   rE   rK   rÄ   {  sª    






ÿ
ÿÿ

    þ


ÿrÄ   c                 C   sà  t | tjƒ t| tj|d ƒ t| tj|d ƒ |d dkrNt| tj|d ƒ |d dk	r|t|d ƒdkr|t| tj	|d ƒ |d r˜t
| tj|d ƒ nB|d }t tj||ftd	�¡dk}|d |  ¡ }t
| tj|ƒ |d
 dk	�r|d dk	�rt| tj|d ƒ t
| tj|d
 ƒ |d dk	�rHt|d ƒdk�rHt| |d ƒ |d dk	�r’t|d ƒdk�r’t | tjƒ t| tj|d ƒ t| tjƒ d|k�r®t| tj|d ƒ d|k�rÐt
| tjt |d ¡ƒ t| tjƒ dS )z Write a noise covariance matrix.ri   rb   re   r   rc   Nrh   ra   r(  rf   rg   rM   rd   rj   rk   )r"   r   rÀ  r$   rÂ  rÄ  rÅ  rn   r%   rÈ  r&   rË  rU   rÍ  r˜  r�  ZravelrÊ  r'   rÏ  rÎ  r   ZFIFFB_MNE_BAD_CHANNELSZFIFF_MNE_CH_NAME_LISTr#   r(   rÆ  rÇ  rx  )ry   r‰   rb   r[   rÓ  rE   rE   rK   rx   î  s>      

  ÿrx   r‰   r`   c                C   s:   t | dtf|ƒ t d| f ¡ t| tƒs6t| dd�} | S )Nz	path-likezNoise covariance  : %sFr`   )r8   r_   r/   rT   rñ   rÇ   )r‰   r  r0   rE   rE   rK   Ú_ensure_cov"  s
    
rÔ  )N)NN)r   NrÚ   NNNrÛ   NrÜ   NNFTNN)Trj   TN)TNNNrÛ   NrÜ   NNFr  NN)N)TN)NNNr›  N)NNNFTr›  N)r  r  r  rd   Tr  r  r  r  r  r  r  r  r  r  NNN)NNNN)	NNNNFFFr3   N)NNNNN)FN)r‰   )ur{   r   Ú	itertoolsr�  Úmathr   ÚnumpyrU   Údefaultsr   r   r   r	   Zio.writer
   Zio.projr   r   r   r   r   r   r   r   Úior   r   Zio.pickr   r   r   r   r   r   r   r   Zio.constantsr   Zio.meas_infor   r   Zio.tagr    Zio.treer!   r"   r#   r$   r%   r&   r'   r(   r)   rX   r*   Úeventr+   r»   r,   rî   r-   Úutilsr.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r¡   r?   Úfixesr@   rA   rB   rC   rD   rP   r^   r  r_   rÇ   rÕ   rÙ   rû   r  r÷   r3  rF  r8  ri  r[  rZ  rU  rW  r—  r"  rš  rŸ  rP  rˆ  r¹  r½  rµ   rÄ   rx   rÔ  rE   rE   rE   rK   Ú<module>   s  (($L	  &$
                   ü -      ÿ
B                 ü  >	 
   ÿ
>8I
      ÿ:         þ>                         ü 4  ÿ
%          ýo    ÿ,r4