U
    f»{jKI ã                -   @   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	 d dl
mZ 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 dd
lmZmZ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%m&Z&m'Z'm(Z( ddl)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z: dd„ Z;dÆdd„Z<edÇdd„ƒZ=e3ƒ Z>dd„ e> ?¡ D ƒZ@dd„ e> ?¡ D ƒZAe"jBde"jCde"jDde"jEde"jFd e"jGd!iZHd"d#„ ZIG d$d%„ d%e&ƒZJG d&d'„ d'eKƒZLG d(d)„ d)eKƒZMedÈd*d+„ƒZNd,d-„ ZOe	G d.d/„ d/ƒƒZPe Qd0¡ZRePd1d2d3eRjSd3d4�d5�ePd6d7d8eRjSd8d4�d5�ePd9d:d;eRjSd;d4�d5�ePd<d=d>eRjSd>d4�d5�ePd?d@dAeRjSdAd4�d5�ePdBdCdDeRjSdDd4�d5�ePdEdFdGeRjSdGd4�d5�ePdHdIdJeRjSdJd4�d5�ePdKdLdMeRjSdMd4�d5�ePdNdOdPeRjSdPd4�d5�ePdQdOdReRjSdRd4�d5�ePdSdOdTeRjSdTd4�d5�ePdUdVdWeRjSdWd4�d5�ePdXdYdZeRjSdZd4�d5�ePd[d\d]eRjSd]d4�d5�ePd^d_d`eRjSd`d4�d5�ePdadOdbdd5�ePdcdOdddd5�ePdedOdfdd5�ePdgdOdhdd5�ePdidOdjdd5�ePdkdOdldd5�ePdmdOdndd5�ePdodpdqeRjSdqd4�d5�ePdrdsdteRjSdtd4�d5�ePdudvdweRjSdwd4�d5�ePdxdydzeRjSdzd4�d5�ePd{d|d}eRjSd}d4�d5�ePd~dd€eRjSd€d4�d5�ePd�dOd‚eRjSd‚d4�d5�ePdƒd„d…eRjSd…d4�d5�ePd†d‡dˆeRjSdˆd4�d5�ePd‰dŠd‹eRjSd‹d4�d5�ePdŒd�dŽeRjSdŽd4�d5�ePd�d�d‘eRjSd‘d4�d5�ePd’d“d”eRjSd”d4�d5�ePd•d–d—eRjSd—d4�d5�ePd˜dOd™eRjSd™d4�d5�ePdšdOd›eRjSd›d4�d5�g'ZTeddœœd�dž„ƒZUedÉdŸd „ƒZVd¡d¢„ ZWed£d¤„ ƒZXed¥d¦„ ƒZYedÊd§d¨„ƒZZdËd©dª„Z[d«d¬„ Z\edÌd®d¯„ƒZ]dÍd±d²„Z^d³d´dµd¶d·d¸d¹dºd»g	Z_d¼d½d¾d¿gZ`dÎdÀdÁ„ZadÂdÃ„ ZbedÏdÄdÅ„ƒZcdS )Ðé    N)ÚPath)ÚOrderedDict)Ú	dataclass)Údeepcopy)Úpartial)ÚUnioné   )ÚHEAD_SIZE_DEFAULTÚ_handle_default)
ÚverboseÚloggerÚwarnÚ_check_preloadÚ_validate_typeÚfill_docÚ_check_optionÚ_get_stim_channelÚ_check_fnameÚ_check_dict_keys)ÚFIFF)Úanonymize_infoÚInfoÚMontageMixinÚcreate_infoÚ_rename_comps)Úchannel_typeÚ	pick_infoÚ
pick_typesÚ_picks_by_typeÚ_check_excludes_includesÚ_contains_ch_typeÚchannel_indices_by_typeÚpick_channelsÚ_picks_to_idxÚget_channel_type_constantsÚ_pick_data_channels)Ú_rename_list)Ú	DATE_NONE)Ú
setup_projc                 C   sþ   d}| d D ]à}|d t jkr|d d@ }t dd„ | d D ƒ¡}|t jkrVd} qöq|d	 d
krld} qöq|t jks€|t jkr–|dkrŒdnd} qöq|t jkrªd} qöq|t jkrÂd}d} qöq|t j	krÖd} qöq|t j
krd}d} qöqd}d}||fS )z5Educated guess for the helmet type based on channels.TÚchsÚkindÚ	coil_typeéÿÿ  c                 S   s   g | ]}|d  t jk‘qS ©r*   )r   ÚFIFFV_MEG_CH©Ú.0Úc© r2   úT/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/channels/channels.pyÚ
<listcomp>1   s     z#_get_meg_system.<locals>.<listcomp>Z122miè  é   Z306mé–   ZMagnes_3600whZMagnes_2500whZCTF_275ZKITFZ	BabySQUIDZ
ARTEMIS123Úunknown)r   r.   ÚnpÚsumÚFIFFV_COIL_NM_122ÚFIFFV_COIL_MAGNES_MAGÚFIFFV_COIL_MAGNES_GRADÚFIFFV_COIL_CTF_GRADÚFIFFV_COIL_KIT_GRADZFIFFV_COIL_BABY_GRADZFIFFV_COIL_ARTEMIS123_GRAD)ÚinfoZhave_helmetÚchr+   ZnmagÚsystemr2   r2   r3   Ú_get_meg_system)   sF    ÿ

ÿ



rB   Fc                 C   s€   |dkr|dddddddd	d
ddddddg}||r6dgng 7 }|D ]2}t | tƒrbt| |ƒrr|} q|q@|| kr@|} q|q@tdƒ‚|S )z¨Choose a single channel type (usually for plotting).

    Usually used in plotting to plot a single datatype, e.g. look for mags,
    then grads, then ... to plot.
    NÚmagÚgradZplanar1Zplanar2ÚeegÚcsdÚfnirs_cw_amplitudeÚfnirs_fd_ac_amplitudeÚfnirs_fd_phaseÚfnirs_odÚhboÚhbrÚecogÚseegÚdbsÚref_megz No plottable channel types found)Ú
isinstancer   r    ÚRuntimeError)ÚinstÚch_typeZallow_ref_megÚallowed_typesÚtype_r2   r2   r3   Ú_get_ch_typeQ   s.          ý

rW   Tc                    s¼  ddl m} ddlm} ddlm} ddlm} ddlm	} ddl
m} ddlm}	m}
 ||||	|||
|f}d	}| D ]}t||d
|ƒ qt| d j‰ t d¡ dd„ | D ƒ}tˆ ƒj|Ž }tˆ ƒj|Ž }tt|| ƒƒ}t ‡ fdd„|D ƒ¡}t t|ƒ¡|  ¡ }d}g }| D ]€}|j|k�r„t||ƒ�rPt|j|g dd�}t|||dd�}n|�r^| ¡ }|j|dd� t|jƒt|ƒk�r„d}|  |¡ �q|�r¨t d| ¡ n|�r¸t d¡ |S )a]  Equalize channel picks and ordering across multiple MNE-Python objects.

    First, all channels that are not common to each object are dropped. Then,
    using the first object in the list as a template, the channels of each
    object are re-ordered to match the template. The end result is that all
    given objects define the same channels, in the same order.

    Parameters
    ----------
    instances : list
        A list of MNE-Python objects to equalize the channels for. Objects can
        be of type Raw, Epochs, Evoked, AverageTFR, Forward, Covariance,
        CrossSpectralDensity or Info.
    copy : bool
        When dropping and/or re-ordering channels, an object will be copied
        when this parameter is set to ``True``. When set to ``False`` (the
        default) the dropping and re-ordering of channels happens in-place.

        .. versionadded:: 0.20.0
    %(verbose)s

    Returns
    -------
    equalized_instances : list
        A list of MNE-Python objects that have the same channels defined in the
        same order.

    Notes
    -----
    This function operates inplace.
    r   )Ú
Covariance©ÚBaseRaw)r   ©Ú
BaseEpochs)ÚEvoked)ÚForward)Ú_BaseTFRÚCrossSpectralDensityzKRaw, Epochs, Evoked, TFR, Forward, Covariance, CrossSpectralDensity or InfozInstances to be modifiedr   zIdentifying common channels ...c                 S   s   g | ]}t |jƒ‘qS r2   )ÚsetÚch_names©r0   rS   r2   r2   r3   r4   Ÿ   s     z%equalize_channels.<locals>.<listcomp>c                    s   g | ]}ˆ   |¡‘qS r2   ©Úindex©r0   r@   ©Zchan_templater2   r3   r4   ¥   s     FT)ÚexcludeÚordered)Úcopyr   ©ri   z"Dropped the following channels:
%szChannels have been re-ordered.)!ZcovrX   Zio.baserZ   Úio.meas_infor   Úepochsr\   Zevokedr]   Úforwardr^   Útime_frequencyr_   r`   r   rb   r   r?   ra   ÚintersectionÚunionÚlistr8   ÚargsortÚarrayÚtolistrQ   r"   r   rj   ÚlenÚappend)Z	instancesrj   r   rX   rZ   r   r\   r]   r^   r_   r`   rU   Zallowed_types_strrS   ZchannelsZcommon_channelsZall_channelsZdroppedÚorderZ	reorderedZequalized_instancesÚselr2   rg   r3   Úequalize_channelsj   sZ    !
  ÿÿ


ÿ
rz   c                 C   s    i | ]\}}||  d tj¡“qS r-   )Úgetr   ÚFIFFV_COIL_NONE©r0   ÚkÚvr2   r2   r3   Ú
<dictcomp>Ã   s      r€   c                 C   s    i | ]\}}||  d tj¡“qS )Úunit)r{   r   ÚFIFF_UNIT_NONEr}   r2   r2   r3   r€   Å   s      ÚVÚTzT/mÚMZNAÚCc                 C   sV   t | }| d |krJ|D ]0}| d |d d krtd| d |d f ƒ‚q|| d< dS )z1Ensure type change is compatible with projectors.r*   Úch_nameÚdataÚ	col_namesz;Cannot change channel type for channel %s in projector "%s"ÚdescN)Ú_human2fiffrR   )r@   ÚprojsrT   Znew_kindÚprojr2   r2   r3   Ú
_check_setÏ   s    þrŽ   c                   @   sp   e Zd ZdZeddd„ƒZddd	„Zd
d„ Zeddd„ƒZeddd„ƒZ	eddd„ƒZ
eddd„ƒZdd„ ZdS )ÚSetChannelsMixinú$Mixin class for Raw, Evoked, Epochs.ÚaverageFÚautoNc                 C   s$   ddl m} || |d|||d�d S )aO  Specify which reference to use for EEG data.

        Use this function to explicitly specify the desired reference for EEG.
        This can be either an existing electrode or a new virtual channel.
        This function will re-reference the data according to the desired
        reference.

        Parameters
        ----------
        %(ref_channels_set_eeg_reference)s
        %(projection_set_eeg_reference)s
        %(ch_type_set_eeg_reference)s
        %(forward_set_eeg_reference)s
        %(verbose)s

        Returns
        -------
        inst : instance of Raw | Epochs | Evoked
            Data with EEG channels re-referenced. If ``ref_channels='average'``
            and ``projection=True`` a projection will be added instead of
            directly re-referencing the data.
        %(set_eeg_reference_see_also_notes)s
        r   )Úset_eeg_referenceF)Úref_channelsrj   Ú
projectionrT   rn   r   )Úio.referencer“   )Úselfr”   r•   rT   rn   r   r“   r2   r2   r3   r“   Þ   s     þþz"SetChannelsMixin.set_eeg_referencec                    sf   t | j|ƒ}| jd ‰ t ‡ fdd„|D ƒ¡}t tjt |¡dd�dk¡}|dkrbtd |¡ƒ‚|S )zàGet channel locations from info.

        Parameters
        ----------
        picks : str | list | slice | None
            None gets good data indices.

        Notes
        -----
        .. versionadded:: 0.9.0
        r)   c                    s    g | ]}ˆ | d  dd… ‘qS ©ÚlocNr5   r2   ©r0   r~   ©r)   r2   r3   r4     s     z;SetChannelsMixin._get_channel_positions.<locals>.<listcomp>é   ©Úaxisr   z3Could not extract channel positions for {} channels)r#   r?   r8   rt   r9   ÚabsÚ
ValueErrorÚformat)r—   ÚpicksÚposZn_zeror2   r›   r3   Ú_get_channel_positionsý   s    
ÿz'SetChannelsMixin._get_channel_positionsc                 C   s®   t |ƒt |ƒkrtdƒ‚tj|tjd�}|jd dks@|jdkrTd|jf }t|ƒ‚t||ƒD ]J\}}|| jkr˜| j 	|¡}|| j
d | d d	d…< q^d
| }t|ƒ‚q^d	S )aC  Update channel locations in info.

        Parameters
        ----------
        pos : array-like | np.ndarray, shape (n_points, 3)
            The channel positions to be set.
        names : list of str
            The names of the channels to be set.

        Notes
        -----
        .. versionadded:: 0.9.0
        zCNumber of channel positions not equal to the number of names given.©Údtypeéÿÿÿÿr5   r   z;Channel positions must have the shape (n_points, 3) not %s.r)   r™   Nz0%s was not found in the info. Cannot be updated.)rv   r    r8   ÚasarrayZfloat64ÚshapeÚndimÚziprb   re   r?   )r—   r£   ÚnamesÚmsgÚnameÚpÚidxr2   r2   r3   Ú_set_channel_positions  s     ÿ
ÿz'SetChannelsMixin._set_channel_positionsc              	   C   sØ  | j d }tƒ }| ¡ D �]‚\}}||kr6td| ƒ‚| |¡}|tkrftd|d tt 	¡ ƒ¡f ƒ‚t
| j d | | j d |ƒ | j d | d }t| }	|tkr´td||f ƒ‚|t| krðt| t|	 f}
|
|krâtƒ ||
< ||
  |¡ t| | j d | d< |d	k�rtj}nr|d
k�r*tj}n`|dk�r<tj}nN|dk�rNtj}n<|dk�r`tj}n*|dk�rrtj}n|dk�r„tj}ntj}|| j d | d< qd}| ¡ D ](\}
}t|jd t|ƒ¡f|
žŽ ƒ �qª| S )aÞ  Define the sensor type of channels.

        Parameters
        ----------
        mapping : dict
            A dictionary mapping a channel to a sensor type (str), e.g.,
            ``{'EEG061': 'eog'}``.
        %(verbose)s

        Returns
        -------
        inst : instance of Raw | Epochs | Evoked
            The instance (modified in place).

            .. versionchanged:: 0.20
               Return the instance.

        Notes
        -----
        The following sensor types are accepted:

            ecg, eeg, emg, eog, exci, ias, misc, resp, seeg, dbs, stim, syst,
            ecog, hbo, hbr, fnirs_cw_amplitude, fnirs_fd_ac_amplitude,
            fnirs_fd_phase, fnirs_od

        .. versionadded:: 0.9.0
        rb   z-This channel name (%s) doesn't exist in info.zTThis function cannot change to this channel type: %s. Accepted channel types are %s.ú, r)   rŒ   r�   zQChannel '%s' has unknown unit (%s). Please fix the measurement info of your data.)rE   rN   rM   rO   rK   rL   rG   rH   rI   rJ   r+   z8The unit for channel(s) {0} has changed from {1} to {2}.)r?   ÚdictÚitemsr    re   r‹   ÚjoinÚsortedÚ_human2unitÚkeysrŽ   Ú_unit2humanrr   rw   r   ÚFIFFV_COIL_EEGZFIFFV_COIL_FNIRS_HBOZFIFFV_COIL_FNIRS_HBRZFIFFV_COIL_FNIRS_CW_AMPLITUDEZ FIFFV_COIL_FNIRS_FD_AC_AMPLITUDEZFIFFV_COIL_FNIRS_FD_PHASEZFIFFV_COIL_FNIRS_ODr|   r   r¡   )r—   Úmappingr   rb   Zunit_changesr‡   rT   Úc_indZunit_oldZunit_newZthis_changer+   r­   r¬   r2   r2   r3   Úset_channel_types1  s^    
ÿ
ÿýþ







"z"SetChannelsMixin.set_channel_typesc                    sº   ddl m} t| jd ƒ}t| jˆ |ƒ t| |ƒr¶tt|| jd ƒƒ‰ | jdk	r‚ˆ  	¡ D ](\}}||krX| j| | j|< | j|= qX| j
j}t|ƒD ]"\}	}
t‡ fdd„|
D ƒƒ||	< q’| S )aŠ  Rename channels.

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

        Returns
        -------
        inst : instance of Raw | Epochs | Evoked
            The instance (modified in place).

            .. versionchanged:: 0.20
               Return the instance.

        Notes
        -----
        .. versionadded:: 0.9.0
        r   rY   rb   Nc                 3   s   | ]}ˆ   ||¡V  qd S ©N)r{   )r0   r®   ©r»   r2   r3   Ú	<genexpr>§  s     z3SetChannelsMixin.rename_channels.<locals>.<genexpr>)ÚiorZ   rr   r?   Úrename_channelsrQ   r³   r«   Z_orig_unitsr´   Úannotationsrb   Ú	enumerateÚtuple)r—   r»   Úallow_duplicatesr   rZ   Zch_names_origZold_nameÚnew_namerb   Úcir@   r2   r¿   r3   rÂ   ‚  s    


z SetChannelsMixin.rename_channelsÚtopomapTc                 C   s.   ddl m} || j|||||||||	|
|d�S )a�  Plot sensor positions.

        Parameters
        ----------
        kind : str
            Whether to plot the sensors as 3d, topomap or as an interactive
            sensor selection dialog. Available options 'topomap', '3d',
            'select'. If 'select', a set of channels can be selected
            interactively by using lasso selector or clicking while holding
            control key. The selected channels are returned along with the
            figure instance. Defaults to 'topomap'.
        ch_type : None | str
            The channel type to plot. Available options 'mag', 'grad', 'eeg',
            'seeg', 'dbs', 'ecog', 'all'. If ``'all'``, all the available mag,
            grad, eeg, seeg, dbs, and ecog channels are plotted. If
            None (default), then channels are chosen in the order given above.
        title : str | None
            Title for the figure. If None (default), equals to ``'Sensor
            positions (%%s)' %% ch_type``.
        show_names : bool | array of str
            Whether to display all channel names. If an array, only the channel
            names in the array are shown. Defaults to False.
        ch_groups : 'position' | array of shape (n_ch_groups, n_picks) | None
            Channel groups for coloring the sensors. If None (default), default
            coloring scheme is used. If 'position', the sensors are divided
            into 8 regions. See ``order`` kwarg of :func:`mne.viz.plot_raw`. If
            array, the channels are divided by picks given in the array.

            .. versionadded:: 0.13.0
        to_sphere : bool
            Whether to project the 3d locations to a sphere. When False, the
            sensor array appears similar as to looking downwards straight above
            the subject's head. Has no effect when kind='3d'. Defaults to True.

            .. versionadded:: 0.14.0
        axes : instance of Axes | instance of Axes3D | None
            Axes to draw the sensors to. If ``kind='3d'``, axes must be an
            instance of Axes3D. If None (default), a new axes will be created.

            .. versionadded:: 0.13.0
        block : bool
            Whether to halt program execution until the figure is closed.
            Defaults to False.

            .. versionadded:: 0.13.0
        show : bool
            Show figure if True. Defaults to True.
        %(sphere_topomap_auto)s
        %(verbose)s

        Returns
        -------
        fig : instance of Figure
            Figure containing the sensor topography.
        selection : list
            A list of selected channels. Only returned if ``kind=='select'``.

        See Also
        --------
        mne.viz.plot_layout

        Notes
        -----
        This function plots the sensor locations from the info structure using
        matplotlib. For drawing the sensors using PyVista see
        :func:`mne.viz.plot_alignment`.

        .. versionadded:: 0.12.0
        r   )Úplot_sensors)r*   rT   ÚtitleÚ
show_namesÚ	ch_groupsÚ	to_sphereÚaxesÚblockÚshowÚspherer   )Z	viz.utilsrÊ   r?   )r—   r*   rT   rË   rÌ   rÍ   rÎ   rÏ   rÐ   rÑ   rÒ   r   rÊ   r2   r2   r3   rÊ   «  s    J     ýzSetChannelsMixin.plot_sensorsc                 C   s&   t | j|||d� |  | jd ¡ | S )aŒ  Anonymize measurement information in place.

        Parameters
        ----------
        %(daysback_anonymize_info)s
        %(keep_his_anonymize_info)s
        %(verbose)s

        Returns
        -------
        inst : instance of Raw | Epochs | Evoked
            The modified instance.

        Notes
        -----
        %(anonymize_info_notes)s

        .. versionadded:: 0.13.0
        )ÚdaysbackÚkeep_hisr   Ú	meas_date)r   r?   Úset_meas_date)r—   rÓ   rÔ   r   r2   r2   r3   Ú	anonymizeû  s
    
ÿzSetChannelsMixin.anonymizec              	   C   s´   ddl m} ||ƒ}| j ¡ � || jd< W 5 Q R X |dkrždD ]\}| j |¡}|dk	r@d|ksdt‚td |d< td	 |d
< |d  ¡ }d|dd…< ||d< q@t| dƒr°|| j _	| S )a¥  Set the measurement start date.

        Parameters
        ----------
        meas_date : datetime | float | tuple | None
            The new measurement date.
            If datetime object, it must be timezone-aware and in UTC.
            A tuple of (seconds, microseconds) or float (alias for
            ``(meas_date, 0)``) can also be passed and a datetime
            object will be automatically created. If None, will remove
            the time reference.

        Returns
        -------
        inst : instance of Raw | Epochs | Evoked
            The modified raw instance. Operates in place.

        See Also
        --------
        mne.io.Raw.anonymize

        Notes
        -----
        If you want to remove all time references in the file, call
        :func:`mne.io.anonymize_info(inst.info) <mne.io.anonymize_info>`
        after calling ``inst.set_meas_date(None)``.

        .. versionadded:: 0.20
        r   )Ú_handle_meas_daterÕ   N)Zfile_idZmeas_idÚmsecsr   Zsecsrœ   ZusecsZmachidrÃ   )
rÃ   rØ   r?   Z_unlockr{   ÚAssertionErrorr'   rj   ÚhasattrZ
_orig_time)r—   rÕ   rØ   ÚkeyÚvalueZ_tmpr2   r2   r3   rÖ     s"    

zSetChannelsMixin.set_meas_date)r‘   Fr’   NN)N)N)FN)rÉ   NNFNTNFTNN)NFN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r“   r¤   r±   r½   rÂ   rÊ   r×   rÖ   r2   r2   r2   r3   r�   Û   s6         ÿ
P(              ýOr�   c                   @   s†   e Zd ZdZeddd„ƒZeddd	œd
d„ƒZeddd	œdd„ƒZdd„ Zdd„ Z	edd	œdd„ƒZ
dd„ Zddd„Zedd„ ƒZdS )ÚUpdateChannelsMixinz0Mixin class for Raw, Evoked, Epochs, AverageTFR.Fr’   r2   ÚbadsNc                 C   sª   t | j|||||||||	|
||||||||||||||d�}|  |¡ t| ddƒdk	rvt| jƒD ]}|| kr`| j|= q`t| ddƒdk	r¦t| jƒD ]}|| kr�| j|= q�| S )aÏ
  Pick some channels by type and names.

        Parameters
        ----------
        meg : bool | str
            If True include MEG channels. If string it can be 'mag', 'grad',
            'planar1' or 'planar2' to select only magnetometers, all
            gradiometers, or a specific type of gradiometer.
        eeg : bool
            If True include EEG channels.
        stim : bool
            If True include stimulus channels.
        eog : bool
            If True include EOG channels.
        ecg : bool
            If True include ECG channels.
        emg : bool
            If True include EMG channels.
        ref_meg : bool | str
            If True include CTF / 4D reference channels. If 'auto', reference
            channels are included if compensations are present and ``meg`` is
            not False. Can also be the string options for the ``meg``
            parameter.
        misc : bool
            If True include miscellaneous analog channels.
        resp : bool
            If ``True`` include respiratory channels.
        chpi : bool
            If True include continuous HPI coil channels.
        exci : bool
            Flux excitation channel used to be a stimulus channel.
        ias : bool
            Internal Active Shielding data (maybe on Triux only).
        syst : bool
            System status channel information (on Triux systems only).
        seeg : bool
            Stereotactic EEG channels.
        dipole : bool
            Dipole time course channels.
        gof : bool
            Dipole goodness of fit channels.
        bio : bool
            Bio channels.
        ecog : bool
            Electrocorticography channels.
        fnirs : bool | str
            Functional near-infrared spectroscopy channels. If True include all
            fNIRS channels. If False (default) include none. If string it can
            be 'hbo' (to include channels measuring oxyhemoglobin) or 'hbr' (to
            include channels measuring deoxyhemoglobin).
        csd : bool
            EEG-CSD channels.
        dbs : bool
            Deep brain stimulation channels.
        include : list of str
            List of additional channels to include. If empty do not include
            any.
        exclude : list of str | str
            List of channels to exclude. If 'bads' (default), exclude channels
            in ``info['bads']``.
        selection : list of str
            Restrict sensor channels (MEG, EEG) to this list of channel names.
        %(verbose)s

        Returns
        -------
        inst : instance of Raw, Epochs, or Evoked
            The modified instance.

        See Also
        --------
        pick_channels

        Notes
        -----
        .. versionadded:: 0.9.0
        )ÚmegrE   ÚstimÚeogÚecgÚemgrP   ÚmiscÚrespÚchpiÚexciÚiasÚsystrN   ÚdipoleÚgofÚbiorM   ÚfnirsrF   rO   Úincluderh   Ú	selectionÚrejectNÚflat)r   r?   Ú_pick_drop_channelsÚgetattrrr   rõ   rö   )r—   rä   rE   rå   ræ   rç   rè   rP   ré   rê   rë   rì   rí   rî   rN   rï   rð   rñ   rM   rò   rF   rO   ró   rh   rô   r   r°   rT   r2   r2   r3   r   N  sJ    T                    û


zUpdateChannelsMixin.pick_types)r   c                C   s   t | jd ||d�}|  |¡S )a…  Pick some channels.

        Parameters
        ----------
        ch_names : list
            The list of channels to select.
        ordered : bool
            If True (default False), ensure that the order of the channels in
            the modified instance matches the order of ``ch_names``.

            .. versionadded:: 0.20.0
        %(verbose)s

            .. versionadded:: 1.1

        Returns
        -------
        inst : instance of Raw, Epochs, or Evoked
            The modified instance.

        See Also
        --------
        drop_channels
        pick_types
        reorder_channels

        Notes
        -----
        The channel names given are assumed to be a set, i.e. the order
        does not matter. The original order of the channels is preserved.
        You can use ``reorder_channels`` to set channel order if necessary.

        .. versionadded:: 0.9.0
        rb   rk   )r"   r?   r÷   )r—   rb   ri   r   r¢   r2   r2   r3   r"   º  s    $z!UpdateChannelsMixin.pick_channelsc                C   s   t | j|d|dd�}|  |¡S )a°  Pick a subset of channels.

        Parameters
        ----------
        %(picks_all)s
        exclude : list | str
            Set of channels to exclude, only used when picking based on
            types (e.g., exclude="bads" when picks="meg").
        %(verbose)s

            .. versionadded:: 0.24.0

        Returns
        -------
        inst : instance of Raw, Epochs, or Evoked
            The modified instance.
        ÚallF)Zallow_empty)r#   r?   r÷   )r—   r¢   rh   r   r2   r2   r3   Úpická  s    ÿzUpdateChannelsMixin.pickc                 C   sN   t |ƒ tƒ }|D ]0}| j |¡}||kr8td|f ƒ‚| |¡ q|  |¡S )aø  Reorder channels.

        Parameters
        ----------
        ch_names : list
            The desired channel order.

        Returns
        -------
        inst : instance of Raw, Epochs, or Evoked
            The modified instance.

        See Also
        --------
        drop_channels
        pick_types
        pick_channels

        Notes
        -----
        Channel names must be unique. Channels that are not in ``ch_names``
        are dropped.

        .. versionadded:: 0.16.0
        zChannel name repeated: %s)r   rr   rb   re   r    rw   r÷   )r—   rb   r°   r‡   Úiir2   r2   r3   Úreorder_channelsø  s    z$UpdateChannelsMixin.reorder_channelsc                    sÖ   t |tƒr|g}ztdd„ |D ƒƒ}W n( tk
rN   td t|ƒ|¡ƒ‚Y nX |sltd dd„ |D ƒ¡ƒ‚‡ fdd„|D ƒ}t|ƒdkr¢d}t| d	 |¡¡ƒ‚‡ fd
d„|D ƒ}t	 
t	 tˆ jƒ¡|¡}ˆ  |¡S )aÊ  Drop channel(s).

        Parameters
        ----------
        ch_names : iterable or str
            Iterable (e.g. list) of channel name(s) or channel name to remove.

        Returns
        -------
        inst : instance of Raw, Epochs, or Evoked
            The modified instance.

        See Also
        --------
        reorder_channels
        pick_channels
        pick_types

        Notes
        -----
        .. versionadded:: 0.9.0
        c                 S   s   g | ]}t |tƒ‘qS r2   ©rQ   Ústrrf   r2   r2   r3   r4   6  s     z5UpdateChannelsMixin.drop_channels.<locals>.<listcomp>z.'ch_names' must be iterable, got type {} ({}).z/Each element in 'ch_names' must be str, got {}.c                 S   s   g | ]}t |ƒ‘qS r2   )Útyperf   r2   r2   r3   r4   =  s     c                    s   g | ]}|ˆ j kr|‘qS r2   ©rb   rf   ©r—   r2   r3   r4   ?  s     
 r   z*Channel(s) {0} not found, nothing dropped.r²   c                    s"   g | ]}|ˆ j krˆ j  |¡‘qS r2   )rb   re   rf   r  r2   r3   r4   D  s    
ÿ)rQ   rþ   rù   Ú	TypeErrorr    r¡   rÿ   rv   rµ   r8   Ú	setdiff1dÚarangerb   r÷   )r—   rb   Zall_strÚmissingr­   Zbad_idxr°   r2   r  r3   Údrop_channels  s(    
 ÿÿz!UpdateChannelsMixin.drop_channelsc          
         sl  ddl m} ddlm}m} d}t| |ƒrF| jd k	rPt| |› d�ƒ n
t| |ƒ t| dd ƒd k	rl| j	ˆ  | _	t| dd ƒd k	r’‡ fdd	„| j
D ƒ| _
t| d
ƒr¨| jˆ  | _t| jˆ dd� dD ]4}t| |d ƒ}|d k	r¼t| ||ˆ  d d …ˆ f ƒ q¼t| ||fƒ�rdnd}	t| dƒ�r*| jjˆ |	d�| _nt| |ƒ�r>| j�rBt‚t| |ƒ�r`| jj| jdd� |  ¡  | S )Nr   rY   )Ú
AverageTFRÚ	EpochsTFRz(adding, dropping, or reordering channelsz after calling .apply_proj()r¢   Ú_read_picksc                    s   g | ]}|ˆ  ‘qS r2   r2   ©r0   Úr©r°   r2   r3   r4   Z  s     z;UpdateChannelsMixin._pick_drop_channels.<locals>.<listcomp>Ú_calsF©rj   )Ú_compÚ
_projectoréýÿÿÿéþÿÿÿÚ_datar�   Úignore)Z
on_missing)rÁ   rZ   ro   r  r  rQ   r  r   rø   r¢   r	  rÛ   r  r   r?   Úsetattrr  ÚtakeZpreloadrÚ   rÃ   Z_prune_ch_namesÚ_pick_projs)
r—   r°   r   rZ   r  r  r­   rÜ   Zmatrž   r2   r  r3   r÷   I  s4    



z'UpdateChannelsMixin._pick_drop_channelsc                 C   s„   g }t | jd ƒD ]0\}}t| jd ƒt|d d ƒ@ s| |¡ q|D ]}t d| jd | › �¡ qH|r€t| dƒr€|  |¡ | S )z<Keep only projectors which apply to at least 1 data channel.rŒ   rb   rˆ   r‰   zRemoving projector Údel_proj)rÄ   r?   ra   rw   r   rÛ   r  )r—   Zdrop_idxr°   r�   r2   r2   r3   r  s  s    
zUpdateChannelsMixin._pick_projsc                    s>  ddl m}m} ddlm} t|ttfdƒ |ˆg D ]}t|dƒ q6t	ˆ|ƒrZd‰ |}n t	ˆ|ƒrnd‰ |}nd‰ t
ˆƒ}|D ]}t||dƒ q~d	d
„ ˆg| D ƒ}‡ fdd
„t|d jƒD ƒ}	t dd
„ |D ƒ¡dd…|	f }
|
D ],}|
d | dk ¡ sätd|
d |f ƒ‚qä~
ˆjgdd
„ |D ƒ ‰|ˆ|d�}t	ˆjtjƒ�r2ˆ dk�r2tjdk�r2tdd„ |D ƒƒf|d jdd…  }t |¡ˆjjj }ˆj ¡  ˆjj |¡ tjˆjjdˆjj|d�ˆ_ˆjj|k�sÜt‚ˆjj|k�sît‚t |d ƒ}|dd… D ](}t |ƒ}|ˆj||| …< ||7 }�qntj!|ˆ d�ˆ_|ˆ_t	ˆ|ƒ�rät !dd
„ ˆg| D ƒ¡ˆ_"dgtdd„ ˆdd… D ƒƒ ‰t‡fdd„ˆj#D ƒƒ�s®t‚‡fdd
„ˆj#D ƒˆ_#t‡fdd„ˆj#D ƒƒ�s:t‚nVt	ˆ|ƒ�r:t $ˆjjd ¡ˆ_%t&ˆdƒ�r:ˆj'�rdnˆj(}t)ˆjd|d�\ˆ_*ˆ_ˆS ) a_  Append new channels to the instance.

        Parameters
        ----------
        add_list : list
            A list of objects to append to self. Must contain all the same
            type as the current object.
        force_update_info : bool
            If True, force the info for objects to be appended to match the
            values in ``self``. This should generally only be used when adding
            stim channels for which important metadata won't be overwritten.

            .. versionadded:: 0.12

        Returns
        -------
        inst : instance of Raw, Epochs, or Evoked
            The modified instance.

        See Also
        --------
        drop_channels

        Notes
        -----
        If ``self`` is a Raw instance that has been preloaded into a
        :obj:`numpy.memmap` instance, the memmap will be resized.
        r   )rZ   Ú_merge_infor[   ZInputzadding channelsr   rœ   z	All inputc                 S   s   g | ]
}|j ‘qS r2   )r  rc   r2   r2   r3   r4   ³  s     z4UpdateChannelsMixin.add_channels.<locals>.<listcomp>c                    s   g | ]}|ˆ kr|‘qS r2   r2   ©r0   Úi)Úcon_axisr2   r3   r4   ¶  s      c                 S   s   g | ]
}|j ‘qS r2   ©r©   )r0   Zdatr2   r2   r3   r4   ·  s     Nz<All data dimensions except channels must match, got %s != %sc                 S   s   g | ]
}|j ‘qS r2   ©r?   rc   r2   r2   r3   r4   À  s     )Zforce_update_to_firstÚdarwinc                 s   s   | ]}|j d  V  qdS )r   Nr  )r0   Údr2   r2   r3   rÀ   Ç  s     z3UpdateChannelsMixin.add_channels.<locals>.<genexpr>zr+)Úmoder¦   r©   r�   c                 S   s   g | ]}t |d ƒ‘qS )r  )rø   rc   r2   r2   r3   r4   Ø  s   ÿiÿÿÿc                 s   s   | ]}|d  V  qdS ©ÚnchanNr2   )r0   r?   r2   r2   r3   rÀ   Ü  s     c                 3   s"   | ]}t |ƒˆ d  d kV  qdS )r   r#  N©rv   r
  )Úinfosr2   r3   rÀ   Ý  s     c                    s   g | ]}t  |ˆ g¡‘qS r2   )r8   Úconcatenater
  )Ú	extra_idxr2   r3   r4   Þ  s    c                 3   s    | ]}t |ƒˆ jd  kV  qdS r"  )rv   r?   r
  r  r2   r3   rÀ   à  s     r  F)Úactivate)+rÁ   rZ   r  rm   r\   r   rr   rÅ   r   rQ   rÿ   Úrangerª   r8   rt   rù   rÚ   r?   r  ZmemmapÚsysÚplatformr9   r©   Úprodr¦   ÚitemsizeÚflushÚbaseÚresizeÚfilenameÚnbytesrv   r&  r  r	  r  r¢   rÛ   Z_do_delayed_projr�   r(   r  )r—   Zadd_listZforce_update_inforZ   r  r\   rS   Z
comp_classrˆ   Zcompare_axesZshapesr©   Znew_infoZ	out_shapeZn_bytesÚoffsetr   Zthis_lenr(  r2   )r  r'  r%  r—   r3   Úadd_channels‚  s€    

 
þÿ&
 ÿ
ÿ
 
ÿ ÿz UpdateChannelsMixin.add_channelsc                 C   s   ddl m} || |dd�S )aÛ  Add reference channels to data that consists of all zeros.

        Adds reference channels to data that were not included during
        recording. This is useful when you need to re-reference your data
        to different channels. These added channels will consist of all zeros.

        Parameters
        ----------
        %(ref_channels)s

        Returns
        -------
        inst : instance of Raw | Epochs | Evoked
               The modified instance.
        r   )Úadd_reference_channelsFr  )r–   r5  )r—   r”   r5  r2   r2   r3   r5  ê  s    z*UpdateChannelsMixin.add_reference_channels)FFFFFFr’   FFFFFFFFFFFFFFr2   rã   NN)F)r2   )F)rÞ   rß   rà   rá   r   r   r"   rú   rü   r  r÷   r  r4  r   r5  r2   r2   r2   r3   râ   K  sJ                                         ûk&#.)
hrâ   c                   @   s   e Zd ZdZed	dd„ƒZdS )
ÚInterpolationMixinr�   TÚaccurater’   Nr2   c                    s  ddl m} ddlm}m}	m}
 t| dƒ td|ƒ}|D ]}td|dƒ q8td	|d
 dƒ td|d dƒ td|d dƒ t	| j
d ƒdkr˜tdƒ | S t 
d¡ ||| j
ƒ}|d
 dkrÎ|| |ˆ d� d}nd}|	| |||ˆ d� |
| ˆ d� |dk�r‡ fdd„| j
d D ƒ| j
d< | S )aZ  Interpolate bad MEG and EEG channels.

        Operates in place.

        Parameters
        ----------
        reset_bads : bool
            If True, remove the bads from info.
        mode : str
            Either ``'accurate'`` or ``'fast'``, determines the quality of the
            Legendre polynomial expansion used for interpolation of channels
            using the minimum-norm method.
        origin : array-like, shape (3,) | str
            Origin of the sphere in the head coordinate frame and in meters.
            Can be ``'auto'`` (default), which means a head-digitization-based
            origin fit.

            .. versionadded:: 0.17
        method : dict
            Method to use for each channel type.
            Currently only the key "eeg" has multiple options:

            - ``"spline"`` (default)
                Use spherical spline interpolation.
            - ``"MNE"``
                Use minimum-norm projection to a sphere and back.
                This is the method used for MEG channels.

            The value for "meg" is "MNE", and the value for
            "fnirs" is "nearest". The default (None) is thus an alias for::

                method=dict(meg="MNE", eeg="spline", fnirs="nearest")

            .. versionadded:: 0.21
        exclude : list | tuple
            The channels to exclude from interpolation. If excluded a bad
            channel will stay in bads.
        %(verbose)s

        Returns
        -------
        inst : instance of Raw, Epochs, or Evoked
            The modified instance.

        Notes
        -----
        .. versionadded:: 0.9.0
        r   )Ú_check_originrœ   )Ú_interpolate_bads_eegÚ_interpolate_bads_meegÚ_interpolate_bads_nirsÚinterpolationZinterpolation_methodzmethod[key])rä   rE   rò   zmethod['eeg']rE   )ÚsplineÚMNEzmethod['meg']rä   )r>  zmethod['fnirs']rò   )Znearestrã   r   z0No bad channels to interpolate. Doing nothing...zInterpolating bad channelsr=  )Úoriginrh   FT)r!  r?  rE   rh   ©rh   c                    s   g | ]}|ˆ kr|‘qS r2   r2   rf   r@  r2   r3   r4   S  s      z7InterpolationMixin.interpolate_bads.<locals>.<listcomp>)Zbemr8  r<  r9  r:  r;  r   r
   r   rv   r?   r   r   )r—   Z
reset_badsr!  r?  Úmethodrh   r   r8  r9  r:  r;  rÜ   Zeeg_mner2   r@  r3   Úinterpolate_bads  s4    4



ÿ
ÿz#InterpolationMixin.interpolate_bads)Tr7  r’   Nr2   N)rÞ   rß   rà   rá   r   rB  r2   r2   r2   r3   r6     s          þr6  c                    sª  t | tdƒ |  ¡  t| d ƒ}t| d ƒ‰ tˆtƒr^tˆˆ ddd� ‡ fdd„ˆ ¡ D ƒ}n2tˆƒr~‡fdd„t	ˆ ƒD ƒ}nt
d	tˆƒf ƒ‚|D ]}t |d
 ddƒ q”|D ]6\}}t	|ƒD ]\}}	|	ˆ | kr¾|||< q¾|ˆ |< q®tˆ ƒtt ˆ ¡ƒk�r|�st
dƒ‚|| d< tƒ }
t| d ˆ ƒD ]\}}||
|d < ||d< �q(t|  dg ¡|
ƒ d| k�r–| d D ](}t|d d |
ƒ|d d dd…< �ql|  ¡  |  ¡  dS )zžRename channels.

    Parameters
    ----------
    %(info_not_none)s Note: modified in place.
    %(mapping_rename_channels_duplicates)s
    %(verbose)s
    r?   rã   rb   zchannel name(s))Zkey_descriptionZvalid_key_sourcec                    s   g | ]\}}ˆ   |¡|f‘qS r2   rd   )r0   r‡   rÇ   r   r2   r3   r4   k  s   ÿz#rename_channels.<locals>.<listcomp>c                    s   g | ]\}}|ˆ |ƒf‘qS r2   r2   )r0   rÈ   r‡   r¿   r2   r3   r4   n  s   ÿz(mapping must be callable or dict, not %srœ   rþ   zNew channel mappingsz1New channel names are not unique, renaming failedr)   r‡   ÚcompsrŒ   rˆ   r‰   N)r   r   Ú_check_consistencyrr   rQ   r³   r   r´   ÚcallablerÄ   r    rÿ   rv   r8   Úuniquer«   r   r{   r&   Z_update_redundant)r?   r»   rÆ   r   rã   Z	new_namesrÇ   r¼   ZbiÚbadZch_names_mappingr@   r‡   r�   r2   )rb   r»   r3   rÂ   X  sN    

ÿ
ÿ
ÿÿ


ÿrÂ   c                 C   s.   t | ƒdkr*t| d |ƒs*dd„ | D ƒ} q| S )zUnpack mat files in Python.r   c                 S   s   g | ]}|D ]}|‘qqS r2   r2   ©r0   r   r1   r2   r2   r3   r4   —  s       z&_recursive_flatten.<locals>.<listcomp>)rv   rQ   )Úcellr¦   r2   r2   r3   Ú_recursive_flatten“  s    rJ  c                   @   s6   e Zd ZU eed< eed< eed< eedf ed< dS )Ú_BuiltinChannelAdjacencyr®   ÚdescriptionÚfnameNÚ
source_url)rÞ   rß   rà   rþ   Ú__annotations__r   r2   r2   r2   r3   rK  ›  s   
rK  zLhttps://github.com/fieldtrip/fieldtrip/raw/master/template/neighbours/$fnameZ	biosemi16zBiosemi 16-electrode capzbiosemi16_neighb.mat)rM  )r®   rL  rM  rN  Z	biosemi32zBiosemi 32-electrode capzbiosemi32_neighb.matZ	biosemi64zBiosemi 64-electrode capzbiosemi64_neighb.matÚbti148zBTI 148-channel systemzbti148_neighb.matÚbti248zBTI 248-channel systemzbti248_neighb.matÚ
bti248gradzBTI 248 gradiometer systemzbti248grad_neighb.matÚctf64zCTF 64 axial gradiometerzctf64_neighb.matÚctf151zCTF 151 axial gradiometerzctf151_neighb.matÚctf275zCTF 275 axial gradiometerzctf275_neighb.matzeasycap32ch-avgÚ zeasycap32ch-avg_neighb.matzeasycap64ch-avgzeasycap64ch-avg_neighb.matzeasycap128ch-avgzeasycap128ch-avg_neighb.matZ	easycapM1z
Easycap M1zeasycapM1_neighb.matZ
easycapM11zEasycap M11zeasycapM11_neighb.matZ
easycapM14zEasycap M14zeasycapM14_neighb.matZ
easycapM15zEasycap M15zeasycapM15_neighb.matzKIT-157zKIT-157_neighb.matzKIT-208zKIT-208_neighb.matzKIT-NYU-2019zKIT-NYU-2019_neighb.matz	KIT-UMD-1zKIT-UMD-1_neighb.matz	KIT-UMD-2zKIT-UMD-2_neighb.matz	KIT-UMD-3zKIT-UMD-3_neighb.matz	KIT-UMD-4zKIT-UMD-4_neighb.matÚneuromag306magzNeuromag306, only magnetometerszneuromag306mag_neighb.matÚneuromag306planarz%Neuromag306, only planar gradiometerszneuromag306planar_neighb.matZneuromag122cmbz.Neuromag122, only combined planar gradiometerszneuromag122cmb_neighb.matZneuromag306cmbz.Neuromag306, only combined planar gradiometerszneuromag306cmb_neighb.matZecog256z$ECOG 256channels, average referencedzecog256_neighb.matZecog256bipolarz$ECOG 256channels, bipolar referencedzecog256bipolar_neighb.matZeeg1010_neighbzeeg1010_neighb.matZelec1005zStandard 10-05 systemzelec1005_neighb.matZelec1010zStandard 10-10 systemzelec1010_neighb.matZelec1020zStandard 10-20 systemzelec1020_neighb.matZitab28zITAB 28-channel systemzitab28_neighb.matZitab153zITAB 153-channel systemzitab153_neighb.matzlanguage29ch-avgz1MPI for Psycholinguistic: Averaged 29-channel capzlanguage29ch-avg_neighb.matZmpi_59_channelsz(MPI for Psycholinguistic: 59-channel capzmpi_59_channels_neighb.matZyokogawa160zyokogawa160_neighb.matZyokogawa440zyokogawa440_neighb.mat©Zdescriptionsc                 C   s:   | rt dd„ tD ƒdd„ d�S t dd„ tD ƒtjd�S dS )a‘  Get a list of all FieldTrip neighbor definitions shipping with MNE.

    The names of the these neighbor definitions can be passed to
    :func:`read_ch_adjacency`.

    Parameters
    ----------
    descriptions : bool
        Whether to return not only the neighbor definition names, but also
        their corresponding descriptions. If ``True``, a list of tuples is
        returned, where the first tuple element is the neighbor definition name
        and the second is the description. If ``False`` (default), only the
        names are returned.

    Returns
    -------
    neighbor_name : list of str | list of tuple
        If ``descriptions=False``, the names of all builtin FieldTrip neighbor
        definitions that can be loaded directly via :func:`read_ch_adjacency`.

        If ``descriptions=True``, a list of tuples ``(name, description)``.

    Notes
    -----
    .. versionadded:: 1.1
    c                 S   s   g | ]}|j |jf‘qS r2   )r®   rL  ©r0   Úmr2   r2   r3   r4   ´  s     z.get_builtin_ch_adjacencies.<locals>.<listcomp>c                 S   s   | d   ¡ S )Nr   )Úcasefold)Úxr2   r2   r3   Ú<lambda>µ  ó    z,get_builtin_ch_adjacencies.<locals>.<lambda>)rÜ   c                 S   s   g | ]
}|j ‘qS r2   ©r®   rZ  r2   r2   r3   r4   ¹  s     N)r¶   Ú_BUILTIN_CHANNEL_ADJACENCIESrþ   r\  rY  r2   r2   r3   Úget_builtin_ch_adjacencies–  s    þþrb  c           
         sx  ddl m} t | ¡r&t| ddd�} n†| ‰ ~ ˆ  d¡rBˆ  dd¡‰ ˆ tƒ krhtdˆ › d	d
 	tƒ ¡› �ƒ‚‡ fdd„t
D ƒd }|j} ttƒ ¡ jd d }t||  ddd�} || ƒd }t|d tƒ‰ttˆƒ|ƒ}dd„ |d  ¡ D ƒ}tˆƒt|ƒksþt‚tˆ|ƒ}|| dd…|f }‡fdd„|D ƒ‰tˆƒD ]8\}}	|	 d¡�r6|	d dk�s6|	 dd¡}	|	ˆ|< �q6|ˆfS )af  Read a channel adjacency ("neighbors") file that ships with MNE.

    More information on these neighbor definitions can be found on the related
    `FieldTrip documentation pages
    <http://www.fieldtriptoolbox.org/template/neighbours/>`__.

    Parameters
    ----------
    fname : str
        The path to the file to load, or the name of a channel adjacency
        matrix that ships with MNE-Python.

        .. note::
            You can retrieve the names of all
            built-in channel adjacencies via
            :func:`mne.channels.get_builtin_ch_adjacencies`.
    %(picks_all)s
        Picks must match the template.

    Returns
    -------
    ch_adjacency : scipy.sparse.csr_matrix, shape (n_channels, n_channels)
        The adjacency matrix.
    ch_names : list
        The list of channel names present in adjacency matrix.

    See Also
    --------
    get_builtin_ch_adjacencies
    mne.viz.plot_ch_adjacency
    find_ch_adjacency
    mne.stats.combine_adjacency

    Notes
    -----
    If the neighbor definition you need is not shipped by MNE-Python,
    you may use :func:`find_ch_adjacency` to compute the
    adjacency matrix based on your 2D sensor locations.

    Note that depending on your use case, you may need to additionally use
    :func:`mne.stats.combine_adjacency` to prepare a final "adjacency"
    to pass to the eventual function.
    r   )ÚloadmatÚreadT)rM  Ú	overwriteÚ
must_existz_neighb.matrV  z6No built-in channel adjacency matrix found with name: z. Valid names are: r²   c                    s   g | ]}|j ˆ kr|‘qS r2   r`  )r0   Úa)Úch_adj_namer2   r3   r4   ÿ  s    
ÿz%read_ch_adjacency.<locals>.<listcomp>rˆ   Ú	neighborsZ
neighboursÚlabelc                 S   s   g | ]}t |tƒ‘qS r2   )rJ  rþ   r/   r2   r2   r3   r4     s     ZneighblabelNc                    s   g | ]}ˆ | ‘qS r2   r2   ©r0   r¯   r   r2   r3   r4     s     ÚMEGr5   ú úMEG )Zscipy.iorc  ÚopÚisabsr   ÚendswithÚreplacerb  r    rµ   ra  rM  r   Ú__file__ÚresolveÚparentrJ  rþ   r#   rv   ÚflattenrÚ   Ú_ch_neighbor_adjacencyrÄ   Ú
startswith)
rM  r¢   rc  Zch_adjZtemplates_dirÚnbri  Z	adjacencyr°   r‡   r2   )rh  rb   r3   Úread_ch_adjacency¾  sP    -
ý

ÿÿý
ÿ
rz  c           	         sÌ   ddl m} tˆ ƒt|ƒkr$tdƒ‚dd„ |D ƒ}|tˆ ƒ }t|ƒdkrRtdƒ‚|D ](}t|tƒsVtdd„ |D ƒƒsVtd	ƒ‚qVtj	tˆ ƒt
d
�}t|ƒD ]"\}}d||‡ fdd„|D ƒf< qš| |¡}|S )aœ  Compute sensor adjacency matrix.

    Parameters
    ----------
    ch_names : list of str
        The channel names.
    neighbors : list of list
        A list of list of channel names. The neighbors to
        which the channels in ch_names are connected with.
        Must be of the same length as ch_names.

    Returns
    -------
    ch_adjacency : scipy.sparse.spmatrix
        The adjacency matrix.
    r   ©Úsparsez4`ch_names` and `neighbors` must have the same lengthc                 S   s   h | ]}|D ]}|’qqS r2   r2   rH  r2   r2   r3   Ú	<setcomp>2  s       z)_ch_neighbor_adjacency.<locals>.<setcomp>zCSome of your neighbors are not present in the list of channel namesc                 s   s   | ]}t |tƒV  qd S r¾   rý   r/   r2   r2   r3   rÀ   :  s     z)_ch_neighbor_adjacency.<locals>.<genexpr>z*`neighbors` must be a list of lists of strr¥   Tc                    s   g | ]}ˆ   |¡‘qS r2   rd   r  r   r2   r3   r4   ?  s     z*_ch_neighbor_adjacency.<locals>.<listcomp>)Úscipyr|  rv   r    ra   rQ   rr   rù   r8   ÚeyeÚboolrÄ   Ú
csr_matrix)	rb   ri  r|  Zset_neighborsÚrestZneighÚch_adjacencyrû   Úneigbsr2   r   r3   rw    s"    
ÿ

rw  c                 C   sò  |dkr>t | ƒ}tdd„ | ¡ D ƒƒdkr2tdƒ‚t| dƒ}ntd|dd	d
gƒ t| ƒ\}}}}}}}	}
}}}}}d}|rŠ|dkrŠd}�n0|rž|d	kržd}�n|�rXd| d k�r| d  d¡}| d | d tj	k}| d | d tj
k}|d	krþ|rþd}n|dk�rV|�rVd}nBd| d k�rº|dk�rº| d  d¡}| d | d tj
k�rºd}nb|�r–|dk�r–| d dk �r|d}n| d dk�r�d}nd}n$|	dk�rºddlm} | | d ¡}|dk	�rÞt d|› d�¡ t|ƒS t d ¡ t| |ƒS )!aÀ  Find the adjacency matrix for the given channels.

    This function tries to infer the appropriate adjacency matrix template
    for the given channels. If a template is not found, the adjacency matrix
    is computed using Delaunay triangulation based on 2D sensor locations.

    Parameters
    ----------
    %(info_not_none)s
    ch_type : str | None
        The channel type for computing the adjacency matrix. Currently
        supports ``'mag'``, ``'grad'``, ``'eeg'`` and ``None``.
        If ``None``, the info must contain only one channel type.

    Returns
    -------
    ch_adjacency : scipy.sparse.csr_matrix, shape (n_channels, n_channels)
        The adjacency matrix.
    ch_names : list
        The list of channel names present in adjacency matrix.

    See Also
    --------
    mne.viz.plot_ch_adjacency
    mne.stats.combine_adjacency
    get_builtin_ch_adjacencies
    read_ch_adjacency

    Notes
    -----
    .. versionadded:: 0.15

    Automatic detection of an appropriate adjacency matrix template only
    works for MEG data at the moment. This means that the adjacency matrix
    is always computed for EEG data and never loaded from a template file. If
    you want to load a template for a given montage use
    :func:`read_ch_adjacency` directly.

    Note that depending on your use case, you may need to additionally use
    :func:`mne.stats.combine_adjacency` to prepare a final "adjacency"
    to pass to the eventual function.
    Nc                 S   s   g | ]}t |ƒd k‘qS )r   r$  rk  r2   r2   r3   r4   r  s     z%find_ch_adjacency.<locals>.<listcomp>rœ   z;info must contain only one channel type if ch_type is None.r   rT   rC   rD   rE   rW  rX  zMEG 248rb   r)   r+   rR  rQ  zMEG 148rP  r#  éd   rS  éÈ   rU  rT  r   )ÚKIT_NEIGHBORSZkit_system_idzReading adjacency matrix for Ú.zeCould not find a adjacency matrix for the data. Computing adjacency based on Delaunay triangulations.)r!   r9   Úvaluesr    r   r   Ú_get_ch_infore   r   r<   r;   Zio.kit.constantsr‡  r{   r   r?   rz  Ú_compute_ch_adjacency)r?   rT   r¢   Ú
has_vv_magÚhas_vv_gradÚ	is_old_vvÚ
has_4D_magÚctf_other_typesÚhas_CTF_gradÚn_kit_gradsÚhas_any_megÚhas_eeg_coilsÚhas_eeg_coils_and_megÚhas_eeg_coils_onlyÚhas_neuromag_122_gradÚhas_csd_coilsZ	conn_namer°   rD   rC   r‡  r2   r2   r3   Úfind_ch_adjacencyD  s`    ,ý     


r™  c                    s¬  ddl m} ddlm} ddlm} ddlm}m} |dkoXt	‡ fdd	„t
jt
jfD ƒƒ}ttˆ g d
�ƒ| }‡ fdd	„|D ƒ}	|rÄ|ˆ dg d�}
t|
ƒt|ƒkrªtdƒ‚|ˆ |ddd… td�}n|ˆ |td�}||ƒ}||jƒ}|�rztjt|ƒtd�}t|j|jƒD ]b\}}tdƒD ]N}tdƒD ]>}d||d | |d | f< d||d | |d | f< �q&�q�q
| |¡}n*| |¡}| t d|jd ¡¡ | ¡ }||	fS )aÑ  Compute channel adjacency matrix using Delaunay triangulations.

    Parameters
    ----------
    %(info_not_none)s
    ch_type : str
        The channel type for computing the adjacency matrix. Currently
        supports 'mag', 'grad' and 'eeg'.

    Returns
    -------
    ch_adjacency : scipy.sparse.csr_matrix, shape (n_channels, n_channels)
        The adjacency matrix.
    ch_names : list
        The list of channel names present in adjacency matrix.
    r   r{  )ÚDelaunayr   )Úspatial_tris_adjacency)Ú_find_topomap_coordsÚ_pair_grad_sensorsrD   c                    s"   g | ]}|d d„ ˆ d D ƒk‘qS )c                 S   s   g | ]}|d  ‘qS )r+   r2   rf   r2   r2   r3   r4   ¸  s   ÿz4_compute_ch_adjacency.<locals>.<listcomp>.<listcomp>r)   r2   )r0   r+   r  r2   r3   r4   ¸  s   þÿz)_compute_ch_adjacency.<locals>.<listcomp>r@  c                    s   g | ]}ˆ d  | ‘qS r   r2   )r0   rú   r  r2   r3   r4   ¿  s     F)Ztopomap_coordsrh   zQCannot find a pair for some of the gradiometers. Cannot compute adjacency matrix.N)rÒ   r¥   Trœ   ) r~  r|  Zscipy.spatialrš  rV  r›  Zchannels.layoutrœ  r�  Úanyr   ÚFIFFV_COIL_VV_PLANAR_T1r:   r³   r   rv   rR   r	   Z	simplicesr8   r  r€  r«   ÚrowÚcolr)  r�  Z
lil_matrixZsetdiagÚrepeatr©   Ztocsr)r?   rT   r|  rš  r›  rœ  r�  Zcombine_gradsr¢   rb   ÚpairsZxyZtriri  rƒ  r°   r„  rû   Zjjr2   r  r3   r‹  ¡  sB    ÿýÿ
(
r‹  c              
   C   sV   t | |ƒ}|D ]}tj| d | d< qt dt|ƒtt| dg d�ƒf ¡ |  ¡  dS )a  Fix magnetometer coil types.

    Parameters
    ----------
    %(info_not_none)s Corrections are done in-place.
    use_cal : bool
        If True, further refine the check for old coil types by checking
        ``info['chs'][ii]['cal']``.

    Notes
    -----
    This function changes magnetometer coil types 3022 (T1: SQ20483N) and
    3023 (T2: SQ20483-A) to 3024 (T3: SQ20950N) in the channel definition
    records in the info structure.

    Neuromag Vectorview systems can contain magnetometers with two
    different coil sizes (3022 and 3023 vs. 3024). The systems
    incorporating coils of type 3024 were introduced last and are used at
    the majority of MEG sites. At some sites with 3024 magnetometers,
    the data files have still defined the magnetometers to be of type
    3022 to ensure compatibility with older versions of Neuromag software.
    In the MNE software as well as in the present version of Neuromag
    software coil type 3024 is fully supported. Therefore, it is now safe
    to upgrade the data files to use the true coil type.

    .. note:: The effect of the difference between the coil sizes on the
              current estimates computed by the MNE software is very small.
              Therefore the use of ``fix_mag_coil_types`` is not mandatory.
    r)   r+   z-%d of %d magnetometer types replaced with T3.rC   ©rä   rh   N)Ú_get_T1T2_mag_indsr   ÚFIFFV_COIL_VV_MAG_T3r   r?   rv   r   rD  )r?   Úuse_calÚold_mag_indsrû   r2   r2   r3   Úfix_mag_coil_typesÝ  s    
ÿÿr©  c                 C   sf   t | dg d�}g }|D ]J}| d | }|d tjtjfkr|rV|d dkr`| |¡ q| |¡ q|S )z#Find T1/T2 magnetometer coil types.rC   r¤  r)   r+   Úcalgpé~À=)r   r   ÚFIFFV_COIL_VV_MAG_T1ÚFIFFV_COIL_VV_MAG_T2rw   )r?   r§  r¢   r¨  rû   r@   r2   r2   r3   r¥    s    
ÿr¥  c                    sZ  | d }dd„ |D ƒ‰ dd„ |D ƒ}t ‡ fdd„tjtjtjfD ƒƒ}t ‡ fdd„tjtjtjfD ƒƒ}t ‡ fdd„tjfD ƒƒ}d	|d
 d k}tj	ˆ k}tj
tjtjf‰tjˆ kpÔtj|koÔt ‡fdd„ˆ D ƒƒ}tdd„ |D ƒƒ}	t |||||	gƒ}
tjˆ k�otj|k}|�o|
}|�o$|
 }tjˆ k�o:tj|k}||||ˆ||	|
|||||fS )z2Get channel info for inferring acquisition device.r)   c                 S   s   h | ]}|d  d@ ’qS )r+   r,   r2   rf   r2   r2   r3   r}    s     z_get_ch_info.<locals>.<setcomp>c                 S   s   h | ]}|d  ’qS r-   r2   rf   r2   r2   r3   r}    s     c                 3   s   | ]}|ˆ kV  qd S r¾   r2   rš   ©Ú
coil_typesr2   r3   rÀ      s     z_get_ch_info.<locals>.<genexpr>c                 3   s   | ]}|ˆ kV  qd S r¾   r2   rš   r­  r2   r3   rÀ   #  s     c                 3   s   | ]}|ˆ kV  qd S r¾   r2   rš   r­  r2   r3   rÀ   &  s   ÿrm  r   r‡   c                 3   s   | ]}|ˆ kV  qd S r¾   r2   rš   )r�  r2   r3   rÀ   1  s     c                 s   s    | ]}|d  d@ t jkV  qdS )r+   r,   N)r   r>   rf   r2   r2   r3   rÀ   4  s   ÿ)rž  r   r«  r¬  r¦  rŸ  ZFIFFV_COIL_VV_PLANAR_T2ZFIFFV_COIL_VV_PLANAR_T3r:   r;   ZFIFFV_COIL_CTF_REF_MAGZFIFFV_COIL_CTF_REF_GRADZFIFFV_COIL_CTF_OFFDIAG_REF_GRADr=   r.   r9   rº   ZFIFFV_EEG_CHZFIFFV_COIL_EEG_CSD)r?   r)   Zchannel_typesrŒ  r�  r—  rŽ  r�  r‘  r’  r“  r”  r•  r–  r˜  r2   )r®  r�  r3   rŠ    sb    ÿÿþ
ÿ
þ

þÿ
ÿÿ
ÿ
     ýrŠ  Úzc           
         sÚ   t | dƒ z$ddlm} || ƒ}|j‰ |j}W n  tk
rN   | d }d‰ Y nX tg g g d�}t|ƒD ]P\}}|d  ¡ }||krˆd}	n | 	¡ rft
|ƒd	 r d
nd}	nqf||	  |¡ qfˆ dk	rÖ‡ fdd„| ¡ D ƒ}|S )a‚  Return dict mapping from ROI names to lists of picks for 10/20 setups.

    This passes through all channel names, and uses a simple heuristic to
    separate channel names into three Region of Interest-based selections:
    Left, Midline and Right. The heuristic is that channels ending on any of
    the characters in ``midline`` are filed under that heading, otherwise those
    ending in odd numbers under "Left", those in even numbers under "Right".
    Other channels are ignored. This is appropriate for 10/20 files, but not
    for other channel naming conventions.
    If an info object is provided, lists are sorted from posterior to anterior.

    Parameters
    ----------
    %(info_not_none)s If possible, the channel lists will be sorted
        posterior-to-anterior; otherwise they default to the order specified in
        ``info["ch_names"]``.
    midline : str
        Names ending in any of these characters are stored under the
        ``Midline`` key. Defaults to 'z'. Note that capitalization is ignored.

    Returns
    -------
    selections : dict
        A dictionary mapping from ROI names to lists of picks (integers).
    r?   rœ   )Úfind_layoutrb   N)ÚLeftÚMidlineÚRightr§   r²  r   r±  r³  c                    s,   i | ]$\}}|t  |¡ˆ |d f  ¡  “qS )rœ   )r8   rt   rs   )r0   rô   r¢   ©r£   r2   r3   r€   z  s   ÿ z0make_1020_channel_selections.<locals>.<dictcomp>)r   Úlayoutr°  r£   r¬   rR   r³   rÄ   ÚlowerÚisdigitÚintrw   r´   )
r?   Zmidliner°  rµ  rb   Z
selectionsrú   ZchannelZ	last_charrô   r2   r´  r3   Úmake_1020_channel_selectionsF  s.    



ÿr¹  Úmeanc                    s–  ddl m}m} ddlm}m}m}	m}
 t| |ƒr6dnd‰ t	t
| jd ƒƒ‰| jd ‰|  ¡ ‰t| |	ƒrn| jn|  ¡ ‰tt|ƒƒ}t|tƒrÐ‡ fdd	„d
D ƒ}z|| }W n$ tk
rÎ   td|› d�ƒ‚Y nX g g g   }}}t|tƒsþtdt|ƒ› d�ƒ‚|�r`t	t| jddd�ƒ}|�rX‡fdd„|D ƒ}‡fdd„|D ƒ}‡ ‡fdd„|D ƒ}ntdƒ g ‰t|tƒ�s„tdt|ƒ› d�ƒ‚|�r¦| jd �r¦tˆ| jd ƒ‰| ¡ D ]ê\}}t‡fdd„|D ƒƒ�sÖtdƒ‚t ˆ¡| }tt|ƒƒdk�rd  t|ƒ¡}td|› d|› d�ƒ‚‡fdd„|D ƒ}‡fd d„|D ƒ}|�rZt! d!|› d"|› �¡ tt|ƒƒdk �r‚td#|› d$|› d�ƒ t"||d d%�||< �q®| ¡ D ]H\}}| #|¡ | #|d& ¡ |d' }tj$ˆ|ˆ d(�}| #||ƒ¡ �q¢t %|dˆ ¡}t&| jd) ||d*�}t| |ƒ�r,|||| j'd+�}nft| |ƒ�rn|||| j(| j)d | j*d,�}| j+d-k	�r’| j+ ,¡ |_+n$t| |	ƒ�r’|
||| j)d | j*d.�}|S )/a�  Combine channels based on specified channel grouping.

    Parameters
    ----------
    inst : instance of Raw, Epochs, or Evoked
        An MNE-Python object to combine the channels for. The object can be of
        type Raw, Epochs, or Evoked.
    groups : dict
        Specifies which channels are aggregated into a single channel, with
        aggregation method determined by the ``method`` parameter. One new
        pseudo-channel is made per dict entry; the dict values must be lists of
        picks (integer indices of ``ch_names``). For example::

            groups=dict(Left=[1, 2, 3, 4], Right=[5, 6, 7, 8])

        Note that within a dict entry all channels must have the same type.
    method : str | callable
        Which method to use to combine channels. If a :class:`str`, must be one
        of 'mean', 'median', or 'std' (standard deviation). If callable, the
        callable must accept one positional input (data of shape ``(n_channels,
        n_times)``, or ``(n_epochs, n_channels, n_times)``) and return an
        :class:`array <numpy.ndarray>` of shape ``(n_times,)``, or ``(n_epochs,
        n_times)``. For example with an instance of Raw or Evoked::

            method = lambda data: np.mean(data, axis=0)

        Another example with an instance of Epochs::

            method = lambda data: np.median(data, axis=1)

        Defaults to ``'mean'``.
    keep_stim : bool
        If ``True``, include stimulus channels in the resulting object.
        Defaults to ``False``.
    drop_bad : bool
        If ``True``, drop channels marked as bad before combining. Defaults to
        ``False``.

    Returns
    -------
    combined_inst : instance of Raw, Epochs, or Evoked
        An MNE-Python object of the same type as the input ``inst``, containing
        one virtual channel for each group in ``groups`` (and, if ``keep_stim``
        is ``True``, also containing stimulus channels).
    r   )rZ   ÚRawArray)r\   ÚEpochsArrayr]   ÚEvokedArrayrœ   r   r#  rb   c                    s    i | ]}|t tt|ƒˆ d �“qS ©r�   )r   rø   r8   )r0   rÜ   )Úch_axisr2   r3   r€   ¼  s   ÿ z$combine_channels.<locals>.<dictcomp>)rº  ÚmedianZstdzH"method" must be a callable, or one of "mean", "median", or "std"; got "z".z&"keep_stim" must be of type bool, not rˆ  FT)rä   rå   c                    s   g | ]}ˆ | ‘qS r2   r2   ©r0   r°   r   r2   r3   r4   Ì  s     z$combine_channels.<locals>.<listcomp>c                    s   g | ]}ˆ | ‘qS r2   r2   rÁ  )Úch_typesr2   r3   r4   Í  s     c                    s   g | ]}t jˆ|ˆ d �‘qS r¾  )r8   r  rÁ  )r¿  Ú	inst_datar2   r3   r4   Î  s   ÿz!Could not find stimulus channels.z%"drop_bad" must be of type bool, not rã   c                 3   s   | ]}|ˆ kV  qd S r¾   r2   rÁ  )Úch_idxr2   r3   rÀ   Þ  s     z#combine_channels.<locals>.<genexpr>z'Some channel indices are out of bounds.r²   z,Cannot combine sensors of different types; "z" contains types c                    s   g | ]}|ˆ kr|‘qS r2   r2   rÁ  ©Ú
ch_idx_badr2   r3   r4   ç  s      c                    s   g | ]}|ˆ kr|‘qS r2   r2   rÁ  rÅ  r2   r3   r4   è  s      z(Dropped the following channels in group z: zLess than 2 channels in group "z" when combining by method ")r¢   rT   rT   r¢   r�   Úsfreq)rÇ  rb   rÂ  )Ú
first_samp)ÚeventsÚtminÚbaselineN)rÊ  rË  )-rÁ   rZ   r»  rV  r\   r¼  r]   r½  rQ   rr   r)  r?   Zget_channel_typesrˆ   Úget_datar   r   rþ   ÚKeyErrorr    r€  r  rÿ   r   r   r"   r´   rù   r8   rt   rv   ra   rµ   r   r³   rw   r  Zswapaxesr   rÈ  rÉ  ÚtimesrË  Úmetadatarj   )rS   ÚgroupsrA  Z	keep_stimZdrop_badrZ   r»  r\   r¼  r]   r½  Zmethod_dictZnew_ch_namesZnew_ch_typesZnew_dataZstim_ch_idxZ
this_groupZ
this_picksZthis_ch_typeÚtypesZ
these_badsZthis_group_dictZ	this_datar?   Zcombined_instr2   )r¿  rÄ  rÆ  rb   rÂ  rÃ  r3   Úcombine_channels€  sŽ    /


ÿ
ÿ
ÿ
 ÿÿrÒ  ZVertexúLeft-temporalúRight-temporalúLeft-parietalúRight-parietalúLeft-occipitalúRight-occipitalúLeft-frontalúRight-frontalzEEG 1-32z	EEG 33-64z	EEG 65-96z
EEG 97-128c              
   C   s–  ddl m} t| g d�}t|ƒd }t dd„ | d D ƒ¡}|j\}}}|t || ¡| d…  }	t ||	¡}|t || ¡d|…  }
t ||
¡}|t || ¡d|…  }t ||¡}t	||ƒ\}}t	|	|ƒ\}}t	|
|ƒ\}}t	||ƒ\}}tj
d	d
��4 t ||| ƒ¡}t |¡t |dk¡d  }W 5 Q R X tt ||¡ƒ}tj
d	d
��< t ||| ƒ¡}t |t |¡t |dk¡d  ¡}W 5 Q R X tt ||¡ƒ}t || ¡}t || ¡}|D ]>}t|||  ƒt|||  ƒk �rú| |¡ n
| |¡ �qÈ|�r^td| dd�}t|ƒdk�r^||||||||fD ]}| | d  |d ¡¡ �q>td|fd|fd|fd|fd|fd|fd|fd|fgƒS )z(Divide channels to regions by positions.r   )Úzscorer@  é   c                 S   s   g | ]}|d  dd… ‘qS r˜   r2   rf   r2   r2   r3   r4     s     z&_divide_to_regions.<locals>.<listcomp>r)   Nr  )Úinvalidg       @F)Zraise_errorrb   rÙ  rÚ  rÕ  rÖ  r×  rØ  rÓ  rÔ  )Zscipy.statsrÛ  r%   rv   r8   rt   r„   rs   r  Ú_divide_sideZerrstaterŸ   Úwhererr   rw   rº  r   re   r   )r?   Zadd_stimrÛ  r¢   Zchs_in_lober£   r]  Úyr¯  ZfrontalZ	occipitalZtemporalÚltÚrtÚlfÚrfÚloÚroZlpÚrpZzsZoutliersZl_meanZr_meanZoutlierZstim_chÚregionr2   r2   r3   Ú_divide_to_regions  sT    &."   ýré  c              
   C   s¶   t  | ¡} t  ||  ¡}| t  ||  |k ¡d  }| t  ||  |k¡d  }t  ||  |k¡d }t  t  || |ddd…  g¡¡}t  t  || |ddd…  g¡¡}t|ƒt|ƒfS )z5Make a separation between left and right lobe evenly.r   rœ   Nr   )r8   r¨   rÀ  rß  Úsortr&  rr   )Zlober]  rÀ  ÚleftÚrightZmediansr2   r2   r3   rÞ  I  s    
""rÞ  c              	   C   s¾  t | ttfƒs| g} t |tƒrXt|ddd�}t|ƒdkrRd|d |d  krRd}qxd}n |d	k	rttd
t|ƒf ƒ‚nd}|d	kr–t 	t 
t¡ddd¡}t|ddd�}dd„ | D ƒ}t|dƒ�¦}g }|D ]–}	|	 ¡ }	t|	ƒdksÆ|	d dkrìqÆ|	 d¡}
|
dk �rt d¡ qÆ|	d	|
… }| D ]>}| |¡dk�r| |	|
d d	…  d¡¡ d||<  qÆ�qqÆW 5 Q R X | ¡ D ]\}}|�sptd| ƒ‚�qptt|ƒƒ}| ¡  |dk�rºdd„ |D ƒ}|S )a  Read Neuromag Vector View channel selection from a file.

    Parameters
    ----------
    name : str | list of str
        Name of the selection. If a list, the selections are combined.
        Supported selections are: ``'Vertex'``, ``'Left-temporal'``,
        ``'Right-temporal'``, ``'Left-parietal'``, ``'Right-parietal'``,
        ``'Left-occipital'``, ``'Right-occipital'``, ``'Left-frontal'`` and
        ``'Right-frontal'``. Selections can also be matched and combined by
        spcecifying common substrings. For example, ``name='temporal`` will
        produce a combination of ``'Left-temporal'`` and ``'Right-temporal'``.
    fname : str
        Filename of the selection file (if ``None``, built-in selections are
        used).
    %(info)s Used to determine which channel naming convention to use, e.g.
        ``'MEG 0111'`` (with space) for old Neuromag systems and ``'MEG0111'``
        (without space) for new ones.
    %(verbose)s

    Returns
    -------
    sel : list of str
        List with channel names in the selection.
    Tr2   r¤  r   rm  rb   ÚnewÚoldNz0info must be an instance of Info or None, not %sz..rˆ   zmne_analyze.selrd  )rf  re  c                 S   s   i | ]
}|d “qS )Fr2   )r0   Únr2   r2   r3   r€   ˆ  s      z-read_vectorview_selection.<locals>.<dictcomp>r  ú#ú:z9":" delimiter not found in selections file, skipping linerœ   ú|z&No match for selection name "%s" foundc                 S   s   g | ]}|  d d¡‘qS )rn  rl  )rr  )r0   Úsr2   r2   r3   r4   §  s     z-read_vectorview_selection.<locals>.<listcomp>)rQ   rr   rÅ   r   r   rv   r  rÿ   ro  rµ   Údirnamers  r   ÚopenÚstripÚfindr   r?   ÚextendÚsplitr´   r    ra   rê  )r®   rM  r?   r   r¢   ÚspacingZ
name_foundZfidry   Úliner£   Zsel_name_filerï  Úfoundr2   r2   r3   Úread_vectorview_selectionW  sP    
 ÿ



rý  )F)TN)FN)N)F)F)r¯  )rº  FF)T)NNN)dÚos.pathÚpathro  Úpathlibr   r*  Úcollectionsr   Údataclassesr   rj   r   Ú	functoolsr   ÚstringÚtypingr   Únumpyr8   Údefaultsr	   r
   Úutilsr   r   r   r   r   r   r   r   r   r   Zio.constantsr   rl   r   r   r   r   r   Zio.pickr   r   r   r   r   r    r!   r"   r#   r$   r%   Zio.tagr&   Zio.writer'   Zio.projr(   rB   rW   rz   Zchannel_type_constantsr´   r‹   r·   ZFIFF_UNIT_VZFIFF_UNIT_TZFIFF_UNIT_T_MZFIFF_UNIT_MOLr‚   ZFIFF_UNIT_CELr¹   rŽ   r�   Úobjectrâ   r6  rÂ   rJ  rK  ÚTemplateZ_ft_neighbor_url_tÚ
substitutera  rb  rz  rw  r™  r‹  r©  r¥  rŠ  r¹  rÒ  Z_SELECTIONSZ_EEG_SELECTIONSré  rÞ  rý  r2   r2   r2   r3   Ú<module>   sŠ  04(
Wÿÿ     û  r   8X:ÿ
ü
ü
ü
ü
ü
ü
ü
ü
ü
ü
ü
ü
ü
ü
ü
üüüüüüüü
ü
ü
ü
ü
ü
ü
ü
ü
ü
ü
ü
ü
ü
ü
ü
ü€ › o'^'
\
;(
-9  ÿ
    þ
6