U
    f»{j’�  ã                   @   s„  d dl mZ d dlmZ d dlZddl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mZmZmZmZmZmZ d
dlmZmZmZ d
dlmZmZmZm Z m!Z! G dd„ de"ƒZ#G dd„ de$ƒZ%d4dd„Z&edddœdd„ƒZ'ddœdd„Z(d5dd„Z)d6dd„Z*d7d d!„Z+d"d#„ Z,e d8d$d%„ƒZ-ed9d&d'„ƒZ.ed:d(d)„ƒZ/ed;d*d+„ƒZ0d<d,d-„Z1d.d/„ Z2ed=d0d1„ƒZ3d>d2d3„Z4dS )?é    )Údeepcopy)ÚcountNé   )ÚFIFF)Ú
pick_typesÚ	pick_info)Úfind_tagÚ_rename_list)Údir_tree_find)Ú	write_intÚwrite_floatÚwrite_stringÚwrite_name_listÚwrite_float_matrixÚ	end_blockÚstart_blocké   )Ú_INTERPOLATION_DEFAULTÚ_BORDER_DEFAULTÚ_EXTRAPOLATE_DEFAULT)ÚloggerÚverboseÚwarnÚfill_docÚ_validate_typec                       sf   e Zd ZdZdejdddœ‡ fdd„
Zdd	„ Zd
d„ Ze	dddddddde
dddefdd„ƒZ‡  ZS )Ú
Projectiona)  Projection vector.

    A basic class to proj a meaningful print for projection vectors.

    .. warning:: This class is generally not meant to be instantiated
                 directly, use ``compute_proj_*`` functions instead.

    Parameters
    ----------
    data : dict
        The data dictionary.
    desc : str
        The projector description.
    kind : int
        The projector kind.
    active : bool
        Whether or not the projector has been applied.
    explained_var : float | None
        The explained variance (proportion).
    Ú FN)ÚdescÚkindÚactiveÚexplained_varc                   s   t ƒ j|||||d� d S )N)r   r   r   Údatar    )ÚsuperÚ__init__)Úselfr!   r   r   r   r    ©Ú	__class__© úJ/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/io/proj.pyr#   .   s    ÿzProjection.__init__c                 C   sd   d| d  }|d| d  7 }|dt | d d ƒ› �7 }| d d k	r\|d	| d d
 d›d�7 }d| S )Nz%sr   z, active : %sr   z, n_channels : r!   Ú	col_namesr    z, exp. var : éd   ú0.2fú%z<Projection | %s>)Úlen)r$   Úsr'   r'   r(   Ú__repr__3   s    zProjection.__repr__c                 C   sX   | j }| |¡}|  ¡ D ]:\}}|dkrJ| ¡ }|d  ¡ |d< |||< q|||< q|S )zMake a deepcopy.r!   )r&   Ú__new__ÚitemsÚcopy)r$   ZmemodictÚclsÚresultÚkÚvr'   r'   r(   Ú__deepcopy__<   s    


zProjection.__deepcopy__Té@   r   Úheadé   ©NNc                 C   s2   ddl m} || |||||||||	|
||||d�S )a¼  Plot topographic maps of SSP projections.

        Parameters
        ----------
        %(info_not_none)s Used to determine the layout.
        %(proj_topomap_kwargs)s
        %(sphere_topomap_auto)s
        %(border_topomap)s

        Returns
        -------
        fig : instance of Figure
            Figure distributing one image per channel across sensor topography.

        Notes
        -----
        .. versionadded:: 0.15.0
        r   ©Úplot_projs_topomap)ÚcolorbarÚresÚsizeÚshowÚoutlinesÚcontoursÚimage_interpÚaxesÚvlimÚsphereÚborder)Úviz.topomapr=   )r$   ÚinfoÚcmapÚsensorsr>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   r=   r'   r'   r(   Úplot_topomapI   s$               üzProjection.plot_topomap)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚFIFFV_PROJ_ITEM_FIELDr#   r/   r7   r   r   r   rM   Ú__classcell__r'   r'   r%   r(   r      s*    ÿ	      ûr   c                   @   sx   e Zd ZdZedd„ ƒZeddd„ƒZeddd	„ƒZddd„Z	e
dddddddddedddeefdd„ƒZddd„ZdS )Ú	ProjMixinaò  Mixin class for Raw, Evoked, Epochs.

    Notes
    -----
    This mixin adds a proj attribute as a property to data containers.
    It is True if at least one proj is present and all of them are active.
    The projs might not be applied yet if data are not preloaded. In
    this case it's the _projector attribute that does the job.
    If a private _data attribute is present then the projs applied
    to it are the ones marked as active.

    A proj parameter passed in constructor of raw or epochs calls
    apply_proj and hence after the .proj attribute is True.

    As soon as you've applied the projs it will stay active in the
    remaining pipeline.

    The suggested pipeline is proj=True in epochs (it's cheaper than for raw).

    When you use delayed SSP in Epochs, projs are applied when you call
    get_data() method. They are not applied to the evoked._data unless you call
    apply_proj(). The reason is that you want to reject with projs although
    it's not stored in proj mode.
    c                 C   s*   t | jd ƒdko(tdd„ | jd D ƒƒS )z&Whether or not projections are active.Úprojsr   c                 s   s   | ]}|d  V  qdS ©r   Nr'   ©Ú.0Úpr'   r'   r(   Ú	<genexpr>ˆ   s     z!ProjMixin.proj.<locals>.<genexpr>)r-   rJ   Úall)r$   r'   r'   r(   Úproj„   s    ÿzProjMixin.projFNc              	   C   sÊ   t |tƒr|g}t |tƒs4tdd„ |D ƒƒs4tdƒ‚t|dd�}|r†tdd„ | jd D ƒƒrdtdƒ‚| j ¡ � || jd< W 5 Q R X n| jd  	|¡ | j ¡ �  t
| jd d	d	d
�| jd< W 5 Q R X | S )ap  Add SSP projection vectors.

        Parameters
        ----------
        projs : list
            List with projection vectors.
        remove_existing : bool
            Remove the projection vectors currently in the file.
        %(verbose)s

        Returns
        -------
        self : instance of Raw | Epochs | Evoked
            The data container.
        c                 s   s   | ]}t |tƒV  qd S ©N)Ú
isinstancer   rW   r'   r'   r(   rZ   Ÿ   s     z%ProjMixin.add_proj.<locals>.<genexpr>z5Only projs can be added. You supplied something else.T©r2   c                 s   s   | ]}|d  V  qdS rV   r'   rW   r'   r'   r(   rZ   §   s     rU   z7Cannot remove projectors that have already been appliedF)Úcheck_activeÚsort)r^   r   Úlistr[   Ú
ValueErrorÚdeactivate_projÚanyrJ   Ú_unlockÚextendÚ_uniquify_projs)r$   rU   Zremove_existingr   r'   r'   r(   Úadd_projŠ   s&    

ÿ
þzProjMixin.add_projc           	      C   sB  ddl m} ddlm} ddlm} | jd dksDt| jd ƒdkrRt d	¡ | S t	| |ƒrr| j
rrt d
¡ d| _
tdd„ | jd D ƒƒr˜t d¡ | S tt| jƒddd�\}}|dkrÆt d¡ | S || | _| _t	| ||fƒrü| jrút | j| j¡| _n8| j�r,t| jƒD ]\}}|  |¡| j|< �qn|  ¡  t d¡ | S )a¦  Apply the signal space projection (SSP) operators to the data.

        Parameters
        ----------
        %(verbose)s

        Returns
        -------
        self : instance of Raw | Epochs | Evoked
            The instance.

        Notes
        -----
        Once the projectors have been applied, they can no longer be
        removed. It is usually not recommended to apply the projectors at
        too early stages, as they are applied automatically later on
        (e.g. when computing inverse solutions).
        Hint: using the copy method individual projection vectors
        can be tested without affecting the original data.
        With evoked data, consider the following example::

            projs_a = mne.read_proj('proj_a.fif')
            projs_b = mne.read_proj('proj_b.fif')
            # add the first, copy, apply and see ...
            evoked.add_proj(a).copy().apply_proj().plot()
            # add the second, copy, apply and see ...
            evoked.add_proj(b).copy().apply_proj().plot()
            # drop the first and see again
            evoked.copy().del_proj(0).apply_proj().plot()
            evoked.apply_proj()  # finally keep both
        r   )Ú
BaseEpochs)ÚEvokedr   )ÚBaseRawrU   Nr   zRNo projector specified for this dataset. Please consider the method self.add_proj.zLeaving delayed SSP mode.Fc                 s   s   | ]}|d  V  qdS rV   r'   rW   r'   r'   r(   rZ   ã   s     z'ProjMixin.apply_proj.<locals>.<genexpr>zFProjections have already been applied. Setting proj attribute to True.T)Úadd_eeg_refÚactivatez9The projections don't apply to these data. Doing nothing.zSSP projectors applied...)Zepochsrj   Zevokedrk   Úbaserl   rJ   r-   r   r^   Z_do_delayed_projr[   Ú
setup_projr   Ú
_projectorZpreloadÚnpÚdotÚ_dataÚ	enumerateZ_project_epochZ	load_data)	r$   r   rj   rk   rl   rq   rJ   ÚiiÚer'   r'   r(   Ú
apply_projµ   s8    ! 


ÿ


zProjMixin.apply_projr[   c              	   C   sä   t |tƒr(|dkr(ttt| jd ƒƒƒ}t t |t	¡¡ 
¡ }|D ]J}| jd | }|d rBt| jd ƒt|d d ƒ@ rBd|› �}t|ƒ‚qBt t| jd ƒ¡}d||< | j ¡ �& d	d
„ t| jd |ƒD ƒ| jd< W 5 Q R X | S )aÔ  Remove SSP projection vector.

        .. note:: The projection vector can only be removed if it is inactive
                  (has not been applied to the data).

        Parameters
        ----------
        idx : int | list of int | str
            Index of the projector to remove. Can also be "all" (default)
            to remove all projectors.

        Returns
        -------
        self : instance of Raw | Epochs | Evoked
            The instance.
        r[   rU   r   Úch_namesr!   r)   z‰Cannot remove projector that has already been applied, unless you first remove all channels it applies to. The problematic projector is: Fc                 S   s   g | ]\}}|r|‘qS r'   r'   )rX   rY   r5   r'   r'   r(   Ú
<listcomp>  s    ÿz&ProjMixin.del_proj.<locals>.<listcomp>)r^   Ústrrb   Úranger-   rJ   rr   Z
atleast_1dÚarrayÚintZravelÚsetrc   Úonesrf   Úzip)r$   Úidxrv   r\   ÚmsgZkeepr'   r'   r(   Údel_projü   s"    ÿÿ

*zProjMixin.del_projTr8   r   r9   r:   r;   c                 C   sj   | j d dk	s t| j d ƒdkr^ddlm} || j d | j ||||||||	|
|||||d�}ntdƒ‚|S )a  Plot SSP vector.

        Parameters
        ----------
        ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg' | None | list
            The channel type to plot. For 'grad', the gradiometers are collec-
            ted in pairs and the RMS for each pair is plotted. If None
            (default), it will return all channel types present. If a list of
            ch_types is provided, it will return multiple figures.
        %(proj_topomap_kwargs)s
        %(sphere_topomap_auto)s
        %(image_interp_topomap)s
        %(extrapolate_topomap)s

            .. versionadded:: 0.20
        %(border_topomap)s

        Returns
        -------
        fig : instance of Figure
            Figure distributing one image per channel across sensor topography.
        rU   Nr   r   r<   )rK   rL   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   ÚextrapolaterH   z'Info is missing projs. Nothing to plot.)rJ   r-   rI   r=   rc   )r$   Zch_typerK   rL   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   r…   rH   r=   Zfigr'   r'   r(   r=   "  s&            úzProjMixin.plot_projs_topomapÚaccurateÚautoc           
   
   C   sø   ddl m} t| jd ƒdkr"| S |  ¡  dD ]Ä}tdd�}d||< t| jf|Ž}t|ƒdkr`q.t| j|ƒ}| ¡ }| 	¡ �4 g |d< |d	kr¬t
|d ƒr¬t|dd
�g|d< W 5 Q R X |||||d�}	t |	| jd|d d …f ¡| jd|d d …f< q.| S )Nr   )Ú_map_meg_or_eeg_channelsrU   r   )ÚmegÚeegF)r‰   TrŠ   )r   )ÚmodeÚorigin.)Úforwardrˆ   r-   rJ   rx   Údictr   r   r2   rf   Ú_has_eeg_average_ref_projÚmake_eeg_average_ref_projrr   Úmatmulr!   )
r$   r‹   rŒ   rˆ   r   ÚkwargsZpicksZ	info_fromZinfo_toÚmappingr'   r'   r(   Ú_reconstruct_projM  s<    


ÿ
ÿ   ÿ ÿzProjMixin._reconstruct_proj)FN)N)r[   )r†   r‡   )rN   rO   rP   rQ   Úpropertyr\   r   ri   rx   r„   r   r   r   r   r=   r”   r'   r'   r'   r(   rT   j   s2   
*F
&       ú*rT   Tc                 C   s¸   | d |d ks| o²| d |d ko²| d |d ko²| d d |d d ko²| d d |d d ko²| d d |d d ko²| d d |d d ko²t  | d d |d d k¡}|S )	z!Test if two projectors are equal.r   r   r   r!   r)   Ú	row_namesÚncolÚnrow)rr   r[   )ÚaÚbr`   Úequalr'   r'   r(   Ú_proj_equalg  s     ÿþýüûúùrœ   )Úch_names_mappingr   c                C   s’  |d kri n|}t ƒ }t|tjƒ}t|ƒdkr2|S t|d tjƒ}|D �]Ì}t| |tjƒ}|d k	rj|j}	n&t| |tj	ƒ}|d k	rˆ|j}	nt
dƒ‚t| |tjƒ}|d k	r²t|jƒ}
nt
dƒ‚t| |tjƒ}|d k	rÜt|jƒ}nt
dƒ‚t| |tjƒ}|d k	�r
|j d¡}nt
dƒ‚t| |tjƒ}|d k	�r2|j}nt
dƒ‚t| |tjƒ}|d k	�r^t|jƒ}nd}t| |tjƒ}|d k	�r†t|jƒ}nd }|jd t|ƒk�r´|jd	 |k�r´|j}|jd	 t|ƒk�rÐt
d
ƒ‚t|ƒ}t||ƒ|d d …< t|
||	t||d ||d�|d�}| |¡ qFt|ƒdk�rŽt dt|ƒ ¡ |D ]R}|d �rLdnd}t d|d › d|d d › dt|d d ƒ› d|› �¡ �q:|S )Nr   z#Projection item description missingzProjection item kind missingz*Number of projection vectors not specifiedú:z$Projection item channel list missingzProjection item data missingFr   z>Number of channel names does not match the size of data matrix)r˜   r—   r–   r)   r!   )r   r   r   r!   r    z(    Read a total of %d projection items:r   z idlez        r   z (r!   r˜   z x r)   z) )rb   r
   r   Ú
FIFFB_PROJr-   ÚFIFFB_PROJ_ITEMr   ZFIFF_DESCRIPTIONr!   Ú	FIFF_NAMErc   ÚFIFF_PROJ_ITEM_KINDr~   ÚFIFF_PROJ_ITEM_NVECÚFIFF_PROJ_ITEM_CH_NAME_LISTÚsplitÚFIFF_PROJ_ITEM_VECTORSÚFIFF_MNE_PROJ_ITEM_ACTIVEÚboolÚFIFF_MNE_ICA_PCA_EXPLAINED_VARÚfloatÚshapeÚTr	   r   rŽ   Úappendr   rJ   )ÚfidÚnoder�   r   rU   Znodesr1   ÚitemÚtagr   r   ÚnvecÚnamesr!   r   r    ÚnchanÚoner\   Úmiscr'   r'   r(   Ú
_read_projt  st    




$ ÿý>r·   )r�   c                C   sn  t |ƒdkrdS |dkrtƒ n|}t|ttfdƒ t|ƒD ]\}}t|td|› d�ƒ q:t| tj	ƒ |D ]ô}t| tj
ƒ t| tjt |d d ƒƒ t|d d |ƒ}t| tj|ƒ t| tj|d ƒ t| tj|d	 ƒ |d	 tjkròt| tjd
ƒ t| tj|d d ƒ t| tj|d ƒ t| tj|d d ƒ |d dk	�rPt| tj|d ƒ t| tj
ƒ qht| tj	ƒ dS )z¹Write a projection operator to a file.

    Parameters
    ----------
    fid : file
        The file descriptor of the open file.
    projs : dict
        The projection operator.
    r   NrU   zprojs[ú]r!   r)   r   r   g        r˜   r   r    )r-   rŽ   r   rb   Útupleru   r   r   r   rŸ   r    r   Z
FIFF_NCHANr	   r   r¤   r   r¡   r¢   rR   r   ZFIFF_PROJ_ITEM_TIMEr£   r§   r   r¦   r©   r   )r®   rU   r�   Úpir\   r³   r'   r'   r(   Ú_write_projà  s6    

ÿÿr»   c                 C   s`   t | ttfƒs tdt| ƒf ƒ‚t| ƒD ]&\}}t |tƒs(td|t|ƒf ƒ‚q(|r\t| ƒS | S )z)Check that projs is a list of Projection.z%projs must be a list or tuple, got %szPAll entries in projs list must be Projection instances, but projs[%d] is type %s)r^   rb   r¹   Ú	TypeErrorÚtyperu   r   r   )rU   r2   rº   rY   r'   r'   r(   Ú_check_projs  s    ÿ

þr¾   r'   c                 C   s   t | |||ƒS )aR  Create an SSP operator from SSP projection vectors.

    Parameters
    ----------
    projs : list
        List of projection vectors.
    ch_names : list of str
        List of channels to include in the projection matrix.
    bads : list of str
        Some bad channels to exclude. If bad channels were marked
        in the raw file when projs were calculated using mne-python,
        they should not need to be included here as they will
        have been automatically omitted from the projectors.
    include_active : bool
        Also include projectors that are already active.

    Returns
    -------
    proj : array of shape [n_channels, n_channels]
        The projection operator to apply to the data.
    nproj : int
        How many items in the projector.
    U : array
        The orthogonal basis of the projection vectors.
    )Ú_make_projector)rU   ry   ÚbadsÚinclude_activer'   r'   r(   Úmake_projector  s    rÂ   Fc                    s~  ddl m} t|ƒ}|dkr$tdƒ‚t ||¡dt |df¡f}| dkrL|S d}d}	| D ](‰ ˆ d rh|rX|	d7 }	|ˆ d d 7 }qX|	dkrŽ|S t ||f¡}
d}d}t|ƒ}t	| ƒD �]&\}‰ ˆ d rÊ|r´tˆ d d	 ƒtt 
ˆ d d	 ¡ƒkrütd
| ƒ‚g }g }tˆ d d	 ƒ}t	|ƒD ]@\}}||k�r||k�r| |¡ | ˆ d d	  |¡¡ �qˆ d d }|
dd…||| …f }t|ƒdk�r®ˆ d d dd…|f j||< tˆ d d ƒD ]Â}tj |dd…|f ¡}|dk�r¾ˆ d d jdd� ¡ }|dk �r^|�s^ˆ d tjk�s*t|ƒdk�r^tdtˆ d ƒ› dd| d›dt|ƒ› d|› d�	ƒ |dd…|f  |  < |d7 }�q¾|�rÌ|| jˆ d d< ‡ fdd„|D ƒˆ d d	< tˆ d d	 ƒˆ d d< |ˆ d d 7 }q´|dk�sî|�rò|S |j|
dd…d|…f dd�\}}}t ||d  dk¡}	|dd…d|	…f }t ||¡t ||j¡ }|	|k�rttd|	|f ƒ‚||	|fS )zÿSubselect projs based on ch_names and bads.

    Use inplace=True mode to modify ``projs`` inplace so that no
    warning will be raised next time projectors are constructed with
    the given inputs. If inplace=True, no meaningful data are returned.
    r   )ÚlinalgzNo channel names specifiedNr   r   r!   r˜   r)   z@Channel name list in projection item %d contains duplicate items)ZaxisgÍÌÌÌÌÌì?r   zProjection vector r   z has been reduced to r*   r+   z,% of its original magnitude by subselecting ú/aå   of the original channels. If the ignored channels were bad during SSP computation, we recommend recomputing proj (via compute_proj_raw or related functions) with the bad channels properly marked, because computing SSP with bad channels present in the data but unmarked is dangerous (it can bias the PCA used by SSP). On the other hand, if you know that all channels were good during SSP computation, you can safely use info.normalize_proj() to suppress this warning during projection.c                    s   g | ]}ˆ d  d | ‘qS )r!   r)   r'   )rX   rv   ©rY   r'   r(   rz   ’  s   ÿz#_make_projector.<locals>.<listcomp>r—   F)Zfull_matricesg{®Gáz„?zFApplication of %d projectors for %d channels will yield no components.)ZscipyrÃ   r-   rc   rr   ÚeyeÚemptyZzerosr   ru   Úuniquer­   Úindexr¬   r|   Znormre   Úsumr   ÚFIFFV_PROJ_ITEM_EEG_AVREFr   ÚreprZsvdrs   ÚRuntimeError)rU   ry   rÀ   rÁ   ÚinplacerÃ   r´   Zdefault_returnr²   ÚnprojZvecsZnonzeror5   ÚselZvecselZp_setÚcÚnamer˜   Z	this_vecsr6   ÚpsizeZorig_nÚUÚSÚ_r\   r'   rÅ   r(   r¿   8  sŒ    ÿÿ

ÿ
þ.ÿ
ÿ$
ÿr¿   c                 C   s,   t | d |  d|  d¡¡| d ddd� dS )zÎNormalize proj after subselection to avoid warnings.

    This is really only useful for tests, and might not be needed
    eventually if we change or improve our handling of projectors
    with picks.
    rU   ry   r³   rÀ   T)rÁ   rÎ   N)r¿   Úget)rJ   r'   r'   r(   Ú_normalize_proj«  s
      ÿrØ   c                 C   s(   t | d | d | d |ƒ\}}}||fS )a¤  Make an SSP operator using the measurement info.

    Calls make_projector on good channels.

    Parameters
    ----------
    %(info_not_none)s
    include_active : bool
        Also include projectors that are already active.

    Returns
    -------
    proj : array of shape [n_channels, n_channels]
        The projection operator to apply to the data.
    nproj : int
        How many items in the projector.
    rU   ry   rÀ   )rÂ   )rJ   rÁ   r\   rÏ   rÖ   r'   r'   r(   Úmake_projector_info·  s
     ÿ
rÙ   c                 C   s4   |rt | ƒ} | D ]}d|d< qt dt| ƒ ¡ | S )a4  Set all projections to active.

    Useful before passing them to make_projector.

    Parameters
    ----------
    projs : list
        The projectors.
    copy : bool
        Modify projs in place or operate on a copy.
    %(verbose)s

    Returns
    -------
    projs : list
        The projectors.
    Tr   z%d projection items activated©r   r   rJ   r-   ©rU   r2   r   r\   r'   r'   r(   Úactivate_projÏ  s    
rÜ   c                 C   s4   |rt | ƒ} | D ]}d|d< qt dt| ƒ ¡ | S )aB  Set all projections to inactive.

    Useful before saving raw data without projectors applied.

    Parameters
    ----------
    projs : list
        The projectors.
    copy : bool
        Modify projs in place or operate on a copy.
    %(verbose)s

    Returns
    -------
    projs : list
        The projectors.
    Fr   z%d projection items deactivatedrÚ   rÛ   r'   r'   r(   rd   î  s    
rd   c           
         s¬   |   dd¡rtdƒ‚t d¡ t| ddddd�}| d ‰ ‡ fd	d
„|D ƒ}t|ƒ}|dkrbtdƒ‚t d|f¡}|t 	|¡ }d}t
|d|d|d�}t||dtj|d�}	|	S )a  Create an EEG average reference SSP projection vector.

    Parameters
    ----------
    %(info_not_none)s
    activate : bool
        If True projections are activated.
    %(verbose)s

    Returns
    -------
    eeg_proj: instance of Projection
        The SSP/PCA projector.
    Úcustom_ref_appliedFz”A custom reference has been applied to the data earlier. Please use the mne.io.set_eeg_reference function to move from one EEG reference to another.z(Adding average EEG reference projection.TrÀ   ©r‰   rŠ   Zref_megÚexcludery   c                    s   g | ]}ˆ | ‘qS r'   r'   )rX   r5   ©ry   r'   r(   rz   '  s     z-make_eeg_average_ref_proj.<locals>.<listcomp>r   zACannot create EEG average reference projector (no EEG data found)r   N)r)   r–   r!   r˜   r—   úAverage EEG reference)r   r!   r   r   r    )r×   rÍ   r   rJ   r   r-   rc   rr   r€   ÚsqrtrŽ   r   r   rË   )
rJ   rn   r   Úeeg_selZ	eeg_namesZn_eegZvecr    Zeeg_proj_dataÚeeg_projr'   rà   r(   r�     s2    

ÿ  ÿýr�   c                 C   s:   | D ]0}|d dks"|d t jkr|r.|d r dS qdS )z¤Determine if a list of projectors has an average EEG ref.

    Optionally, set check_active=True to additionally check if the CAR
    has already been applied.
    r   rá   r   r   TF)r   rË   )rU   r`   r\   r'   r'   r(   r�   8  s    ÿr�   c                 C   s6   t | ddddd�}t|ƒdko4| d  o4t| d ƒ S )zÆDetermine if the EEG needs an averge EEG reference.

    This returns True if no custom reference has been applied and no average
    reference projection is present in the list of projections.
    FTrÀ   rÞ   r   rÝ   rU   )r   r-   r�   )rJ   rã   r'   r'   r(   Ú_needs_eeg_average_ref_projF  s    
ÿÿþrå   c              	   C   s�   |r&t | ƒr&t| |d�}| d  |¡ t| ƒ\}}|dkrN|rHt d¡ d}nt d| ¡ |rˆ|  ¡ � t| d dd�| d< W 5 Q R X || fS )	a  Set up projection for Raw and Epochs.

    Parameters
    ----------
    %(info_not_none)s Warning: will be modified in-place.
    add_eeg_ref : bool
        If True, an EEG average reference will be added (unless one
        already exists).
    activate : bool
        If True projections are activated.
    %(verbose)s

    Returns
    -------
    projector : array of shape [n_channels, n_channels]
        The projection operator to apply to the data.
    info : mne.Info
        The modified measurement info.
    )rn   rU   r   z5The projection vectors do not apply to these channelsNz1Created an SSP operator (subspace dimension = %d)Fr_   )rå   r�   r­   rÙ   r   rJ   rf   rÜ   )rJ   rm   rn   r   rä   Z	projectorrÏ   r'   r'   r(   rp   S  s    
ÿ
rp   c                    s\   g }| D ]&‰t ‡ ‡fdd„|D ƒƒs| ˆ¡ qtt|ƒƒ‰‡fdd„}|rXt||d�S |S )zMake unique projs.c                 3   s   | ]}t |ˆˆ ƒV  qd S r]   )rœ   rW   )r`   r\   r'   r(   rZ   „  s     z"_uniquify_projs.<locals>.<genexpr>c                    s8   dd„ | d D ƒ}|r$t |d ƒ}ntˆ ƒ}|| d fS )zSort in a nice way.c                 S   s   g | ]}|  ¡ r|‘qS r'   )Úisdigit)rX   r.   r'   r'   r(   rz   ‹  s      z3_uniquify_projs.<locals>.sorter.<locals>.<listcomp>r   éÿÿÿÿ)r~   Únext)ÚxÚdigitsZsort_idx)Úmy_countr'   r(   Úsorter‰  s
    z_uniquify_projs.<locals>.sorter)Úkey)re   r­   r   r-   Úsorted)rU   r`   ra   Zfinal_projsrì   r'   )r`   rë   r\   r(   rh   €  s    	rh   )T)T)r'   T)r'   TF)T)TN)TN)TN)F)TTN)TT)5r2   r   Ú	itertoolsr   Únumpyrr   Ú	constantsr   Úpickr   r   r±   r   r	   Útreer
   Úwriter   r   r   r   r   r   r   Údefaultsr   r   r   Úutilsr   r   r   r   r   rŽ   r   ÚobjectrT   rœ   r·   r»   r¾   rÂ   r¿   rØ   rÙ   rÜ   rd   r�   r�   rå   rp   rh   r'   r'   r'   r(   Ú<module>   sF   $R ~
k.

  ÿ
s*
,