CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
xdawn.cpython-310.pyc262 linesDownload Raw Back to __pycache__
1o

2'�Yi2L�@s�ddlZddlmZddlmZmZddlmZm	Z	ddl3mZddlm
Z
ddlmZmZdd	lmZdd4lmZmZmZdd�Zd
d�Z							ddd�ZGdd�de�ZdS)�N)�linalg�)�_pick_data_channels�	pick_info)�5Covariance�_regularized_covariance)�XdawnTransformer)�6BaseEpochs)�Evoked�EvokedArray)�BaseRaw)�
_check_option�logger�pinvcCs�|j\}}}||t|�}t�|dd�df�t||�}t�|dd�df�t||�d}	|	|}7|j\}}}|dd�df|d}t�||8f�}t|�D]}
||
}||}||
|dd�||�f<qS|S)z1Reconstruct pseudo continuous signal from epochs.Nr��rr)�shape�float�np�min�int�max�zeros�range)�epochs�events�sfreq�tmin�n_epochs�9n_channels�n_times�tmax�start�stop�	n_samplesZ10events_pos�raw�idxZonset�offset�r(��E:\DocsHouse\542 percep lab latest\PerceptionLab\PerceptionLab_Portable\python_embed\Lib\site-packages\mne/preprocessing/xdawn.py�_construct_signal_from_epochss"&r*cCsb|j\}}}||t|�}|��}|dd�df|dt||�8<t||||�}t||�t||�}	}11|12|	}|jd}t�}
t�|dd�df�}t|�D]-\}}|dd�df|k}t�	|f�}||df|	}d||<|
�13t�|d|�|��qUt�
|
�}
t�|
�}t�tt�||j��|�}t�||j�}t�t�|t|��d�}||
fS)aLeast square estimation of evoked response from epochs data.14 15    Parameters16    ----------17    epochs_data : array, shape (n_channels, n_times)18        The epochs data to estimate evoked.19    events : array, shape (n_events, 3)20        The events typically returned by the read_events function.21        If some events don't match the events of interest as specified22        by event_id, they will be ignored.23    tmin : float24        Start time before event.25    sfreq : float26        Sampling frequency.27 28    Returns29    -------30    evokeds : array, shape (n_class, n_components, n_times)31        An concatenated array of evoked data for each event type.32    toeplitz : array, shape (n_class * n_components, n_channels)33        An concatenated array of toeplitz matrix for each event type.34    Nrrrr)rrr)rr�copyrr*�listr�unique�	enumerater�appendr�toeplitz�array�concatenate�dotr�T�	transposeZvsplit�len)�epochs_datarrrrrr r!r%Zn_minZn_max�windowr$r0�classes�iiZ35this_class�selZtrigZix_trig�XZ	predictor�evokedsr(r(r)�_least_square_evoked%s,(363738r>���?c39Cst|tj�r|jdkrtd��t�|�}40|dur%tt�|�|||	dd�}nt|t�r-|j	}t|tj�rAt�41|jt�|jdd��sEtd��|durSt
||||�\}}n&t�t�}}|42D]}
|�tj|||
kdd�dd�fd	d43��|�d�q\t�}t�}t||�D]p\}}t�||�}t||||	dd�}z44t�||�\}}Wntjjy�}ztd|�d
���d}~ww|dd�t�|�ddd�f}|t�tjjd	|�}t|j�}|�|dd�d|�fj�|�|dd�d|�fj�q�tj|d	d45�}tj|d	d46�}t�|�}|||fS)a�Fit filters and coefs using Xdawn Algorithm.47 48    Xdawn is a spatial filtering method designed to improve the signal49    to signal + noise ratio (SSNR) of the event related responses. Xdawn was50    originally designed for P300 evoked potential by enhancing the target51    response with respect to the non-target response. This implementation is a52    generalization to any type of event related response.53 54    Parameters55    ----------56    epochs_data : array, shape (n_epochs, n_channels, n_times)57        The epochs data.58    y : array, shape (n_epochs)59        The epochs class.60    n_components : int (default 2)61        The number of components to decompose the signals signals.62    reg : float | str | None (default None)63        If not None (same as ``'empirical'``, default), allow64        regularization for covariance estimation.65        If float, shrinkage is used (0 <= shrinkage <= 1).66        For str options, ``reg`` will be passed as ``method`` to67        :func:`mne.compute_covariance`.68    signal_cov : None | Covariance | array, shape (n_channels, n_channels)69        The signal covariance used for whitening of the data.70        if None, the covariance is estimated from the epochs signal.71    events : array, shape (n_epochs, 3)72        The epochs events, used to correct for epochs overlap.73    tmin : float74        Epochs starting time. Only used if events is passed to correct for75        epochs overlap.76    sfreq : float77        Sampling frequency.  Only used if events is passed to correct for78        epochs overlap.79 80    Returns81    -------82    filters : array, shape (n_channels, n_channels)83        The Xdawn components used to decompose the data for each event type.84        Each row corresponds to one component.85    patterns : array, shape (n_channels, n_channels)86        The Xdawn patterns used to restore the signals for each event type.87    evokeds : array, shape (n_class, n_components, n_times)88        The independent evoked responses per condition.89    �zepochs_data must be 3D ndarrayN�full)ZrankrrzWsignal_cov must be None, a covariance instance, or an array of shape (n_chans, n_chans)r�Zaxisr@z=Could not compute eigenvalues, ensure proper regularization (�)�����)�90isinstancer�ndarray�ndim�91ValueErrorr-r�hstackr�dataZarray_equalrZtiler>r,r/�mean�zipr3rZeighZLinAlgError�argsortZapply_along_axisZnormrr4r2r1)r7�y�n_components�reg�92signal_covrrr�
method_params�infor9r=Z	toeplitzs�c�filters�patternsZevor0Zevo_covZevalsZevecs�exp�	_patternsr(r(r)�93_fit_xdawnbsV894�95��*96��� 979899rZcsheZdZdZ	d�fdd�	Zddd�Zd	d100�Zddd�Zd
d�Zdd�Z	dd�Z101dd�Zdd�Z�Z
S)�Xdawna5Implementation of the Xdawn Algorithm.102 103    Xdawn :footcite:`RivetEtAl2009,RivetEtAl2011` is a spatial104    filtering method designed to improve the signal to signal + noise105    ratio (SSNR) of the ERP responses. Xdawn was originally designed for106    P300 evoked potential by enhancing the target response with respect107    to the non-target response. This implementation is a generalization108    to any type of ERP.109 110    Parameters111    ----------112    n_components : int, (default 2)113        The number of components to decompose the signals.114    signal_cov : None | Covariance | ndarray, shape (n_channels, n_channels)115        (default None). The signal covariance used for whitening of the data.116        if None, the covariance is estimated from the epochs signal.117    correct_overlap : 'auto' or bool (default 'auto')118        Compute the independent evoked responses per condition, while119        correcting for event overlaps if any. If 'auto', then120        overlapp_correction = True if the events do overlap.121    reg : float | str | None (default None)122        If not None (same as ``'empirical'``, default), allow123        regularization for covariance estimation.124        If float, shrinkage is used (0 <= shrinkage <= 1).125        For str options, ``reg`` will be passed as ``method`` to126        :func:`mne.compute_covariance`.127 128    Attributes129    ----------130    filters_ : dict of ndarray131        If fit, the Xdawn components used to decompose the data for each event132        type, else empty. For each event type, the filters are in the rows of133        the corresponding array.134    patterns_ : dict of ndarray135        If fit, the Xdawn patterns used to restore the signals for each event136        type, else empty.137    evokeds_ : dict of Evoked138        If fit, the evoked response for each event type.139    event_id_ : dict140        The event id.141    correct_overlap_ : bool142        Whether overlap correction was applied.143 144    See Also145    --------146    mne.decoding.CSP, mne.decoding.SPoC147 148    Notes149    -----150    .. versionadded:: 0.10151 152    References153    ----------154    .. footbibliography::155    rN�autocs(t�j|||d�td|gd��|_dS)zInit.)rPrRrQ�correct_overlap)r\TFN)�super�__init__r
r])�selfrPrRr]rQ��	__class__r(r)r_s156157�zXdawn.__init__cCs�t|t�s	td��t|j�}t|j|�}|�|�}|dur&|jdd�dfn|}|j|_	|j158}|dkrUt�t�
|jdd�df��}t|j|j|jd�}|��|k}|jr^|r^td��d\}	}159}|rp|j}	|j}160|jd}||_|jd	}t||||j|j|	|161||j|d162163\}
}}|
�d||
jd�}
|�d||jd�}t�t�t�|_|_|_t�dd
�|j��D��}t |j|
|||||�D]%\}}}}||j|<||j|<t!||�}t"|||j||d�}||j|<q�|S)amFit Xdawn from epochs.164 165        Parameters166        ----------167        epochs : instance of Epochs168            An instance of Epoch on which Xdawn filters will be fitted.169        y : ndarray | None (default None)170            If None, used epochs.events[:, 2].171 172        Returns173        -------174        self : instance of Xdawn175            The Xdawn instance.176        z epochs must be an Epochs object.Nrr\rrz6Cannot apply correct_overlap if epochs were baselined.)Nr?r@r)rPrQrRrrrrSrTrEcSsg|]\}}|�qSr(r()�.0�_�valuer(r(r)�177<listcomp>ZszXdawn.fit.<locals>.<listcomp>)r�commentZnave)#rFr	rIrrTr�get_datar�event_id�	event_id_r]r�diff�sortrr!rrZbaselineZcorrect_overlap_rrZrQrRZcov_method_paramsZreshape�dict�filters_�	patterns_Zevokeds_rN�itemsrMr6r)r`rrO�picksZuse_infor<r]Zisir8rrrrPrVrWr=r&�eidZthis_filterZthis_patternZthis_evoZn_events�evokedr(r(r)�fits`178179180181182183184��185186�z	Xdawn.fitcs�t|t�r|jdd�}n#t|t�r|j}nt|tj�r+|}|jdvr*td|j����ntd���fdd��j	�187�D�}tj|dd	�}t�||�}|jd188krR|�
d�}|S)amApply Xdawn dim reduction.189 190        Parameters191        ----------192        inst : Epochs | Evoked | ndarray, shape ([n_epochs, ]n_channels, n_times)193            Data on which Xdawn filters will be applied.194 195        Returns196        -------197        X : ndarray, shape ([n_epochs, ]n_components * n_event_types, n_times)198            Spatially filtered signals.199        F)r+)rrAzX must be 2D or 3D, got z/Data input must be of Epoch type or numpy arraycsg|]	}|d�j��qS�N)rP)rcZfilt�r`r(r)rfsz#Xdawn.transform.<locals>.<listcomp>rrCrA)rrr)rFr	rhr200rKrrGrHrIrn�valuesr2r3r5)r`�instr<rVr(rvr)�	transformgs 201
202203�204205zXdawn.transformcCs�|dur|j}t|ttBtB�std��t|j�}tt	|j206t|j���}|dur+|}ntt
t|�t|���}t|t�rH|j|||||d�}|St|t�rY|j|||||d�}|St|t�rh|j|||||d�}|S)a Remove selected components from the signal.207 208        Given the unmixing matrix, transform data,209        zero out components, and inverse transform the data.210        This procedure will reconstruct the signals from which211        the dynamics described by the excluded components is subtracted.212 213        Parameters214        ----------215        inst : instance of Raw | Epochs | Evoked216            The data to be processed.217        event_id : dict | list of str | None (default None)218            The kind of event to apply. if None, a dict of inst will be return219            one for each type of event xdawn has been fitted.220        include : array_like of int | None (default None)221            The indices referring to columns in the ummixing matrix. The222            components to be kept. If None, the first n_components (as defined223            in the Xdawn constructor) will be kept.224        exclude : array_like of int | None (default None)225            The indices referring to columns in the ummixing matrix. The226            components to be zeroed out. If None, all the components except the227            first n_components will be exclude.228 229        Returns230        -------231        out : dict232            A dict of instance (from the same type as inst input) for each233            event type in event_id.234        Nz-Data input must be Raw, Epochs or Evoked type)r%�include�excluderirq)rrzrqr{ri)rsrzrqr{ri)rjrFrr	r235rIrrTr,rrPr6Zch_names�set�236_apply_raw�
_apply_epochs�
_apply_evoked)r`rxrirzr{rqZdefault_exclude�outr(r(r)�apply�sH237238�239��240��zXdawn.applyc241Csf|jstd��t�}|D]$}||dd�fd}|�||||�}|��}	||	|dd�f<|	||<q|S)�Aux method.z)Raw data must be preloaded to apply XdawnNr)�preloadrIrm�
_pick_sourcesr+)242r`r%rzr{rirqZrawsrrrKZraw_rr(r(r)r}�s243zXdawn._apply_rawcCs�|jstd��t�}t�|�|��}|D]-}|�||||�}	t�t�|	t	|j244�d��}	|����}245|	|246j
dd�|dd�f<|247||<q|S)r�z'Epochs must be preloaded to apply XdawnrN)r�rIrmrrJrhr�r1�splitr6rr+Z	load_data�_data)r`rrzr{rirqZepochs_dictrKrr�data_rZepochs_rr(r(r)r~�s248zXdawn._apply_epochsc249CsH|j|}t�}|D]}|�||||�}	|��||<|	||j|<q250|S)r�)rKrmr�r+)251r`rsrzr{rirqrKr=rrr�r(r(r)r�s252zXdawn._apply_evokedcCs�t�d�t�|j||�}|dt�fvr7tjt|�td�}d|t�	|�<d||<t�dt253|����d��n|dt�fvrRt�	|�}d||<t�dt|��d��t�d�t�|j|j
|�}|S)	r�zTransforming to Xdawn spaceN)ZdtypeFr?zZeroing out z Xdawn componentsz$Inverse transforming to sensor space)rrTrr3rnr,Zonesr6�boolr-r�sumror4)r`rKrzr{rr�sources�maskZexclude_r(r(r)r��s254255256zXdawn._pick_sourcescCstd��)z+Not implemented, see Xdawn.apply() instead.zSee Xdawn.apply())�NotImplementedErrorrvr(r(r)�inverse_transformszXdawn.inverse_transform)rNr\Nru)NNN)�__name__�257__module__�__qualname__�__doc__r_rtryr�r}r~rr�r��
__classcell__r(r(rar)r[�s9�258	N259Fr[)NNNr?r@NN)�numpyrZscipyrZ260_fiff.pickrrZcovrrZdecoding.xdawnrrr	rsr261r�ior�utilsr
rrr*r>rZr[r(r(r(r)�<module>s(A262�u
Aluode/PerceptionLabPortable · CoolFace