U
    f»{jó_  ã                   @   s°   d dl ZddlmZmZ ddlmZ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 dd	lmZmZ d
d„ Zdd„ Zddd„ZG dd„ de
e	ƒZG dd„ deƒZdS )é    Né   )ÚEvokedArrayÚEvoked)Ú
CovarianceÚ_regularized_covariance)ÚTransformerMixinÚBaseEstimator)Ú
BaseEpochs)ÚBaseRaw)Ú_pick_data_channelsÚ	pick_info)ÚloggerÚ_check_optionc                 C   sØ   | j \}}}||t|ƒ  }t |dd…df ¡t|| ƒ }t |dd…df ¡t|| ƒ d }	|	| }
| j \}}}|dd…df |d  }t ||
f¡}t|ƒD ],}|| }|| }| | |dd…||…f< q¦|S )z1Reconstruct pseudo continuous signal from epochs.Nr   é   ©r   r   )ÚshapeÚfloatÚnpÚminÚintÚmaxÚzerosÚrange)ÚepochsÚeventsÚsfreqÚtminÚn_epochsÚ
n_channelsÚn_timesÚtmaxÚstartÚstopÚ	n_samplesZ
events_posÚrawÚidxZonsetÚoffset© r'   úV/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/preprocessing/xdawn.pyÚ_construct_signal_from_epochs   s    "&r)   c                 C   sr  ddl m} | j\}}}||t|ƒ  }| ¡ }|dd…df  |d t|| ƒ 8  < t| |||ƒ}	t|| ƒt|| ƒ }
}||
 }|	jd }tƒ }t 	|dd…df ¡}t
|ƒD ]\\}}|dd…df |k}t |df¡}||df |
 }d||< | | |d|… |¡¡ q¶t |¡}t |¡}t | t ||j¡¡|¡}t ||	j¡}t t |t|ƒ¡d¡}||fS )a  Least square estimation of evoked response from epochs data.

    Parameters
    ----------
    epochs_data : array, shape (n_channels, n_times)
        The epochs data to estimate evoked.
    events : array, shape (n_events, 3)
        The events typically returned by the read_events function.
        If some events don't match the events of interest as specified
        by event_id, they will be ignored.
    tmin : float
        Start time before event.
    sfreq : float
        Sampling frequency.

    Returns
    -------
    evokeds : array, shape (n_class, n_components, n_times)
        An concatenated array of evoked data for each event type.
    toeplitz : array, shape (n_class * n_components, n_channels)
        An concatenated array of toeplitz matrix for each event type.
    r   ©ÚlinalgNr   r   r   )r   r   r   )Úscipyr+   r   r   Úcopyr   r)   Úlistr   ÚuniqueÚ	enumerater   ÚappendÚtoeplitzÚarrayÚconcatenateÚdotÚpinvÚTÚ	transposeZvsplitÚlen)Úepochs_datar   r   r   r+   r   r   r   r    r$   Zn_minZn_maxÚwindowr#   r2   ÚclassesÚiiZ
this_classÚselZtrigZix_trigÚXZ	predictorÚevokedsr'   r'   r(   Ú_least_square_evoked&   s.    (


rA   ç        ç      ð?c
                 C   s6  ddl m}
 t| tjƒr"| jdkr*tdƒ‚t |¡}|dkrVtt 	| ¡|||	dd�}nt|t
ƒrf|j}t|tjƒrŽt |jt | jd d	¡¡s–td
ƒ‚|dk	r²t| |||ƒ\}}nLtƒ tƒ  }}|D ]8}| tj| ||kdd…dd…f dd�¡ | d¡ qÄtƒ }tƒ }t||ƒD ]ð\}}t ||¡}t||||	dd�}z|
 ||¡\}}W n6 tjjk
�r„ } ztd|f ƒ‚W 5 d}~X Y nX |dd…t |¡ddd… f }|t tjjd|¡ }tj |j¡}| |dd…d|…f j¡ | |dd…d|…f j¡ �qtj|dd�}tj|dd�}t |¡}|||fS )aË  Fit filters and coefs using Xdawn Algorithm.

    Xdawn is a spatial filtering method designed to improve the signal
    to signal + noise ratio (SSNR) of the event related responses. Xdawn was
    originally designed for P300 evoked potential by enhancing the target
    response with respect to the non-target response. This implementation is a
    generalization to any type of event related response.

    Parameters
    ----------
    epochs_data : array, shape (n_epochs, n_channels, n_times)
        The epochs data.
    y : array, shape (n_epochs)
        The epochs class.
    n_components : int (default 2)
        The number of components to decompose the signals signals.
    reg : float | str | None (default None)
        If not None (same as ``'empirical'``, default), allow
        regularization for covariance estimation.
        If float, shrinkage is used (0 <= shrinkage <= 1).
        For str options, ``reg`` will be passed as ``method`` to
        :func:`mne.compute_covariance`.
    signal_cov : None | Covariance | array, shape (n_channels, n_channels)
        The signal covariance used for whitening of the data.
        if None, the covariance is estimated from the epochs signal.
    events : array, shape (n_epochs, 3)
        The epochs events, used to correct for epochs overlap.
    tmin : float
        Epochs starting time. Only used if events is passed to correct for
        epochs overlap.
    sfreq : float
        Sampling frequency.  Only used if events is passed to correct for
        epochs overlap.

    Returns
    -------
    filters : array, shape (n_channels, n_channels)
        The Xdawn components used to decompose the data for each event type.
        Each row corresponds to one component.
    patterns : array, shape (n_channels, n_channels)
        The Xdawn patterns used to restore the signals for each event type.
    evokeds : array, shape (n_class, n_components, n_times)
        The independent evoked responses per condition.
    r   r*   é   zepochs_data must be 3D ndarrayNÚfull)Zrankr   r   zWsignal_cov must be None, a covariance instance, or an array of shape (n_chans, n_chans)©ZaxisrC   z@Could not compute eigenvalues, ensure proper regularization (%s)éÿÿÿÿ)r,   r+   Ú
isinstancer   ÚndarrayÚndimÚ
ValueErrorr/   r   Úhstackr   ÚdataZarray_equalr   ZtilerA   r.   r1   ZmeanÚzipr5   ZeighZLinAlgErrorÚargsortZapply_along_axisZnormr6   r7   r4   r3   )r:   ÚyÚn_componentsÚregÚ
signal_covr   r   r   Úmethod_paramsÚinfor+   r<   r@   Z	toeplitzsÚcÚfiltersÚpatternsZevor2   Zevo_covZevalsZevecsÚexpZ	_patternsr'   r'   r(   Ú
_fit_xdawnd   sj    .
    ÿ
ÿÿ   ÿ
*
ÿÿ  
rZ   c                   @   s>   e Zd ZdZddd„Zddd„Zdd	„ Zd
d„ Zddd„ZdS )Ú_XdawnTransformera¥  Implementation of the Xdawn Algorithm compatible with scikit-learn.

    Xdawn is a spatial filtering method designed to improve the signal
    to signal + noise ratio (SSNR) of the event related responses. Xdawn was
    originally designed for P300 evoked potential by enhancing the target
    response with respect to the non-target response. This implementation is a
    generalization to any type of event related response.

    .. note:: _XdawnTransformer does not correct for epochs overlap. To correct
              overlaps see ``Xdawn``.

    Parameters
    ----------
    n_components : int (default 2)
        The number of components to decompose the signals.
    reg : float | str | None (default None)
        If not None (same as ``'empirical'``, default), allow
        regularization for covariance estimation.
        If float, shrinkage is used (0 <= shrinkage <= 1).
        For str options, ``reg`` will be passed to ``method`` to
        :func:`mne.compute_covariance`.
    signal_cov : None | Covariance | array, shape (n_channels, n_channels)
        The signal covariance used for whitening of the data.
        if None, the covariance is estimated from the epochs signal.
    method_params : dict | None
        Parameters to pass to :func:`mne.compute_covariance`.

        .. versionadded:: 0.16

    Attributes
    ----------
    classes_ : array, shape (n_classes)
        The event indices of the classes.
    filters_ : array, shape (n_channels, n_channels)
        The Xdawn components used to decompose the data for each event type.
    patterns_ : array, shape (n_channels, n_channels)
        The Xdawn patterns used to restore the signals for each event type.
    r   Nc                 C   s   || _ || _|| _|| _dS )úInit.N)rQ   rS   rR   rT   )ÚselfrQ   rR   rS   rT   r'   r'   r(   Ú__init__ö   s    z_XdawnTransformer.__init__c                 C   sF   |   ||¡\}}t |¡| _t||| j| j| j| jd�\| _	| _
}| S )av  Fit Xdawn spatial filters.

        Parameters
        ----------
        X : array, shape (n_epochs, n_channels, n_samples)
            The target data.
        y : array, shape (n_epochs,) | None
            The target labels. If None, Xdawn fit on the average evoked.

        Returns
        -------
        self : Xdawn instance
            The Xdawn instance.
        )rQ   rR   rS   rT   )Ú	_check_Xyr   r/   Úclasses_rZ   rQ   rR   rS   rT   Úfilters_Ú	patterns_)r]   r?   rP   Ú_r'   r'   r(   Úfitþ   s        þz_XdawnTransformer.fitc                 C   s^   |   |¡\}}| jjd |jd krBtd| jjd |jd f ƒ‚t | j|¡}| d¡}|S )a8  Transform data with spatial filters.

        Parameters
        ----------
        X : array, shape (n_epochs, n_channels, n_samples)
            The target data.

        Returns
        -------
        X : array, shape (n_epochs, n_components * n_classes, n_samples)
            The transformed data.
        r   z(X must have %i channels, got %i instead.©r   r   r   )r_   ra   r   rK   r   r5   r8   )r]   r?   rc   r'   r'   r(   Ú	transform  s    
 ÿ
z_XdawnTransformer.transformc                 C   sd   |   |¡\}}|j\}}}|| jt| jƒ krJtd| jt| jƒ |f ƒ‚t | jj	|¡ 
ddd¡S )aK  Remove selected components from the signal.

        Given the unmixing matrix, transform data, zero out components,
        and inverse transform the data. This procedure will reconstruct
        the signals from which the dynamics described by the excluded
        components is subtracted.

        Parameters
        ----------
        X : array, shape (n_epochs, n_components * n_classes, n_times)
            The transformed data.

        Returns
        -------
        X : array, shape (n_epochs, n_channels * n_classes, n_times)
            The inverse transform data.
        z)X must have %i components, got %i insteadr   r   r   )r_   r   rQ   r9   r`   rK   r   r5   rb   r7   r8   )r]   r?   rc   r   Zn_compr   r'   r'   r(   Úinverse_transform/  s     ÿz#_XdawnTransformer.inverse_transformc                 C   s^   t |tjƒr|jdkrtdƒ‚|dkr4t t|ƒ¡}t |¡}t|ƒt|ƒkrVtdƒ‚||fS )z#Check X and y types and dimensions.rD   z>X must be an array of shape (n_epochs, n_channels, n_samples).Nz!X and y must have the same length)rH   r   rI   rJ   rK   Úonesr9   Zasarray)r]   r?   rP   r'   r'   r(   r_   K  s    
z_XdawnTransformer._check_Xy)r   NNN)N)N)	Ú__name__Ú
__module__Ú__qualname__Ú__doc__r^   rd   rf   rg   r_   r'   r'   r'   r(   r[   Î   s   '  ÿ

r[   c                       sf   e Zd ZdZd‡ fdd„	Zddd„Zd	d
„ Zddd„Zdd„ Zdd„ Z	dd„ Z
dd„ Zdd„ Z‡  ZS )ÚXdawna5  Implementation of the Xdawn Algorithm.

    Xdawn :footcite:`RivetEtAl2009,RivetEtAl2011` is a spatial
    filtering method designed to improve the signal to signal + noise
    ratio (SSNR) of the ERP responses. Xdawn was originally designed for
    P300 evoked potential by enhancing the target response with respect
    to the non-target response. This implementation is a generalization
    to any type of ERP.

    Parameters
    ----------
    n_components : int, (default 2)
        The number of components to decompose the signals.
    signal_cov : None | Covariance | ndarray, shape (n_channels, n_channels)
        (default None). The signal covariance used for whitening of the data.
        if None, the covariance is estimated from the epochs signal.
    correct_overlap : 'auto' or bool (default 'auto')
        Compute the independent evoked responses per condition, while
        correcting for event overlaps if any. If 'auto', then
        overlapp_correction = True if the events do overlap.
    reg : float | str | None (default None)
        If not None (same as ``'empirical'``, default), allow
        regularization for covariance estimation.
        If float, shrinkage is used (0 <= shrinkage <= 1).
        For str options, ``reg`` will be passed as ``method`` to
        :func:`mne.compute_covariance`.

    Attributes
    ----------
    filters_ : dict of ndarray
        If fit, the Xdawn components used to decompose the data for each event
        type, else empty. For each event type, the filters are in the rows of
        the corresponding array.
    patterns_ : dict of ndarray
        If fit, the Xdawn patterns used to restore the signals for each event
        type, else empty.
    evokeds_ : dict of Evoked
        If fit, the evoked response for each event type.
    event_id_ : dict
        The event id.
    correct_overlap_ : bool
        Whether overlap correction was applied.

    See Also
    --------
    mne.decoding.CSP, mne.decoding.SPoC

    Notes
    -----
    .. versionadded:: 0.10

    References
    ----------
    .. footbibliography::
    r   NÚautoc                    s.   t t| ƒj|||d� td|dddgƒ| _dS )r\   )rQ   rS   rR   Úcorrect_overlaprn   TFN)Úsuperrm   r^   r   ro   )r]   rQ   rS   ro   rR   ©Ú	__class__r'   r(   r^   ’  s     ÿþzXdawn.__init__c                 C   sô  t |tƒstdƒ‚t|jƒ}t|j|ƒ}| ¡ dd…|dd…f }|dkr\|jdd…df n|}|j| _	| j
}|dkrºt t |jdd…df ¡¡}t|j|j |jd  ƒ}| ¡ |k }|jrÌ|rÌtdƒ‚d\}	}
}|rð|j}	|j}
|jd }|| _|jd	 }t|||| j| j|	|
|| j|d
�
\}}}| d||jd ¡}| d||jd ¡}tƒ tƒ tƒ   | _| _| _t dd„ |j ¡ D ƒ¡}t |j|| || || ƒD ]L\}}}}|| j|< || j|< t!|| ƒ}t"|||j||d�}|| j|< �q¢| S )am  Fit Xdawn from epochs.

        Parameters
        ----------
        epochs : instance of Epochs
            An instance of Epoch on which Xdawn filters will be fitted.
        y : ndarray | None (default None)
            If None, used epochs.events[:, 2].

        Returns
        -------
        self : instance of Xdawn
            The Xdawn instance.
        z epochs must be an Epochs object.Nr   rn   r   r   z6Cannot apply correct_overlap if epochs were baselined.)NrB   rC   r   )rQ   rR   rS   r   r   r   rT   rU   rG   c                 S   s   g | ]\}}|‘qS r'   r'   )Ú.0rc   Úvaluer'   r'   r(   Ú
<listcomp>Õ  s     zXdawn.fit.<locals>.<listcomp>)r   ÚcommentZnave)#rH   r	   rK   r   rU   r   Úget_datar   Úevent_idÚ	event_id_ro   r   ÚdiffÚsortr   r    r   r   ZbaselineZcorrect_overlap_r   rZ   rR   rS   rT   ZreshapeÚdictra   rb   Zevokeds_rO   ÚitemsrN   r9   r   )r]   r   rP   ÚpicksZuse_infor?   ro   Zisir;   r   r   r   rQ   rW   rX   r@   r%   ÚeidZthis_filterZthis_patternZthis_evoZn_eventsÚevokedr'   r'   r(   rd   ›  sh    





       ý   ÿ


 ÿz	Xdawn.fitc                    s¤   t |tƒr| ¡ }nFt |tƒr&|j}n4t |tjƒrR|}|jdkrZtd|jf ƒ‚ntdƒ‚‡ fdd„ˆ j	 
¡ D ƒ}tj|dd�}t ||¡}|jdkr | d	¡}|S )
am  Apply Xdawn dim reduction.

        Parameters
        ----------
        inst : Epochs | Evoked | ndarray, shape ([n_epochs, ]n_channels, n_times)
            Data on which Xdawn filters will be applied.

        Returns
        -------
        X : ndarray, shape ([n_epochs, ]n_components * n_event_types, n_times)
            Spatially filtered signals.
        )r   rD   zX must be 2D or 3D, got %sz/Data input must be of Epoch type or numpy arrayc                    s   g | ]}|d ˆ j … ‘qS )N)rQ   )rs   Zfilt©r]   r'   r(   ru   ø  s   ÿz#Xdawn.transform.<locals>.<listcomp>r   rF   rD   re   )rH   r	   rw   r   rM   r   rI   rJ   rK   ra   Úvaluesr4   r5   r8   )r]   Úinstr?   rW   r'   r�   r(   rf   à  s"    




ÿ

zXdawn.transformc                 C   sÎ   |dkr| j }t|tttfƒs&tdƒ‚t|jƒ}tt	| j
t|jƒƒƒ}|dkrT|}nttt|ƒt|ƒ ƒƒ}t|tƒrŒ| j|||||d�}n>t|tƒr¬| j|||||d�}nt|tƒrÊ| j|||||d�}|S )a   Remove selected components from the signal.

        Given the unmixing matrix, transform data,
        zero out components, and inverse transform the data.
        This procedure will reconstruct the signals from which
        the dynamics described by the excluded components is subtracted.

        Parameters
        ----------
        inst : instance of Raw | Epochs | Evoked
            The data to be processed.
        event_id : dict | list of str | None (default None)
            The kind of event to apply. if None, a dict of inst will be return
            one for each type of event xdawn has been fitted.
        include : array_like of int | None (default None)
            The indices referring to columns in the ummixing matrix. The
            components to be kept. If None, the first n_components (as defined
            in the Xdawn constructor) will be kept.
        exclude : array_like of int | None (default None)
            The indices referring to columns in the ummixing matrix. The
            components to be zeroed out. If None, all the components except the
            first n_components will be exclude.

        Returns
        -------
        out : dict
            A dict of instance (from the same type as inst input) for each
            event type in event_id.
        Nz-Data input must be Raw, Epochs or Evoked type)r$   ÚincludeÚexcluderx   r~   )r   r„   r~   r…   rx   )r€   r„   r~   r…   rx   )ry   rH   r
   r	   r   rK   r   rU   r.   r   rQ   r9   Zch_namesÚsetÚ
_apply_rawÚ_apply_epochsÚ_apply_evoked)r]   rƒ   rx   r„   r…   r~   Zdefault_excludeÚoutr'   r'   r(   Úapply   s2    


 ÿ

 ÿ

 ÿzXdawn.applyc           
      C   sf   |j stdƒ‚tƒ }|D ]H}||dd…f d }|  ||||¡}| ¡ }	||	|dd…f< |	||< q|S )úAux method.z)Raw data must be preloaded to apply XdawnNr   )ÚpreloadrK   r|   Ú_pick_sourcesr-   )
r]   r$   r„   r…   rx   r~   Zrawsr   rM   Zraw_rr'   r'   r(   r‡   7  s    
zXdawn._apply_rawc                 C   s’   |j stdƒ‚tƒ }t | ¡ dd…|f ¡}|D ]Z}|  ||||¡}	t t |	t	|j
ƒd¡¡}	| ¡  ¡ }
|	|
jdd…|dd…f< |
||< q2|S )rŒ   z'Epochs must be preloaded to apply XdawnNr   )r�   rK   r|   r   rL   rw   rŽ   r3   Úsplitr9   r   r-   Z	load_dataÚ_data)r]   r   r„   r…   rx   r~   Zepochs_dictrM   r   Údata_rZepochs_rr'   r'   r(   rˆ   H  s    
zXdawn._apply_epochsc           
      C   sH   |j | }tƒ }|D ].}|  ||||¡}	| ¡ ||< |	|| j |< q|S )rŒ   )rM   r|   rŽ   r-   )
r]   r€   r„   r…   rx   r~   rM   r@   r   r‘   r'   r'   r(   r‰   [  s    
zXdawn._apply_evokedc                 C   sº   t  d¡ t | j| |¡}|dtƒ fkrftjt|ƒtd�}d|t 	|¡< d||< t  d| 
¡  ¡ n2|dtƒ fkr˜t 	|¡}d||< t  dt|ƒ ¡ t  d¡ t | j| j|¡}|S )rŒ   zTransforming to Xdawn spaceN)ZdtypeFrB   zZeroing out %i Xdawn componentsz$Inverse transforming to sensor space)r   rU   r   r5   ra   r.   rh   r9   Úboolr/   Úsumrb   r7   )r]   rM   r„   r…   r   ÚsourcesÚmaskZexclude_r'   r'   r(   rŽ   j  s    


zXdawn._pick_sourcesc                 C   s   t dƒ‚dS )z+Not implemented, see Xdawn.apply() instead.zSee Xdawn.apply()N)ÚNotImplementedErrorr�   r'   r'   r(   rg     s    zXdawn.inverse_transform)r   Nrn   N)N)NNN)ri   rj   rk   rl   r^   rd   rf   r‹   r‡   rˆ   r‰   rŽ   rg   Ú__classcell__r'   r'   rq   r(   rm   Y  s   8  ÿ	
E 
7rm   )NNNrB   rC   NN)Únumpyr   Ú r   r   Zcovr   r   Zdecodingr   r   r   r	   Úior
   Zio.pickr   r   Úutilsr   r   r)   rA   rZ   r[   rm   r'   r'   r'   r(   Ú<module>   s&   >          ÿ
j 