U
    f»{j‹U ã                   @   sò  d Z ddlmZ ddlmZ ddlmZ ddlZddlZddl	m
Z ddlZddl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mZmZmZmZ dd	lm Z m!Z!m"Z"m#Z#m$Z$ dd
l%m&Z&m'Z' ddl(m)Z) ddl*m+Z+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8 ddl9m:Z:m;Z; ddl<m=Z=m>Z> ddl?m@Z@ ddlAmBZB ddlCmDZDmEZEmFZF ddlGmHZHmIZImJZJ ddlKmLZLmMZMmNZN ddlOmPZP ddlQmRZRmSZSmTZT ddlUmVZV ddlWmXZXmYZYmZZZm[Z[m\Z\m]Z] ddl^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZkmlZlmmZmmnZnmoZompZpmqZqmrZrmsZsmtZtmuZumvZvmwZwmxZxmyZymzZzm{Z{m|Z| ddl}m~Z~ ddlm€Z€m�Z�m‚Z‚ dd„ Zƒd d!„ Z„d"d#„ Z…d$d%„ Z†d&d'„ Z‡d(d)„ Zˆe~G d*d+„ d+e;e$eHeIeJeMelegeke‚ƒƒZ‰dcd-d.„ZŠddd/d0„Z‹e~G d1d2„ d2e‰ƒƒZŒe~G d3d4„ d4e‰ƒƒZ�ded6d7„ZŽdfd9d:„Z�d;d<„ Z�d=d>„ Z‘ebd?g dfd@dA„ƒZ’dBdC„ Z“ebdgdDdE„ƒZ”G dFdG„ dGe•ƒZ–e~G dHdI„ dIe‰ƒƒZ—e~dhdJdK„ƒZ˜dLdM„ Z™ebdidNdO„ƒZšdjdPdQœdRdS„Z›dTdU„ ZœebdkdPddVœdWdX„ƒZ�ebdld]d^„ƒZžebdmdadb„ƒZŸdS )nz$Tools for working with epoched data.é    )Úpartial)ÚCounter©ÚdeepcopyNé   )Ú_construct_bids_filename)Ústart_and_end_fileÚstart_blockÚ	end_blockÚ	write_intÚwrite_floatÚwrite_float_matrixÚwrite_double_matrixÚwrite_complex_float_matrixÚwrite_complex_double_matrixÚwrite_idÚwrite_stringÚ_get_split_sizeÚ_NEXT_FILE_BUFFERÚ	INT32_MAX)Úread_meas_infoÚwrite_meas_infoÚ_merge_infoÚ_ensure_infos_matchÚContainsMixin)Ú	fiff_openÚ_get_next_fname)Údir_tree_find)Úread_tagÚread_tag_info)ÚFIFF)Ú_get_fname_rep)Úchannel_indices_by_typeÚchannel_typeÚpick_channelsÚ	pick_infoÚ_pick_data_channelsÚ_DATA_CH_TYPES_SPLITÚ_picks_to_idx)Ú
setup_projÚ	ProjMixin)ÚBaseRawÚ_get_ch_factors)Ú_check_origin)ÚEvokedArray)ÚrescaleÚ_log_rescaleÚ_check_baseline)ÚUpdateChannelsMixinÚSetChannelsMixinÚInterpolationMixin)ÚdetrendÚFilterMixinÚ
_check_fun)Úparallel_func)Ú_read_events_fifÚmake_fixed_length_eventsÚmatch_event_names)Úrng_uniform)Úplot_epochsÚplot_epochs_psdÚplot_epochs_psd_topomapÚplot_epochs_imageÚplot_topo_image_epochsÚplot_drop_log)Ú_check_fnameÚcheck_fnameÚloggerÚverboseÚcheck_random_stateÚwarnÚ_plÚ
sizeof_fmtÚ	SizeMixinÚcopy_function_doc_to_method_docÚ_check_pandas_installedÚ_check_preloadÚGetEpochsMixinÚ	TimeMixinÚ_prepare_read_metadataÚ_prepare_write_metadataÚ_check_event_idÚ_gen_eventsÚ_check_optionÚ_check_combineÚ_build_data_frameÚ_check_pandas_index_argumentsÚ_convert_timesÚ_scale_dataframe_dataÚ_check_time_formatÚobject_sizeÚ_on_missingÚ_validate_typeÚ_ensure_eventsÚ
_path_like)Úfill_doc)Ú_write_annotationsÚ_read_annotations_fifÚEpochAnnotationsMixinc                 C   s0   t ƒ }dD ] }t| |d ƒ}|d k	r
|||< q
|S )N)ÚrejectÚflatÚreject_tminÚreject_tmax)ÚdictÚgetattr)ÚepochsÚreject_paramsÚkeyÚval© ro   úI/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/epochs.pyÚ_pack_reject_paramsG   s    
rq   c              	   C   sÚ   t  |¡\}}|dkrV|dkr.d|||f }n(|dks:t‚t|||dd�}t||d� d}	||d	 k r¬|dkr‚d||d	 |f }	n |dksŽt‚t|||d	 dd�}	|d	 }
nd}
t|ƒ�}t|| |||	|
ƒ W 5 Q R X dS )
zˆSplit epochs.

    Anything new added to this function also needs to be added to
    BaseEpochs.save to account for new file sizes.
    r   Úneuromagz%s-%d%sZbidsF)Úvalidate)Ú	overwriteNr   )ÚopÚsplitextÚAssertionErrorr   rC   r   Ú
_save_part)rk   ÚfnameÚpart_idxÚn_partsÚfmtÚsplit_namingrt   ÚbaseÚextÚ
next_fnameÚnext_idxÚfidro   ro   rp   Ú_save_splitP   s*    ÿÿ

rƒ   c                 C   sZ  |j }|d }t| tjƒ t| tjƒ |d d k	rDt| tj|d ƒ t| |ƒ t| tjƒ t| tj	ƒ | 
¡ }td|ddgƒ t |¡r¤|dkr–t}	q¾|dkr¾t}	n|dkr²t}	n|dkr¾t}	t|dg ƒ}
|
d k	rät|
ƒrät| |
ƒ t| tjƒ t| tj|jjƒ t| tjt|jƒƒ t| tjƒ |jd k	�r^t| tj ƒ t!|jƒ}t| tj|ƒ t| tj ƒ t"t#|j$|d  ƒƒ}|t|j%ƒ d }t| tj&|ƒ t| tj'|ƒ t(| tj)|j*ƒ |j+d k	�rä|j+\}}t(| tj,|ƒ t(| tj-|ƒ t .|d ¡}t/|d ƒD ]2}d	|d
 | d |d
 |  0dd	¡  ||< �qþ||tj1d d …tj1f 9 }|	| tj2|ƒ ||tj1d d …tj1f  }t| tj3t4 5|j6¡ƒ t7|ƒ}|�r¬t| tj8t4 5|¡ƒ t| tj9|j:ƒ |d k	�r2|dk�r2t| tj;ƒ t| tj<tj=ƒ t| tj>t? @|¡ƒ |d k	�rt| tjA|ƒ t| tjB|ƒ t| tj;ƒ t| tj	ƒ t| tjƒ t| tjƒ d S )NÚmeas_idr|   ÚsingleÚdoubleÚannotationsÚsfreqr   Únchanç      ð?ÚchsÚcalÚscale)CÚinfor	   r    Z
FIFFB_MEASr   ZFIFF_BLOCK_IDZFIFF_PARENT_BLOCK_IDr   ÚFIFFB_PROCESSED_DATAÚFIFFB_MNE_EPOCHSÚget_datarU   ÚnpÚiscomplexobjr   r   r   r   rj   Úlenrb   ZFIFFB_MNE_EVENTSr   ZFIFF_MNE_EVENT_LISTÚeventsÚTr   ÚFIFF_DESCRIPTIONÚ_event_id_stringÚevent_idr
   ÚmetadataÚFIFFB_MNE_METADATArR   ÚintÚroundÚtminÚtimesÚFIFF_FIRST_SAMPLEÚFIFF_LAST_SAMPLEr   ÚFIFF_MNE_EPOCHS_RAW_SFREQÚ
_raw_sfreqÚbaselineÚFIFF_MNE_BASELINE_MINÚFIFF_MNE_BASELINE_MAXÚemptyÚrangeÚgetÚnewaxisÚ
FIFF_EPOCHÚFIFF_MNE_EPOCHS_DROP_LOGÚjsonÚdumpsÚdrop_logrq   ÚFIFF_MNE_EPOCHS_REJECT_FLATÚFIFF_MNE_EPOCHS_SELECTIONÚ	selectionZ	FIFFB_REFZFIFF_REF_ROLEZFIFFV_ROLE_NEXT_FILEZFIFF_REF_FILE_NAMEru   ÚbasenameZFIFF_REF_FILE_IDZFIFF_REF_FILE_NUM)r‚   rk   r|   r{   r€   r�   rŽ   r„   ÚdataZwrite_functionr‡   rš   ÚfirstÚlastÚbminÚbmaxZdecalÚkrl   ro   ro   rp   rx   r   sŽ    




ÿ
ÿÿÿ
rx   c                 C   s   d  dd„ |  ¡ D ƒ¡S )Nú;c                 S   s    g | ]\}}|d  t |ƒ ‘qS )ú:©Ústr©Ú.0r¹   Úvro   ro   rp   Ú
<listcomp>Û   s     z$_event_id_string.<locals>.<listcomp>)ÚjoinÚitems©r™   ro   ro   rp   r˜   Ú   s    r˜   c              	      s  |  ¡ }|   ¡ }tƒ }tj| dd…df dd�\}}||dk D �]¤}| dd…df |k ¡ d }t | |df ¡}	t|	ƒdkrˆ|	d nd}
t | |df ¡}t|ƒdkr¶|d }� nþt| ¡ ƒ‰ t| ¡ ƒ‰‡ ‡fdd„|D ƒ}|D ](}t| 	d	¡ƒt|ƒkræ|| } �q´qæt tj
t| ¡ ƒ| dd…dd…f  ¡ fdd
�¡}|d dk�rXd}nBt |¡}t |dk¡d }t|ƒdk�r†dn|d }|| d }d	 t|ƒ¡}t|ƒ||< |
||d df< |||d df< | |dd… ¡ q@t ||d¡}t ||d¡}|||fS )zMerge repeated events.Nr   T)Zreturn_countsr   é   c                    s   g | ]}ˆ ˆ  |¡ ‘qS ro   )Úindex)r¿   Úvalue©Zevent_id_keysZevent_id_valsro   rp   rÁ   ú   s   ÿz!_merge_events.<locals>.<listcomp>ú/©Úaxiséÿÿÿÿ)ÚcopyÚlistr’   ÚuniqueÚnonzeror”   ÚkeysÚvaluesÚsetÚsplitÚconcatenateÚflattenÚdiffÚwhererÂ   Úsortedrœ   ÚextendÚdelete)r•   r™   r²   Ú
new_eventsZevent_idxs_to_deleteÚunique_eventsÚcountsÚevÚidxsZunique_priorsZ	new_priorZev_valsZnew_event_valZnew_key_compsrm   ZdiffsÚidxZnew_event_id_keyÚnew_selectionro   rÈ   rp   Ú_merge_eventsÞ   sR    ÿÿþÿ
rã   c                    sf  t | ƒt |ƒkst‚t |¡}tj| dd…df dd�\}}t |ƒt | ƒkrX| |||fS td|dddgƒ t|ƒ}|dkr„td	ƒ‚n |dkrÒt 	d
¡ | | }|| }t 
||¡}	|	D ]}
||
 d ||
< q¶|}nR|dk�r$t 	d¡ t| ||ƒ\}}}t 
||¡}	|	D ]}
||
 d ||
< �q|}t|ƒ}|dd…dd…f  ¡ ‰ ‡ fdd„| ¡ D ƒ}||||fS )zMHandle repeated events.

    Note that drop_log will be modified inplace
    Nr   T)Zreturn_indexÚevent_repeatedÚerrorÚdropÚmergezUEvent time samples were not unique. Consider setting the `event_repeated` parameter."ziMultiple event values for single event times found. Keeping the first occurrence and dropping all others.)zDROP DUPLICATEzlMultiple event values for single event times found. Creating new event value to reflect simultaneous events.)zMERGE DUPLICATEr   c                    s   i | ]\}}|ˆ kr||“qS ro   ro   r¾   ©rÑ   ro   rp   Ú
<dictcomp>O  s       z*_handle_event_repeated.<locals>.<dictcomp>)r”   rw   r’   ZasarrayrÏ   rU   rÎ   ÚRuntimeErrorrE   rŽ   Ú	setdiff1drã   ÚtuplerÖ   rÃ   )r•   r™   rä   r²   r¯   rÝ   Z	u_ev_idxsrÜ   râ   Zdrop_ev_idxsrá   ro   rè   rp   Ú_handle_event_repeated#  s:    





ÿrí   c                       s‚  e Zd ZdZed‚ddddœdd„ƒZdd„ Zdd„ Zdd„ Zedƒddœdd„ƒZ	dd„ Z
ed„dd„ƒZed…dd„ƒZd†dd„Zd‡dd „Zedˆd"d#„ƒZed‰d$d%„ƒZdŠd&d'„Zed(d)„ ƒZd*d+„ Zed,d-„ ƒZeeƒd‹ddd1œd2d3„ƒZeeƒd4ejddd	dd	dd5ddd6d7d8d9dd/ddd	dddd:dfd;d<„ƒZeeƒdŒd?d@„ƒZee ƒd�dGdH„ƒZ!edŽdJdK„ƒZ"d�dMdN„Z#ee$ƒd�dQdR„ƒZ$ee%ƒd‘dSdT„ƒZ&ed’dVdW„ƒZ'd“dXdY„Z(dZd[„ Z)ed”ddddd\œd]d^„ƒZ*ed_d`„ ƒZ+ed•dadb„ƒZ,ed–dcdd„ƒZ-ededf„ ƒZ.dgdh„ Z/didj„ Z0ed—‡ fdkdl„	ƒZ1dmdn„ Z2dodp„ Z3ed˜dtdu„ƒZ4ed™d	ddvœdwdx„ƒZ5dšdzd{„Z6ed›ddœd|d}„ƒZ7dœd€d�„Z8‡  Z9S )�Ú
BaseEpochsa¶  Abstract base class for `~mne.Epochs`-type classes.

    .. warning:: This class provides basic functionality and should never be
                 instantiated directly.

    Parameters
    ----------
    %(info_not_none)s
    data : ndarray | None
        If ``None``, data will be read from the Raw object. If ndarray, must be
        of shape (n_epochs, n_channels, n_times).
    %(events_epochs)s
    %(event_id)s
    %(epochs_tmin_tmax)s
    %(baseline_epochs)s
        Defaults to ``(None, 0)``, i.e. beginning of the the data until
        time point zero.
    %(raw_epochs)s
    %(picks_all)s
    %(reject_epochs)s
    %(flat)s
    %(decim)s
    %(epochs_reject_tmin_tmax)s
    %(detrend_epochs)s
    %(proj_epochs)s
    %(on_missing_epochs)s
    preload_at_end : bool
        %(epochs_preload)s
    selection : iterable | None
        Iterable of indices of selected epochs. If ``None``, will be
        automatically generated, corresponding to all non-zero events.
    drop_log : tuple | None
        Tuple of tuple of strings indicating which epochs have been marked to
        be ignored.
    filename : str | None
        The filename (if the epochs are read from disk).
    %(metadata_epochs)s
    %(event_repeated_epochs)s
    %(verbose)s
    raw_sfreq : float
        The original Raw object sampling rate. If None, then it is set to
        ``info['sfreq']``.
    annotations : instance of mne.Annotations | None
        Annotations to set.

    Notes
    -----
    The ``BaseEpochs`` class is public to allow for stable type-checking in
    user code (i.e., ``isinstance(my_epochs, BaseEpochs)``) but should not be
    used as a constructor for Epochs objects (use instead :class:`mne.Epochs`).
    Nçš™™™™™É¿ç      à?©Nr   r   TÚraiseFrå   )rF   Ú	raw_sfreqr‡   c          )         s\  |d k	r4t |ƒ}| ¡ }|tkr4tdt› d|› �ƒ‚t||ƒ}|ˆ_~|d k	�rzˆj ¡ D ]2\}}||d d …df krZd||f }t||ƒ qZt 	t
|ƒ¡ˆ_|ˆ_tjjˆˆ dd� ~tˆj ¡ ƒ}t t ˆjd d …df |¡¡d } |d krø| }nt |t¡}|jt
| ƒfk�r*td| j|jf ƒ‚|ˆ_|d k�rnt‡fd	d
„ttt
ˆjƒtˆjƒd ƒƒD ƒƒˆ_n|ˆ_ˆj|  ˆ_tˆjˆj|ˆjˆjƒ\ˆ_ˆ_ˆ_ˆ_t t |ˆj¡¡d }!tˆ tƒ�rà‡ fdd„|!D ƒ‰ nˆ d k	�rôˆ j|! ‰ tjjˆd dd� ˆ ˆ_Š t
ˆjƒ}"|"dk�rVt ˆj tj¡d d …df ¡  ¡ dk�rVt!dt"ƒ |"dk�rpt# $d|" ¡ ntdƒ‚ntƒ ˆ_t g t¡ˆ_ˆ ˆ_|dk�s¬t|t%ƒ�r´tdƒ‚|ˆ_&|ˆ_'| (¡  t)||	dddd�ˆ_*t+|ˆj*ƒˆ_$~dˆ_,|d k�rdˆ_-d ˆ_.dˆ_/nx|dk�st0‚|j1dk�sP|jd t2|| ˆj$d  ƒd k�rXt3dƒ‚|jd t
ˆjƒk�rvtdƒ‚dˆ_-|ˆ_.dˆ_/d ˆ_4||k�r tdƒ‚t5ˆj$d ƒ}#tt2||# ƒƒ}$t 	|$tt2||# ƒƒd ¡|# ˆ_6ˆ 7ˆj6¡ |d k	�r&t 8||¡�rˆj9}n||k �r&td|› d�ƒ‚|d k	�r`t 8||¡�rFˆj:}n||k�r`td|› d�ƒ‚|d k	�r”|d k	�r”||k�r”td|› d |› d�ƒ‚|ˆ_;|ˆ_<dˆ_=ˆ >|¡ t?|ˆj@ˆj$d d!�ˆ_AˆjAd k	�rˆjA|k�rt# $d"ˆjAd › d#ˆjAd › d$�¡ t# $tBˆjAƒ¡ d ˆ_Cd ˆ_Dˆ E|
|¡ dd%dg}%||%k�rPtd&|%|f ƒ‚|d%k�rldˆ_Ft# $d'¡ ndˆ_FˆjF�r~dn|}&tGˆj$d|&d(�\ˆ_Hˆ_$|�rÊˆj.d k�s°t0‚ˆj-dk�sÀt0‚ˆ I¡  nJ|dk�rˆjHd k	�r|d k	�rtJˆj.ƒD ]\}'}(t KˆjH|(¡ˆj.|'< �qô|d k	�r&tL|ƒn|ˆ_M|d k�r@ˆj$d }|ˆ_Nˆ (¡  ˆ O|¡ d S ))Nz$events array values must not exceed z, got rÅ   z-No matching events found for %s (event id %i)F©rF   r   z'selection must be shape %s got shape %sc                 3   s    | ]}|ˆ j krd ndV  qdS )ro   ©ZIGNOREDN)r²   ©r¿   r¹   ©Úselfro   rp   Ú	<genexpr>¼  s   ÿz&BaseEpochs.__init__.<locals>.<genexpr>r   c                    s   g | ]}ˆ | ‘qS ro   ro   )r¿   Ús)rš   ro   rp   rÁ   Í  s     z'BaseEpochs.__init__.<locals>.<listcomp>zLThe events passed to the Epochs constructor are not chronologically ordered.z%d matching events foundzNo desired events found.)Nr   r   zdetrend must be None, 0, or 1Úallro   )ÚnoneÚexcludeZallow_emptyTé   rˆ   zbad data shapez8The number of epochs and the number of events must matchz)tmin has to be less than or equal to tmaxz-reject_tmin needs to be None or >= tmin (got ú)z-reject_tmax needs to be None or <= tmax (got zreject_tmin (z) needs to be  < reject_tmax (©rŸ   rˆ   zSetting baseline interval to [ú, z] secZdelayedz "proj" must be one of %s, not %szEntering delayed SSP mode.©Úactivate)Pr_   Úmaxr   Ú
ValueErrorrS   r™   rÃ   r]   r’   Úaranger”   r²   r•   rO   rš   ÚfsetrÎ   rÒ   rØ   Úin1dÚarrayrœ   Úshaperì   r¨   r¯   rí   Ú
isinstanceÚilocr×   ÚastypeZint64ÚminrH   ÚRuntimeWarningrE   rŽ   Úboolr5   Ú_rawÚ_check_consistencyr(   Úpicksr%   Ú_currentÚpreloadÚ_dataÚ_do_baselinerw   Úndimr�   rê   Ú_offsetÚfloatÚ
_raw_timesÚ
_set_timesÚiscloserž   Útmaxrg   rh   Ú_decimZdecimater1   rŸ   r¤   r0   re   rf   Ú_reject_setupÚ_do_delayed_projr)   Ú
_projectorÚ	load_dataÚ	enumerateÚdotr½   Ú	_filenamer£   Úset_annotations))rø   rŽ   r´   r•   r™   rž   r  r¤   Úrawr  re   rf   Údecimrg   rh   r5   ÚprojÚ
on_missingÚpreload_at_endr²   r¯   Úfilenamerš   rä   rF   ró   r‡   Z
events_maxrm   rn   ÚmsgrÒ   ÚselectedÚsubÚn_eventsrˆ   Ú	start_idxZ
valid_projr  ÚiiÚepochro   )rš   rø   rp   Ú__init__Œ  s:   
ÿ

ÿ$
ÿ
ÿþ   þÿ



*ÿ


ÿ
ÿÿ
ÿÿ





ÿ$

ÿ
ÿ
 

zBaseEpochs.__init__c                 C   s¾   t | dƒr:t| jƒt| jƒks"t‚t| jƒt| jƒks:t‚t| jƒtdd„ | jD ƒƒks\t‚t | dƒsjt‚| jjd rzt‚t	| jt
ƒsŠt‚tdd„ | jD ƒƒs¢t‚tdd„ | jD ƒƒsºt‚dS )	z"Check invariants of epochs object.r•   c                 s   s   | ]}t |ƒd kV  qdS ©r   N©r”   )r¿   Údlro   ro   rp   rù   _  s     z0BaseEpochs._check_consistency.<locals>.<genexpr>Ú_times_readonlyZ	WRITEABLEc                 s   s   | ]}t |tƒV  qd S ©N©r  rì   )r¿   Úlogro   ro   rp   rù   c  s     c                 s   s"   | ]}|D ]}t |tƒV  q
qd S r:  ©r  r½   )r¿   r<  rú   ro   ro   rp   rù   d  s       N)Úhasattrr”   r²   r•   rw   r¯   ÚsumrŸ   Úflagsr  rì   rû   r÷   ro   ro   rp   r  Y  s    

ÿ
zBaseEpochs._check_consistencyc                 C   s2   t  t| jƒ¡| _tƒ ft| jƒ | _|  ¡  dS )a�  Reset the drop_log and selection entries.

        This method will simplify ``self.drop_log`` and ``self.selection``
        so that they are meaningless (tuple of empty tuples and increasing
        integers, respectively). This can be useful when concatenating
        many Epochs instances, as ``drop_log`` can accumulate many entries
        which can become problematic when saving.
        N)r’   r  r”   r•   r²   rì   r¯   r  r÷   ro   ro   rp   Úreset_drop_log_selectionf  s    	z#BaseEpochs.reset_drop_log_selectionc                 C   s`   | j r
| S |  ¡ | _d| _ d| _tdddƒ| _d| _| j| _| jj	d t
| jƒksVt‚d| _| S )züLoad the data if not already preloaded.

        Returns
        -------
        epochs : instance of Epochs
            The epochs object.

        Notes
        -----
        This function operates in-place.

        .. versionadded:: 0.10.0
        TFNr   rÌ   )r  Ú	_get_datar  r  ÚsliceÚ_decim_slicer  rŸ   r  r
  r”   rw   r  r÷   ro   ro   rp   r#  s  s    
zBaseEpochs.load_datarô   c                C   s~   t || j| jd d�}| jr`| jdk	r6|dkr6tdƒ‚d| _| j}t| j	| j|d|d� d| _nt
 t|ƒ¡ d| _|| _| S )a  Baseline correct epochs.

        Parameters
        ----------
        %(baseline_epochs)s
            Defaults to ``(None, 0)``, i.e. beginning of the the data until
            time point zero.
        %(verbose)s

        Returns
        -------
        epochs : instance of Epochs
            The baseline-corrected Epochs object.

        Notes
        -----
        Baseline correction can be done multiple times, but can never be
        reverted once the data has been loaded.

        .. versionadded:: 0.10.0
        rˆ   r   NzSYou cannot remove baseline correction from preloaded data once it has been applied.TF)rÍ   r  )r1   rŸ   rŽ   r  r¤   rê   r  Ú_detrend_picksr/   r  rE   r0   )rø   r¤   rF   r  ro   ro   rp   Úapply_baseline�  s    ÿzBaseEpochs.apply_baselinec              	   C   s   t | jƒ}|dk	rt|ƒntƒ }|dk	r0t|ƒntƒ }t||fdƒD ]V\}}t|tƒsftdt|ƒ ƒ‚t| 	¡ ƒt| 	¡ ƒ }t
|ƒdkrDtd||f ƒ‚qD| 	¡ D ]P}t
|| ƒdkr¤t | |tj¡¡sÜ| |d¡dkr¤td| ¡ | ¡ f ƒ‚q¤t||fdƒD ]B\}}| ¡ D ].\}}|dk�s0|dk �rtd	||f ƒ‚�q�q| jdk	�rZ| jntƒ }	| jdk	�rr| jntƒ }
d
}t|	ƒt|ƒ D ]}|	| ||< �qŒ|D ]B}||	k�r¤|| |	| k�r¤t|jd||| |	| dd�ƒ‚�q¤t|
ƒt|ƒ D ]}|
| ||< �qø|D ]B}||
k�r|| |
| k �rt|jd||| |
| dd�ƒ‚�qd| _|| _t
|ƒdk�rr|nd| _t
|ƒdk�rŠ|nd| _| jdk�r°| jdk�r°d| _nl| jdk�rÂd}nt | j| jk¡d }|d }| jdk�ròd}nt | j| jk¡d }|d }t||ƒ| _dS )z1Set self._reject_time and self._channel_type_idx.N)re   rf   z,reject and flat must be dict or None, not %sr   z%Unknown channel types found in %s: %srÌ   z/No %s channel found. Cannot reject based on %s.)Z	RejectionZFlatz(%s value must be a number >= 0, not "%s"zq{kind}["{key}"] == {new} {op} {old} (old value), new {kind} values must be at least as stringent as previous onesre   ú>)Úkindrm   ÚnewÚoldru   rf   ú<F)r"   rŽ   r   ri   Úzipr  Ú	TypeErrorÚtyperÓ   rÑ   r”   ÚKeyErrorr’   Úisfiniter©   Úinfr  ÚupperrÃ   re   rf   ÚformatÚ_bad_droppedÚ_channel_type_idxrg   rh   Ú_reject_timerÐ   rŸ   rC  )rø   re   rf   rá   ÚrejrH  Úbadsrm   rn   Z
old_rejectZold_flatZbad_msgZreject_iminrà   Zreject_imaxro   ro   rp   r   ¹  s€    

ÿÿ$ÿÿÿ ÿÿ ÿÿzBaseEpochs._reject_setupc              	   C   s˜   t |tƒrd|ffS |dkr dS t| jƒ}|jd |k r<dS | jdkrT| jdkrTdS | jdk	rp|dd…| jf }t|| j	| j
| j| jd| jd d	�S dS )
zDetermine if epoch is good.FN)F)ZNO_DATAr   )F)Z	TOO_SHORT©TNTrX  )Úfull_reportÚ
ignore_chs)r  r½   r”   rŸ   r
  re   rf   rV  Ú_is_goodÚch_namesrU  rŽ   )rø   r´   rF   Ún_timesro   ro   rp   Ú_is_good_epoch	  s"    



  þzBaseEpochs._is_good_epochc                 C   sŽ   |dkst |tƒr|S | jdk	rFt| jdd�}t|| | jdd�||< | jrdt|| j| j|ddd� |dd…| j	f }| j
dk	rŠ|| j
7 }|S )z`Aux Function: detrend, baseline correct, offset, decim.

        Note: operates inplace
        Nro   ©rý   r   rÊ   F)r  rÍ   rF   )r  r½   r5   r&   rŽ   r  r/   r  r¤   rD  r  )rø   r4  r  rF   Z	use_picksro   ro   rp   Ú_detrend_offset_decim  s$    
    þ

z BaseEpochs._detrend_offset_decimc                 c   sz   |   ¡  z|  d¡}W n tk
r.   Y qvY nX |\}}| jd }| j}|r^t| jƒ}| ¡ }t|||t|ƒd�V  qdS )a–  Iterate over epochs as a sequence of Evoked objects.

        The Evoked objects yielded will each contain a single epoch (i.e., no
        averaging is performed).

        This method resets the object iteration state to the first epoch.

        Parameters
        ----------
        copy : bool
            If False copies of data and measurement info will be omitted
            to save time.
        Tr   )ÚcommentN)	Ú__iter__Ú__next__ÚStopIterationrŸ   rŽ   r   rÍ   r.   r½   )rø   rÍ   Úoutr´   r™   rž   rŽ   ro   ro   rp   Úiter_evoked=  s    


zBaseEpochs.iter_evokedc                    s  t  d¡ ˆdkr*tˆjg d�}ˆ |¡‰tˆjˆjd�}t|ƒtˆjƒk rì‡fdd„|D ƒ}ttˆjƒ 	|¡ƒ‰ ‡fdd„ˆ D ƒ}‡fdd„|D ƒ‰‡fd	d„ˆD ƒ}t|ƒd
krØd 
‡ fdd„|D ƒ¡}td| ƒ‚t  dd 
ˆ ¡ ¡ tˆjƒtˆjƒk�s t t ˆjˆj ¡¡dk�r(tdƒ‚ˆj�s@ˆj�r@tdƒ ˆj�r\ˆj�s\ˆ ¡  ¡ ‰‡‡fdd„|D ƒ}ˆj�r²ˆjdd…|dd…f  ˆj| ddd…dd…f 8  < nFˆjdk�ràtjtˆjƒtˆjƒftjd�ˆ_ˆj|  ˆj| 8  < t  d¡ ˆS )a´  Subtract an evoked response from each epoch.

        Can be used to exclude the evoked response when analyzing induced
        activity, see e.g. [1]_.

        Parameters
        ----------
        evoked : instance of Evoked | None
            The evoked response to subtract. If None, the evoked response
            is computed from Epochs itself.

        Returns
        -------
        self : instance of Epochs
            The modified instance (instance is also modified inplace).

        References
        ----------
        .. [1] David et al. "Mechanisms of evoked and induced responses in
               MEG/EEG", NeuroImage, vol. 31, no. 4, pp. 1580-1591, July 2006.
        zSubtracting Evoked from EpochsNr`  )Úincludec                    s   g | ]}ˆ j | ‘qS ro   ©r]  ©r¿   r3  ©Úevokedro   rp   rÁ   {  s     z.BaseEpochs.subtract_evoked.<locals>.<listcomp>c                    s   g | ]}ˆ j  |¡‘qS ro   ©r]  rÆ   )r¿   Úchr÷   ro   rp   rÁ   }  s     c                    s   g | ]}t ˆ j|ƒ‘qS ro   )r#   rŽ   )r¿   rá   r÷   ro   rp   rÁ   ~  s     c                    s   g | ]}|t krˆ  |¡‘qS ro   )r'   rÆ   )r¿   Út)Ú
diff_typesro   rp   rÁ     s
     ÿ r   r  c                    s   g | ]}ˆ | ‘qS ro   ro   rj  )Údiff_chro   rp   rÁ   ‚  s     zBThe following data channels are missing in the evoked response: %szB    The following channels are not included in the subtraction: %sgH¯¼šò×z>z=Epochs and Evoked object do not contain the same time points.z,Evoked has SSP applied while Epochs has not.c                    s   g | ]}ˆj  ˆ j | ¡‘qS ro   rm  rj  )rl  rø   ro   rp   rÁ   •  s     ©Údtypez[done])rE   rŽ   r&   Úaverager$   r]  r”   rÎ   rÓ   Ú
differencerÂ   r  rŸ   r’   r  Úabsr*  rH   rÍ   Z
apply_projr  r  r´   r  ÚzerosÚfloat64)rø   rl  r  Zsel_chZdiff_idxZbad_idxZbad_strZep_picksro   )rq  rp  rl  rø   rp   Úsubtract_evoked[  sJ    

ÿÿÿ:ÿ
zBaseEpochs.subtract_evokedÚmeanc                 C   sP   |r>t ƒ }| j ¡ D ]&}| | j||d�}||_| |¡ qn| j||d�}|S )aÜ  Compute an average over epochs.

        Parameters
        ----------
        %(picks_all_data)s
        method : str | callable
            How to combine the data. If "mean"/"median", the mean/median
            are returned.
            Otherwise, must be a callable which, when passed an array of shape
            (n_epochs, n_channels, n_time) returns an array of shape
            (n_channels, n_time).
            Note that due to file type limitations, the kind for all
            these will be "average".
        %(by_event_type)s

        Returns
        -------
        %(evoked_by_event_type_returns)s

        Notes
        -----
        Computes an average of all epochs in the instance, even if
        they correspond to different conditions. To average by condition,
        do ``epochs[condition].average()`` for each condition separately.

        When picks is None and epochs contain only ICA channels, no channels
        are selected, resulting in an error. This is because ICA channels
        are not considered data channels (they are of misc type) and only data
        channels are selected when picks is None.

        The ``method`` parameter allows e.g. robust averaging.
        For example, one could do:

            >>> from scipy.stats import trim_mean  # doctest:+SKIP
            >>> trim = lambda x: trim_mean(x, 0.1, axis=0)  # doctest:+SKIP
            >>> epochs.average(method=trim)  # doctest:+SKIP

        This would compute the trimmed mean.
        )r  Úmode)rÎ   r™   rÑ   Ú_compute_aggregaterb  Úappend)rø   r  ÚmethodÚby_event_typeZevokedsZ
event_typerß   ro   ro   rp   rt  £  s    )
ÿzBaseEpochs.averagec                 C   s   | j |d|d�S )zÓCompute standard error over epochs.

        Parameters
        ----------
        %(picks_all_data)s
        %(by_event_type)s

        Returns
        -------
        %(std_err_by_event_type_returns)s
        Ústd)r  r~  r  )rt  )rø   r  r  ro   ro   rp   Ústandard_error×  s    ÿzBaseEpochs.standard_errorc                 C   sº  |dkr>dd„ | j D ƒ}t |¡r,tdƒ‚nt |¡r>tdƒ t| j ƒ}t| jƒ}| jrÆt| j	ƒ}t
|dd�}|| jƒ}t| j	ƒt| jƒks�t‚|j| jjdd… krÄtd	 |j| jjdd… ¡ƒ‚nº|d
krÖtdƒ‚t ||f¡}d}| D ],}	t |	¡�r| tj¡}||	7 }|d7 }qì|dk�r.|| }n| tj¡ |dk�r€| ¡ }
| d¡ | D ]}	||	|
 d 7 }�qZt || ¡}|dk�ržd}|t |¡ }nd}|  || j|||| j¡S )z?Compute the mean, median, or std over epochs and return Evoked.Nc                 S   s   g | ]}|  d ¡‘qS )ZICA)Ú
startswith©r¿   Úxro   ro   rp   rÁ   ì  s     z1BaseEpochs._compute_aggregate.<locals>.<listcomp>z<picks must be specified (i.e. not None) for ICA channel datazEICA channels will not be included unless explicitly selected in picks)rz  Zmedianr€  )Zvalidr   zLYou passed a function that resulted n data of shape {}, but it should be {}.>   rz  r€  zGIf data are not preloaded, can only compute mean or standard deviation.r   r€  ç        rÅ   r�  rt  )r]  r’   rû   rM  ÚanyrH   r”   rŸ   r  r•   rV   r  rw   r
  rê   rS  r  rw  r“   r  Ú
complex128ÚfillÚnanrÍ   ÚsqrtÚ_evoked_from_epoch_datarŽ   Ú_name)rø   r  r{  Z	check_ICAÚ
n_channelsr^  r1  Úfunr´   ÚeZ	data_meanrH  ro   ro   rp   r|  ç  s\    






 þÿ





 ÿzBaseEpochs._compute_aggregatec                 C   s„   t | jƒdkr"tt| j ¡ ƒƒ}n^t| jdd…df ƒ}tƒ }| j ¡ D ],\}}| 	dt
|| ƒt | jƒ |f ¡ qHd |¡}|S )z5Give a nice string representation based on event ids.r   NrÅ   u
   %.2f Ã— %sz + )r”   r™   ÚnextÚiterrÑ   r   r•   rÎ   rÃ   r}  r  rÂ   )rø   rb  ÚcountÚcommentsrm   rÇ   ro   ro   rp   rŒ  $  s     ÿ

zBaseEpochs._namec              	      s˜   t |ƒ}t||| jd |||dd�‰ | jˆ _ˆ  | j ¡ ¡ t| j|ddƒ}‡ fdd„|D ƒ}ˆ  |¡ t	ˆ jd ƒdkr‚t
d	ƒ‚ˆ jd
k r”tdƒ ˆ S )z(Create an evoked object from epoch data.r   N)rž   rb  ÚnaverH  r¤   Zdata_or_icaro   c                    s   g | ]}ˆ j | ‘qS ro   ri  ©r¿   Úprk  ro   rp   rÁ   A  s     z6BaseEpochs._evoked_from_epoch_data.<locals>.<listcomp>r]  z%No data channel found when averaging.r   z3evoked object is empty (based on less than 1 epoch))r   r.   rŸ   r¤   r  rÍ   r(   rŽ   r$   r”   r  r”  rH   )rø   r´   rŽ   r  r1  rH  rb  r]  ro   rk  rp   r‹  2  s       ÿ

z"BaseEpochs._evoked_from_epoch_datac                 C   s
   | j d S )zChannel names.r]  ©rŽ   r÷   ro   ro   rp   r]  L  s    zBaseEpochs.ch_namesé   ÚautorN  )ÚthemeÚoverview_modec                C   s6   t | |||||||||	|
||||||||||||d�S )N)r  ÚscalingsÚn_epochsr�  Útitler•   Úevent_colorÚorderÚshowÚblockr)  Ú	noise_covÚ	butterflyÚshow_scrollbarsÚshow_scalebarsÚepoch_colorsr™   Úgroup_byÚ
precomputeÚ
use_openglrš  r›  )r=   )rø   r  rœ  r�  r�  rž  r•   rŸ  r   r¡  r¢  r)  r£  r¤  r¥  r¦  r§  r™   r¨  r©  rª  rš  r›  ro   ro   rp   ÚplotQ  s,              özBaseEpochs.plotr   ÚlengthÚblackZlinearr€  g…ëQ¸Õ?rX  c                 C   s<   t | |||||||||	|
|||||||||||||||d�S )N)ÚfminÚfmaxrž   r  r*  Ú	bandwidthÚadaptiveÚlow_biasÚnormalizationr  ÚaxÚcolorÚxscaleÚ	area_modeÚ
area_alphaÚdBÚestimater¡  Ún_jobsrt  Ú
line_alphaÚspatial_colorsÚsphererý   rF   )r>   )rø   r®  r¯  rž   r  r*  r°  r±  r²  r³  r  r´  rµ  r¶  r·  r¸  r¹  rº  r¡  r»  rt  r¼  r½  r¾  rý   rF   ro   ro   rp   Úplot_psde  s0    
             ÷zBaseEpochs.plot_psdÚhead©NNc                 C   s4   t | |||||||||	|
|||||||||||d�S )N)Úbandsrž   r  r*  r°  r±  r²  r³  Úch_typeÚcmapÚagg_funr¹  r»  Ú	normalizeÚcbar_fmtÚoutlinesÚaxesr¡  r¾  ÚvlimrF   )r?   )rø   rÂ  rž   r  r*  r°  r±  r²  r³  rÃ  rÄ  rÅ  r¹  r»  rÆ  rÇ  rÈ  rÉ  r¡  r¾  rÊ  rF   ro   ro   rp   Úplot_psd_topomapx  s0                    úzBaseEpochs.plot_psd_topomapr…  ÚRdBu_rçffffffî?rü   r¹   Úwc                 C   s(   t | |||||||||	|
|||||d�S )N)ÚlayoutÚsigmaÚvminÚvmaxÚcolorbarr   rÄ  Úlayout_scalerž  rœ  ÚborderÚfig_facecolorÚfig_backgroundÚ
font_colorr¡  )rA   )rø   rÏ  rÐ  rÑ  rÒ  rÓ  r   rÄ  rÔ  rž  rœ  rÕ  rÖ  r×  rØ  r¡  ro   ro   rp   Úplot_topo_imageˆ  s$               ûzBaseEpochs.plot_topo_imageÚexistingc                 C   sj   |dkr |dkr| j rdS | j}|dkr.| j}tdd„ ||fD ƒƒrLtdƒ‚|  ||¡ | jd|d� | S )aL  Drop bad epochs without retaining the epochs data.

        Should be used before slicing operations.

        .. warning:: This operation is slow since all epochs have to be read
                     from disk. To avoid reading epochs from disk multiple
                     times, use :meth:`mne.Epochs.load_data()`.

        .. note:: To constrain the time period used for estimation of signal
                  quality, set ``epochs.reject_tmin`` and
                  ``epochs.reject_tmax``, respectively.

        Parameters
        ----------
        %(reject_drop_bad)s
        %(flat_drop_bad)s
        %(verbose)s

        Returns
        -------
        epochs : instance of Epochs
            The epochs with bad epochs dropped. Operates in-place.

        Notes
        -----
        Dropping bad epochs can be done multiple times with different
        ``reject`` and ``flat`` parameters. However, once an epoch is
        dropped, it is dropped forever, so if more lenient thresholds may
        subsequently be applied, `epochs.copy <mne.Epochs.copy>` should be
        used.
        rÚ  Nc                 s   s    | ]}t |tƒo|d kV  qdS )rÚ  Nr=  )r¿   rW  ro   ro   rp   rù   ¼  s   ÿz&BaseEpochs.drop_bad.<locals>.<genexpr>z/reject and flat, if strings, must be "existing"F)rf  rF   )rT  re   rf   r†  r  r   rB  )rø   re   rf   rF   ro   ro   rp   Údrop_bad•  s    !ÿzBaseEpochs.drop_badrõ   c                 C   s   t | j|ƒS )aG  Compute the channel stats based on a drop_log from Epochs.

        Parameters
        ----------
        ignore : list
            The drop reasons to ignore.

        Returns
        -------
        perc : float
            Total percentage of epochs dropped.

        See Also
        --------
        plot_drop_log
        )Ú_drop_log_statsr¯   )rø   Úignorero   ro   rp   Údrop_log_statsÃ  s    zBaseEpochs.drop_log_stats©çÍÌÌÌÌÌì?rà  rà  çš™™™™™é?c              
   C   s(   | j stdƒ‚t| j|||||||d�S )Nz_You cannot use plot_drop_log since bad epochs have not yet been dropped. Use epochs.drop_bad().)rµ  ÚwidthrÝ  r¡  )rT  r  rB   r¯   )rø   Ú	thresholdZ
n_max_plotÚsubjectrµ  râ  rÝ  r¡  ro   ro   rp   rB   Ö  s      þzBaseEpochs.plot_drop_logc                 C   s0   t | |||||||||	|
|||||||||d�S )N)r  rÐ  rÑ  rÒ  rÓ  r   r¡  Úunitsrœ  rÄ  ÚfigrÉ  Úoverlay_timesÚcombiner¨  rl  Úts_argsrž  Úclear)r@   )rø   r  rÐ  rÑ  rÒ  rÓ  r   r¡  rå  rœ  rÄ  ræ  rÉ  rç  rè  r¨  rl  ré  rž  rê  ro   ro   rp   Ú
plot_imageâ  s$    
          úzBaseEpochs.plot_imageÚUSERc           	      C   sæ   t  |¡}|jdkrtdƒ‚|jtkr4t  |¡d }t  |dk |t| jƒ |¡}|dk |t| jƒkB }| 	¡ r†|| d }t
d| ƒ‚t  t  t| jƒ¡|¡}| j||ddd� t|ƒ}t d|t|ƒd ttt  |¡ƒ¡f ¡ | S )	aŸ  Drop epochs based on indices or boolean mask.

        .. note:: The indices refer to the current set of undropped epochs
                  rather than the complete set of dropped and undropped epochs.
                  They are therefore not necessarily consistent with any
                  external indices (e.g., behavioral logs). To drop epochs
                  based on external criteria, do not use the ``preload=True``
                  flag when constructing an Epochs object, and call this
                  method before calling the :meth:`mne.Epochs.drop_bad` or
                  :meth:`mne.Epochs.load_data` methods.

        Parameters
        ----------
        indices : array of int or bool
            Set epochs to remove by specifying indices to remove or a boolean
            mask to apply (where True values get removed). Events are
            correspondingly modified.
        reason : str
            Reason for dropping the epochs ('ECG', 'timeout', 'blink' etc).
            Default: 'USER'.
        %(verbose)s

        Returns
        -------
        epochs : instance of Epochs
            The epochs with indices dropped. Operates in-place.
        r   z'indices must be a scalar or a 1-d arrayr   zEpoch index %d is out of boundsF)rÍ   Údrop_event_idzDropped %d epoch%s: %sr  )r’   Z
atleast_1dr  r  rs  r  rØ   r”   r•   r†  Ú
IndexErrorrë   r  Ú_getitemrE   rŽ   rI   rÂ   Úmapr½   Úsort)	rø   ÚindicesÚreasonrF   Ztry_idxZout_of_boundsrµ   Úkeepr’  ro   ro   rp   ræ   ð  s"    


ÿzBaseEpochs.dropc                 C   s   t ‚dS )zGet a given epoch from disk.N)ÚNotImplementedError)rø   rá   rF   ro   ro   rp   Ú_get_epoch_from_raw"  s    zBaseEpochs._get_epoch_from_rawc                 C   sF   |dkst |tƒr|S | jp | j}| jdk	rB|dkrBt | j|¡}|S )z/Process a raw epoch based on the delayed param.NT)r  r½   r!  r*  r"  r’   r%  )rø   r4  r*  ro   ro   rp   Ú_project_epoch&  s    zBaseEpochs._project_epoch)rå  rž   r  rF   c                C   s  |sp| j p(| jdd�dk	o(| jdd�dk	}t| ddƒ}	| jdkrp| jdkrp|rp| jdkrp|	spt d¡ d| _dS |  	||¡\}
}|dkr’t
dƒ}n| js td	ƒ‚|  |¡}t t| jƒ¡| }t|ƒ}| j rÔ| j}n‚t dt| jd
 ƒt| jƒf¡}d|› dt| jƒ› d�}| jdk�r |d7 }t| jddƒ�rDt d|› d�¡ nt d|› d�¡ |}|dk�rxt| j|ddd�}nt| j|ƒ}|dk	�r |�r t| ||ƒ}| j�r¨|�s²dS | j �r(|| }|dk	�rÜ|dd…|f }|dk	�rü||dd…tjf 9 }|
dk�s|| jjk�r$|d|
|…f }|S | j}t|ƒD ]l\}}|  |¡}|  ||¡}| j�rb|}n
|   |¡}|dk�r˜tj|t| j!ƒt| jƒf|j"d�}|||< �q6�n g }d}t#| j$ƒ}|t| j%ƒk�sÎt&‚| j �sÜ| j}t| j%ƒD �]"\}}| j �r&| j�r| j| }|   |¡}nd}| j| }n |  |¡}|  ||¡}|   |¡}| j�rR|n|}| j'||d�\}}|�sªt(|t)ƒ�s~t&‚t*dd„ |D ƒƒ�s–t&‚|| | ||< �qæ| +|¡ |�sÂ| j �ræ|dk�rø| j �søtj||j,d |j,d f|j"dd�}|||< |d7 }�qæt)|ƒ| _$~d| _t d|t|ƒ  ¡ |�sB| j �r”|j-d �rz|j-d  �rz|j.|f|j,dd…  dd!� n|d|… }| j �r”|| _| j/|ddddd"� |�r|dk	�rÈ|dd…|f }|dk	�rè||dd…tjf 9 }|
dk�s || jjk�r|d|
|…f }|S dS dS )#aH  Load all data, dropping bad epochs along the way.

        Parameters
        ----------
        out : bool
            Return the data. Setting this to False is used to reject bad
            epochs without caching all the data, which saves memory.
        %(picks_all)s
        item : slice | array-like | str | list | None
            See docstring of get_data method.
        %(units)s
        tmin : int | float | None
            Start time of data to get in seconds.
        tmax : int | float | None
            End time of data to get in seconds.
        %(verbose)s
        r   )rá   NrÌ   Úreject_by_annotationFz_get_data is a noop, returningTzgitem must be None in epochs.get_data() unless bads have been dropped. Consider using epochs.drop_bad().r]  zfor z events and z original time pointsr   z (prior to decimation)r  zUsing data from preloaded Raw z ...zLoading data rû   ro   r`  .rr  rô   c                 s   s   | ]}t |tƒV  qd S r:  r=  rƒ  ro   ro   rp   rù   °  s     z'BaseEpochs._get_data.<locals>.<genexpr>ÚC)rs  r   z%d bad epochs droppedZOWNDATAZC_CONTIGUOUS)Zrefcheck)rÍ   rí  Zselect_data)0r  rö  rj   re   rf   rV  rE   ÚdebugrT  Z_handle_tmin_tmaxrC  r  Z_item_to_selectr’   r  r”   r•   r  r§   rŽ   rŸ   r  r  r  r(   r,   rª   ÚsizerE  r$  ra  r!  r÷  r]  rs  rÎ   r¯   r²   rw   r_  r  rì   rû   r}  r
  r@  Úresizerï  )rø   rf  r  Úitemrå  rž   r  rF   Z	in_boundsrø  ÚstartÚstopÚselectÚuse_idxr1  r´   r.  Z
orig_picksZ
ch_factorsÚdetrend_picksr3  rá   Zepoch_noprojZ	epoch_outZgood_idxÚn_outr¯   Úselr4  Zis_goodÚ	bad_tuplero   ro   rp   rB  1  s   þÿÿ

ÿ
 



 ÿ

ÿÿ


 ÿ
 ÿ

ÿ þ
 ÿ

zBaseEpochs._get_datac                 C   s    | j rt| jdddd�S g S d S )NTro   )Úwith_ref_megZwith_auxrý   )r  r&   rŽ   r÷   ro   ro   rp   rE  Ü  s       ÿzBaseEpochs._detrend_picksc                 C   s   | j |||||d�S )a¸  Get all epochs as a 3D array.

        Parameters
        ----------
        %(picks_all)s
        item : slice | array-like | str | list | None
            The items to get. See :meth:`mne.Epochs.__getitem__` for
            a description of valid options. This can be substantially faster
            for obtaining an ndarray than :meth:`~mne.Epochs.__getitem__`
            for repeated access on large Epochs objects.
            None (default) is an alias for ``slice(None)``.

            .. versionadded:: 0.20
        %(units)s

            .. versionadded:: 0.24
        tmin : int | float | None
            Start time of data to get in seconds.

            .. versionadded:: 0.24.0
        tmax : int | float | None
            End time of data to get in seconds.

            .. versionadded:: 0.24.0

        Returns
        -------
        data : array of shape (n_epochs, n_channels, n_times)
            A view on epochs data.
        )r  rý  rå  rž   r  )rB  )rø   r  rý  rå  rž   r  ro   ro   rp   r‘   ä  s    !ÿzBaseEpochs.get_datac              
      s   t | dƒ t| j|ddd�}tˆƒs,tdƒ‚| j‰ |dk	rT|| jjkrT| j |¡| _|�rtt	|ƒ\}‰}|dkrÀt
t	ˆfˆŽ}	|D ]8}
t |	dˆ dd…|
dd…f ¡| jdd…|
dd…f< q„nJ|‡ ‡‡‡fd	d
„|D ƒƒ}t|ƒD ]$\}}|| | jdd…|dd…f< qänt	ˆˆ fˆŽ| _| S )a¯  Apply a function to a subset of channels.

        %(applyfun_summary_epochs)s

        Parameters
        ----------
        %(fun_applyfun)s
        %(picks_all_data_noref)s
        %(dtype_applyfun)s
        %(n_jobs)s
        %(channel_wise_applyfun_epo)s
        %(verbose)s
        %(kwargs_fun)s

        Returns
        -------
        self : instance of Epochs
            The epochs object with transformed data.
        zepochs.apply_functionro   F)rý   r  zfun needs to be a functionNr   rÌ   c                 3   s.   | ]&}ˆˆˆ d d …|d d …f fˆŽV  qd S r:  ro   r•  ©Zdata_inrŽ  ÚkwargsZp_funro   rp   rù   2  s   ÿ ÿÿz,BaseEpochs.apply_function.<locals>.<genexpr>)rN   r(   rŽ   Úcallabler  r  rs  r  r8   r7   r   r’   Zapply_along_axisr$  )rø   rŽ  r  rs  r»  Zchannel_wiserF   r  ÚparallelZ_funrá   Zdata_picks_newÚppr–  ro   r  rp   Úapply_function  s0    
  ÿÿ zBaseEpochs.apply_functionc                 C   s   | j S )zThe filename.)r&  r÷   ro   ro   rp   r-  ;  s    zBaseEpochs.filenamec                    s€  dt ˆ jƒ }|ˆ jrdnd7 }|dˆ jˆ jf 7 }|d7 }ˆ jdkrP|d7 }nL|ˆ jd d	›d
ˆ jd d	›d�7 }ˆ jtˆ jˆ jˆ jd dd�krœ|d7 }|dt	ˆ j
ƒf 7 }|dˆ jr¾dnd 7 }|ˆ jdk	rÖdnd7 }d}‡ fdd„tˆ j ¡ ƒd|… D ƒ}t ˆ jƒdk�r,|dd dg| ¡ 7 }t ˆ jƒ|k�rZt ˆ jƒ| }|d|› d�7 }ˆ jj}|dk�rpdn|}d||f S ) zBuild string representation.z %s events z
(all good)z(good & bad)z, %g - %g secz, baseline NÚoffr   Úgõ    â€“ r   ú secrˆ   Úadjust)rŸ   rˆ   Zon_baseline_outside_dataz8 (baseline period was cropped after baseline correction)z, ~%sz, data%s loadedÚ z notz, with metadataé
   c                    s2   g | ]*\}}d |t ˆ jdd…df |kƒf ‘qS )z%r: %iNrÅ   )r?  r•   r¾   r÷   ro   rp   rÁ   S  s   ÿz'BaseEpochs.__repr__.<locals>.<listcomp>ú,z
 z
 and z more events ...rî   ÚEpochsz	<%s | %s>)r”   r•   rT  rž   r  r¤   r1   rŸ   rŽ   rJ   Ú_sizer  rš   rÎ   r™   rÃ   rÂ   Ú	__class__Ú__name__)rø   rú   Z
max_eventsrÞ   Znot_shown_eventsÚ
class_namero   r÷   rp   Ú__repr__@  s:    

$  þ
ÿzBaseEpochs.__repr__c                 C   sF  ddl m} | jd krd}n,tdd„ | jD ƒƒ}|d › d|d › d�}t| jtƒr g }t| j ¡ ƒD ]6\}}t	| j
d d …d	f |kƒ}| |› d
|› �¡ qfnˆt| jtƒrìg }| jD ]2}t	| j
d d …d	f |kƒ}| |› d
|› �¡ q¶n<t| jtƒ�r$t| j
d d …d	f ƒ}| j› d
|› �g}nd }| d¡}|j| ||d�}|S )Nr   )Úrepr_templates_envr  c                 S   s   g | ]}|d ›‘qS )z.3fro   )r¿   Úbro   ro   rp   rÁ   c  s     z*BaseEpochs._repr_html_.<locals>.<listcomp>r   r  r  rÅ   z: zepochs.html.jinja)rk   r¤   r•   )Zhtml_templatesr  r¤   rì   r  r™   ri   rÙ   rÃ   r?  r•   r}  rÎ   rœ   r”   Zget_templateÚrender)rø   r  r¤   Zevent_stringsr¹   rÀ   r1  ro  ro   ro   rp   Ú_repr_html_^  s,    


zBaseEpochs._repr_html_c                    s„   t | dƒ tƒ j|||d� | jdk	rN| j| jk rNt d| j› d�¡ | j| _| jdk	r€| j| jkr€t d| j› d�¡ | j| _| S )aß  Crop a time interval from the epochs.

        Parameters
        ----------
        tmin : float | None
            Start time of selection in seconds.
        tmax : float | None
            End time of selection in seconds.
        %(include_tmax)s
        %(verbose)s

        Returns
        -------
        epochs : instance of Epochs
            The cropped epochs object, modified in-place.

        Notes
        -----
        %(notes_tmax_included_by_default)s
        zModifying data of epochs)rž   r  Úinclude_tmaxNzPreject_tmin is not in epochs time interval. Setting reject_tmin to epochs.tmin (z sec)zPreject_tmax is not in epochs time interval. Setting reject_tmax to epochs.tmax ()	rN   ÚsuperÚcroprg   rž   rE   rŽ   rh   r  )rø   rž   r  r  rF   ©r  ro   rp   r!  z  s    
ÿÿzBaseEpochs.cropc                 C   s   t | ƒS )z�Return copy of Epochs instance.

        Returns
        -------
        epochs : instance of Epochs
            A copy of the object.
        r   r÷   ro   ro   rp   rÍ   ¢  s    zBaseEpochs.copyc                 C   sR   | j }| |¡}| j ¡ D ]2\}}|dkr8||t|ƒ< n
t||ƒ}||j|< q|S )zMake a deepcopy.)r¯   r  r9  )r  Ú__new__Ú__dict__rÃ   Úidr   )rø   ZmemodictÚclsÚresultr¹   rÀ   ro   ro   rp   Ú__deepcopy__¬  s    

zBaseEpochs.__deepcopy__Ú2GBr…   rr   c              	   C   s(  t |ddƒ t||d�}t|ƒ}td|ddgƒ |  ¡  t| ƒdkrRtdƒ d}n(| d  ¡ }	|	jd	kslt	‚|	j
t| ƒ }|  ¡  d}
|dkr–|d
 }|
d7 }
|
d7 }
|
t| jƒdt| jƒ  7 }
|| jjd 7 }|
tt| jƒƒd 7 }
| jdk	�r|tt| jƒƒ7 }|
d7 }
|
d| jdk	 d 7 }
tt | j¡ƒd }|dt| jƒd  7 }|
|7 }
t| ƒ}|�rz|
tt |¡ƒd 7 }
|| jjd 7 }|
d7 }
|
t7 }
t dt|
ƒ d¡› �¡ t dt|ƒ d¡› �¡ t dt|ƒ d¡› �¡ t| ƒ}|�rþ|| nd}||
 }||k �r4td|› dt |ƒ› d|› d�ƒ‚t!|d ||
  d dƒ}|dk�s`t	|ƒ‚|dk�rœt d|› d�¡ |dk�rœtd |› d!|› d"�ƒ‚t| jƒd#k�rÌtd$t| jƒ› d%t |ƒ› d&�ƒ t" #t" $|¡|¡}t%|ƒD ]<\}}|dk�r | | n| }| j|_t&|||||||ƒ �qædS )'a¾  Save epochs in a fif file.

        Parameters
        ----------
        fname : str
            The name of the file, which should end with ``-epo.fif`` or
            ``-epo.fif.gz``.
        split_size : str | int
            Large raw files are automatically split into multiple pieces. This
            parameter specifies the maximum size of each piece. If the
            parameter is an integer, it specifies the size in Bytes. It is
            also possible to pass a human-readable string, e.g., 100MB.
            Note: Due to FIFF file limitations, the maximum split size is 2GB.

            .. versionadded:: 0.10.0
        fmt : str
            Format to save data. Valid options are 'double' or
            'single' for 64- or 32-bit float, or for 128- or
            64-bit complex numbers respectively. Note: Data are processed with
            double precision. Choosing single-precision, the saved data
            will slightly differ due to the reduction in precision.

            .. versionadded:: 0.17
        %(overwrite)s
            To overwrite original file (the same one that was loaded),
            data must be preloaded upon reading. This defaults to True in 0.18
            but will change to False in 0.19.

            .. versionadded:: 0.18
        %(split_naming)s

            .. versionadded:: 0.24
        %(verbose)s

        Notes
        -----
        Bad epochs will be dropped before saving the epochs to disk.
        rk   ©z-epo.fifz-epo.fif.gzz_epo.fifz_epo.fif.gz)ry   rt   r|   r…   r†   r   zSaving epochs with no data)ú>f8z<f8ú>c16z<c16rÅ   é    é„   é   é   éH   Né8   é(   é   r   z    Overhead size:   é   z    Splittable size: z    Split size:      zThe split size zI is too small to safely write the epochs contents, minimum split size is z (z bytes)zSplitting into z partséd   zSplit size z would result in writing z filesi † zepochs.drop_log contains z" entries which will incur up to a ze writing overhead (per split file), consider using epochs.reset_drop_log_selection() prior to writing)'rD   rC   r   rU   rÛ  r”   rH   r‘   rs  rw   Únbytesr  r\   rŽ   r•   rû  r˜   r™   rš   rR   r¤   r­   r®   r¯   r²   rq   r   rE   rú  r½   Úrjustr  rJ   r  r’   Zarray_splitr  r$  rƒ   )rø   ry   Z
split_sizer|   rt   r}   rF   Zsplit_size_bytesZ
total_sizeÚdZ	over_sizeZ	drop_sizerl   r�  Zn_perZmin_sizer{   Z
epoch_idxsrz   Z	epoch_idxZthis_epochsro   ro   rp   Úsaveº  s€    )
ÿ ÿ

ÿ  ÿzBaseEpochs.save©rt   rF   c                C   s"   ddl m} ||| |||d� dS )a­  Export Epochs to external formats.

        %(export_fmt_support_epochs)s

        %(export_warning)s

        Parameters
        ----------
        %(fname_export_params)s
        %(export_fmt_params_epochs)s
        %(overwrite)s

            .. versionadded:: 0.24.1
        %(verbose)s

        Notes
        -----
        .. versionadded:: 0.24

        %(export_warning_note_epochs)s
        %(export_eeglab_note)s
        r   )Úexport_epochsr;  N)Úexportr<  )rø   ry   r|   rt   rF   r<  ro   ro   rp   r=  B  s    zBaseEpochs.exportÚmintimec                    sÞ  ddl m} t||dfddd� t|tƒr8td|› �ƒ‚|dkrLtˆjƒ}n|sXtdƒ‚ˆj	sfˆ 
¡  tƒ }ˆj‰ t|ƒ}d	}d
d ˆ ¡k�rvdd„ |D ƒ}|D ]}t‡ fdd„|D ƒƒr d}q ‡ fdd„|D ƒ}t|ƒD ]Z\}}	t|	ƒdk�rt|| › d�ƒ‚qÚt‡ fdd„|	D ƒƒdkrÚdd |	¡ }
t|
ƒ‚qÚ|dk�rv‡fdd„|D ƒ}|d  |d ¡}t|ƒ�rvtdƒ‚|D ]}| ˆ |¡¡ �qz‡fdd„|D ƒ}t||ƒ}t dd„ t||ƒD ƒ¡}ˆj|dd� ˆ|fS )ui  Equalize the number of trials in each condition.

        It tries to make the remaining epochs occurring as close as possible in
        time. This method works based on the idea that if there happened to be
        some time-varying (like on the scale of minutes) noise characteristics
        during a recording, they could be compensated for (to some extent) in
        the equalization process. This method thus seeks to reduce any of
        those effects by minimizing the differences in the times of the events
        within a `~mne.Epochs` instance. For example, if one event type
        occurred at time points ``[1, 2, 3, 4, 120, 121]`` and the another one
        at ``[3.5, 4.5, 120.5, 121.5]``, this method would remove the events at
        times ``[1, 2]`` for the first event type â€“ and not the events at times
        ``[120, 121]``.

        Parameters
        ----------
        event_ids : None | list | dict
            The event types to equalize.

            If ``None`` (default), equalize the counts of **all** event types
            present in the `~mne.Epochs` instance.

            If a list, each element can either be a string (event name) or a
            list of strings. In the case where one of the entries is a list of
            strings, event types in that list will be grouped together before
            equalizing trial counts across conditions.

            If a dictionary, the keys are considered as the event names whose
            counts to equalize, i.e., passing ``dict(A=1, B=2)`` will have the
            same effect as passing ``['A', 'B']``. This is useful if you intend
            to pass an ``event_id`` dictionary that was used when creating
            `~mne.Epochs`.

            In the case where partial matching is used (using ``/`` in
            the event names), the event types will be matched according to the
            provided tags, that is, processing works as if the ``event_ids``
            matched by the provided tags had been supplied instead.
            The ``event_ids`` must identify non-overlapping subsets of the
            epochs.
        method : str
            If ``'truncate'``, events will be truncated from the end of each
            type of events. If ``'mintime'``, timing differences between each
            event type will be minimized.

        Returns
        -------
        epochs : instance of Epochs
            The modified instance. It is modified in-place.
        indices : array of int
            Indices from the original events list that were dropped.

        Notes
        -----
        For example (if ``epochs.event_id`` was ``{'Left': 1, 'Right': 2,
        'Nonspatial':3}``:

            epochs.equalize_event_counts([['Left', 'Right'], 'Nonspatial'])

        would equalize the number of trials in the ``'Nonspatial'`` condition
        with the total number of trials in the ``'Left'`` and ``'Right'``
        conditions combined.

        If multiple indices are provided (e.g. ``'Left'`` and ``'Right'`` in
        the example above), it is not guaranteed that after equalization the
        conditions will contribute equally. E.g., it is possible to end up
        with 70 ``'Nonspatial'`` epochs, 69 ``'Left'`` and 1 ``'Right'``.

        .. versionchanged:: 0.23
            Default to equalizing all events in the passed instance if no
            event names were specified explicitly.
        r   )ÚIterableNÚ	event_idszlist-like or None)ÚtypesÚ	item_nameÚ	type_namez<event_ids must be list-like or None, but received a string: z(event_ids must have at least one elementFrÉ   r  c                 S   s    g | ]}t |tƒr|gn|‘qS ro   r=  rƒ  ro   ro   rp   rÁ   ¼  s   ÿz4BaseEpochs.equalize_event_counts.<locals>.<listcomp>c                    s   g | ]}|ˆ k‘qS ro   ro   )r¿   Úid_©Úidsro   rp   rÁ   ¿  s     Tc                    s8   g | ]0‰ t ‡fd d„ˆ D ƒƒr0‡ fdd„ˆD ƒnˆ ‘qS )c                 3   s   | ]}|ˆ kV  qd S r:  ro   )r¿   Zid__rE  ro   rp   rù   È  s     z>BaseEpochs.equalize_event_counts.<locals>.<listcomp>.<genexpr>c                    s&   g | ]‰ t ‡ fd d„ˆD ƒƒrˆ ‘qS )c                 3   s   | ]}|ˆ   d ¡kV  qdS )rÉ   N)rÔ   )r¿   Útag©r¹   ro   rp   rù   Æ  s   ÿzIBaseEpochs.equalize_event_counts.<locals>.<listcomp>.<listcomp>.<genexpr>©rû   ©r¿   ©rD  rH  rp   rÁ   Å  s
    ÿÿz?BaseEpochs.equalize_event_counts.<locals>.<listcomp>.<listcomp>rI  rJ  rE  rK  rp   rÁ   Å  s   þýz* not found in the epoch object's event_id.c                    s   h | ]}|ˆ k’qS ro   ro   )r¿   Zsub_idrE  ro   rp   Ú	<setcomp>Ï  s     z3BaseEpochs.equalize_event_counts.<locals>.<setcomp>r   z:Don't mix hierarchical and regular event_ids like in '%s'.r  c                    s&   g | ]}t ˆ | jd d …df ƒ‘qS rñ   )rÓ   r•   rƒ  r÷   ro   rp   rÁ   Ö  s     zHThe two sets of epochs are overlapping. Provide an orthogonal selection.c                    s   g | ]}ˆ j |d f ‘qS ©r   ©r•   ©r¿   r�  r÷   ro   rp   rÁ   à  s     c                 S   s   g | ]\}}|| ‘qS ro   ro   )r¿   r�  rá   ro   ro   rp   rÁ   ã  s     ÚEQUALIZED_COUNT©ró  )Úcollections.abcr?  r^   r  r½   rM  rÎ   r™   r  rT  rÛ  rÂ   r†  r$  r”   rO  Úintersectionr}  Z_keys_to_idxÚ_get_drop_indicesr’   rÕ   rL  ræ   )rø   r@  r~  r?  Zeq_indsZorig_idsZtaggingZids_r3  rD  ÚerrZevents_ZdoublesÚeqÚevent_timesrò  ro   )rF  rø   rp   Úequalize_event_counts]  s^    H
 ÿ
ÿ
ûÿ



z BaseEpochs.equalize_event_countsc             
      sZ  t ƒ }dddg}	ddg}
t||	ƒ}t||
ƒ}t| j|ddd�}|  ¡ d	d	…|d	d	…f }| j}|j\}}}t 	|¡j
}|r‚| ¡ }t| |||ƒ}tƒ ‰ t ||¡}t| ||ƒ}ˆ  d|f¡ d
d„ | j ¡ D ƒ‰‡fdd„| jd	d	…df D ƒ}ˆ  dt ||¡f¡ ˆ  dt | j|¡f¡ t‡ fdd„ˆ D ƒƒ�s:t‚t| |||ˆ |dddgd�}|S )a,  Export data in tabular structure as a pandas DataFrame.

        Channels are converted to columns in the DataFrame. By default,
        additional columns "time", "epoch" (epoch number), and "condition"
        (epoch event description) are added, unless ``index`` is not ``None``
        (in which case the columns specified in ``index`` will be used to form
        the DataFrame's index instead).

        Parameters
        ----------
        %(picks_all)s
        %(index_df_epo)s
            Valid string values are 'time', 'epoch', and 'condition'.
            Defaults to ``None``.
        %(scalings_df)s
        %(copy_df)s
        %(long_format_df_epo)s
        %(time_format_df)s

            .. versionadded:: 0.20
        %(verbose)s

        Returns
        -------
        %(df_return)s
        Útimer4  Ú	conditionÚmsÚ	timedeltarû   ro   r`  Nc                 S   s   i | ]\}}||“qS ro   ro   r¾   ro   ro   rp   ré     s      z,BaseEpochs.to_data_frame.<locals>.<dictcomp>c                    s   g | ]}ˆ | ‘qS ro   ro   rö   )Úrev_event_idro   rp   rÁ     s     z,BaseEpochs.to_data_frame.<locals>.<listcomp>rÅ   c                 3   s"   | ]}t |ƒt ˆ d  ƒkV  qdS r6  r7  )r¿   Zmdx)Úmindexro   rp   rù     s     z+BaseEpochs.to_data_frame.<locals>.<genexpr>)Zdefault_index)rM   rX   r[   r(   rŽ   r‘   rŸ   r
  r’   Úhstackr–   rÍ   rZ   rÎ   ZtilerY   r}  r™   rÃ   r•   Úrepeatr²   rû   rw   rW   )rø   r  rÆ   rœ  rÍ   Zlong_formatÚtime_formatrF   ÚpdZvalid_index_argsZvalid_time_formatsr´   rŸ   r�  Zn_picksr^  Ú
conditionsZdfro   )r^  r]  rp   Úto_data_frameè  s4    


 ÿzBaseEpochs.to_data_frameÚgradÚfastc                 C   s   ddl m} || ||d�S )aî  Compute virtual epochs using interpolated fields.

        .. Warning:: Using virtual epochs to compute inverse can yield
            unexpected results. The virtual channels have ``'_v'`` appended
            at the end of the names to emphasize that the data contained in
            them are interpolated.

        Parameters
        ----------
        ch_type : str
            The destination channel type. It can be 'mag' or 'grad'.
        mode : str
            Either ``'accurate'`` or ``'fast'``, determines the quality of the
            Legendre polynomial expansion used. ``'fast'`` should be sufficient
            for most applications.

        Returns
        -------
        epochs : instance of mne.EpochsArray
            The transformed epochs object containing only virtual channels.

        Notes
        -----
        This method returns a copy and does not modify the data it
        operates on. It also returns an EpochsArray instance.

        .. versionadded:: 0.20.0
        r   )Ú_as_meg_type_inst)rÃ  r{  )Úforwardrg  )rø   rÃ  r{  rg  ro   ro   rp   Úas_type%  s    zBaseEpochs.as_type)Nrï   rð   rñ   NNNNr   NNNTrò   FNNNNrå   )rñ   )N)N)F)N)Nrz  F)NF)rz  )NNr˜  r˜  NNNNTFr™  NFTTNNrN  NN)NNNFNFTr¬  NNNTNFr™  rÀ  NTNrÁ  N)Nr…  NNNNrÌ  rÍ  NNrü   r¹   NrÎ  T)rÚ  rÚ  N)rõ   )r   r˜  Nrß  rá  rõ   T)Nr…  NNTNTNNNNNNNNTNNF)rì  N)N)TNN)NNNNN)NNNTN)NNTN)r)  r…   Frr   T)r™  )Nr>  )NNNTFN)re  rf  ):r  Ú
__module__Ú__qualname__Ú__doc__rF   r5  r  rA  r#  rF  r   r_  ra  rg  ry  ra   rt  r�  r|  ÚpropertyrŒ  r‹  r]  rL   r=   r«  r>   r’   rQ  r¿  r?   rË  rA   rÙ  rÛ  rÞ  rB   r@   rë  ræ   rö  r÷  rB  rE  r‘   r  r-  r  r  r!  rÍ   r(  r:  r=  rX  rd  ri  Ú__classcell__ro   ro   r"  rp   rî   T  s¤  4                                 ú ø M+P

H3
=

                            ûú
               ú                                 ú                   ü-
       þ                           ü1
  ÿ +
  ÿ#    ÿ2
'
    ÿ 
        þþ<rî   rõ   c                    sV   t | tƒr.tdd„ | D ƒƒr.tdd„ | D ƒƒs6tdƒ‚dt ‡ fdd„| D ƒ¡ }|S )a  Compute drop log stats.

    Parameters
    ----------
    drop_log : list of list
        Epoch drop log from Epochs.drop_log.
    ignore : list
        The drop reasons to ignore.

    Returns
    -------
    perc : float
        Total percentage of epochs dropped.
    c                 s   s   | ]}t |tƒV  qd S r:  r;  ©r¿   r9  ro   ro   rp   rù   V  s     z"_drop_log_stats.<locals>.<genexpr>c                 s   s"   | ]}|D ]}t |tƒV  q
qd S r:  r=  )r¿   r9  rú   ro   ro   rp   rù   W  s       z(drop_log must be a tuple of tuple of strr6  c                    s.   g | ]&}t ‡ fd d„|D ƒƒst|ƒdk‘qS )c                 3   s   | ]}|ˆ kV  qd S r:  ro   )r¿   Úr©rÝ  ro   rp   rù   Z  s     z-_drop_log_stats.<locals>.<listcomp>.<genexpr>r   )r†  r”   ro  rq  ro   rp   rÁ   Y  s    ÿz#_drop_log_stats.<locals>.<listcomp>)r  rì   rû   rM  r’   rz  )r¯   rÝ  Úpercro   rq  rp   rÜ  F  s    
ÿþrÜ  c           *         s   t ƒ }tˆ tfdd� tˆdtttfdd� t|dtttfdd� t|dtttfdd� ˆ sdtdƒ‚dd	„ }	|	ˆƒ‰|	|ƒ}|	|ƒ}t|ƒt|ƒ@ }
|
r°td
d t	|
ƒ¡› �ƒ‚~
t||d� 
¡ D ]P\}}|D ]B}ztˆ |gƒ W qÎ tk
�r   td|› d|› d�ƒ‚Y qÎX qÎqÂt	tˆƒtˆ  ¡ ƒ ƒ}|�rFtdd |¡› �ƒ‚~tt|| ƒƒ}tt|| ƒƒd }|j| dd�}dd„ ˆ  
¡ D ƒ}| t | dd…df tˆ  ¡ ƒ¡ } |j|d  ˆ  ¡ ¡dd…f }‡ fdd„|D ƒ}‡ fdd„|D ƒ}dd„ |D ƒ}dd„ |D ƒ}d*ˆ  ¡ ||||•}t t|ƒt|ƒf¡}|j|||jd�}d|jdd…d f< d}|tˆ  ¡ ƒ t|| ƒ }tj|jdd…||…f< |}d|jdd…|d…f< |jd!d"�D �]È}|j}||j |j|df< |j| }|j| }|j|d# |k|d# |k@ dd…f } | j�r"t‚| jd$d"�D �]R}!|!j|j }"|"| }#t  |#d ¡�rZd n|#}#||!j }$t !|j||$f ¡�s¤|j||$f |#k�s–t‚|$|k�r¤�q.|#|j||$f< || D ]Ä}%|$tˆ |%gƒk�rÔ�qº|%|k�rêd%|%› �}&n
d&|%› �}&|j||%f }'t !|'¡�s:|%|k�r"|'|#k�sº|%|k�r:|'|#k�r:�qº|%ˆ k�rn|$ "|%d¡ "d'd(¡ #d(¡}(|(|j||&f< ~(|#|j||%f< �qº�q.�q¼ˆ�rö‡fd)d„ˆ  
¡ D ƒ})| t | dd…df t|) ¡ ƒ¡ } |j|d  |)¡ }t| ƒt|ƒk�sòt‚|)‰ || ˆ fS )+uF  Generate metadata from events for use with `mne.Epochs`.

    This function mimics the epoching process (it constructs time windows
    around time-locked "events of interest") and collates information about
    any other events that occurred within those time windows. The information
    is returned as a :class:`pandas.DataFrame` suitable for use as
    `~mne.Epochs` metadata: one row per time-locked event, and columns
    indicating presence/absence and latency of each ancillary event type.

    The function will also return a new ``events`` array and ``event_id``
    dictionary that correspond to the generated metadata.

    Parameters
    ----------
    events : array, shape (m, 3)
        The :term:`events array <events>`. By default, the returned metadata
        :class:`~pandas.DataFrame` will have as many rows as the events array.
        To create rows for only a subset of events, pass the ``row_events``
        parameter.
    event_id : dict
        A mapping from event names (keys) to event IDs (values). The event
        names will be incorporated as columns of the returned metadata
        :class:`~pandas.DataFrame`.
    tmin, tmax : float
        Start and end of the time interval for metadata generation in seconds,
        relative to the time-locked event of the respective time window.

        .. note::
           If you are planning to attach the generated metadata to
           `~mne.Epochs` and intend to include only events that fall inside
           your epochs time interval, pass the same ``tmin`` and ``tmax``
           values here as you use for your epochs.

    sfreq : float
        The sampling frequency of the data from which the events array was
        extracted.
    row_events : list of str | str | None
        Event types around which to create the time windows / for which to
        create **rows** in the returned metadata :class:`pandas.DataFrame`. If
        provided, the string(s) must be keys of ``event_id``. If ``None``
        (default), rows are created for **all** event types present in
        ``event_id``.
    keep_first : str | list of str | None
        Specify subsets of :term:`hierarchical event descriptors` (HEDs,
        inspired by :footcite:`BigdelyShamloEtAl2013`) matching events of which
        the **first occurrence** within each time window shall be stored in
        addition to the original events.

        .. note::
           There is currently no way to retain **all** occurrences of a
           repeated event. The ``keep_first`` parameter can be used to specify
           subsets of HEDs, effectively creating a new event type that is the
           union of all events types described by the matching HED pattern.
           Only the very first event of this set will be kept.

        For example, you might have two response events types,
        ``response/left`` and ``response/right``; and in trials with both
        responses occurring, you want to keep only the first response. In this
        case, you can pass ``keep_first='response'``. This will add two new
        columns to the metadata: ``response``, indicating at what **time** the
        event  occurred, relative to the time-locked event; and
        ``first_response``, stating which **type** (``'left'`` or ``'right'``)
        of event occurred.
        To match specific subsets of HEDs describing different sets of events,
        pass a list of these subsets, e.g.
        ``keep_first=['response', 'stimulus']``. If ``None`` (default), no
        event aggregation will take place and no new columns will be created.

        .. note::
           By default, this function will always retain  the first instance
           of any event in each time window. For example, if a time window
           contains two ``'response'`` events, the generated ``response``
           column will automatically refer to the first of the two events. In
           this specific case, it is therefore **not** necessary to make use of
           the ``keep_first`` parameter â€“ unless you need to differentiate
           between two types of responses, like in the example above.

    keep_last : list of str | None
        Same as ``keep_first``, but for keeping only the **last**  occurrence
        of matching events. The column indicating the **type** of an event
        ``myevent`` will be named ``last_myevent``.

    Returns
    -------
    metadata : pandas.DataFrame
        Metadata for each row event, with the following columns:

        - ``event_name``, with strings indicating the name of the time-locked
          event ("row event") for that specific time window

        - one column per event type in ``event_id``, with the same name; floats
          indicating the latency of the event in seconds, relative to the
          time-locked event

        - if applicable, additional columns named after the ``keep_first`` and
          ``keep_last`` event types; floats indicating the latency  of the
          event in seconds, relative to the time-locked event

        - if applicable, additional columns ``first_{event_type}`` and
          ``last_{event_type}`` for ``keep_first`` and ``keep_last`` event
          types, respetively; the values will be strings indicating which event
          types were matched by the provided HED patterns

    events : array, shape (n, 3)
        The events corresponding to the generated metadata, i.e. one
        time-locked event per row.
    event_id : dict
        The event dictionary corresponding to the new events array. This will
        be identical to the input dictionary unless ``row_events`` is supplied,
        in which case it will only contain the events provided there.

    Notes
    -----
    The time window used for metadata generation need not correspond to the
    time window used to create the `~mne.Epochs`, to which the metadata will
    be attached; it may well be much shorter or longer, or not overlap at all,
    if desired. The can be useful, for example, to include events that occurred
    before or after an epoch, e.g. during the inter-trial interval.

    .. versionadded:: 0.23

    References
    ----------
    .. footbibliography::
    r™   )rA  rB  NÚ
row_eventsÚ
keep_firstÚ	keep_lastz3event_id dictionary must contain at least one entryc                 S   s(   | d krg S t | tƒr| gS t| ƒS d S r:  )r  r½   rÎ   )r„  ro   ro   rp   Ú_ensure_listê  s
    
z#make_metadata.<locals>._ensure_listz[The event names in keep_first and keep_last must be mutually exclusive. Specified in both: r  )rt  ru  zEvent "z", specified in z(, cannot be found in event_id dictionaryz2Present in row_events, but missing from event_id: r   )ÚsampleZprev_idr%  )Úcolumnsc                 S   s   i | ]\}}||“qS ro   ro   r¾   ro   ro   rp   ré   	  s      z!make_metadata.<locals>.<dictcomp>rÅ   r%  c                    s   g | ]}|ˆ kr|‘qS ro   ro   ©r¿   ÚcolrÄ   ro   rp   rÁ   "	  s      z!make_metadata.<locals>.<listcomp>c                    s   g | ]}|ˆ kr|‘qS ro   ro   ry  rÄ   ro   rp   rÁ   #	  s      c                 S   s   g | ]}d |› �‘qS )Úfirst_ro   ry  ro   ro   rp   rÁ   $	  s     c                 S   s   g | ]}d |› �‘qS )Úlast_ro   ry  ro   ro   rp   rÁ   %	  s     Ú
event_name)r´   rx  rÆ   r  r   ZRowEvent)Únamerw  ÚEventr{  r|  z//rÉ   c                    s   i | ]\}}|ˆ kr||“qS ro   ro   )r¿   r~  rn   )rs  ro   rp   ré   �	  s    ÿ )r}  )$rM   r^   ri   r½   rÎ   rì   r  rÓ   rÂ   rÙ   rÃ   r;   rO  rÑ   rœ   r�   Z	DataFramer’   r  rÒ   ÚlocÚisinr§   r”   rÆ   r  r‰  Z
itertuplesÚIndexr%  rw  rw   r  ÚisnanÚreplaceÚstrip)*r•   r™   rž   r  rˆ   rs  rt  ru  rb  rv  Zkeep_first_and_lastÚ
param_namerÒ   Zfirst_last_event_nameZevent_name_diffZstart_sampleZstop_sampleZ	events_dfZid_to_name_mapZkeep_first_colsZkeep_last_colsZ
first_colsZ	last_colsrx  r´   rš   r2  Zstop_idxZ	row_eventZrow_idxZwindow_start_sampleZwindow_stop_sampleZevents_in_windowÚeventZevent_sampleÚ
event_timer}  Zevent_group_nameZfirst_last_colZold_timer~  Zevent_id_timelockedro   )r™   rs  rp   Úmake_metadata^  s   ÿÿÿÿÿÿ$ û
ÿÿ



ÿÿ

 ÿ


ÿþý
 ÿ þý
ÿÿr‰  c                       s4   e Zd ZdZed‡ fdd„	ƒZeddd„ƒZ‡  ZS )r  am  Epochs extracted from a Raw instance.

    Parameters
    ----------
    %(raw_epochs)s
    %(events_epochs)s
    %(event_id)s
    %(epochs_tmin_tmax)s
    %(baseline_epochs)s
        Defaults to ``(None, 0)``, i.e. beginning of the the data until
        time point zero.
    %(picks_all)s
    preload : bool
        %(epochs_preload)s
    %(reject_epochs)s
    %(flat)s
    %(proj_epochs)s
    %(decim)s
    %(epochs_reject_tmin_tmax)s
    %(detrend_epochs)s
    %(on_missing_epochs)s
    %(reject_by_annotation_epochs)s
    %(metadata_epochs)s
    %(event_repeated_epochs)s
    %(verbose)s

    Attributes
    ----------
    %(info_not_none)s
    event_id : dict
        Names of conditions corresponding to event_ids.
    ch_names : list of string
        List of channel names.
    selection : array
        List of indices of selected events (not dropped or ignored etc.). For
        example, if the original event array had 4 events and the second event
        has been dropped, this attribute would be np.array([0, 2, 3]).
    preload : bool
        Indicates whether epochs are in memory.
    drop_log : tuple of tuple
        A tuple of the same length as the event array used to initialize the
        Epochs object. If the i-th original event is still part of the
        selection, drop_log[i] will be an empty tuple; otherwise it will be
        a tuple of the reasons the event is not longer in the selection, e.g.:

        - 'IGNORED'
            If it isn't part of the current subset defined by the user
        - 'NO_DATA' or 'TOO_SHORT'
            If epoch didn't contain enough data names of channels that exceeded
            the amplitude threshold
        - 'EQUALIZED_COUNTS'
            See :meth:`~mne.Epochs.equalize_event_counts`
        - 'USER'
            For user-defined reasons (see :meth:`~mne.Epochs.drop`).
    filename : str
        The filename of the object.
    times :  ndarray
        Time vector in seconds. Goes from ``tmin`` to ``tmax``. Time interval
        between consecutive time samples is equal to the inverse of the
        sampling frequency.

    See Also
    --------
    mne.epochs.combine_event_ids
    mne.Epochs.equalize_event_counts

    Notes
    -----
    When accessing data, Epochs are detrended, baseline-corrected, and
    decimated, then projectors are (optionally) applied.

    For indexing and slicing using ``epochs[...]``, see
    :meth:`mne.Epochs.__getitem__`.

    All methods for iteration over objects (using :meth:`mne.Epochs.__iter__`,
    :meth:`mne.Epochs.iter_evoked` or :meth:`mne.Epochs.next`) use the same
    internal state.

    If ``event_repeated`` is set to ``'merge'``, the coinciding events
    (duplicates) will be merged into a single event_id and assigned a new
    id_number as::

        event_id['{event_id_1}/{event_id_2}/...'] = new_id_number

    For example with the event_id ``{'aud': 1, 'vis': 2}`` and the events
    ``[[0, 0, 1], [0, 0, 2]]``, the "merge" behavior will update both event_id
    and events to be: ``{'aud/vis': 3}`` and ``[[0, 0, 3]]`` respectively.

    There is limited support for :class:`~mne.Annotations` in the
    :class:`~mne.Epochs` class. Currently annotations that are present in the
    :class:`~mne.io.Raw` object will be preserved in the resulting
    :class:`~mne.Epochs` object, but:

    1. It is not yet possible to add annotations
       to the Epochs object programmatically (via code) or interactively
       (through the plot window)
    2. Concatenating :class:`~mne.Epochs` objects
       that contain annotations is not supported, and any annotations will
       be dropped when concatenating.
    3. Annotations will be lost on save.
    Nrï   rð   rñ   FTr   rò   rå   c                    sz   t |tƒstdƒ‚t|jƒ}|p$|j}|| _|jd }tt| ƒj	|d |||||||||	|
|||||||||||j
d� d S )NzDThe first argument to `Epochs` must be an instance of mne.io.BaseRawrˆ   )rš   r¤   r(  r  re   rf   r)  rg   rh   r5   r*  r+  r,  rä   rF   ró   r‡   )r  r+   r  r   rŽ   r*  rø  r   r  r5  r‡   )rø   r(  r•   r™   rž   r  r¤   r  r  re   rf   r*  r)  rg   rh   r5   r+  rø  rš   rä   rF   rŽ   ró   r"  ro   rp   r5  õ	  s>    




                ùzEpochs.__init__c                 C   s  | j dkrtdƒ‚| j jd }| j|df }| j j}tt|| jd |  ƒƒ}||8 }|t| jƒ }| j	}|dkr|| jd }tt|||  ƒƒ}	|	|8 }	| j
}
|
dkr°| jd }
tt| jd |
 | ƒƒ}|| }t d||f ¡ | j  ||| j|	|| j¡}|S )a  Load one epoch from disk.

        Returns
        -------
        data : array | str | None
            If string, it's details on rejection reason.
            If array, it's the data in the desired range (good segment)
            If None, it means no data is available.
        Nz`An error has occurred, no valid raw file found. Please report this to the mne-python developers.rˆ   r   rÌ   z    Getting epoch for %d-%d)r  r  rŽ   r•   Ú
first_samprœ   r�   r  r”   rg   rh   rE   rú  Z_check_bad_segmentr  rø  )rø   rá   rF   rˆ   Ú
event_samprŠ  rþ  rÿ  rg   Zreject_startrh   r×   Zreject_stopr´   ro   ro   rp   rö  
  s2    


 þzEpochs._get_epoch_from_raw)Nrï   rð   rñ   NFNNTr   NNNrò   TNrå   N)N©r  rj  rk  rl  rF   r5  rö  rn  ro   ro   r"  rp   r  �	  s*   f                          ûr  c                       s&   e Zd ZdZed‡ fdd„	ƒZ‡  ZS )	ÚEpochsArrayaˆ
  Epochs object from numpy array.

    Parameters
    ----------
    data : array, shape (n_epochs, n_channels, n_times)
        The channels' time series for each epoch. See notes for proper units of
        measure.
    %(info_not_none)s Consider using :func:`mne.create_info` to populate this
        structure.
    events : None | array of int, shape (n_events, 3)
        The events typically returned by the read_events function.
        If some events don't match the events of interest as specified
        by event_id, they will be marked as 'IGNORED' in the drop log.
        If None (default), all event values are set to 1 and event time-samples
        are set to range(n_epochs).
    tmin : float
        Start time before event. If nothing provided, defaults to 0.
    event_id : int | list of int | dict | None
        The id of the event to consider. If dict,
        the keys can later be used to access associated events. Example:
        dict(auditory=1, visual=3). If int, a dict will be created with
        the id as string. If a list, all events with the IDs specified
        in the list are used. If None, all events will be used with
        and a dict is created with string integer names corresponding
        to the event id integers.
    %(reject_epochs)s
    %(flat)s
    reject_tmin : scalar | None
        Start of the time window used to reject epochs (with the default None,
        the window will start with tmin).
    reject_tmax : scalar | None
        End of the time window used to reject epochs (with the default None,
        the window will end with tmax).
    %(baseline_epochs)s
        Defaults to ``None``, i.e. no baseline correction.
    proj : bool | 'delayed'
        Apply SSP projection vectors. See :class:`mne.Epochs` for details.
    on_missing : str
        See :class:`mne.Epochs` docstring for details.
    metadata : instance of pandas.DataFrame | None
        See :class:`mne.Epochs` docstring for details.

        .. versionadded:: 0.16
    selection : ndarray | None
        The selection compared to the original set of epochs.
        Can be None to use ``np.arange(len(events))``.

        .. versionadded:: 0.16
    %(verbose)s

    See Also
    --------
    create_info
    EvokedArray
    io.RawArray

    Notes
    -----
    Proper units of measure:

    * V: eeg, eog, seeg, dbs, emg, ecg, bio, ecog
    * T: mag
    * T/m: grad
    * M: hbo, hbr
    * Am: dipole
    * AU: misc

    EpochsArray does not set `Annotations`. If you would like to create
    simulated data with Annotations that are then preserved in the Epochs
    object, you would use `mne.io.RawArray` first and then create an
    `mne.Epochs` object.
    Nr   Trò   c                    s<  t  t  |¡¡rt jnt j}t j||d�}|jdkr<tdƒ‚t|d ƒ|j	d krZtdƒ‚|d krrt|ƒ}t
|ƒ}| ¡ }|j	d d |d  | }tt| ƒj|||||||
||||	d|||||d	� | jd k	rÖd
| _t|ƒt  | jd d …df t| j ¡ ƒ¡ ¡ k�rtdƒ‚| j}| jD ]}|  ||¡ �q|  ¡  d S )Nrr  rþ   zBData must be a 3D array of shape (n_epochs, n_channels, n_samples)r]  r   z0Info and data must have same number of channels.rÅ   rˆ   )
re   rf   rg   rh   r)  rš   r²   r*  r+  rF   Tz8The events must only contain event numbers from event_id)r’   r†  Z	iscomplexr‡  rx  Ú
asanyarrayr  r  r”   r
  rT   rÍ   r   r�  r5  r¤   r  r  r•   rÎ   r™   rÒ   r?  rE  r  ra  rÛ  )rø   r´   rŽ   r•   rž   r™   re   rf   rg   rh   r¤   r*  r+  rš   r²   rF   rs  r�  r  r  r�  r"  ro   rp   r5  ‹
  sP    

            û
ÿ
zEpochsArray.__init__)Nr   NNNNNNTrò   NNN)r  rj  rk  rl  rF   r5  rn  ro   ro   r"  rp   r�  @
  s   I                 ür�  Tc                    s  |rˆ   ¡ nˆ ‰ t |¡}t|tƒr2t|ƒ|i}n.t|tƒsDtdƒ‚tt	| 
¡ ƒƒdks`tdƒ‚t	| ¡ ƒd }t |¡}|ˆ j ¡ kr�tdƒ‚t ‡ fdd„|D ƒ¡}tjˆ jdd…d	f dd…tjf |tjdd…f kdd
�}|ˆ j|d	f< |D ]}ˆ j |¡ qöˆ j |¡ ˆ S )a  Collapse event_ids from an epochs instance into a new event_id.

    Parameters
    ----------
    epochs : instance of Epochs
        The epochs to operate on.
    old_event_ids : str, or list
        Conditions to collapse together.
    new_event_id : dict, or int
        A one-element dict (or a single integer) for the new
        condition. Note that for safety, this cannot be any
        existing id (in epochs.event_id.values()).
    copy : bool
        Whether to return a new instance or modify in place.

    Returns
    -------
    epochs : instance of Epochs
        The modified epochs.

    Notes
    -----
    This For example (if epochs.event_id was ``{'Left': 1, 'Right': 2}``::

        combine_event_ids(epochs, ['Left', 'Right'], {'Directional': 12})

    would create a 'Directional' entry in epochs.event_id replacing
    'Left' and 'Right' (combining their trials).
    z"new_event_id must be a dict or intr   z%new_event_id dict must have one entryr   z)new_event_id value must not already existc                    s   g | ]}ˆ j | ‘qS ro   rÄ   )r¿   rm   ©rk   ro   rp   rÁ   à
  s     z%combine_event_ids.<locals>.<listcomp>NrÅ   rÊ   )rÍ   r’   rŽ  r  rœ   r½   ri   r  r”   rÎ   rÑ   rÒ   ÚoperatorrÆ   r™   r	  r†  r•   rª   ÚpopÚupdate)rk   Zold_event_idsZnew_event_idrÍ   Znew_event_numZold_event_numsÚindsrm   ro   r�  rp   Úcombine_event_ids³
  s.    



"ÿÿr”  r>  c                 C   sp   t dd„ | D ƒƒstdƒ‚| D ]}|js| ¡  qdd„ | D ƒ}t||ƒ}t| |ƒD ]\}}|j|dd� qTdS )	a–  Equalize the number of trials in multiple Epoch instances.

    Parameters
    ----------
    epochs_list : list of Epochs instances
        The Epochs instances to equalize trial counts for.
    method : str
        If 'truncate', events will be truncated from the end of each event
        list. If 'mintime', timing differences between each event list will be
        minimized.

    Notes
    -----
    This tries to make the remaining epochs occurring as close as possible in
    time. This method works based on the idea that if there happened to be some
    time-varying (like on the scale of minutes) noise characteristics during
    a recording, they could be compensated for (to some extent) in the
    equalization process. This method thus seeks to reduce any of those effects
    by minimizing the differences in the times of the events in the two sets of
    epochs. For example, if one had event times [1, 2, 3, 4, 120, 121] and the
    other one had [3.5, 4.5, 120.5, 121.5], it would remove events at times
    [1, 2] in the first epochs and not [120, 121].

    Examples
    --------
    >>> equalize_epoch_counts([epochs1, epochs2])  # doctest: +SKIP
    c                 s   s   | ]}t |tƒV  qd S r:  )r  rî   rO  ro   ro   rp   rù   
  s     z(equalize_epoch_counts.<locals>.<genexpr>z#All inputs must be Epochs instancesc                 S   s   g | ]}|j d d …df ‘qS rñ   rN  rO  ro   ro   rp   rÁ     s     z)equalize_epoch_counts.<locals>.<listcomp>rP  rQ  N)rû   r  rT  rÛ  rT  rL  ræ   )Úepochs_listr~  r�  rW  rò  r“  ro   ro   rp   Úequalize_epoch_countsî
  s    

r–  c                 C   s”   t  dd„ | D ƒ¡}| | }td|ddgƒ tƒ }| D ]X}|dkrNt||ƒ}n&t j|jd td�}d||jd d	…< | t  	t  
|¡¡d ¡ q6|S )
z5Get indices to drop from multiple event timing lists.c                 S   s   g | ]}|j d  ‘qS rM  )r
  rO  ro   ro   rp   rÁ     s     z%_get_drop_indices.<locals>.<listcomp>r~  r>  Útruncater   rr  FN)r’   ÚargminrU   rÎ   Ú_minimize_time_diffÚonesr
  r  r}  rØ   Zlogical_not)rW  r~  Z	small_idxZsmall_e_timesrò  r�  Úmaskro   ro   rp   rT    s    rT  c                    sœ  ddl m} tjtˆ ƒtd�}t| ƒdk r`| d¡ t| ƒdkr\t t ˆ |  ¡¡}d||< |S t tˆ ƒ¡}t 	t| ƒ¡}t
dddd�}||| fd	| d
 i|—Ž}ttˆ ƒt| ƒ ƒD ]Þ}	| tj¡ tjtˆ ƒtd�|  }
d|
dd…| f< t 	tˆ ƒ|	 d ¡}t ‡ fdd„|
D ƒ¡}|||fd|dd…d
f dœ|—Ž}||ƒ|  }||ƒ| }t ||¡jdd�t ||¡jdd� ||< d|t |¡< q¸|S )z3Find a boolean mask to minimize timing differences.r   )Úinterp1drr  rÅ   Fr   T)rÍ   Zbounds_errorZassume_sortedÚ
fill_valuerÌ   Nc                    s   g | ]}ˆ | ‘qS ro   ro   )r¿   Úkm©Út_longerro   rp   rÁ   A  s     z'_minimize_time_diff.<locals>.<listcomp>)rË   r�  rÊ   )Zscipy.interpolaterœ  r’   rš  r”   r  rˆ  r˜  rv  r  ri   r¨   rQ  Úeyer	  r?  )Z	t_shorterr   rœ  rô  rá   ZscoresÚx1r  Zshorter_interpr3  Z	keep_maskZx2Zt_keepsZlonger_interpZd1Zd2ro   rŸ  rp   r™  (  s<    
ÿ
ÿþ,r™  Fc              	      s^  t ƒ }d}	tjtˆ ƒtd�}
d|
tj‡fdd„ˆ D ƒtd�< t||gtjtjgddgƒD ]à\}}}|dk	rX| 	¡ D ]Ä\}}|| ‰| 
¡ }tˆƒdkrr| ˆ }tj|d	d
�tj|d	d
� }|
ˆ }t t |||ƒ|¡¡d }t|ƒdkrr‡ ‡fdd„|D ƒ}|	�st d|||f ¡ d}	|�s*  dS |t |ƒ7 }qrqX|�sDdS |dk�rRdS d|fS dS )z¤Test if data segment e is good according to reject and flat.

    If full_report=True, it will give True/False as well as a list of all
    offending channels.
    Frr  c                    s   g | ]}|ˆ k‘qS ro   ro   )r¿   Úc)r[  ro   rp   rÁ   W  s   ÿz_is_good.<locals>.<listcomp>r  rf   Nr   r   rÊ   c                    s   g | ]}ˆ ˆ|  ‘qS ro   ro   )r¿   Úi)r]  rá   ro   rp   rÁ   f  s     z'    Rejecting %s epoch based on %s : %sTro   rY  )rì   r’   rš  r”   r  r	  rL  ZgreaterÚlessrÃ   rR  r  r  rØ   Úlogical_andrE   rŽ   )r�  r]  Zchannel_type_idxre   rf   rZ  r[  rF   r  Zhas_printedZ	checkableZreflÚfro  rm   Zthreshr~  Ze_idxZdeltasZcheckable_idxZ
idx_deltasZ	bad_namesro   )r]  rá   r[  rp   r\  L  sL    ÿÿÿ&ÿÿÿ
r\  c           (         s  | ��Ú}t ||dd�\‰ }t||ƒ}t||ƒ\}}d}t|tjƒ}	t|	ƒdkrŽ|	d d D ]2}
|
j}|
j}|tj	krZt
||ƒj}t|ƒ} qŽqZt|tjƒ}~t|ƒdkr°tdƒ‚t|tjƒ}t|ƒdkrþt|tjƒ}t|ƒdkrþt|dƒ}t|ƒdkrþtdƒ‚|d }d}d}d	\}}d}d}d}d}i }t|d
 ƒD �]ˆ}|d | j}|d | j}|tjk�r|t
||ƒ}t|jƒ}�q6|tjk�r t
||ƒ}t|jƒ}�q6|tjk�rÔ| |d¡ t|ƒ}||_|jdA |_nê|tjdfk�rút
||ƒ}t|jƒ}nÄ|tjdfk�r t
||ƒ}t|jƒ}nž|tjk�rDt
||ƒ}t |j¡}nz|tjk�r~t
||ƒ}|j}t  |¡}t!dd„ |D ƒƒ}n@|tj"k�r¢t
||ƒ}t  |j¡}n|tj#k�r6t
||ƒ}|j}�q6|dk	�sÖ|dk	�rÞ||f}|| d }t$ %d¡ t$ %dd| ˆ d  d| ˆ d  f ¡ ˆ d dk	�rBt$ %dtˆ d ƒ ¡ |dk�rTtdƒ‚tˆ d ƒ|f}t|ƒt &|¡ }|jtj'k�r�tj(} d}!nL|jtj)k�rªtj(} d}!n2|jtj*k�rÄtj+} d}!n|jtj,k�rÜtj+} d}!t -|!¡j.}"|"dk�söt/‚|j0|" d|"  }#|#|k�s"td|#|f ƒ‚t ‡ fd d!„tˆ d" ƒD ƒtj(¡}$|�rht
||jƒj 1| ¡}||$9 }|ˆ d  }%|ˆ d  }&|dk�rªd#d$„ t 2|dd…d%f ¡D ƒn|}'|dk�rÆt 3t|ƒ¡}|dk�rÜd&t|ƒ }W 5 Q R X ˆ ||||'||%|&|||||$||!||fS )'zRead a single FIF file.T)Z
clean_badsNr   Ú	directoryzCould not find processed dataéz   zCould not find epochs datarÁ  Znenti   @i0  i1  c                 s   s   | ]}t |ƒV  qd S r:  )rì   rƒ  ro   ro   rp   rù   È  s     z'_read_one_epoch_file.<locals>.<genexpr>r   z    Found the data of interest:z         t = %10.2f ... %10.2f mséè  rˆ   Úcompsz.        %d CTF compensation matrices availablezEpochs data not foundr]  ú>f4r+  ú>c8r,  )r0  r4  r/  r/  z.Incorrect number of samples (%d instead of %d)c                    s2   g | ]*}ˆ d  | d ˆ d  |   dd¡ g‘qS )r‹   rŒ   r�   rŠ   )r©   rö   r—  ro   rp   rÁ   ÷  s   þÿz(_read_one_epoch_file.<locals>.<listcomp>r‰   c                 S   s   i | ]}t |ƒ|“qS ro   r¼   rO  ro   ro   rp   ré     s      z(_read_one_epoch_file.<locals>.<dictcomp>rÅ   )ro   )4r   rc   r9   r   r    r›   r”   rH  Úposr—   r   r´   rQ   r�   r  r�   r¨   r    rœ   r¡   r«   Úseekr   rN  r¥   r  r¦   r±   r’   r	  r¬   r­   Úloadsrì   r°   r¢   rE   rŽ   ÚprodZFIFFT_FLOATrx  ZFIFFT_DOUBLEZFIFFT_COMPLEX_FLOATr‡  ZFIFFT_COMPLEX_DOUBLErs  Úitemsizerw   rû  r  rÏ   r  )(r§  Útreer  r‚   Zmeasr‡   r•   Zmappingsrš   Zmetadata_treeÚddrH  r®  Ú	processedZepochs_nodeZ	my_epochsr´   Údata_tagr·   r¸   r¤   r²   r¯   ró   rl   r¹   rG  rµ   r¶   Zn_sampÚepoch_shapeZsize_expectedÚdatatyper|   Zfmt_itemsizeZsize_actualÚcalsrž   r  r™   ro   r—  rp   Ú_read_one_epoch_filey  s
   













ÿÿ
ÿ

ÿ
þþÿ$ÿ

       þrº  c                 C   s   t | |||ƒS )aF  Read epochs from a fif file.

    Parameters
    ----------
    %(fname_epochs)s
    %(proj_epochs)s
    preload : bool
        If True, read all epochs from disk immediately. If ``False``, epochs
        will be read on demand.
    %(verbose)s

    Returns
    -------
    epochs : instance of Epochs
        The epochs.
    )Ú	EpochsFIF)ry   r*  r  rF   ro   ro   rp   Úread_epochs  s    r¼  c                   @   s    e Zd ZdZdd„ Zdd„ ZdS )Ú_RawContainerz Helper for a raw data container.c                 C   s.   || _ || _|| _|| _|| _d| _|| _d S )NF)r‚   r¶  Úevent_sampsr·  r¹  r*  r|   )rø   r‚   r¶  r¾  r·  r¹  r|   ro   ro   rp   r5  )  s    z_RawContainer.__init__c                 C   s   | j  ¡  d S r:  )r‚   Úcloser÷   ro   ro   rp   Ú__del__3  s    z_RawContainer.__del__N)r  rj  rk  rl  r5  rÀ  ro   ro   ro   rp   r½  &  s   
r½  c                       s4   e Zd ZdZed‡ fdd„	ƒZed	dd„ƒZ‡  ZS )
r»  a_  Epochs read from disk.

    Parameters
    ----------
    %(fname_epochs)s
    %(proj_epochs)s
    preload : bool
        If True, read all epochs from disk immediately. If False, epochs will
        be read on demand.
    %(verbose)s

    See Also
    --------
    mne.Epochs
    mne.epochs.combine_event_ids
    mne.Epochs.equalize_event_counts
    TNc           (         sð  t |ƒr&t|ddd� t|ddd�}n|s2tdƒ‚|g}tƒ }tƒ }|D �]0}t|ƒ}t d| ¡ t||d	�\}	}
}t	|	||
ƒ}t
|	|
|ƒ\}}}}}}}}}}}}}}}}}|d d …d
f d
k  ¡ rø| ¡ }tdƒ t dt|ƒd ¡|d d …d
f< t||||||d |d||dd|d�}||_d|_| |¡ |�sh| tt|ƒd
 ||d d …d
f  ¡ |||ƒ¡ |d k	rH| |¡ qH|d k}t||dd�\}}}}}}}}}}}tt |d d …d
f ¡ƒt|ƒk�rÔtdƒ‚t|ƒt|ƒ d
k�sît‚t|ƒt|ƒ } t | t|ƒd | ¡}!t|ƒ}t|!d d… |!dd … ƒD ]P\}"}#||"|#… }$tt||$ƒƒD ]*\}%\}&}'|&dk�rX|'dk�rX|'||%< �qX�q6t|d | … ƒ}tt| ƒj||||||fd ||dd|||||||dœ|—Ž || _d| _d| _ || _!d S )Nrk   r*  )ry   ZfiletypeZendingsTÚread)ry   Z
must_existrt   z+preload must be used with file-like objectszReading %s ...©r  r   z[Incorrect events detected on disk, setting event numbers to consecutive increasing integersr   rÝ  F)r¤   rš   r+  r²   r¯   r*  rF   ró   )Ú	with_dataÚ
add_offsetz"Event time samples were not uniquerÌ   rõ   )r¤   r(  r*  r,  r+  r²   r¯   r-  rš   rF   ró   r‡   )"r`   rD   rC   r  rÎ   r!   rE   rŽ   r   r   rº  r†  rÍ   rH   r’   r  r”   rî   r¤   r  r}  r½  Ú_concatenate_epochsrÏ   rê   rw   rL  r$  rì   r   r»  r5  rT  Z_unsafe_annot_add)(rø   ry   r*  r  rF   ÚfnamesZep_listr(  Z	fname_repr‚   r³  Ú_r€   rŽ   r´   r¶  r•   r™   rš   rž   r  r¤   r²   r¯   r·  r¹  rl   r|   r‡   ró   r4  Zunsafe_annot_addÚstepÚoffsetsÚi1Úi2Z	other_logr¹   Úar  r"  ro   rp   r5  K  sÖ     þÿ

ý                 û
  þþ  $"
     ÿ       úúzEpochsFIF.__init__c           
      C   s  | j |df }| jD ]Z}t |j|k¡d }t|ƒdkr|j}|d }t |j¡t 	|¡j
 }|| d } qxqtdƒ‚|j |jj| d¡ |dkrœd}n|dkrªd}n|}t |j |¡|¡}	||krâ|	 |¡}	|	 tj¡}	n|	 tj¡}	|j|	_|	|j9 }	|	S )	zLoad one epoch from disk.r   r   r/  zFCorrect epoch could not be found, please contact mne-python developersr­  r¬  r,  r+  )r•   r  r’   rØ   r¾  r”   r|   r±  r·  rs  r²  rê   r‚   r¯  r¶  r®  Z
frombufferrÁ  Úviewr  r‡  rx  r
  r¹  )
rø   rá   rF   r‹  r(  r|   rû  ÚoffsetZread_fmtr´   ro   ro   rp   rö  ©  s0    



zEpochsFIF._get_epoch_from_raw)TTN)NrŒ  ro   ro   r"  rp   r»  7  s     ÿ]r»  c                 C   sD   | j stdƒ‚t|ƒ}|  ¡ }t|jƒ}t|ƒd||ƒ}|| }|S )zúCompute epochs selected by bootstrapping.

    Parameters
    ----------
    epochs : Epochs instance
        epochs data to be bootstrapped
    %(random_state)s

    Returns
    -------
    epochs : Epochs instance
        The bootstrap samples
    zhModifying data of epochs is only supported when preloading is used. Use preload=True in the constructor.r   )r  rê   rG   rÍ   r”   r•   r<   )rk   Zrandom_stateÚrngZepochs_bootstrapr1  rá   ro   ro   rp   Ú	bootstrapÕ  s    
rÐ  c                 C   s|   t dd„ | D ƒƒdkrtdƒ‚t dd„ | D ƒƒdkr<tdƒ‚t dd„ | D ƒƒdkrZtdƒ‚t d	d„ | D ƒƒdkrxtd
ƒ‚dS )zAux function.c                 S   s   h | ]}t |j ¡ ƒ’qS ro   )rì   r™   rÃ   ©r¿   rk   ro   ro   rp   rL  ó  s     z&_check_merge_epochs.<locals>.<setcomp>r   z'Epochs with unequal values for event_idc                 S   s   h | ]
}|j ’qS ro   )rž   rÑ  ro   ro   rp   rL  õ  s     z#Epochs with unequal values for tminc                 S   s   h | ]
}|j ’qS ro   )r  rÑ  ro   ro   rp   rL  ÷  s     z#Epochs with unequal values for tmaxc                 S   s   h | ]
}|j ’qS ro   )r¤   rÑ  ro   ro   rp   rL  ù  s     z'Epochs with unequal values for baselineN)r”   rõ  )r•  ro   ro   rp   Ú_check_merge_epochsñ  s    rÒ  c           	         s.  t dd„ | D ƒƒstdƒ‚tdd„ | D ƒƒ}dd„ | D ƒ}t| ƒ |D ] }t|ƒt|d ƒkrFtdƒ‚qFtj|d	d
�}t|d ƒ|jd	 kr˜d}t|ƒ‚| d j	 
¡ ‰ t ‡ fdd„| d	d… D ƒƒ}|sÐtdƒ‚tdd„ | D ƒƒ}| d  
¡ }||_d|_ˆ |_	d|_d|_||_t|jd|d�\|_|_|S )aL  Concatenate channels, info and data from two Epochs objects.

    Parameters
    ----------
    epochs_list : list of Epochs
        Epochs object to concatenate.
    %(verbose)s Defaults to True if any of the input epochs have verbose=True.

    Returns
    -------
    epochs : instance of Epochs
        Concatenated epochs.
    c                 s   s   | ]}|j V  qd S r:  rÂ  rO  ro   ro   rp   rù     s     z&add_channels_epochs.<locals>.<genexpr>zAll epochs must be preloaded.c                 S   s   g | ]
}|j ‘qS ro   r—  rÑ  ro   ro   rp   rÁ     s     z'add_channels_epochs.<locals>.<listcomp>c                 S   s   g | ]
}|j ‘qS ro   )r  rÑ  ro   ro   rp   rÁ     s     r   z%all epochs must be of the same lengthr   rÊ   r‹   z<Data shape does not match channel number in measurement infoc                 3   s   | ]}t  ˆ |j¡V  qd S r:  )r’   Úarray_equalr•   rÑ  rN  ro   rp   rù     s   ÿNzEvents must be the same.c                 s   s   | ]}|j V  qd S r:  )r*  rO  ro   ro   rp   rù   "  s     TFr  )rû   r  r   rÒ  r”   r’   rÕ   r
  rê   r•   rÍ   r†  rŽ   r  r  rT  r  r)   r"  )	r•  rF   rŽ   r´   r9  rU  Zall_samer*  rk   ro   rN  rp   Úadd_channels_epochsý  s<    

ÿÿrÔ  rò   ©Úon_mismatchc          "      C   sr  t | ttfƒs tdt| ƒf ƒ‚d}t| ƒD ]f\}}t |tƒsRtd|t|ƒf ƒ‚t|ddƒdk	r,t|j	ƒdkr,|s,d}t
dƒ | ¡ }| d¡ q,| d }dg}|r¼| ¡  | t|ƒ¡ |jg}	|jg}
|j|j|j  }}}|j}t|jƒ}|j}t|jƒ}|j}td	| |jd
  ƒ}tt |	d dd…df ¡ƒ| }d}d}t| dd… dƒD �]®\}}t|j|d|› d�|d� t |j| d j¡�sœt dƒ‚|j|k�r°t dƒ‚|j|k�rÎ|�sÎd}t
dƒ tt!|ƒ "t!|jƒ¡ƒ}|D ]:}|| |j| k�sêd}t | #||| |j| ¡ƒ‚�qê|�rB| ¡  | t|ƒ¡ |j ¡ }t|jƒdk�rft
dƒ nf|�rÌtt |dd…df ¡ƒ}|dd…df  |7  < ||| 7 }|t$k�rÌt
dt$› d�ƒ d}d}|	 |¡ t %||jf¡}||j }| &|j¡ |
 |j¡ �qZtj%|	dd�}	|�r@t 'dt|	ƒd ¡|	dd…df< t(dd„ |
D ƒƒ}|dk�rbd}
nP|t|
ƒk�r†t d|t|
ƒf ƒ‚n,t)dd�}|dk	�r¦| *|
¡}
nt(|
tƒ ƒ}
t|ƒ|�rÆt| ƒndd k�sÖt+‚d}|�rXt ,|¡}t-|dd… |dd… | ƒD ]P\}} }| .¡ }!|dk�rHtj/|d t|j0ƒt|jƒf|!j1d�}|!||| …< �q||||	||||
|||fS )z,Auxiliary function for concatenating epochs.z+epochs_list must be a list or tuple, got %sFz5epochs_list[%d] must be an instance of Epochs, got %sr‡   Nr   TzaConcatenation of Annotations within Epochs is not supported yet. All annotations will be dropped.r  rˆ   r   zepochs[ú]rÕ  zEpochs must have same timesz$Baseline must be same for all epochszfThe original raw sampling rate of the Epochs does not match for all Epochs. Please proceed cautiously.zˆevent_id values must be the same for identical keys for all concatenated epochs. Key "{}" maps to {} in some epochs and to {} in others.z3One of the Epochs objects to concatenate was empty.zEvent number greater than zM created, events[:, 0] will be assigned consecutive increasing integer valuesrÊ   c                 s   s   | ]}|d k	V  qd S r:  ro   )r¿   Z	this_metaro   ro   rp   rù   ‘  s     z&_concatenate_epochs.<locals>.<genexpr>zN%d of %d epochs instances have metadata, either all or none must have metadata)ÚstrictrÌ   rr  )2r  rÎ   rì   rM  rN  r$  rî   rj   r”   r‡   rH   rÍ   r'  rÛ  r}  r•   rš   r¤   rž   r  r£   r   rŽ   r¯   r™   r²   rœ   r’   r  r   ÚallcloserŸ   r  rÓ   rS  rS  r   rÕ   r’  r  r?  rM   Úconcatrw   ZcumsumrL  r‘   r§   r]  rs  )"r•  rÃ  rÄ  rÖ  ZwarnedÚeirk   rf  rÉ  r•   rš   r¤   rž   r  ró   rŽ   r¯   r™   r²   ÚshiftZevents_offsetZevents_overflowr3  Zcommon_keysrm   r.  ZevsZmax_timestampZn_haverb  r´   rþ  rÿ  Z	this_dataro   ro   rp   rÅ  0  sÐ    ÿ

ÿÿþ

"ÿÿ





 

þ

$
&
þ  ÿrÅ  c                 C   sF   t  dd„ |
D ƒ¡d }	t| |||||||	|
dd||d�}| ¡  |S )z3Finish concatenation for epochs not read from disk.c                 S   s   g | ]}t |ƒd k‘qS rM  r7  ro  ro   ro   rp   rÁ   °  s     z"_finish_concat.<locals>.<listcomp>r   FrÝ  )r¤   r²   r¯   r*  r+  rš   ró   )r’   rØ   rî   rÛ  )rŽ   r´   ró   r•   r™   rž   r  rš   r¤   r²   r¯   rf  ro   ro   rp   Ú_finish_concat­  s$              ýrÝ  )rÖ  rF   c                C   s   t t| ||d�Ž S )a  Concatenate a list of `~mne.Epochs` into one `~mne.Epochs` object.

    .. note:: Unlike `~mne.concatenate_raws`, this function does **not**
              modify any of the input data.

    Parameters
    ----------
    epochs_list : list
        List of `~mne.Epochs` instances to concatenate (in that order).
    add_offset : bool
        If True, a fixed offset is added to the event times from different
        Epochs sets, such that they are easy to distinguish after the
        concatenation.
        If False, the event times are unaltered during the concatenation.
    %(on_mismatch_info)s
    %(verbose)s

        .. versionadded:: 0.24

    Returns
    -------
    epochs : instance of Epochs
        The result of the concatenation.

    Notes
    -----
    .. versionadded:: 0.9.0
    )rÄ  rÖ  )rÝ  rÅ  )r•  rÄ  rÖ  rF   ro   ro   rp   Úconcatenate_epochs¹  s    þrÞ  r™  r4  rþ   ç      Y@c           ?      C   sz  ddl m}m}m}m}m}m}m}m}m	}m
} |dkr@tdƒ‚ddlm} t| tƒshtdt| ƒf ƒ‚|dkrz| jd n|}t|ƒ}t|tjƒrš||ƒ}|\}}}~|| ƒ t|| jdƒ}||| jd	ƒ}t d
t| jƒ ¡ t | jdd…df t | jdd…df ¡¡�stdƒ‚| j ¡ }|||||	ƒ\}}}} }!||||||ƒ\}"}t| jƒt| jƒ }#}$t t  |#¡|¡}%t !|#|$f¡}&d}'t"|||  d	d�}(|||	d�})||(|	d�}*||ƒ d}+|||gƒ\},}-d}.d}/|"|  }0t#||d	|d�}1||ƒ},t$| ƒD �]z\}2}3| j| j%d df | }4t &||4k¡d }5t|5ƒdk�rL|d d }6n6|5d }5t 't (||5 ||5g j)g¡ddddggg¡}6d *dd„ |6dd…df d D ƒ¡}7|/dk�s¾t +|/|6¡�sÞt d|2d |7f ¡ d}8|6}/nt d|2d f ¡ d	}8|3 ¡ }3|8�s8||1|*|6|0d�}9tj, -|9dd…d|,…f ¡}:|9|:9 }9|.|97 }.|3|�rPt.dƒn|  |:9  < |&|37 }&|+|:7 }+|'d7 }'�qü~(d};|'dk�r˜|& /tj0¡ n˜|&|  |+  < |&|%  |�rº|+n|'  < |.|+ }.d|1d< ||1|)|ƒ}<||1d< |<|" }<||.ƒd d|,… }=|=|0j)9 }=t 1|<|=¡};t 1|;|&||   ¡|&|< ||d< | j2|&|||'d| j3d �}>||>ƒ t d!|'f ¡ |
�rv|>|;fS |>S )"u  Average data using Maxwell filtering, transforming using head positions.

    Parameters
    ----------
    epochs : instance of Epochs
        The epochs to operate on.
    %(head_pos_maxwell)s
    orig_sfreq : float | None
        The original sample frequency of the data (that matches the
        event sample numbers in ``epochs.events``). Can be ``None``
        if data have not been decimated or resampled.
    %(picks_all_data)s
    %(origin_maxwell)s
    weight_all : bool
        If True, all channels are weighted by the SSS basis weights.
        If False, only MEG channels are weighted, other channels
        receive uniform weight per epoch.
    %(int_order_maxwell)s
    %(ext_order_maxwell)s
    %(destination_maxwell_dest)s
    %(ignore_ref_maxwell)s
    return_mapping : bool
        If True, return the mapping matrix.
    %(mag_scale_maxwell)s

        .. versionadded:: 0.13
    %(verbose)s

    Returns
    -------
    evoked : instance of Evoked
        The averaged epochs.

    See Also
    --------
    mne.preprocessing.maxwell_filter
    mne.chpi.read_head_pos

    Notes
    -----
    The Maxwell filtering version of this algorithm is described in [1]_,
    in section V.B "Virtual signals and movement correction", equations
    40-44. For additional validation, see [2]_.

    Regularization has not been added because in testing it appears to
    decrease dipole localization accuracy relative to using all components.
    Fine calibration and cross-talk cancellation, however, could be added
    to this algorithm based on user demand.

    .. versionadded:: 0.11

    References
    ----------
    .. [1] Taulu S. and Kajola M. "Presentation of electromagnetic
           multichannel data: The signal space separation method,"
           Journal of Applied Physics, vol. 97, pp. 124905 1-10, 2005.
    .. [2] Wehner DT, HÃ¤mÃ¤lÃ¤inen MS, Mody M, Ahlfors SP. "Head movements
           of children in MEG: Quantification, effects on source
           estimation, and compensation. NeuroImage 40:541â€“550, 2008.
    r   )
Ú_trans_sss_basisÚ_reset_meg_badsÚ_check_usableÚ_col_norm_pinvÚ_get_n_momentsÚ_get_mf_picks_fix_magsÚ_prep_mf_coilsÚ_check_destinationÚ_remove_meg_projsÚ_get_coil_scaleNz,head_pos must be provided and cannot be None)Úhead_pos_to_trans_rot_tz,epochs must be an instance of Epochs, not %srˆ   rÀ  Tz&Aligning and averaging up to %s epochsr   z0Epochs must have monotonically increasing events)rÍ   )Ú
ignore_refr…  )Ú	int_orderÚ	ext_orderZ
head_frameÚoriginZ
dev_head_tÚtransrÌ   rŠ   r  c                 s   s   | ]}d | V  qdS )z%0.1fNro   )r¿   Útrro   ro   rp   rù   X  s     z$average_movements.<locals>.<genexpr>rþ   rª  z0    Processing epoch %s (device location: %s mm)Fz/    Processing epoch %s (device location: same))Ú
coil_scalerí  rt  )r1  rH  rb  z%Created Evoked dataset from %s epochs)4Zpreprocessing.maxwellrà  rá  râ  rã  rä  rå  ræ  rç  rè  ré  rM  Zchpirê  r  rî   rN  rŽ   r  r’   Zndarrayr-   rE   r”   r•   rÓ  rÏ   rê   rÍ   r]  rŸ   rë   r  rw  r%   ri   r$  r  rØ   Zvstackr_  r–   rÂ   rÙ  ZlinalgZnormrC  rˆ  r‰  r%  r‹  rŒ  )?rk   Zhead_posZ
orig_sfreqr  rî  Z
weight_allrì  rí  Zdestinationrë  Zreturn_mappingZ	mag_scalerF   rà  rá  râ  rã  rä  rå  ræ  rç  rè  ré  rê  ZtrnZrotro  Zrecon_transZinfo_toZ	meg_picksZ	mag_picksZ
grad_picksZ	good_maskrÇ  rñ  r�  r^  Zother_picksr´   r’  Z	info_fromZall_coils_reconZ	all_coilsZw_sumZn_inr  ZS_decompZ
last_transZdecomp_coil_scaleÚexprÛ  r4  rˆ  r  rï  Zloc_strZreuseÚSÚweightÚmappingZS_reconZpS_averl  ro   ro   rp   Úaverage_movementsÝ  sÒ    A0
ÿ
ÿ0
ÿ    ÿÿÿ$
ÿÿÿ


 þrö  rŠ   r…  c           
      C   s@   t | |||d�}d| jd  }	t| ||gd||	 d||||d�
S )a  Divide continuous raw data into equal-sized consecutive epochs.

    Parameters
    ----------
    raw : instance of Raw
        Raw data to divide into segments.
    duration : float
        Duration of each epoch in seconds. Defaults to 1.
    %(preload)s
    %(reject_by_annotation_epochs)s

        .. versionadded:: 0.21.0
    %(proj_epochs)s

        .. versionadded:: 0.22.0
    overlap : float
        The overlap between epochs, in seconds. Must be
        ``0 <= overlap < duration``. Default is 0, i.e., no overlap.

        .. versionadded:: 0.23.0
    id : int
        The id to use (default 1).

        .. versionadded:: 0.24.0
    %(verbose)s

    Returns
    -------
    epochs : instance of Epochs
        Segmented data.

    Notes
    -----
    .. versionadded:: 0.20
    )r%  ÚdurationÚoverlaprŠ   rˆ   r   N)r™   rž   r  r¤   r  rø  r*  rF   )r:   rŽ   r  )
r(  r÷  r  rø  r*  rø  r%  rF   r•   Údeltaro   ro   rp   Úmake_fixed_length_epochs“  s    'ÿ  ýrú  )rõ   )NNN)T)r>  )TTN)N)N)TT)T)NNNr™  Tr4  rþ   NFFrß  N)rŠ   FTTr…  r   N) rl  Ú	functoolsr   Úcollectionsr   rÍ   r   r­   r�  Úos.pathÚpathru   Únumpyr’   Zio.utilsr   Zio.writer   r	   r
   r   r   r   r   r   r   r   r   r   r   r   Zio.meas_infor   r   r   r   r   Zio.openr   r   Zio.treer   Zio.tagr   r   Zio.constantsr    Zio.fiff.rawr!   Zio.pickr"   r#   r$   r%   r&   r'   r(   Zio.projr)   r*   Zio.baser+   r,   Zbemr-   rl  r.   r¤   r/   r0   r1   Zchannels.channelsr2   r3   r4   Úfilterr5   r6   r7   r
  r8   r‡  r9   r:   r;   Úfixesr<   Zvizr=   r>   r?   r@   rA   rB   ÚutilsrC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   Z
utils.docsra   r‡   rb   rc   rd   rq   rƒ   rx   r˜   rã   rí   rî   rÜ  r‰  r  r�  r”  r–  rT  r™  r\  rº  r¼  Úobjectr½  r»  rÐ  rÒ  rÔ  rÅ  rÝ  rÞ  rö  rú  ro   ro   ro   rp   Ú<module>   sô   @$ €	"hE1     þ             ~
     ÿ
  1 3r
;
)$ ÿ,  2ÿ}ÿ#                ý 6         þ