U
    f»{j{‡  ã                   @   sœ   d dl Zd dlZddlmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ dd	lmZmZmZmZ eG d
d„ deeƒƒZddd„ZeG dd„ deƒƒZdS )é    Né   )ÚBaseEstimator)ÚTransformerMixiné   )Ú_regularized_covariance)Ú_INTERPOLATION_DEFAULT)Úpinv)Úfill_docÚ_check_optionÚ_validate_typeÚcopy_docc                       sü   e Zd ZdZd-dd	„Zd.d
d„Zdd„ Zdd„ Zee	j
ƒ‡ fdd„ƒZ
eddddddddddddddddddddeddfdd„ƒZeddddddddddddddddddddedfdd„ƒZdd „ Zd!d"„ Zd#d$„ Zd%d&„ Zd'd(„ Zd)d*„ Zd+d,„ Z‡  ZS )/ÚCSPa
  M/EEG signal decomposition using the Common Spatial Patterns (CSP).

    This class can be used as a supervised decomposition to estimate spatial
    filters for feature extraction. CSP in the context of EEG was first
    described in :footcite:`KolesEtAl1990`; a comprehensive tutorial on CSP can
    be found in :footcite:`BlankertzEtAl2008`. Multi-class solving is
    implemented from :footcite:`Grosse-WentrupBuss2008`.

    Parameters
    ----------
    n_components : int (default 4)
        The number of components to decompose M/EEG signals. This number should
        be set by cross-validation.
    reg : float | str | None (default None)
        If not None (same as ``'empirical'``, default), allow regularization
        for covariance estimation. If float (between 0 and 1), shrinkage is
        used. For str values, ``reg`` will be passed as ``method`` to
        :func:`mne.compute_covariance`.
    log : None | bool (default None)
        If ``transform_into`` equals ``'average_power'`` and ``log`` is None or
        True, then apply a log transform to standardize features, else features
        are z-scored. If ``transform_into`` is ``'csp_space'``, ``log`` must be
        None.
    cov_est : 'concat' | 'epoch' (default 'concat')
        If ``'concat'``, covariance matrices are estimated on concatenated
        epochs for each class. If ``'epoch'``, covariance matrices are
        estimated on each epoch separately and then averaged over each class.
    transform_into : 'average_power' | 'csp_space' (default 'average_power')
        If 'average_power' then ``self.transform`` will return the average
        power of each spatial filter. If ``'csp_space'``, ``self.transform``
        will return the data in CSP space.
    norm_trace : bool (default False)
        Normalize class covariance by its trace. Trace normalization is a step
        of the original CSP algorithm :footcite:`KolesEtAl1990` to eliminate
        magnitude variations in the EEG between individuals. It is not applied
        in more recent work :footcite:`BlankertzEtAl2008`,
        :footcite:`Grosse-WentrupBuss2008` and can have a negative impact on
        pattern order.
    cov_method_params : dict | None
        Parameters to pass to :func:`mne.compute_covariance`.

        .. versionadded:: 0.16
    %(rank_none)s

        .. versionadded:: 0.17
    component_order : 'mutual_info' | 'alternate' (default 'mutual_info')
        If ``'mutual_info'`` order components by decreasing mutual information
        (in the two-class case this uses a simplification which orders
        components by decreasing absolute deviation of the eigenvalues from 0.5
        :footcite:`BarachantEtAl2010`). For the two-class case, ``'alternate'``
        orders components by starting with the largest eigenvalue, followed by
        the smallest, the second-to-largest, the second-to-smallest, and so on
        :footcite:`BlankertzEtAl2008`.

        .. versionadded:: 0.21

    Attributes
    ----------
    filters_ :  ndarray, shape (n_channels, n_channels)
        If fit, the CSP components used to decompose the data, else None.
    patterns_ : ndarray, shape (n_channels, n_channels)
        If fit, the CSP patterns used to restore M/EEG signals, else None.
    mean_ : ndarray, shape (n_components,)
        If fit, the mean squared power for each component.
    std_ : ndarray, shape (n_components,)
        If fit, the std squared power for each component.

    See Also
    --------
    mne.preprocessing.Xdawn, SPoC

    References
    ----------
    .. footbibliography::
    é   NÚconcatÚaverage_powerFÚmutual_infoc
           
      C   s¸   t |tƒstdƒ‚|| _|| _|| _|dks<|dks<tdƒ‚|| _td|ddgƒ| _|dkrx|d k	rˆt |t	ƒsˆtdƒ‚n|d k	rˆtd	ƒ‚|| _
t|t	d
ƒ || _|| _td|	dƒ| _d S )Nz n_components must be an integer.r   Úepochz$unknown covariance estimation methodÚtransform_intor   Z	csp_spacez;log must be a boolean if transform_into == "average_power".z4log must be a None if transform_into == "csp_space".Ú
norm_traceÚcomponent_order)r   Ú	alternate)Ú
isinstanceÚintÚ
ValueErrorÚn_componentsÚrankÚregÚcov_estr
   r   ÚboolÚlogr   r   Úcov_method_paramsr   )
Úselfr   r   r   r   r   r   r    r   r   © r"   úO/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/decoding/csp.pyÚ__init__d   s0    
ÿ
þzCSP.__init__c                 C   s^   t |tjƒstdt|ƒ ƒ‚|dk	rHt|ƒt|ƒks@t|ƒdk rHtdƒ‚|jdk rZtdƒ‚dS )zCheck input data.ú%X should be of type ndarray (got %s).Nr   z"X and y must have the same length.é   z"X must have at least 3 dimensions.)r   ÚnpÚndarrayr   ÚtypeÚlenÚndim)r!   ÚXÚyr"   r"   r#   Ú	_check_XyŠ   s    ÿ
zCSP._check_Xyc           	         s   |   ||¡ t |¡| _t| jƒ}|dk r2tdƒ‚|dkrR| jdkrRtd |¡ƒ‚|  ||¡\}}|  	||¡\}}|  
||||| j¡}|dd…|f }|j| _t|ƒ| _| jd| j… ‰ t ‡ fdd„|D ƒ¡}|d jdd�}|jd	d�| _|jd	d�| _| S )
a}  Estimate the CSP decomposition on epochs.

        Parameters
        ----------
        X : ndarray, shape (n_epochs, n_channels, n_times)
            The data on which to estimate the CSP.
        y : array, shape (n_epochs,)
            The class for each epoch.

        Returns
        -------
        self : instance of CSP
            Returns the modified instance.
        r   zn_classes must be >= 2.r   zzcomponent_order='alternate' requires two classes, but data contains {} classes; use component_order='mutual_info' instead.Nc                    s   g | ]}t  ˆ |¡‘qS r"   ©r'   Údot©Ú.0r   ©Zpick_filtersr"   r#   Ú
<listcomp>¼   s     zCSP.fit.<locals>.<listcomp>©Úaxisr   )r.   r'   ÚuniqueÚ_classesr*   r   r   ÚformatÚ_compute_covariance_matricesÚ_decompose_covsÚ_order_componentsÚTÚfilters_r   Ú	patterns_r   ÚasarrayÚmeanÚmean_ÚstdÚstd_)	r!   r,   r-   Ú	n_classesÚcovsÚsample_weightsÚeigen_vectorsÚeigen_valuesÚixr"   r3   r#   Úfit•   s4    
ýÿ
 ÿ
zCSP.fitc                    s¬   t |tjƒstdt|ƒ ƒ‚| jdkr.tdƒ‚| jd| j… ‰ t ‡ fdd„|D ƒ¡}| j	dkr¨|d j
dd�}| jdkr~d	n| j}|r”t |¡}n|| j8 }|| j }|S )
a  Estimate epochs sources given the CSP filters.

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

        Returns
        -------
        X : ndarray
            If self.transform_into == 'average_power' then returns the power of
            CSP features averaged over time and shape (n_epochs, n_sources)
            If self.transform_into == 'csp_space' then returns the data in CSP
            space and shape is (n_epochs, n_sources, n_times).
        r%   Nz9No filters available. Please first fit CSP decomposition.c                    s   g | ]}t  ˆ |¡‘qS r"   r/   r1   r3   r"   r#   r4   Þ   s     z!CSP.transform.<locals>.<listcomp>r   r   r5   T)r   r'   r(   r   r)   r>   ÚRuntimeErrorr   r@   r   rA   r   rB   rD   )r!   r,   r   r"   r3   r#   Ú	transformÇ   s    



zCSP.transformc                    s   t ƒ j|fd|i|—ŽS )Nr-   )ÚsuperÚfit_transform)r!   r,   r-   Z
fit_params©Ú	__class__r"   r#   rO   ë   s    zCSP.fit_transformZRdBu_rTza.u.é@   r   z%3.1fzCSP%01dÚheadé   c                 C   s’   ddl m} |dkr t | j¡}t |¡}| ¡ � d|d< W 5 Q R X || jj	|dd�}|j
||||||||||	|
d||||||||||||d	�S )
a.  Plot topographic patterns of components.

        The patterns explain how the measured data was generated from the
        neural sources (a.k.a. the forward model).

        Parameters
        ----------
        %(info_not_none)s Used for fitting. If not available, consider using
            :func:`mne.create_info`.
        components : float | array of float | None
           The patterns to plot. If None, n_components will be shown.
        ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg' | None
            The channel type to plot. For 'grad', the gradiometers are
            collected in pairs and the RMS for each pair is plotted.
            If None, then first available channel type from order given
            above is used. Defaults to None.
        vmin : float | callable
            The value specifying the lower bound of the color range.
            If None, and vmax is None, -vmax is used. Else np.min(data).
            If callable, the output equals vmin(data).
        vmax : float | callable
            The value specifying the upper bound of the color range.
            If None, the maximum absolute value is used. If vmin is None,
            but vmax is not, default np.min(data).
            If callable, the output equals vmax(data).
        cmap : matplotlib colormap | (colormap, bool) | 'interactive' | None
            Colormap to use. If tuple, the first value indicates the colormap
            to use and the second value is a boolean defining interactivity. In
            interactive mode the colors are adjustable by clicking and dragging
            the colorbar with left and right mouse button. Left mouse button
            moves the scale up and down and right mouse button adjusts the
            range. Hitting space bar resets the range. Up and down arrows can
            be used to change the colormap. If None, 'Reds' is used for all
            positive data, otherwise defaults to 'RdBu_r'. If 'interactive',
            translates to (None, True). Defaults to 'RdBu_r'.

            .. warning::  Interactive mode works smoothly only for a small
                amount of topomaps.
        sensors : bool | str
            Add markers for sensor locations to the plot. Accepts matplotlib
            plot format string (e.g., 'r+' for red plusses). If True,
            a circle will be used (via .add_artist). Defaults to True.
        colorbar : bool
            Plot a colorbar.
        scalings : dict | float | None
            The scalings of the channel types to be applied for plotting.
            If None, defaults to ``dict(eeg=1e6, grad=1e13, mag=1e15)``.
        units : dict | str | None
            The unit of the channel type used for colorbar label. If
            scale is None the unit is automatically determined.
        res : int
            The resolution of the topomap image (n pixels along each side).
        size : float
            Side length per topomap in inches.
        cbar_fmt : str
            String format for colorbar values.
        name_format : str
            String format for topomap values. Defaults to "CSP%%01d".
        show : bool
            Show figure if True.
        show_names : bool | callable
            If True, show channel names on top of the map. If a callable is
            passed, channel names will be formatted using the callable; e.g.,
            to delete the prefix 'MEG ' from all channel names, pass the
            function lambda x: x.replace('MEG ', ''). If ``mask`` is not None,
            only significant sensors will be shown.
        title : str | None
            Title. If None (default), no title is displayed.
        %(mask_patterns_topomap)s
        %(mask_params_topomap)s
        %(outlines_topomap)s
        contours : int | array of float
            The number of contour lines to draw. If 0, no contours will be
            drawn. When an integer, matplotlib ticker locator is used to find
            suitable values for the contour thresholds (may sometimes be
            inaccurate, use array for accuracy). If an array, the values
            represent the levels for the contours. Defaults to 6.
        %(image_interp_topomap)s
        average : float | None
            The time window around a given time to be used for averaging
            (seconds). For example, 0.01 would translate into window that
            starts 5 ms before and ends 5 ms after a given time point.
            Defaults to None, which means no averaging.
        %(sphere_topomap_auto)s

        Returns
        -------
        fig : instance of matplotlib.figure.Figure
           The figure.
        r   ©ÚEvokedArrayNç      ð?Úsfreqr   ©ZtminÚs)ÚtimesÚch_typeÚvminÚvmaxÚcmapÚcolorbarÚresÚcbar_fmtÚsensorsÚscalingsÚunitsÚ	time_unitÚtime_formatÚsizeÚ
show_namesÚtitleÚmask_paramsÚmaskÚoutlinesÚcontoursÚimage_interpÚshowÚaverageÚsphere)Ú rV   r'   Úaranger   ÚcpÚdeepcopyÚ_unlockr?   r=   Úplot_topomap)r!   ÚinfoÚ
componentsr\   r]   r^   r_   rc   r`   rd   re   ra   rh   rb   Úname_formatrp   ri   rj   rl   rk   rm   rn   ro   rq   rr   rV   Úpatternsr"   r"   r#   Úplot_patternsï   sB    c

                øzCSP.plot_patternsc                 C   s�   ddl m} |dkr t | j¡}t |¡}| ¡ � d|d< W 5 Q R X || jj	|dd�}|j
||||||||||	|
d|||||||||||d	�S )
a¸  Plot topographic filters of components.

        The filters are used to extract discriminant neural sources from
        the measured data (a.k.a. the backward model).

        Parameters
        ----------
        %(info_not_none)s Used for fitting. If not available, consider using
            :func:`mne.create_info`.
        components : float | array of float | None
           The patterns to plot. If None, n_components will be shown.
        ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg' | None
            The channel type to plot. For 'grad', the gradiometers are
            collected in pairs and the RMS for each pair is plotted.
            If None, then first available channel type from order given
            above is used. Defaults to None.
        vmin : float | callable
            The value specifying the lower bound of the color range.
            If None, and vmax is None, -vmax is used. Else np.min(data).
            If callable, the output equals vmin(data).
        vmax : float | callable
            The value specifying the upper bound of the color range.
            If None, the maximum absolute value is used. If vmin is None,
            but vmax is not, defaults to np.min(data).
            If callable, the output equals vmax(data).
        cmap : matplotlib colormap | (colormap, bool) | 'interactive' | None
            Colormap to use. If tuple, the first value indicates the colormap
            to use and the second value is a boolean defining interactivity. In
            interactive mode the colors are adjustable by clicking and dragging
            the colorbar with left and right mouse button. Left mouse button
            moves the scale up and down and right mouse button adjusts the
            range. Hitting space bar resets the range. Up and down arrows can
            be used to change the colormap. If None, 'Reds' is used for all
            positive data, otherwise defaults to 'RdBu_r'. If 'interactive',
            translates to (None, True). Defaults to 'RdBu_r'.

            .. warning::  Interactive mode works smoothly only for a small
                amount of topomaps.
        sensors : bool | str
            Add markers for sensor locations to the plot. Accepts matplotlib
            plot format string (e.g., 'r+' for red plusses). If True,
            a circle will be used (via .add_artist). Defaults to True.
        colorbar : bool
            Plot a colorbar.
        scalings : dict | float | None
            The scalings of the channel types to be applied for plotting.
            If None, defaults to ``dict(eeg=1e6, grad=1e13, mag=1e15)``.
        units : dict | str | None
            The unit of the channel type used for colorbar label. If
            scale is None the unit is automatically determined.
        res : int
            The resolution of the topomap image (n pixels along each side).
        size : float
            Side length per topomap in inches.
        cbar_fmt : str
            String format for colorbar values.
        name_format : str
            String format for topomap values. Defaults to "CSP%%01d".
        show : bool
            Show figure if True.
        show_names : bool | callable
            If True, show channel names on top of the map. If a callable is
            passed, channel names will be formatted using the callable; e.g.,
            to delete the prefix 'MEG ' from all channel names, pass the
            function lambda x: x.replace('MEG ', ''). If ``mask`` is not None,
            only significant sensors will be shown.
        title : str | None
            Title. If None (default), no title is displayed.
        mask : ndarray of bool, shape (n_channels, n_times) | None
            The channels to be marked as significant at a given time point.
            Indices set to `True` will be considered. Defaults to None.
        mask_params : dict | None
            Additional plotting parameters for plotting significant sensors.
            Default (None) equals::

                dict(marker='o', markerfacecolor='w', markeredgecolor='k',
                     linewidth=0, markersize=4)
        %(outlines_topomap)s
        contours : int | array of float
            The number of contour lines to draw. If 0, no contours will be
            drawn. When an integer, matplotlib ticker locator is used to find
            suitable values for the contour thresholds (may sometimes be
            inaccurate, use array for accuracy). If an array, the values
            represent the levels for the contours. Defaults to 6.
        %(image_interp_topomap)s
        average : float | None
            The time window around a given time to be used for averaging
            (seconds). For example, 0.01 would translate into window that
            starts 5 ms before and ends 5 ms after a given time point.
            Defaults to None, which means no averaging.

        Returns
        -------
        fig : instance of matplotlib.figure.Figure
           The figure.
        r   rU   NrW   rX   r   rY   rZ   )r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   )rs   rV   r'   rt   r   ru   rv   rw   r>   r=   rx   )r!   ry   rz   r\   r]   r^   r_   rc   r`   rd   re   ra   rh   rb   r{   rp   ri   rj   rl   rk   rm   rn   ro   rq   rV   Úfiltersr"   r"   r#   Úplot_filtersg  s@    h

                ùzCSP.plot_filtersc                 C   s’   |j \}}}| jdkr| j}n| jdkr.| j}g }g }| jD ]@}||||k ƒ\}	}
| jrh|	t |	¡ }	| |	¡ | |
¡ q<t 	|¡t 
|¡fS )Nr   r   )Úshaper   Ú_concat_covÚ
_epoch_covr8   r   r'   ÚtraceÚappendÚstackÚarray)r!   r,   r-   Ú_Ú
n_channelsZcov_estimatorrF   rG   Z
this_classÚcovÚweightr"   r"   r#   r:   ã  s    



z CSP._compute_covariance_matricesc                 C   sR   |j \}}}t |dddg¡}| |d¡}t|| j| j| jd�}|j d }||fS )z3Concatenate epochs before computing the covariance.r   r   r   éÿÿÿÿ©r   Zmethod_paramsr   )r€   r'   Ú	transposeÚreshaper   r   r    r   )r!   Úx_classr‡   rˆ   r‰   rŠ   r"   r"   r#   r�   ø  s      þ
zCSP._concat_covc                    s2   t ‡ fdd„|D ƒƒ}|t|ƒ }t|ƒ}||fS )zMean of per-epoch covariances.c                 3   s$   | ]}t |ˆ jˆ jˆ jd �V  qdS )rŒ   N)r   r   r    r   )r2   Zthis_X©r!   r"   r#   Ú	<genexpr>  s   ý ýz!CSP._epoch_cov.<locals>.<genexpr>)Úsumr*   )r!   r�   r‰   rŠ   r"   r�   r#   r‚     s    ýzCSP._epoch_covc                 C   s`   ddl m} t|ƒ}|dkr8| |d | d¡¡\}}n t|ƒ\}}|  |j||¡}d }||fS )Nr   ©Úlinalgr   )Úscipyr”   r*   Úeighr’   Ú	_ajd_phamÚ_normalize_eigenvectorsr=   )r!   rF   rG   r”   rE   rI   rH   ÚDr"   r"   r#   r;     s    
ÿzCSP._decompose_covsc              	   C   sº   ||  ¡  }g }t|jd ƒD ]–}d\}}t||ƒD ]b\}	}
t t |d d …|f j|	¡|d d …|f ¡}||
t t |¡¡ 7 }||
|d d  7 }q4|d|d    }| 	|¡ q|S )Nr   )r   r   r   g      È?)
r’   Úranger€   Úzipr'   r0   r=   r   Úsqrtr„   )r!   rF   rG   rH   Zclass_probasr   ÚjjZaaZbbr‰   ZprobÚtmpÚmir"   r"   r#   Ú_compute_mutual_info  s    ÿzCSP._compute_mutual_infoc                 C   st   t j|d|d�}t|jd ƒD ]P}t  t  |d d …|f j|¡|d d …|f ¡}|d d …|f  t  |¡  < q|S )Nr   )r6   Úweightsr   )r'   rq   rš   r€   r0   r=   rœ   )r!   rH   rF   rG   Zmean_covÚiirž   r"   r"   r#   r˜   .  s    ÿ zCSP._normalize_eigenvectorsc           
      C   sÜ   t | jƒ}|dkr>|dkr>|  |||¡}t |¡d d d… }nš|dkrn|dkrnt t |d ¡¡d d d… }nj|dkrØ|dkrØt |¡}	t |	¡}|	d t |	ƒd … |dd d…< |	t |	ƒd d … d d d… |dd d…< |S )Nr   r   r‹   g      à?r   r   r   )r*   r8   r    r'   ÚargsortÚabsZ
empty_like)
r!   rF   rG   rH   rI   r   rE   r   rJ   Úir"   r"   r#   r<   8  s    
ÿ 

(zCSP._order_components)	r   NNr   r   FNNr   )N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r$   r.   rK   rM   r   r   rO   r	   r   r}   r   r:   r�   r‚   r;   r    r˜   r<   Ú__classcell__r"   r"   rP   r#   r      s†   L        ý
&
2$              ùw              ú{
r   ç�íµ ÷Æ°>é   c                 C   sü  | j d }tj| dd�j}|j \}}t |¡}||d  | }t|ƒD �]Ž}	d}
td|ƒD �]j}t|ƒD �]Z}t |||¡}t |||¡}|||f }|||f }t |||f | ¡}t |||f | ¡}t || ¡}t || ¡}t || ¡}t || ¡}|| | |d  }|| | t	|d dƒ }|| }t 
|| | ¡}|
||t 
|¡ ||   d 7 }
ddt || ¡  }t |t |d ||  ¡ ¡}t d| | g| | dgg¡}t ||||gdd…f ¡|||gdd…f< tj|dd…|f |dd…|f f }tj||| dfd	d
�}t ||j¡}tj|||d fd	d
�}|dd…d|…f |dd…|f< |dd…|d…f |dd…|f< t ||||gdd…f ¡|||gdd…f< qhqZ|
|k rF �qØqFt ||d|f¡ ddd¡}||fS )av  Approximate joint diagonalization based on Pham's algorithm.

    This is a direct implementation of the PHAM's AJD algorithm [1].

    Parameters
    ----------
    X : ndarray, shape (n_epochs, n_channels, n_channels)
        A set of covariance matrices to diagonalize.
    eps : float, default 1e-6
        The tolerance for stopping criterion.
    max_iter : int, default 1000
        The maximum number of iteration to reach convergence.

    Returns
    -------
    V : ndarray, shape (n_channels, n_channels)
        The diagonalizer.
    D : ndarray, shape (n_epochs, n_channels, n_channels)
        The set of quasi diagonal matrices.

    References
    ----------
    .. [1] Pham, Dinh Tuan. "Joint approximate diagonalization of positive
           definite Hermitian matrices." SIAM Journal on Matrix Analysis and
           Applications 22, no. 4 (2001): 1136-1152.

    r   r5   r   g•Ö&è.>g       @y              à?r   NÚF)Úorderr‹   )r€   r'   Zconcatenater=   Úeyerš   rt   rA   rœ   ÚmaxZconjÚimagÚrealr†   r0   Zc_rŽ   r�   )r,   ÚepsZmax_iterÚn_epochsÚAZn_timesZn_mÚVÚepsilonÚitZdecrr¢   r�   ZIiZIjÚc1Úc2Zg12Zg21Zomega21Zomega12Úomegarž   Ztmp1Ztmp2Zh12Zh21Útaur™   r"   r"   r#   r—   I  sN    


" ",&  0r—   c                       s6   e Zd ZdZd‡ fdd„	Zdd„ Z‡ fd	d
„Z‡  ZS )ÚSPoCaõ  Implementation of the SPoC spatial filtering.

    Source Power Comodulation (SPoC) :footcite:`DahneEtAl2014` allows to
    extract spatial filters and
    patterns by using a target (continuous) variable in the decomposition
    process in order to give preference to components whose power correlates
    with the target variable.

    SPoC can be seen as an extension of the CSP driven by a continuous
    variable rather than a discrete variable. Typical applications include
    extraction of motor patterns using EMG power or audio patterns using sound
    envelope.

    Parameters
    ----------
    n_components : int
        The number of components to decompose M/EEG 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`.
    log : None | bool (default None)
        If transform_into == 'average_power' and log is None or True, then
        applies a log transform to standardize the features, else the features
        are z-scored. If transform_into == 'csp_space', then log must be None.
    transform_into : {'average_power', 'csp_space'}
        If 'average_power' then self.transform will return the average power of
        each spatial filter. If 'csp_space' self.transform will return the data
        in CSP space. Defaults to 'average_power'.
    cov_method_params : dict | None
        Parameters to pass to :func:`mne.compute_covariance`.

        .. versionadded:: 0.16
    %(rank_none)s

        .. versionadded:: 0.17

    Attributes
    ----------
    filters_ : ndarray, shape (n_channels, n_channels)
        If fit, the SPoC spatial filters, else None.
    patterns_ : ndarray, shape (n_channels, n_channels)
        If fit, the SPoC spatial patterns, else None.
    mean_ : ndarray, shape (n_components,)
        If fit, the mean squared power for each component.
    std_ : ndarray, shape (n_components,)
        If fit, the std squared power for each component.

    See Also
    --------
    mne.preprocessing.Xdawn, CSP

    References
    ----------
    .. footbibliography::
    r   Nr   c              
      s8   t t| ƒj|||dd|||d� t| dƒ t| dƒ dS )zInit of SPoC.r   F)r   r   r   r   r   r   r   r    r   r   N)rN   r½   r$   Údelattr)r!   r   r   r   r   r    r   rP   r"   r#   r$   Ú  s      ý
zSPoC.__init__c                    s†  ddl m} |  ||¡ tt |¡ƒdk r2tdƒ‚| tj¡}|| 	¡ 8 }|| 
¡  }|jdd… \}}t |||f¡}t|ƒD ]"\}}	t|	| j| j| jd�||< q€| 	d¡}
tj	||dd…tjtjf  dd�}| ||
¡\}}|j}|j}t t |¡¡ddd… }|dd…|f j}| |¡j| _|| _| jd| j… ‰ t ‡ fd	d
„|D ƒ¡}|d j	dd�}|j	dd�| _|j
dd�| _| S )a€  Estimate the SPoC decomposition on epochs.

        Parameters
        ----------
        X : ndarray, shape (n_epochs, n_channels, n_times)
            The data on which to estimate the SPoC.
        y : array, shape (n_epochs,)
            The class for each epoch.

        Returns
        -------
        self : instance of SPoC
            Returns the modified instance.
        r   r“   r   z)y must have at least two distinct values.NrŒ   r5   r‹   c                    s   g | ]}t  ˆ |¡‘qS r"   r/   r1   r3   r"   r#   r4     s     zSPoC.fit.<locals>.<listcomp>)r•   r”   r.   r*   r'   r7   r   ZastypeZfloat64rA   rC   r€   ÚemptyÚ	enumerater   r   r    r   Znewaxisr–   r²   r£   r¤   r=   r   r?   r>   r   r@   rB   rD   )r!   r,   r-   r”   Útargetr´   rˆ   rF   r¢   r   ÚCZCzZevalsZevecsrJ   r"   r3   r#   rK   è  s>      þ
$zSPoC.fitc                    s   t t| ƒ |¡S )a  Estimate epochs sources given the SPoC filters.

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

        Returns
        -------
        X : ndarray
            If self.transform_into == 'average_power' then returns the power of
            CSP features averaged over time and shape (n_epochs, n_sources)
            If self.transform_into == 'csp_space' then returns the data in CSP
            space and shape is (n_epochs, n_sources, n_times).
        )rN   r½   rM   )r!   r,   rP   r"   r#   rM   *  s    zSPoC.transform)r   NNr   NN)r¦   r§   r¨   r©   r$   rK   rM   rª   r"   r"   rP   r#   r½   �  s   ;     þBr½   )r«   r¬   )Úcopyru   Únumpyr'   Úbaser   Zmixinr   r‰   r   Údefaultsr   Úfixesr   Úutilsr	   r
   r   r   r   r—   r½   r"   r"   r"   r#   Ú<module>
   s        6
T