U
    f»{j”’ ã                   @   sØ  d dl mZ d dlmZ d dlmZ d dlZd dlmZ	 d dl
Z
d dlmZ d dlZddlmZ ddlmZmZ dd	lmZmZmZmZmZ dd
lmZmZmZ ddlmZm Z m!Z!m"Z" ddl#m$Z$m%Z%m&Z&m'Z' ddl(m)Z)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8 ddl9m:Z:m;Z;m<Z< ddl=m>Z>m?Z?m@Z@mAZAmBZBmCZC ddlDmEZE ddlmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^ ddl_m`Z` ddlambZbmcZcmdZdmeZe ddlfmgZgmhZh ddl9miZimjZjmkZk eJG dd„ de"ee$e%e&e^eSe>ƒ
ƒZldd„ Zmd;dd„Zndd „ Zod!d"„ Zpd#d$„ ZqG d%d&„ d&erƒZsG d'd(„ d(erƒZtd)d*„ ZuG d+d,„ d,ƒZvd-d.„ ZweJd/d0„ ƒZxd1d2„ Zyd3d4„ ZzePd<d5dd6œd7d8„ƒZ{d9d:„ Z|dS )=é    )Únullcontext©Údeepcopy)Ú	timedeltaN)Údefaultdicté   )ÚFIFF)Ú_construct_bids_filenameÚ_check_orig_units)Ú
pick_typesÚpick_channelsÚ	pick_infoÚ_picks_to_idxÚchannel_type)Úwrite_meas_infoÚ_ensure_infos_matchÚContainsMixin)Ú
setup_projÚactivate_projÚ_proj_equalÚ	ProjMixiné   )ÚUpdateChannelsMixinÚSetChannelsMixinÚInterpolationMixinÚ_unit2human)Úset_current_compÚmake_compensator)Ústart_and_end_fileÚstart_blockÚ	end_blockÚwrite_dau_pack16Úwrite_floatÚwrite_doubleÚwrite_complex64Úwrite_complex128Ú	write_intÚwrite_idÚwrite_stringÚ_get_split_sizeÚ_NEXT_FILE_BUFFER)Ú_annotations_starts_stopsÚ_write_annotationsÚ_handle_meas_date)ÚFilterMixinÚnotch_filterÚresampleÚ_resamp_ratio_lenÚ_resample_stim_channelsÚ
_check_fun)Úparallel_func)Ú_check_fnameÚ_check_pandas_installedÚ
sizeof_fmtÚ_check_pandas_index_argumentsÚfill_docÚcopy_docÚcheck_fnameÚ_get_stim_channelÚ_stamp_to_dtÚloggerÚverboseÚ
_time_maskÚwarnÚ	SizeMixinÚcopy_function_doc_to_method_docÚ_validate_typeÚ_check_preloadÚ_get_argvaluesÚ_check_optionÚ_build_data_frameÚ_convert_timesÚ_scale_dataframe_dataÚ_check_time_formatÚ_arange_divÚ	TimeMixin)Ú_handle_default)Úplot_rawÚplot_raw_psdÚplot_raw_psd_topoÚ_RAW_CLIP_DEF)Úfind_eventsÚconcatenate_events)ÚAnnotationsÚ_combine_annotationsÚ_sync_onsetc                        sH  e Zd ZdZeddddddejddf	ddœd	d
„ƒZed”dd„ƒZe	dd„ ƒZ
ed•dd„ƒZdd„ Zd–dd„Zed—dd„ƒZdd„ Ze	dd„ ƒZe	dd„ ƒZe	dd„ ƒZe	d d!„ ƒZe	d"d#„ ƒZd˜‡ fd$d%„	Ze	d&d'„ ƒZe	d(d)„ ƒZe	d*d+„ ƒZed™ddœd.d/„ƒZd0d1„ Zd2d3„ Zd4d5„ Zd6d7„ Zd8d9„ Zdšd:d;„Zd<d=„ Z ed›dddd>œd?d@„ƒZ!edœdAdB„ƒZ"e#e$j%ƒd�‡ fdJdK„	ƒZ%edždMdN„ƒZ&edŸdPdQ„ƒZ'ed ddœdSdT„ƒZ(ed¡ddœdUdV„ƒZ)ed¢dZd[„ƒZ*ed£ddd\œd]d^„ƒZ+d_d`„ Z,e-e.ƒddadRdbdcddddedd,dddd,ddddfe/dd,dgddCddd,d,dhddfddddiœdjdk„ƒZ0ee-e1ƒdej2dddddd,dddldmdndod,dCd,dddd,ddFdpdfdqdr„ƒƒZ3e-e4ƒd¤dvdw„ƒZ5e	dxdy„ ƒZ6e	dzd{„ ƒZ7e	d|d}„ ƒZ8d~d„ Z9ed¥d€d�„ƒZ:e;d¦d‚dƒ„ƒZ<d„d…„ Z=d†d‡„ Z>dˆd‰„ Z?d§dŠd‹„Z@d¨dŒd�„ZAd©dŽd�„ZBedªddœd�d‘„ƒZCd«d’d“„ZD‡  ZES )¬ÚBaseRawa±	  Base class for Raw data.

    Parameters
    ----------
    %(info_not_none)s
    preload : bool | str | ndarray
        Preload data into memory for data manipulation and faster indexing.
        If True, the data will be preloaded into memory (fast, requires
        large amount of memory). If preload is a string, preload is the
        file name of a memory-mapped file which is used to store the data
        on the hard drive (slower, requires less memory). If preload is an
        ndarray, the data are taken from that array. If False, data are not
        read until save.
    first_samps : iterable
        Iterable of the first sample number from each raw file. For unsplit raw
        files this should be a length-one list or tuple.
    last_samps : iterable | None
        Iterable of the last sample number from each raw file. For unsplit raw
        files this should be a length-one list or tuple. If None, then preload
        must be an ndarray.
    filenames : tuple
        Tuple of length one (for unsplit raw files) or length > 1 (for split
        raw files).
    raw_extras : list of dict
        The data necessary for on-demand reads for the given reader format.
        Should be the same length as ``filenames``. Will have the entry
        ``raw_extras['orig_nchan']`` added to it for convenience.
    orig_format : str
        The data format of the original raw file (e.g., ``'double'``).
    dtype : dtype | None
        The dtype of the raw data. If preload is an ndarray, its dtype must
        match what is passed here.
    buffer_size_sec : float
        The buffer size in seconds that should be written by default using
        :meth:`mne.io.Raw.save`.
    orig_units : dict | None
        Dictionary mapping channel names to their units as specified in
        the header file. Example: {'FC1': 'nV'}.

        .. versionadded:: 0.17
    %(verbose)s

    See Also
    --------
    mne.io.Raw : Documentation of attribute and methods.

    Notes
    -----
    This class is public to allow for stable type-checking in user
    code (i.e., ``isinstance(my_raw_object, BaseRaw)``) but should not be used
    as a constructor for `Raw` objects (use instead one of the subclass
    constructors, or one of the ``mne.io.read_raw_*`` functions).

    Subclasses must provide the following methods:

        * _read_segment_file(self, data, idx, fi, start, stop, cals, mult)
          (only needed for types that support on-demand disk reads)
    F)r   N©NÚdoubleç      ð?©r?   c             	      sV  t |tjƒrz|jtjtjfkr,td|j ƒ‚|j|kr>tdƒ‚|ˆ_dˆ_	t
|ƒdksZt‚|d ˆjjd  d g}d}n$|d krŠtdƒ‚|sšdˆ_	d}nd}t |¡ˆ_t |¡ˆ_ˆ d }ˆ jdd	��$ t ˆ d
 tƒrêtˆ d
 ƒˆ d
< W 5 Q R X ˆ ˆ_t|	ƒˆ_t ˆ d ¡}tˆ d ƒD ]*}ˆ d | d ˆ d | d  ||< �qt |dk¡d }t
|ƒdk�r„td‡fdd„|D ƒ ƒ‚|ˆ_tdd„ |D ƒƒˆ_ˆjD ]}ˆ d |d< �q¤‡ fdd„tt
|ƒƒD ƒˆ_ˆjˆ_ˆjd k	�rt
ˆ d ƒ�rt dˆj ¡ d ˆ_ t|ƒˆ_!t"|t#dƒ t$d|dƒ |ˆ_%ˆ�rt ˆt&ƒ�sXtd 't(ˆƒ¡ƒ‚t)ˆƒ‰t*|ˆ d ƒD ]*\}}|ˆk�rnˆ| }ˆ|= |ˆ|< �qntˆ d ƒ}d|k�rÌˆj+d  ,d¡�sÌ| -d¡ ‡fdd„|D ƒ}t.|ƒ�s|| /d¡ }td '|¡ƒ‚t0ˆƒ‰ˆˆ_1tƒ ˆ_2d ˆ_3|ˆ_4ˆ 5d ¡ |d ˆ_6|�rJˆ 7|¡ t8ƒ ˆ_9d S ) Nz.datatype must be float64 or complex128, not %szpreload and dtype must matchTr   r   Fz5last_samps must be given unless preload is an ndarrayÚch_names)Zcheck_afterÚ	meas_dateÚnchanÚchsÚrangeÚcalzBad cals for channels %sc                    s   i | ]}|ˆ j | “qS © )r]   )Ú.0Úii©Úselfrc   úJ/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/io/base.pyÚ
<dictcomp>¢   s      z$BaseRaw.__init__.<locals>.<dictcomp>c                 s   s    | ]}|d krt ƒ n|V  qd S rY   )Údict©rd   Úrrc   rc   rh   Ú	<genexpr>¤   s     z#BaseRaw.__init__.<locals>.<genexpr>Z
orig_nchanc                    s   g | ]}t  ˆ d  ¡‘qS )r_   )ÚnpÚarange)rd   Ú_©Úinforc   rh   Ú
<listcomp>§   s   ÿz$BaseRaw.__init__.<locals>.<listcomp>ÚcompszCurrent compensation grade : %dÚorig_format)rZ   ÚsingleÚintÚshortz,orig_units must be of type dict, but got  {}zSTI 014ú.fifc                    s   g | ]}|ˆ k‘qS rc   rc   )rd   Úch)Ú
orig_unitsrc   rh   rs   Ð   s     z+Channel {} has no associated original unit.):Ú
isinstancern   ÚndarrayÚdtypeÚfloat64Z
complex128ÚRuntimeErrorÚ
ValueErrorÚ_dataÚpreloadÚlenÚAssertionErrorÚshapeÚarrayÚ_last_sampsÚ_first_sampsÚ_unlockÚtupler=   rr   ÚfloatÚbuffer_size_secÚemptyra   ÚwhereÚ_calsÚlistÚ_raw_extrasÚ_read_picksÚcompensation_gradeÚ_read_comp_grader>   Ú_compÚ
_filenamesrD   ÚstrrG   ru   rj   ÚformatÚtyper   ÚzipÚ	filenamesÚendswithÚremoveÚallÚindexr
   Z_orig_unitsZ_projectorsÚ
_projectorÚ_dtype_Úset_annotationsÚ_cropped_sampÚ_preload_datarF   Z_init_kwargs)rg   rr   rƒ   Zfirst_sampsZ
last_sampsrœ   Z
raw_extrasru   r~   r�   r{   r?   Zload_from_diskZorig_ch_namesÚcalsÚkÚbadrl   Zold_chZnew_chZ	this_unitr]   Zch_correspondZch_without_orig_unitrc   )rr   r{   rg   rh   Ú__init__v   s®    ÿ

(ÿ


ÿÿ
  ÿÿ

ÿ

ÿ


zBaseRaw.__init__c           	      C   sö   t |ƒ}| j}||krò| jr$tdƒ‚| jr.|n| j}t| j||ƒ}t d||f ¡ t	| j|ƒ | jrìt d¡ t
 t
 dt| jƒd¡t| jƒgg¡}t|dd… |dd… ƒD ]8\}}t
 || jdd…||…f ¡| jdd…||…f< q°n|| _| S )	aë  Apply CTF gradient compensation.

        .. warning:: The compensation matrices are stored with single
                     precision, so repeatedly switching between different
                     of compensation (e.g., 0->1->3->2) can increase
                     numerical noise, especially if data are saved to
                     disk in between changing grades. It is thus best to
                     only use a single gradient compensation level in
                     final analyses.

        Parameters
        ----------
        grade : int
            CTF gradient compensation level.
        %(verbose)s

        Returns
        -------
        raw : instance of Raw
            The modified Raw instance. Works in-place.
        zECannot change compensation on data where projectors have been appliedz*Compensator constructed to change %d -> %dz#Applying compensator to loaded datar   i'  Néÿÿÿÿr   )rw   r”   Úprojr€   rƒ   r•   r   rr   r>   r   rn   Úconcatenatero   r„   Útimesr›   Údotr‚   r–   )	rg   Zgrader?   Zcurrent_compZ	from_compÚcompZlimsÚstartÚstoprc   rc   rh   Úapply_gradient_compensationä   s.    ÿ

ÿ" ÿz#BaseRaw.apply_gradient_compensationc                 C   s   | j S )z@Datatype for loading data (property so subclasses can override).)r¢   rf   rc   rc   rh   Ú_dtype  s    zBaseRaw._dtyper   c              
   C   s|  t |ƒ}|dkr| jntt |ƒ| jgƒ}||kr8tdƒ‚|dkrT| jd }tdƒ}nt|ƒ}t|ƒ}~|| jd ksxt‚||| f}	| j	}
t
|tjƒr¸|j|	kr²td|j|	f ƒ‚|}nt||	|
ƒ}t dgtj| jdd�f¡}t |¡}t t ||dd… ¡t |d |dd	… ¡¡}tt t| jƒ¡| ƒ}| j ¡ tjdd…f }|dk	�r„|jd |jd   k�r~|jd k�s„n t‚| jdk	�rÆ|dk	�r¶| j| }t || |¡}n| j| | }n|dk	�rÞ|| | }nd}~|dk�r|j| }|j|dfk�st‚|}nhd}|j|t| jƒfk�s0t‚t tj|dd
�¡d }|dd…|f }t  !dt|ƒ› dt| jƒ› d�¡ |dk|dkA �s�t‚d}t "|¡d D ]Ô}| j#| }|dk�rÊ||||  7 }t |||  | j#|  | j$| d g¡}|| j#| k �s||k �rtdƒ‚|| }t||| ƒ}t| j%| | ƒ}t&| ƒ '|dd…|f ||t |ƒt |ƒ||¡ ||7 }�q¢|S )aZ  Read a chunk of raw data.

        Parameters
        ----------
        start : int, (optional)
            first sample to include (first is 0). If omitted, defaults to the
            first sample in data.
        stop : int, (optional)
            First sample to not include.
            If omitted, data is included to the end.
        sel : array, optional
            Indices of channels to select.
        data_buffer : array or str, optional
            numpy array to fill with data read, must have the correct shape.
            If str, a np.memmap with the correct data type will be used
            to store the data.
        projector : array
            SSP operator to apply to the data.
        %(verbose)s

        Returns
        -------
        data : array, [channels x samples]
           the data matrix (channels x samples).
        NzNo data in this ranger_   z)data_buffer has incorrect shape: %s != %sr   rw   ©r~   r   rª   )ZaxiszReading ú/z channels due to projectionz"Bad array indexing, could be a bug)(rw   Ún_timesÚminr�   rr   Úslicer„   Ú_convert_slicer…   r³   r|   rn   r}   r†   Ú_allocate_datar¬   r‡   Ú_raw_lengthsÚcumsumÚlogical_andÚlessÚgreater_equalro   r]   r�   ÚravelÚnewaxisr–   r®   ÚTr�   Úanyr>   ÚdebugZnonzeror‰   rˆ   r“   Ú_ReadSegmentFileProtectorÚ_read_segment_file)rg   r°   r±   ÚselÚdata_bufferÚ	projectorr?   Zn_outÚidxZ
data_shaper~   ÚdataÚ
cumul_lensZ
files_usedr¦   ÚmultZneed_idxÚoffsetÚfiZ
start_fileZ	stop_fileZn_readÚthis_slZorig_idxrc   rc   rh   Ú_read_segment  sœ     


ÿÿ



ÿÿ
0




ÿ

ÿ     þzBaseRaw._read_segmentc                 C   s   t ‚dS )a”  Read a segment of data from a file.

        Only needs to be implemented for readers that support
        ``preload=False``. Any implementation should only make use of:

        - self._raw_extras[fi]
        - self._filenames[fi]

        So be sure to store any information necessary for reading raw data
        in self._raw_extras[fi]. Things like ``info`` can be decoupled
        from the original data (e.g., different subsets of channels) due
        to picking before preload, for example.

        Parameters
        ----------
        data : ndarray, shape (n_out, stop - start + 1)
            The data array. Should be modified inplace.
        idx : ndarray | slice
            The requested channel indices.
        fi : int
            The file index that must be read from.
        start : int
            The start sample in the given file.
        stop : int
            The stop sample in the given file (inclusive).
        cals : ndarray, shape (len(idx), 1)
            Channel calibrations (already sub-indexed).
        mult : ndarray, shape (n_out, len(idx) | None
            The compensation + projection + cals matrix, if applicable.
        N)ÚNotImplementedError©rg   rË   rÊ   rÏ   r°   r±   r¦   rÍ   rc   rc   rh   rÆ   Œ  s    zBaseRaw._read_segment_filec                 C   sª   |dk rdS |r’t | jƒdkr’| j}| jd }t| |jƒ}	t |	|| k ¡}
t |	|
 |j|
  || k¡}
|j|
 D ]}| 	¡  
d¡rv|  S qv| j|t||ƒfdd�S )aw  Check if data segment is bad.

        If the slice is good, returns the data in desired range.
        If rejected based on annotation, returns description of the
        bad segment as a string.

        Parameters
        ----------
        start : int
            First sample of the slice.
        stop : int
            End of the slice.
        picks : array of int
            Channel picks.
        reject_start : int
            First sample to check for overlaps with bad annotations.
        reject_stop : int
            Last sample to check for overlaps with bad annotations.
        reject_by_annotation : bool
            Whether to perform rejection based on annotations.
            False by default.

        Returns
        -------
        data : array | str
            Data in the desired range (good segment) or description of the bad
            segment.
        r   NÚsfreqr¨   F©Úreturn_times)r„   Úannotationsrr   rW   Úonsetrn   r�   ÚdurationÚdescriptionÚlowerÚ
startswithÚ_getitemr¸   )rg   r°   r±   ÚpicksZreject_startZreject_stopÚreject_by_annotationÚannotrÔ   rØ   ÚoverlapsÚdescrrc   rc   rh   Ú_check_bad_segment­  s    
ÿ
zBaseRaw._check_bad_segmentc                 C   s   | j s|  d¡ | S )a|  Load raw data.

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

        Returns
        -------
        raw : instance of Raw
            The raw object with data.

        Notes
        -----
        This function will load raw data if it was not already preloaded.
        If data were already preloaded, it will do nothing.

        .. versionadded:: 0.10.0
        T)rƒ   r¥   )rg   r?   rc   rc   rh   Ú	load_dataÚ  s    
zBaseRaw.load_datac                 C   s„   |}t |ttjfƒr|sd}t ddt| jƒd d| jd f ¡ | j|| j	d�| _
t| j
ƒ| jd kslt‚d	| _d| _|  ¡  dS )
zActually preload the data.Nz-Reading %d ... %d  =  %9.3f ... %9.3f secs...r   r   ç        rª   ©rÈ   rÉ   r_   T)r|   Úboolrn   Zbool_r>   rr   r„   r­   rÑ   r¡   r‚   r…   rƒ   r–   Úclose)rg   rƒ   rÈ   rc   rc   rh   r¥   ò  s    ÿ ÿzBaseRaw._preload_datac                 C   s   | j t| jd ƒ S ©NrÔ   )Ú
first_samprŒ   rr   rf   rc   rc   rh   Ú_first_time   s    zBaseRaw._first_timec                 C   s   | j S )z@The first data sample.

        See :term:`first_samp`.
        )r¤   rf   rc   rc   rh   rê     s    zBaseRaw.first_sampc                 C   s   | j S )z>The first time point (including first_samp but not meas_date).)rë   rf   rc   rc   rh   Ú
first_time  s    zBaseRaw.first_timec                 C   s   | j t| jƒ d S )zThe last data sample.r   )rê   Úsumr»   rf   rc   rc   rh   Ú	last_samp  s    zBaseRaw.last_sampc                 C   s   | j t| jd ƒ S ré   )rî   rŒ   rr   rf   rc   rc   rh   Ú
_last_time  s    zBaseRaw._last_timec                    sv   t |ƒ}|dkrd}n@| jd dkr4td|f ƒ‚n"| jd td| jƒ }||  ¡ }t |¡| }tt	| ƒ 
||¡S )aÊ  Convert time to indices.

        Parameters
        ----------
        times : list-like | float | int
            List of numbers or a number representing points in time.
        use_rounding : bool
            If True, use rounding (instead of truncation) when converting
            times to indices. This can help avoid non-unique indices.
        origin : datetime | float | int | None
            Time reference for times. If None, ``times`` are assumed to be
            relative to :term:`first_samp`.

            .. versionadded:: 0.17.0

        Returns
        -------
        index : ndarray
            Indices relative to :term:`first_samp` corresponding to the times
            supplied.
        Nr   r^   z:origin must be None when info["meas_date"] is None, got %s)r-   rr   r�   r   rë   Útotal_secondsrn   Ú
atleast_1dÚsuperrX   Útime_as_index)rg   r­   Úuse_roundingÚoriginÚdeltaZfirst_samp_in_abs_time©Ú	__class__rc   rh   ró     s    ÿ
ÿzBaseRaw.time_as_indexc                 C   s   dd„ t | j| jƒD ƒS )Nc                 S   s   g | ]\}}|| d  ‘qS )r   rc   )rd   ÚfÚlrc   rc   rh   rs   A  s     z(BaseRaw._raw_lengths.<locals>.<listcomp>)r›   r‰   rˆ   rf   rc   rc   rh   r»   ?  s    zBaseRaw._raw_lengthsc                 C   s   | j S )z7:class:`~mne.Annotations` for marking segments of data.©Ú_annotationsrf   rc   rc   rh   r×   C  s    zBaseRaw.annotationsc                 C   s
   t | jƒS )zThe filenames used.)r‹   r—   rf   rc   rc   rh   rœ   H  s    zBaseRaw.filenamesTÚraisec          
      C   s  t | jd ƒ}|dkr(tg g g |ƒ| _nÜt|tdƒ |dkrN|jdk	rNtdƒ‚d| jd  }| ¡ }| | j|¡ |jdkr¨|j	d| j
d | |d	� | j| j7  _nP|td| jƒ }|t| j
d | d
� }	|j	||	|d� | j||j  ¡ 8  _||_|| _| S )aõ  Setter for annotations.

        This setter checks if they are inside the data range.

        Parameters
        ----------
        annotations : instance of mne.Annotations | None
            Annotations to set. If None, the annotations is defined
            but empty.
        %(emit_warning)s
            The default is True.
        %(on_missing_ch_names)s
        %(verbose)s

        Returns
        -------
        self : instance of Raw
            The raw object with annotations.
        r^   Nr×   aQ  Ambiguous operation. Setting an Annotation object with known ``orig_time`` to a raw object which has ``meas_date`` set to None is ambiguous. Please, either set a meaningful ``meas_date`` to the raw object; or set ``orig_time`` to None in which case the annotation onsets would be taken in reference to the first sample of the raw object.r[   rÔ   r   rª   )Úemit_warning)Úseconds)ÚtminÚtmaxrþ   )r-   rr   rU   rü   rD   Ú	orig_timer€   ÚcopyZ_prune_ch_namesÚcropr­   rØ   rë   r   rð   Z
_orig_time)
rg   r×   rþ   Z
on_missingr?   r^   rö   Znew_annotationsr   r  rc   rc   rh   r£   M  s2    

ÿÿÿzBaseRaw.set_annotationsc                 C   sP   t | dƒrLt| jdd ƒd k	rL| jj}| `zt |¡ W n tk
rJ   Y nX d S )Nr‚   Úfilename)ÚhasattrÚgetattrr‚   r  Úosrž   ÚOSError)rg   r  rc   rc   rh   Ú__del__ˆ  s    
ÿzBaseRaw.__del__c                 C   s   | S )zEntering with block.rc   rf   rc   rc   rh   Ú	__enter__•  s    zBaseRaw.__enter__c                 C   s0   z|   ¡  W n tk
r*   |||f Y S X dS )zExit with block.N)rè   Ú	Exception)rg   Zexception_typeZexception_valÚtracerc   rc   rh   Ú__exit__™  s    zBaseRaw.__exit__c                 C   s0  t |tƒs|tdddƒf}t|ƒdkr.tdƒ‚t| j|d ƒ}t |d tƒrl|d }|j|j|j	  }}}nT|d }t
 |d ¡jjdkr’t|ƒ}t |tt
jfƒr¸||d d  }}}ntdƒ‚|dkrÌd}|dk	rè|dkrètd| ƒ‚t |tt
jfƒ�rt
 |g¡}|dk	�r&t|ƒdk�r&td	ƒ‚|||fS )
z+Parse the __getitem__ / __setitem__ tuples.Nr   z7Unable to access raw data (need both channels and time)r   r   Úiz%Must pass int or slice to __getitem__zstep needs to be 1 : %d givenzEmpty channel list)r|   r‹   r¸   r„   r€   r   rr   r°   r±   Ústeprn   r‡   r~   Úkindrw   Úintegerr�   )rg   ÚitemrÇ   Z
time_slicer°   r±   r  Zitem1rc   rc   rh   Ú_parse_get_set_params   s2    
ÿzBaseRaw._parse_get_set_paramsc                 C   s
   |   |¡S )aý  Get raw data and times.

        Parameters
        ----------
        item : tuple or array-like
            See below for use cases.

        Returns
        -------
        data : ndarray, shape (n_channels, n_times)
            The raw data.
        times : ndarray, shape (n_times,)
            The times associated with the data.

        Examples
        --------
        Generally raw data is accessed as::

            >>> data, times = raw[picks, time_slice]  # doctest: +SKIP

        To get all data, you can thus do either of::

            >>> data, times = raw[:]  # doctest: +SKIP

        Which will be equivalent to:

            >>> data, times = raw[:, :]  # doctest: +SKIP

        To get only the good MEG data from 10-20 seconds, you could do::

            >>> picks = mne.pick_types(raw.info, meg=True, exclude='bads')  # doctest: +SKIP
            >>> t_idx = raw.time_as_index([10., 20.])  # doctest: +SKIP
            >>> data, times = raw[picks, t_idx[0]:t_idx[1]]  # doctest: +SKIP

        )rÝ   )rg   r  rc   rc   rh   Ú__getitem__Ç  s    $zBaseRaw.__getitem__c                 C   sz   |   |¡\}}}| jr*| j|||…f }n| j|||| jd�}|rrtj|||jd  td�}|| j	d  }||fS |S d S )N)r°   r±   rÇ   rÉ   r   r´   rÔ   )
r  rƒ   r‚   rÑ   r¡   rn   ro   r†   rŒ   rr   )rg   r  rÖ   rÇ   r°   r±   rË   r­   rc   rc   rh   rÝ   í  s    
ÿzBaseRaw._getitemc                 C   s0   t | dƒ |  |¡\}}}|| j|||…f< dS )zSet raw data content.zModifying data of RawN)rE   r  r‚   )rg   r  ÚvaluerÇ   r°   r±   rc   rc   rh   Ú__setitem__ÿ  s    
zBaseRaw.__setitem__)r   r  r?   c             
   C   s  t |dddd� t |dddd� t| j|dd	d
�}|dk	rFt| ||ƒ}
t t | jd ¡| ¡}|  ||¡\}}|dkr||n|}|dkrŒ|n|}tt	d|ƒ| j
ƒ}tt	d|ƒ| j
ƒ}t| jƒdksÌ|dk�r>| j|t||ƒf|d�}|�r|\}}|dk	�r||
dd…tjf 9 }||fS |dk	�r:||
dd…tjf 9 }|S td| ¡ ddgƒ t| dgƒ\}}||k ||k@ }t || |¡}t || |¡}t|ƒdk�ræ| |||…f \}}|dk	�rÔ||
dd…tjf 9 }|�râ||fS |S || }t |t¡}t||ƒD ],\}}||k�r�qd||| || …< �qt dg|dgg¡}t |dd…  |dd… @ ¡d | }t |dd… |dd…  @ ¡d | }||  ¡ }|| }|dk�rÀ|dk�rjd}t | |||| ||| ¡¡ t t|ƒ|f¡}t |jd ¡}d}t||ƒD ]T\}}||k�r(�q|| | }| |||…f \|dd…||…f< |||…< |}�qnTd}t | |||| ||| ¡¡ | |||…f \}}tj|dd…|dd…  f< n| |||…f \}}|dk	�rô||
dd…tjf 9 }|�r||fS |S )aÌ  Get data in the given range.

        Parameters
        ----------
        %(picks_all)s
        start : int
            The first sample to include. Defaults to 0.
        stop : int | None
            End sample (first not to include). If None (default), the end of
            the data is  used.
        reject_by_annotation : None | 'omit' | 'NaN'
            Whether to reject by annotation. If None (default), no rejection is
            done. If 'omit', segments annotated with description starting with
            'bad' are omitted. If 'NaN', the bad samples are filled with NaNs.
        return_times : bool
            Whether to return times as well. Defaults to False.
        %(units)s
        tmin : int | float | None
            Start time of data to get in seconds. The ``tmin`` parameter is
            ignored if the ``start`` parameter is bigger than 0.

            .. versionadded:: 0.24.0
        tmax : int | float | None
            End time of data to get in seconds. The ``tmax`` parameter is
            ignored if the ``stop`` parameter is defined.

            .. versionadded:: 0.24.0
        %(verbose)s

        Returns
        -------
        data : ndarray, shape (n_channels, n_times)
            Copy of the data in the given range.
        times : ndarray, shape (n_times,)
            Times associated with the data samples. Only returned if
            return_times=True.

        Notes
        -----
        .. versionadded:: 0.14.0
        úint-liker°   rw   )ÚtypesÚ	item_nameÚ	type_name)r  Nr±   z	int, NonerŸ   rc   ©ÚexcludeNr_   r   rÕ   rß   ZomitÚnanÚBADFrª   r   zBOmitting {} of {} ({:.2%}) samples, retaining {} ({:.2%}) samples.zHSetting {} of {} ({:.2%}) samples to NaN, retaining {} ({:.2%}) samples.) rD   r   rr   Ú_get_ch_factorsrn   rñ   ro   Z_handle_tmin_tmaxr·   Úmaxr¶   r„   r×   rÝ   r¸   rÁ   rG   rÛ   r+   ÚmaximumÚminimumÚonesrç   r›   r¬   r�   rí   r>   r™   Úzerosr†   r  )rg   rÞ   r°   r±   rß   rÖ   Úunitsr   r  r?   Ú
ch_factorsZ
tmin_startZ	tmax_stopÚgetitemrË   r­   ZonsetsZendsZkeepÚ	n_samplesÚusedrØ   ÚendZstartsZstopsZn_keptZ
n_rejectedÚmsgrÊ   rc   rc   rh   Úget_data  s¨    .ÿÿ ÿ


ÿ

((

 þ
,
 þ
zBaseRaw.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¤|D ],}	t	ˆˆ |	dd…f fˆŽ| j|	dd…f< qtnD|‡ ‡‡‡fdd	„|D ƒƒ}
t
|ƒD ]\}}|
| | j|dd…f< qÈn(t	ˆˆ |dd…f fˆŽ| j|dd…f< | S )
aÆ  Apply a function to a subset of channels.

        %(applyfun_summary_raw)s

        Parameters
        ----------
        %(fun_applyfun)s
        %(picks_all_data_noref)s
        %(dtype_applyfun)s
        %(n_jobs)s
        %(channel_wise_applyfun)s

            .. versionadded:: 0.18
        %(verbose)s
        %(kwargs_fun)s

        Returns
        -------
        self : instance of Raw
            The raw object with transformed data.
        zraw.apply_functionrc   F©r  Zwith_ref_megzfun needs to be a functionNr   c                 3   s    | ]}ˆˆˆ | fˆŽV  qd S rY   rc   )rd   Úp©Zdata_inÚfunÚkwargsZp_funrc   rh   rm   ¾  s    z)BaseRaw.apply_function.<locals>.<genexpr>)rE   r   rr   Úcallabler�   r‚   r~   Úastyper4   r3   Ú	enumerate)rg   r1  rÞ   r~   Ún_jobsZchannel_wiser?   r2  ÚparallelrÊ   Zdata_picks_newÚppr/  rc   r0  rh   Úapply_function“  s4    
ÿÿ ÿÿzBaseRaw.apply_functionÚautoÚfirÚzeroÚhammingÚfirwin©ÚedgeÚbad_acq_skipÚreflect_limitedc                    s*   t ƒ j|||||||||	|
|||||d�S )N)	r6  ÚmethodÚ
iir_paramsÚphaseÚ
fir_windowÚ
fir_designÚskip_by_annotationÚpadr?   )rò   Úfilter)rg   Zl_freqZh_freqrÞ   Úfilter_lengthZl_trans_bandwidthZh_trans_bandwidthr6  rC  rD  rE  rF  rG  rH  rI  r?   r÷   rc   rh   rJ  É  s"              ûzBaseRaw.filterçš™™™™™©?c                 C   s\   t | jd ƒ}t| j|ddd�}t| dƒ t| j||||||||	|
||d||||d�| _| S )aÚ  Notch filter a subset of channels.

        Parameters
        ----------
        freqs : float | array of float | None
            Specific frequencies to filter out from data, e.g.,
            ``np.arange(60, 241, 60)`` in the US or ``np.arange(50, 251, 50)``
            in Europe. ``None`` can only be used with the mode
            ``'spectrum_fit'``, where an F test is used to find sinusoidal
            components.
        %(picks_all_data)s
        %(filter_length_notch)s
        notch_widths : float | array of float | None
            Width of each stop band (centred at each freq in freqs) in Hz.
            If None, ``freqs / 200`` is used.
        trans_bandwidth : float
            Width of the transition band in Hz.
            Only used for ``method='fir'``.
        %(n_jobs_fir)s
        %(method_fir)s
        %(iir_params)s
        mt_bandwidth : float | None
            The bandwidth of the multitaper windowing function in Hz.
            Only used in 'spectrum_fit' mode.
        p_value : float
            P-value to use in F-test thresholding to determine significant
            sinusoidal components to remove when ``method='spectrum_fit'`` and
            ``freqs=None``. Note that this will be Bonferroni corrected for the
            number of frequencies, so large p-values may be justified.
        %(phase)s
        %(fir_window)s
        %(fir_design)s
        %(pad_fir)s
            The default is ``'reflect_limited'``.

            .. versionadded:: 0.15
        %(verbose)s

        Returns
        -------
        raw : instance of Raw
            The raw instance with filtered data.

        See Also
        --------
        mne.filter.notch_filter
        mne.io.Raw.filter

        Notes
        -----
        Applies a zero-phase notch filter to the channels selected by
        "picks". By default the data of the Raw object is modified inplace.

        The Raw object has to have the data loaded e.g. with ``preload=True``
        or ``self.load_data()``.

        .. note:: If n_jobs > 1, more memory is required as
                  ``len(picks) * n_times`` additional time points need to
                  be temporaily stored in memory.

        For details, see :func:`mne.filter.notch_filter`.
        rÔ   rc   Zdata_or_ica)r  Únonezraw.notch_filterF)rK  Únotch_widthsÚtrans_bandwidthrC  rD  Úmt_bandwidthÚp_valuerÞ   r6  r  rE  rF  rG  rI  )rŒ   rr   r   rE   r/   r‚   )rg   ZfreqsrÞ   rK  rN  rO  r6  rC  rD  rP  rQ  rE  rF  rG  rI  r?   Úfsrc   rc   rh   r/   ×  s.    D
           úzBaseRaw.notch_filterÚboxcarc	              	      sÊ  |dkr*zt | ƒ}	W n tk
r(   Y nX tˆƒ‰t| jd ƒ‰ t dgt | j¡f¡}
|dkrvt| jdddg d�}nt	| j|ddd�}t
ˆˆ ||||d	�}t‡ ‡fd
d„| jD ƒŽ \}}|d t |t¡ }}t dgt|ƒ ¡}| j�r
t t| jƒ|d f| jj¡}tt| j|ƒƒD �]6\}\}}t|| ||d  ƒ}| j�r®| jdd…|
| |
|d  …f }t|f|Ž|dd…|f< t|ƒdk�rPt|| ||jd ƒ|||f< n¢tt| jƒƒD ]’}| j||
| |
|d  dd�d }|dk�r|dk�rt t| jƒ|d f|j¡}||k�r4t|||jd ƒd }nt|f|Ž}||||f< �q¼�qtt | j| ¡ƒ| _t | j| ¡ t¡| _t | j¡| d | _ t|ƒ| j|< t !|| j | j d ¡�sÄt"‚|| _d| _| j #d¡}|dk�rìtj$n|}| j %¡ �$ t&|ˆd ƒ| jd< ˆ| jd< W 5 Q R X |dk�rpz&t | ƒ}t|ƒt|	ƒk�rRt'dƒ W n tk
�rj   Y nX | S | (¡ }t )t |dd…df | ¡ t¡| jjd | j* d ¡|dd…df< | |fS dS )aa  Resample all channels.

        If appropriate, an anti-aliasing filter is applied before resampling.
        See :ref:`resampling-and-decimating` for more information.

        .. warning:: The intended purpose of this function is primarily to
                     speed up computations (e.g., projection calculation) when
                     precise timing of events is not required, as downsampling
                     raw data effectively jitters trigger timings. It is
                     generally recommended not to epoch downsampled data,
                     but instead epoch and then downsample, as epoching
                     downsampled data jitters triggers.
                     For more, see
                     `this illustrative gist
                     <https://gist.github.com/larsoner/01642cb3789992fbca59>`_.

                     If resampling the continuous data is desired, it is
                     recommended to construct events using the original data.
                     The event onsets can be jointly resampled with the raw
                     data using the 'events' parameter (a resampled copy is
                     returned).

        Parameters
        ----------
        sfreq : float
            New sample rate to use.
        %(npad)s
        %(window_resample)s
        stim_picks : list of int | None
            Stim channels. These channels are simply subsampled or
            supersampled (without applying any filtering). This reduces
            resampling artifacts in stim channels, but may lead to missing
            triggers. If None, stim channels are automatically chosen using
            :func:`mne.pick_types`.
        %(n_jobs_cuda)s
        events : 2D array, shape (n_events, 3) | None
            An optional event matrix. When specified, the onsets of the events
            are resampled jointly with the data. NB: The input events are not
            modified, but a new array is returned with the raw instead.
        %(pad)s
            The default is ``'reflect_limited'``.

            .. versionadded:: 0.15
        %(verbose)s

        Returns
        -------
        raw : instance of Raw
            The resampled version of the raw object.
        events : array, shape (n_events, 3) | None
            If events are jointly resampled, these are returned with the raw.

        See Also
        --------
        mne.io.Raw.filter
        mne.Epochs.resample

        Notes
        -----
        For some data, it may be more accurate to use ``npad=0`` to reduce
        artifacts. This is dataset dependent -- check your data!

        For optimum performance and to make use of ``n_jobs > 1``, the raw
        object has to have the data loaded e.g. with ``preload=True`` or
        ``self.load_data()``, but this increases memory requirements. The
        resulting raw object will have the data loaded into memory.
        NrÔ   r   FT)ZmegZref_megZstimr  rc   r.  )ÚupZdownÚnpadÚwindowr6  rI  c                 3   s   | ]}t ˆˆ |ƒV  qd S rY   )r1   )rd   Zold_len©Zo_sfreqrÔ   rc   rh   rm   ˆ  s   ÿz#BaseRaw.resample.<locals>.<genexpr>rª   r   Úerrorr\   Úlowpassg       @z¨Resampling of the stim channels caused event information to become unreliable. Consider finding events on the original data and passing the event matrix as a parameter.)+rS   r  rŒ   rr   rn   r¬   r¼   r»   r   r   rj   r›   r‡   rw   r‘   rƒ   rŽ   r„   r]   r‚   r~   r5  r¸   r0   r2   r†   ra   r-  Úroundr¤   r‰   r4  rˆ   Zarray_equalr…   ÚgetÚinfrŠ   r·   rA   r  r#  rê   )rg   rÔ   rU  rV  Z
stim_picksr6  ÚeventsrI  r?   Zoriginal_eventsÚoffsetsr2  ÚratioZn_newsZnew_offsetsZnew_dataÚriZn_origZn_newrÐ   Z
data_chunkÚciZresamprY  Zresampled_eventsrc   rW  rh   r0   '  s¶    L
 ÿ
ÿ
 ÿÿ ÿ"  ÿ  
 ÿÿþ
  ÿÿ
þzBaseRaw.resamplerå   c             	      s6  ˆ j d ˆ jd  }|dkr |}||kr8td||f ƒ‚|dk rPtd|f ƒ‚n||krhtd||f ƒ‚t tˆ j||ˆ jd |d�¡d	 d	d
g \}}t d	gtjˆ j	dd�f¡}t 
|¡}t t ||dd… ¡t ||dd
… ¡¡}	t |	¡d	 }	ˆ  j|7  _t ˆ j|	 ¡ˆ _ˆ jd	  |||	d	   7  < t ˆ j|	 ¡ˆ _ˆ jd
  ||	d
 d  d | 8  < ‡ fdd„|	D ƒˆ _t‡ fdd„ˆ jD ƒƒ�s t‚‡ fdd„|	D ƒˆ _‡ fdd„|	D ƒˆ _ˆ j�rðˆ jdd…||d …f  ¡ ˆ _ˆ j}
|
jdk�r&ˆ jd dk�st‚|
 jˆ j8  _ˆ  |
d¡ ˆ S )aÙ  Crop raw data file.

        Limit the data from the raw file to go between specific times. Note
        that the new ``tmin`` is assumed to be ``t=0`` for all subsequently
        called functions (e.g., :meth:`~mne.io.Raw.time_as_index`, or
        :class:`~mne.Epochs`). New :term:`first_samp` and :term:`last_samp`
        are set accordingly.

        Thus function operates in-place on the instance.
        Use :meth:`mne.io.Raw.copy` if operation on a copy is desired.

        Parameters
        ----------
        %(tmin_raw)s
        %(tmax_raw)s
        %(include_tmax)s
        %(verbose)s

        Returns
        -------
        raw : instance of Raw
            The cropped raw object, modified in-place.
        r   rÔ   Nz%tmin (%s) must be less than tmax (%s)rå   ztmin (%s) must be >= 0z@tmax (%s) must be less than or equal to the max time (%0.4f sec))rÔ   Úinclude_tmaxr   rª   rw   r´   c                    s   g | ]}ˆ j | ‘qS rc   )r“   ©rd   r`  rf   rc   rh   rs     s     z BaseRaw.crop.<locals>.<listcomp>c                 3   s$   | ]}t |ƒt ˆ jd  ƒkV  qdS ©r   N)r„   r“   rk   rf   rc   rh   rm     s   ÿzBaseRaw.crop.<locals>.<genexpr>c                    s   g | ]}ˆ j | ‘qS rc   )r’   rc  rf   rc   rh   rs   	  s     c                    s   g | ]}ˆ j | ‘qS rc   )r—   rc  rf   rc   rh   rs   
  s     r^   F)r¶   rr   r�   rn   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Ø   rì   r£   )rg   r   r  rb  r?   Zmax_timeZsminZsmaxrÌ   Zkeepersr×   rc   rf   rh   r  Ï  sf    ÿÿ   þþþÿ

ÿ&ÿ zBaseRaw.cropc                C   sx   |dkr| j }g }|D ]\}|d | j }| jd  d |  k rHdk rPn nd}|  ¡  |||d  ¡}| |¡ q|S )a†  Get crops of raw data file for selected annotations.

        Parameters
        ----------
        annotations : instance of Annotations | None
            The annotations to use for cropping the raw file. If None,
            the annotations from the instance are used.
        %(verbose)s

        Returns
        -------
        raws : list
            The cropped raw objects.
        NrØ   rÔ   r   r   rÙ   )r×   rì   rr   r  r  Úappend)rg   r×   r?   Úrawsrà   rØ   Zraw_croprc   rc   rh   Úcrop_by_annotations  s    $zBaseRaw.crop_by_annotationsrv   Ú2GBÚneuromagc                 C   sˆ  d}|t dd„ |D ƒƒ7 }d}t|ddd�}t|d||d	� t|
ƒ}
| js\|| jkr\td
ƒ‚| jrvt | j	¡rvt
dƒ ttjtjtjtjd�}td|| ¡ ƒ tddddd�}|| }|| }| d d }|dkrät |¡rätdƒ‚t||	dd�}|�r t| jƒ}t|ƒ\}}t|d dd� n
| j}d}|  ||¡\}}|  |¡}t|tdƒ td|dƒ t|| |||||||||||
|dd|	ƒ dS )aÙ  Save raw data to file.

        Parameters
        ----------
        fname : str
            File name of the new dataset. This has to be a new filename
            unless data have been preloaded. Filenames should end with
            ``raw.fif`` (common raw data), ``raw_sss.fif``
            (Maxwell-filtered continuous data),
            ``raw_tsss.fif`` (temporally signal-space-separated data),
            ``_meg.fif`` (common MEG data), ``_eeg.fif`` (common EEG data),
            or ``_ieeg.fif`` (common intracranial EEG data). You may also
            append an additional ``.gz`` suffix to enable gzip compression.
        %(picks_all)s
        %(tmin_raw)s
        %(tmax_raw)s
        buffer_size_sec : float | None
            Size of data chunks in seconds. If None (default), the buffer
            size of the original file is used.
        drop_small_buffer : bool
            Drop or not the last buffer. It is required by maxfilter (SSS)
            that only accepts raw files with buffers of the same size.
        proj : bool
            If True the data is saved with the projections applied (active).

            .. note:: If ``apply_proj()`` was used to apply the projections,
                      the projectons will be active even if ``proj`` is False.
        fmt : 'single' | 'double' | 'int' | 'short'
            Format to use to save raw data. Valid options are 'double',
            'single', 'int', and 'short' for 64- or 32-bit float, or 32- or
            16-bit integers, respectively. It is **strongly** recommended to
            use 'single', as this is backward-compatible, and is standard for
            maintaining precision. Note that using 'short' or 'int' may result
            in loss of precision, complex data cannot be saved as 'short',
            and neither complex data types nor real data stored as 'double'
            can be loaded with the MNE command-line tools. See raw.orig_format
            to determine the format the original data were stored in.
        %(overwrite)s
            To overwrite original file (the same one that was loaded),
            data must be preloaded upon reading.
        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.
        %(split_naming)s

            .. versionadded:: 0.17
        %(verbose)s

        Notes
        -----
        If Raw is a concatenation of several raw files, **be warned** that
        only the measurement information from the first raw file is stored.
        This likely means that certain operations with external tools may not
        work properly on a saved concatenated file (e.g., probably some
        or all forms of SSS). It is recommended not to concatenate and
        then save raw files for this reason.

        Samples annotated ``BAD_ACQ_SKIP`` are not stored in order to optimize
        memory. Whatever values, they will be loaded as 0s when reading file.
        )zraw.fifzraw_sss.fifzraw_tsss.fifz_meg.fifz_eeg.fifz	_ieeg.fifc                 S   s   g | ]}|› d �‘qS )z.gzrc   )rd   Úerc   rc   rh   rs   „  s     z BaseRaw.save.<locals>.<listcomp>)ry   z.fif.gzTrX  ©Ú	overwriter?   Úraw)Úendings_errzGYou cannot save data to the same file. Please use a different filename.zUSaving raw file with complex data. Loading with command-line MNE tools will not work.)rx   rw   rv   rZ   ÚfmtF)r   r   r   rx   z?Complex data must be saved as "single" or "double", not "short")Úfnamerl  r?   Úprojs)r  NÚsplit_naming)ri  Úbids)r‹   r5   r;   r)   rƒ   r—   r�   rn   Ziscomplexobjr‚   rA   rj   r   ZFIFFT_DAU_PACK16Z	FIFFT_INTZFIFFT_FLOATZFIFFT_DOUBLErG   Úkeysr   rr   r   r   Ú_tmin_tmax_to_start_stopÚ_get_buffer_sizerD   r˜   Ú
_write_raw)rg   rp  rÞ   r   r  r�   Údrop_small_bufferr«   ro  rl  Ú
split_sizerr  r?   Zendingsrn  Z	type_dictZ
reset_dictÚreset_rangeÚ	data_typeZ	data_testrr   rÉ   r°   r±   Úbuffer_sizerc   rc   rh   Úsave<  s`    Fýÿ

        þzBaseRaw.saverk  c             	   C   s&   ddl m} ||| |||||d� dS )a  Export Raw to external formats.

        %(export_fmt_support_raw)s

        %(export_warning)s

        Parameters
        ----------
        %(fname_export_params)s
        %(export_fmt_params_raw)s
        %(physical_range_export_params)s
        %(add_ch_type_export_params)s
        %(overwrite)s

            .. versionadded:: 0.24.1
        %(verbose)s

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

        %(export_warning_note_raw)s
        %(export_eeglab_note)s
        %(export_edf_note)s
        r   )Ú
export_raw)Úphysical_rangeÚadd_ch_typerl  r?   N)Úexportr~  )rg   rp  ro  r  r€  rl  r?   r~  rc   rc   rh   r�  ¾  s    
 þzBaseRaw.exportc                 C   s€   t t || jd  ¡ƒ}|d kr(tj}n| jt|ƒdd�d d }t|| j| j	 d ƒ}||ksh|dkrxt
d||f ƒ‚||fS )NrÔ   T)rô   r   r   z*tmin (%s) and tmax (%s) yielded no samples)rw   rn   Úfloorrr   r\  ró   rŒ   r·   rî   rê   r�   )rg   r   r  r°   r±   rc   rc   rh   ru  ß  s    ÿz BaseRaw._tmin_tmax_to_start_stopg      $@é   ÚwZ	lightgrayÚcyané   rš   rŒ   )ÚthemeÚoverview_moder?   c           #   %   C   sN   t | |||||||||	|
|||||||||||||||||||||| |!|"d�#S )N)
Ú	noise_covÚevent_idÚshow_scrollbarsÚshow_scalebarsÚtime_formatÚ
precomputeÚ
use_openglr‡  rˆ  r?   )rO   )#rg   r]  rÙ   r°   Z
n_channelsÚbgcolorÚcolorZ	bad_colorZevent_colorÚscalingsZ	remove_dcÚorderZshow_optionsÚtitleÚshowÚblockZhighpassrY  Z	filtorderZclippingZshow_first_sampr«   Zgroup_byÚ	butterflyZdecimr‰  rŠ  r‹  rŒ  r�  rŽ  r�  r‡  rˆ  r?   rc   rc   rh   Úplotí  s>                        ÷zBaseRaw.plotÚblackZlinearZstdg…ëQ¸Õ?Úbadsc                 C   s<   t | |||||||||	|
|||||||||||||||d�S )N)ÚfminÚfmaxr   r  r«   Ún_fftÚ	n_overlaprß   rÞ   Úaxr‘  ÚxscaleÚ	area_modeÚ
area_alphaÚdBÚestimater•  r6  ÚaverageÚ
line_alphaÚspatial_colorsÚsphererV  r  r?   )rP   )rg   r›  rœ  r   r  r«   r�  rž  rß   rÞ   rŸ  r‘  r   r¡  r¢  r£  r¤  r•  r6  r¥  r¦  r§  r¨  rV  r  r?   rc   rc   rh   Úplot_psd  s.    	             øzBaseRaw.plot_psdéd   é   r§   c                 C   s,   t | |||||||||	|
|||||||d�S )N)r   r  r›  rœ  r«   r�  rž  Úlayoutr‘  Úfig_facecolorÚaxis_facecolorr£  r•  r–  r6  Úaxesr?   )rQ   )rg   r   r  r›  rœ  r«   r�  rž  r¬  r‘  r­  r®  r£  r•  r–  r6  r¯  r?   rc   rc   rh   Úplot_psd_topo  s     
        úzBaseRaw.plot_psd_topoc                 C   s
   | j d S )zChannel names.r]   rq   rf   rc   rc   rh   r]   $  s    zBaseRaw.ch_namesc                 C   s$   t | jt| jd ƒƒ}d|jd< |S )zTime points.rÔ   FZ	WRITEABLE)rL   r¶   rŒ   rr   Úflags)rg   Úoutrc   rc   rh   r­   )  s    
zBaseRaw.timesc                 C   s   | j | j d S )zNumber of time points.r   ©rî   rê   rf   rc   rc   rh   r¶   0  s    zBaseRaw.n_timesc                 C   s   | j S )a  Return the number of time points.

        Returns
        -------
        len : int
            The number of time points.

        Examples
        --------
        This can be used as::

            >>> len(raw)  # doctest: +SKIP
            1000
        ©r¶   rf   rc   rc   rh   Ú__len__5  s    zBaseRaw.__len__c           
   	      sæ   | j d }g }|dk	r¨t| j d ƒ‰ t|ƒ�}dd„ | ¡  ¡ D ƒ}W 5 Q R X ‡ fdd„|D ƒ}t|ƒt|ƒ }|dkr¨|› d|› d	| jd › �}	|s t|	ƒ‚nt|	ƒ ||krÒt	  d
|› d|› �¡ || j d< nt	  d|› �¡ dS )aã  Mark channels as bad from a text file.

        This function operates mostly in the style of the C function
        ``mne_mark_bad_channels``. Each line in the text file will be
        interpreted as a name of a bad channel.

        Parameters
        ----------
        bad_file : path-like | None
            File name of the text file containing bad channels.
            If ``None`` (default), bad channels are cleared, but this
            is more easily done directly with ``raw.info['bads'] = []``.
        force : bool
            Whether or not to force bad channel marking (of those
            that exist) if channels are not found, instead of
            raising an error. Defaults to ``False``.
        %(verbose)s
        rš  Nr]   c                 S   s   g | ]}|r|‘qS rc   rc   )rd   Úlinerc   rc   rh   rs   `  s      z-BaseRaw.load_bad_channels.<locals>.<listcomp>c                    s   g | ]}|ˆ kr|‘qS rc   rc   )rd   ra  ©Únamesrc   rh   rs   a  s      r   z bad channel(s) from:
z
not found in:
zUpdating bad channels: z -> zNo channels updated. Bads are: )
rr   Ú	frozensetÚopenÚreadÚ
splitlinesr„   rœ   r�   rA   r>   )
rg   Zbad_fileÚforcer?   Z	prev_badsZnew_badsÚfidZ	bad_namesZ
count_diffr,  rc   r·  rh   Úload_bad_channelsF  s"    

 
zBaseRaw.load_bad_channelsc              	   C   s*  t |tƒs|g}| g}||7 }t|ƒ | jo<tdd„ |D ƒƒ}|dkrT|rPd}nd}|dkrp| jrhd| _d| _nø| jd }t dd„ | g| D ƒ¡}|d	 }| js²| j	| j
d
�}n| j}t|||f|jƒ}	||	dd…d|d …f< tt|ƒƒD ]l}
||
 j�s4|	dd…||
 ||
d  …f }||
 j	|| j
d� qî||
 j|	dd…||
 ||
d  …f< qî|	| _d| _| j}|j| jd k�s„t‚tƒ }t|ƒD ]²\}
}| j| j d }t||j|| j|j| jd ƒ}| t| jƒt| jƒ |
d  ¡ tj| j|jf | _tj| j|jf | _|  j|j7  _|  j|j7  _|  j|j7  _�q’|j| jd k�s\t‚|jdk�r‚| j| j| jd  8  _|  |¡ |D ]<}t | || jd  dƒ}| j |dd¡ | j |dd¡ �q�t| jƒt| jƒ  k�rt| jƒ  k�rt| jƒ  k�rt| jƒk�s&n t!dƒ‚dS )aC  Concatenate raw instances as if they were continuous.

        .. note:: Boundaries of the raw files are annotated bad. If you wish to
                  use the data as continuous recording, you can remove the
                  boundary annotations after concatenation (see
                  :meth:`mne.Annotations.delete`).

        Parameters
        ----------
        raws : list, or Raw instance
            List of Raw instances to concatenate to the current instance
            (in order), or a single raw instance to concatenate.
        %(preload_concatenate)s
        c                 s   s   | ]}|j V  qd S rY   )rƒ   rk   rc   rc   rh   rm   ‹  s     z!BaseRaw.append.<locals>.<genexpr>NTFr_   c                 S   s   g | ]
}|j ‘qS rc   r´  )rd   Zrrrc   rc   rh   rs   ™  s     z"BaseRaw.append.<locals>.<listcomp>rª   )rÉ   r   r   ræ   r^   rÔ   rå   zBAD boundaryzEDGE boundaryzAppend error)"r|   r‘   Ú_check_raw_compatibilityrƒ   rŸ   r‚   rr   rn   r¼   rÑ   r¡   rº   r~   ra   r„   r×   r  r…   r5  rî   rê   rV   re  rí   rˆ   r‰   Zr_r“   r’   r—   rØ   r£   rW   r€   )rg   rf  rƒ   Zall_rawsZall_preloadedr_   Zc_nsZnsampZ	this_datar‚   r`  rÈ   r×   Z
edge_sampsrl   r)  Z	edge_samprØ   rc   rc   rh   re  r  sŒ    

 
ÿ(   ýÿÿ
ÿ
ÿ
þ
zBaseRaw.appendc                 C   s   dS )z˜Clean up the object.

        Does nothing for objects that close their file descriptors.
        Things like RawFIF will override this method.
        Nrc   rf   rc   rc   rh   rè   Ò  s    zBaseRaw.closec                 C   s   t | ƒS )z‰Return copy of Raw instance.

        Returns
        -------
        inst : instance of Raw
            A copy of the instance.
        r   rf   rc   rc   rh   r  Ú  s    zBaseRaw.copyc                 C   sx   | j d }|d krdnt |¡d }tt| jƒƒ}|d| jr@dnd 7 }d|t| jƒ| j	| j
d |f }d| jj|f S )	Nr   Ú z, z, data%s loadedz notz%s%s x %s (%0.1f s), ~%srª   z	<%s | %s>)rœ   ÚopÚbasenamer˜   r7   Ú_sizerƒ   r„   r]   r¶   r­   rø   Ú__name__)rg   ÚnameÚsize_strÚsrc   rc   rh   Ú__repr__ä  s    
ÿÿzBaseRaw.__repr__c           	      C   sŠ   ddl m} dd„ | jD ƒ}t| j| j dƒ\}}t|dƒ\}}t|ƒd›dt|ƒd›dt|ƒd›�}| d¡}|j| j	j
|d	�||d
�S )Nr   )Úrepr_templates_envc                 S   s    g | ]}|d k	rt j |¡‘qS rY   )r  ÚpathrÃ  )rd   rù   rc   rc   rh   rs   ð  s     z'BaseRaw._repr_html_.<locals>.<listcomp>é<   Ú02dú:zraw.html.jinja)Úcaption)Z	info_reprrœ   rÙ   )Zhtml_templatesrÊ  r—   Údivmodrï   rì   rw   Zget_templateÚrenderrr   Ú_repr_html_)	rg   rÏ  rÊ  Ú	basenamesÚmrÈ  ÚhrÙ   Zraw_templaterc   rc   rh   rÒ  î  s    ÿ&
 þzBaseRaw._repr_html_c                 C   s  t | dƒ t |¡}|jdks,|jd dkr4tdƒ‚t|| jƒ}t| j	|ƒ}t
|ƒdkrdtd| ƒ‚|d }|dd…df  t¡}t || jk ¡s¢t || jk¡r¶td	| j| jf ƒ‚t||dd…df kƒsÖtd
ƒ‚|rìd| j|dd…f< | j||| j f  |dd…df 7  < dS )al  Add events to stim channel.

        Parameters
        ----------
        events : ndarray, shape (n_events, 3)
            Events to add. The first column specifies the sample number of
            each event, the second column is ignored, and the third column
            provides the event value. If events already exist in the Raw
            instance at the given sample numbers, the event values will be
            added together.
        stim_channel : str | None
            Name of the stim channel to add to. If None, the config variable
            'MNE_STIM_CHANNEL' is used. If this is not found, it will default
            to 'STI 014'.
        replace : bool
            If True the old events on the stim channel are removed before
            adding the new ones.

        Notes
        -----
        Data must be preloaded in order to add events.
        zAdding eventsr   r   é   z"events must be shape (n_events, 3)r   zChannel %s not foundNz.event sample numbers must be between %s and %sz%event sample numbers must be integersrå   )rE   rn   ZasarrayÚndimr†   r�   r<   rr   r   r]   r„   r4  rw   rÃ   rê   rî   rŸ   r‚   )rg   r]  Zstim_channelÚreplaceÚpickrÊ   rc   rc   rh   Ú
add_eventsü  s&    

 
ÿzBaseRaw.add_eventsc                 C   s.   |dkr| j }t|ƒ}tt || jd  ¡ƒS )zGet the buffer size.NrÔ   )r�   rŒ   rw   rn   Úceilrr   )rg   r�   rc   rc   rh   rv  &  s    zBaseRaw._get_buffer_sizec	             	   C   s´   t ƒ }
dg}dddg}t||ƒ}t||| jd ƒ}t| j|ddd�}| |||…f \}}|j}|rj| ¡ }t| |||ƒ}tƒ }t	| ||ƒ}| 
d|f¡ t| |||||dgd	�}|S )
aå  Export data in tabular structure as a pandas DataFrame.

        Channels are converted to columns in the DataFrame. By default, an
        additional column "time" is added, unless ``index`` is not ``None``
        (in which case time values form the DataFrame's index).

        Parameters
        ----------
        %(picks_all)s
        %(index_df_raw)s
            Defaults to ``None``.
        %(scalings_df)s
        %(copy_df)s
        start : int | None
            Starting sample index for creating the DataFrame from a temporal
            span of the Raw object. ``None`` (the default) uses the first
            sample.
        stop : int | None
            Ending sample index for creating the DataFrame from a temporal span
            of the Raw object. ``None`` (the default) uses the last sample.
        %(long_format_df_raw)s
        %(time_format_df_raw)s

            .. versionadded:: 0.20
        %(verbose)s

        Returns
        -------
        %(df_return)s
        ÚtimeÚmsr   Údatetimer^   rŸ   rc   r  )Zdefault_index)r6   r8   rK   rr   r   rÂ   r  rJ   r‘   rI   re  rH   )rg   rÞ   r    r’  r  r°   r±   Zlong_formatr�  r?   ÚpdZvalid_index_argsZvalid_time_formatsrË   r­   ZmindexÚdfrc   rc   rh   Úto_data_frame-  s(    $

ÿÿzBaseRaw.to_data_framec                 C   s  ddl m} | jd }ttƒ}| j|d< t|ƒD ]®}| jd | }| | d }|d  t| j|ƒ¡ |d  t	|d  ¡ |d  t
 |¡¡ |d	  ||d
ƒ¡ |d  t
 |¡¡ |d  ||dƒ¡ |d  t
 |¡¡ q0|�rddl}| |¡}	d|	j_|	S tdƒ}
tdƒ}t|ƒD ]b}| |d | ¡}|
 |d | d¡}|dk�r||d |< dD ]}|| |  |9  < �q`�qtdtt|ƒƒƒtdtdd„ |d D ƒƒƒtdtdd„ |d D ƒƒƒtdtdd„ |d D ƒƒƒdœ}t| ƒ tdd|d › �›ddd|d › �›ddd|d › �›ddd|d › �›ddd›dd	d›ddd›ddd›ddd›�ƒ t|ƒD ]®}|d|d › �›d|d | d|d › �›d|d |  ¡ d|d › �›d|d | d|d › �›d�}d D ]}||| | d!›d�7 }�qÚ||d | d!›7 }t|ƒ �qjdS )"aë  Describe channels (name, type, descriptive statistics).

        Parameters
        ----------
        data_frame : bool
            If True, return results in a pandas.DataFrame. If False, only print
            results. Columns 'ch', 'type', and 'unit' indicate channel index,
            channel type, and unit of the remaining five columns. These columns
            are 'min' (minimum), 'Q1' (first quartile or 25% percentile),
            'median', 'Q3' (third quartile or 75% percentile), and 'max'
            (maximum).

        Returns
        -------
        result : None | pandas.DataFrame
            If data_frame=False, returns None. If data_frame=True, returns
            results in a pandas.DataFrame (requires pandas).
        r   )Úscoreatpercentiler_   rÆ  r`   rš   Úunitr·   ÚQ1é   ÚmedianÚQ3éK   r!  Nrz   r’  r&  r   )r·   rä  ræ  rç  r!  r   r†  c                 S   s   g | ]}t |ƒ‘qS rc   ©r„   )rd   Únrc   rc   rh   rs   ž  s     z$BaseRaw.describe.<locals>.<listcomp>c                 S   s   g | ]}t |ƒ‘qS rc   ré  )rd   Útrc   rc   rh   rs   Ÿ  s     c                 S   s   g | ]}t |ƒ‘qS rc   ré  )rd   Úurc   rc   rh   rs      s     )rz   rÆ  rš   rã  ú>z  ú<z>9)r·   rä  ræ  rç  z>9.2f)Zscipy.statsrâ  rr   r   r‘   r]   ra   re  r   r   rn   r·   ræ  r!  ZpandasZ	DataFramer    rÆ  rN   r[  r„   r˜   ÚprintÚupper)rg   Z
data_frameÚqr_   Úcolsr  rz   rË   rß  rà  r’  r&  rã  ÚscalingÚcolZlensr,  rc   rc   rh   Údescribeh  sR    



ýv
hzBaseRaw.describe)N)r   NNNNN)F)N)FN)Trý   )T)Nr   NNFN)NNNTN)Nr:  r:  r:  Nr;  Nr<  r=  r>  r?  rB  N)Nr:  Nr[   Nr;  NNrL  r<  r=  r>  rB  N)r:  rS  NNNrB  N)rå   NT)N)Nr   NNFFrv   Frh  ri  N)r:  r:  F)rå   Nr   rª  Fr«  r   Nr„  r§   r§   TTFNNN)NFN)N)N)NF)N)NNNTNNFN)F)FrÅ  Ú
__module__Ú__qualname__Ú__doc__r?   rn   r   r©   r²   Úpropertyr³   rÑ   rÆ   rã   rä   r¥   rë   rê   rì   rî   rï   ró   r»   r×   rœ   r£   r
  r  r  r  r  rÝ   r  r-  r9  r:   r.   rJ  r/   r0   r  rg  r}  r�  ru  rC   rO   rR   r˜  rP   r\  r©  rQ   r°  r]   r­   r¶   rµ  r¿  r9   re  rè   r  rÉ  rÒ  rÚ  rv  rá  rõ  Ú__classcell__rc   rc   r÷   rh   rX   8   sÚ  ;    üûm.
    ÿr# þ
-




$


  ÿÿ:'&
      ÿ  þ     ÿ5                  û                     üO       þ (M            ý   ÿ ÿ                    ø ÷              ú                     ü


+_



*
           þý:rX   c                 C   s<   | dkrt  ||¡}n"t| ddƒ t jt| ƒd||d�}|S )z4Allocate data in memory or in memmap for preloading.)NTz	path-likerƒ   zw+)Úmoder~   r†   )rn   r%  rD   Zmemmapr˜   )rƒ   r†   r~   rË   rc   rc   rh   rº   ¹  s
    rº   Fc                 C   s   t  | ¡|r|nd }|| S )a�  Convert indices to time.

    Parameters
    ----------
    index : list-like | int
        List of ints or int representing points in time.
    use_first_samp : boolean
        If True, the time returned is relative to the session onset, else
        relative to the recording onset.

    Returns
    -------
    times : ndarray
        Times corresponding to the index supplied.
    r   )rn   rñ   )r    rÔ   rê   Zuse_first_sampr­   rc   rc   rh   Ú_index_as_timeÃ  s    rü  c                 C   s8   t | ƒr0t | ¡dk ¡ r0t| d | d d ƒS | S d S )Nr   r   rª   )r„   rn   ÚdiffrŸ   r¸   )rÇ   rc   rc   rh   r¹   ×  s    r¹   c           
         sØ   t |dttfdd� t t|ƒ¡}tdƒ}| j|d�}t|tƒr€t	t
|ƒt
| ¡ ƒ@ ƒ}t|ƒdkrttd|› d�ƒ‚|d	 |i}t|tƒrÔ| ¡ D ]@\‰ }tˆ |ƒ}|dkr’‡ fd
d„t|ƒD ƒ}	||	  |9  < q’|S )a�  Get scaling factors for data, given units.

    Parameters
    ----------
    inst : instance of Raw | Epochs | Evoked
        The instance.
    %(units)s
    picks_idxs : ndarray
        The picks as provided through _picks_to_idx.

    Returns
    -------
    ch_factors : ndarray of floats, shape(len(picks),)
        The sacling factors for each channel, ordered according
        to picks.

    Nr&  )r  r  Úsi_units)rÞ   r   zI"units" cannot be str if there is more than one channel type with a unit Ú.r   c                    s   g | ]\}}|ˆ kr|‘qS rc   rc   )rd   Zi_chrz   ©Úch_typerc   rh   rs     s    ÿz#_get_ch_factors.<locals>.<listcomp>)rD   r˜   rj   rn   r$  r„   rN   Zget_channel_typesr|   r‘   Úsetrt  r�   ÚitemsÚ_get_scalingr5  )
Úinstr&  Z
picks_idxsr'  rþ  Zch_typesZunit_ch_typeZch_unitró  Úindicesrc   r   rh   r   Þ  s     


r   c                    sz  d}t dƒ‰‡fdd„ˆD ƒ}t dƒ}t| ¡ ƒ}| d¡}| ˆ ¡ krVt| › d�ƒ‚||  ‰t|ƒtˆƒkrŒt|› d| › d	ˆ|  › d
�ƒ‚t|ƒD ]B\‰ }‡ ‡fdd„|D ƒ}||kr”t|› d| › d	ˆ|  › d
�ƒ‚q”t|ƒD ]”\‰ }d}	|d dkrüd}	|dk�s|dk�rd}
n$|d | ¡ k�r6||d  }
nd}
|
dkrà|	�rP|
|
9 }
ˆ dk�rd||
 }qàˆ dkrà||
 }qà|S )a…  Return the scaling factor based on the channel type and a target unit.

    Parameters
    ----------
    ch_type : str
        The channel type.
    target_unit : str
        The target unit for the provided channel type.

    Returns
    -------
    scaling : float
        The scaling factor to convert from the si_unit (used by default for MNE
        objects) to the target unit.
    r[   rþ  c                    s   i | ]}|ˆ |   d ¡“qS )rµ   )Úsplit)rd   Úkey)rþ  rc   rh   ri     s      z _get_scaling.<locals>.<dictcomp>Úprefixesrµ   z5 is not a channel type that can be scaled from units.z is not a valid unit for z, use a sub-multiple of z	 instead.c                    s   g | ]}|ˆˆ   ‘qS rc   rc   )rd   Úprefix)r  Úsi_unit_listrc   rh   rs   ,  s   ÿz _get_scaling.<locals>.<listcomp>Frª   õ   Â²TrÔ  u   mÂ²r   r   )rN   r‘   rt  r  ÚKeyErrorr„   r�   r5  )r  Ztarget_unitró  Zsi_units_splittedr	  Zprefix_listZ	unit_listrã  ZvalidZ
has_squareÚfactorrc   )r  r  rþ  rh   r  
  sP    
ÿÿÿÿ


r  c                   @   s    e Zd ZdZdd„ Zdd„ ZdS )rÅ   zEEnsure only _filenames, _raw_extras, and _read_segment_file are used.c                 C   s(   || _ t|dƒst‚|j| _|j| _d S )Nr¡   )Ú_ReadSegmentFileProtector__rawr  r…   r—   r’   )rg   rm  rc   rc   rh   r©   L  s    z"_ReadSegmentFileProtector.__init__c              
   C   s   | j j | |||||||¡S rY   )r  rø   rÆ   rÓ   rc   rc   rh   rÆ   R  s           ÿz,_ReadSegmentFileProtector._read_segment_fileN)rÅ  rö  r÷  rø  r©   rÆ   rc   rc   rc   rh   rÅ   I  s   rÅ   c                   @   s8   e Zd ZdZdd„ Zedd„ ƒZedd„ ƒZdd	„ Zd
S )Ú	_RawShellzCreate a temporary raw object.c                 C   s.   d | _ d | _d | _d | _d | _d | _d | _d S rY   )rê   rî   rë   rï   r�   Z_rawdirr¡   rf   rc   rc   rh   r©   Z  s    z_RawShell.__init__c                 C   s   | j | j d S )Nr   r³  rf   rc   rc   rh   r¶   c  s    z_RawShell.n_timesc                 C   s   | j S rY   rû   rf   rc   rc   rh   r×   g  s    z_RawShell.annotationsc                 C   s$   |d krt g g g d ƒ}| ¡ | _d S rY   )rU   r  rü   )rg   r×   rc   rc   rh   r£   k  s    z_RawShell.set_annotationsN)	rÅ  rö  r÷  rø  r©   rù  r¶   r×   r£   rc   rc   rc   rh   r  W  s   	

r  c                 C   sÈ  t |jƒ}||ks||kr,td|||f ƒ‚t| |d�} t | ¡\}}|dkrŽ|dkrfd|||f }q’|dksrt‚t|||d ƒ}t||ƒ n| }|dkrÜ|dkrÜt|||d ƒ}t 	dt 
|¡› �¡ t||ƒ t|ƒ}n
|}tƒ }t 	d	| ¡ t||d
dƒ}t|ƒ�\}t||||||jƒ}|�8 t|||||||||	||||
||| ||||dd�}W 5 Q R X W 5 Q R X ||k�r¬|dk�s„t‚t 	dt 
|¡› �¡ d|_t ||¡ |dk�rÀt 	d¡ ||fS )zWrite raw file with splitting.z@Cannot write raw file with no data: %s -> %s (max: %s) requested)rp  rl  r   ri  z%s-%d%srs  r   zReserving possible split file z
Writing %srŸ   rc   T)rl  zRenaming BIDS split file Fz[done])r„   r­   r€   r5   rÂ  Úsplitextr…   r	   r>   rr   rÃ  Ú_ReservedFilenamer   r   r   Ú_start_writing_rawr×   Ú_write_raw_fidrž   ÚshutilÚmove)rp  rm  rr   rÞ   ro  r{  rz  r°   r±   r|  rÉ   rx  ry  rr  Úpart_idxÚ
prev_fnamerl  Zn_times_maxÚbaseÚextÚ	use_fnameÚreserved_fnameÚctxr¾  r¦   Úfinal_fnamerc   rc   rh   rw  s  s|    
ÿÿ



 ÿ                û


rw  c                   @   s$   e Zd Zdd„ Zdd„ Zdd„ ZdS )r  c              	   C   s>   || _ t t |¡¡st|ƒ‚t|dƒ� W 5 Q R X d| _d S )Nr„  T)rp  rÂ  ÚisdirÚdirnamer…   rº  rž   )rg   rp  rc   rc   rh   r©   ±  s
    
z_ReservedFilename.__init__c                 C   s   | S rY   rc   rf   rc   rc   rh   r  ¸  s    z_ReservedFilename.__enter__c                 C   s   | j rt  | j¡ d S rY   )rž   r  rp  )rg   Úexc_typeÚ	exc_valueÚ	tracebackrc   rc   rh   r  »  s    z_ReservedFilename.__exit__N)rÅ  rö  r÷  r©   r  r  rc   rc   rc   rh   r  ¯  s   r  c           '      C   sŒ  | j | }|dkr t|tj|ƒ |dkr–|	d k	r–t|tjƒ t|tjtjƒ t|tj	|	ƒ |d d k	rxt
|tj|d ƒ t|tj|d ƒ t|tjƒ | ¡ }||
kr²td| ƒ‚tt|||ƒƒ}t |¡| }|d |krä||d< t| dƒ\}}d}t|ƒdk�r@t ||¡ ¡ �r.t ||¡ ¡ �r.d}n|dk�r@td	ƒ d}|}t||ƒD �]ð\}}|�r¢||k||k@  ¡ �r†|d7 }�qRn|dk�r¢t|tj|ƒ d}| |||…f \} }!t|!ƒ|| k�sÌt‚|d k	�rât || ¡} |�r||k�rt|!ƒ|k �rt d
¡  �qFt  d|d›d|d›d�¡ t!|| ||ƒ | ¡ }"|"| }#|"|
 t" }$|$dk�rvtd|#|
|$|t"f ƒ‚|"|
|# t" k�r>|| |k �r>|}t#|| ||||||| |||||
||d ||ƒ\}%}&t|tjƒ t|tjtj$ƒ t|tj	t% &|%¡ƒ |d d k	�rt
|tj|d ƒ t|tj|&ƒ t|tjƒ  �qF|"}�qRt d| ¡ | 'dd¡�rpt|tj(ƒ nt|tj)ƒ t|tj*ƒ |S )Nr   Úmeas_idr   z£file is larger than "split_size" after writing measurement information, you must use a larger value for split size: %s plus enough bytes for the chosen buffer_sizerª   rA  FTzeAcquisition skips detected but did not fit evenly into output buffer_size, will be written as zeroes.z2Skipping data chunk due to small buffer ... [done]zWriting FIF Z6dz ... z ...zÀbuffer size (%s) is too large for the given split size (%s) by %s bytes after writing info (%s) and leaving enough space for end tags (%s): decrease "buffer_size_sec" or increase "split_size".z
Closing %sÚ	maxshield)+rê   r&   r   ZFIFF_FIRST_SAMPLEr   Z	FIFFB_REFZFIFF_REF_ROLEZFIFFV_ROLE_PREV_FILEr(   ZFIFF_REF_FILE_NAMEr'   ZFIFF_REF_FILE_IDZFIFF_REF_FILE_NUMr    Útellr�   r‘   ra   rn   r‡   r+   r„   Zin1drŸ   rA   r›   rÃ   ZFIFF_DATA_SKIPr…   r®   r>   rr   rÄ   Ú_write_raw_bufferr*   rw  ZFIFFV_ROLE_NEXT_FILErÂ  rÃ  r[  ÚFIFFB_IAS_RAW_DATAÚFIFFB_RAW_DATAÚ
FIFFB_MEAS)'rm  rr   rÞ   r¾  r¦   r  r°   r±   r|  r  ry  r  rÉ   rx  ro  rp  r  r{  rz  rr  rl  rê   Zpos_prevZfirstsZlastsZ	sk_onsetsZsk_endsZdo_skipsZn_current_skipr  ÚfirstÚlastrË   r­   ÚposZthis_buff_size_bytesZoverageZ
next_fnameZnext_idxrc   rc   rh   r  À  sÄ    
ý$



ÿ

 ÿýÿ

ÿ             ür  c                 C   sø   t ||ƒ}t| tjƒ t| tjƒ |d dk	r@t| tj|d ƒ g }t|d ƒD ]V}|d |d | d< |dkr€d|d | d	< | |d | d
 |d | d	  ¡ qPt	| |||d� t
|ƒdkrÎt| |ƒ | dd¡rèt| tjƒ nt| tjƒ |S )aÂ  Start write raw data in file.

    Parameters
    ----------
    fid : file
        The created file.
    %(info_not_none)s
    sel : array of int | None
        Indices of channels to include. If None, all channels
        are included.
    data_type : int
        The data_type in case it is necessary. Should be 4 (FIFFT_FLOAT),
        5 (FIFFT_DOUBLE), 16 (FIFFT_DAU_PACK16), or 3 (FIFFT_INT) for raw data.
    reset_range : bool
        If True, the info['chs'][k]['range'] parameter will be set to unity.
    annotations : instance of Annotations
        The annotations to write.

    Returns
    -------
    fid : file
        The file descriptor.
    cals : list
        calibration factors.
    r$  Nr_   r   r`   ZscannoTr[   ra   rb   )r{  rz  r   r%  F)r   r   r   r*  r'   ZFIFF_BLOCK_IDZFIFF_PARENT_BLOCK_IDra   re  r   r„   r,   r[  r(  r)  )r¾  rr   rÇ   r{  rz  r×   r¦   r§   rc   rc   rh   r  3	  s$    
(
r  c                 C   sÔ   |j d t|ƒkrtdƒ‚td|ddddgƒ d}t |¡rt|dkrNt}d	}q˜|dkr`t}d	}q˜|dkrnt}q˜t	}n$|dkr‚t
}n|dkr�t}ntd
ƒ‚|t |¡dd…df  }|rÂ| tj¡}|| tj|ƒ dS )a¶  Write raw buffer.

    Parameters
    ----------
    fid : file descriptor
        an open raw data file.
    buf : array
        The buffer to write.
    cals : array
        Calibration factors.
    fmt : str
        'short', 'int', 'single', or 'double' for 16/32 bit int or 32/64 bit
        float for each item. This will be doubled for complex datatypes. Note
        that short and int formats cannot be used for complex data.
    r   z)buffer and calibration sizes do not matchro  rx   rw   rv   rZ   FTz=only "single" and "double" supported for writing complex dataN)r†   r„   r�   rG   rn   Z	isrealobjr!   r&   r"   r#   r$   r%   rÀ   r4  Zint32r   ZFIFF_DATA_BUFFER)r¾  Úbufr¦   ro  Zcast_intZwrite_functionrc   rc   rh   r'  y	  s.    
r'  c                    sx  t dtˆ ƒƒD �]8}tˆ | tˆ d ƒƒs:td|› d�ƒ‚dD ]R}ˆ | j| ˆ d j|  }}||kr>td|› d|› dt|ƒ› dt|ƒ› �ƒ‚q>tˆ | jd	 ƒtˆ d jd	 ƒksÂtd
| ƒ‚tˆ | j	ˆ d j	kƒsætd| ƒ‚tˆ d jd ƒtˆ | jd ƒk�rtdƒ‚tdd„ t
ˆ d jd ˆ | jd ƒD ƒƒstdƒ‚qt‡ fdd„ˆ D ƒƒ�sttdƒ dˆ d _dS )z7Ensure all instances of Raw have compatible parameters.r   r   zraw[z] type must match)r_   rš  rÔ   z].info[z] must match:
z != r]   z&raw[%d]['info']['ch_names'] must matchzraw[%d]._cals must matchrq  z,SSP projectors in raw files must be the samec                 s   s   | ]\}}t ||ƒV  qd S rY   )r   )rd   Úp1Zp2rc   rc   rh   rm   º	  s     z+_check_raw_compatibility.<locals>.<genexpr>c                 3   s   | ]}|j ˆ d  j kV  qdS rd  )ru   rk   ©rm  rc   rh   rm   ½	  s     zuraw files do not all have the same data format, could result in precision mismatch. Setting raw.orig_format="unknown"ÚunknownN)ra   r„   r|   rš   r�   rr   Úreprr  rŸ   r�   r›   rA   ru   )rm  r`  r  ÚaÚbrc   r0  rh   rÀ  ©	  s,    "ÿ$&ÿ
rÀ  rý   )Úon_mismatchr?   c          
      C   s¸   t | dd… dd�D ](\}}t| d j|jd|› d�|d� q|dk	r€t|ƒt| ƒkr^tdƒ‚td	d
„ | D ƒŽ \}}t|||ƒ}	| d  | dd… |¡ |dkr¨| d S | d |	fS dS )a‹  Concatenate `~mne.io.Raw` instances as if they were continuous.

    .. note:: ``raws[0]`` is modified in-place to achieve the concatenation.
              Boundaries of the raw files are annotated bad. If you wish to use
              the data as continuous recording, you can remove the boundary
              annotations after concatenation (see
              :meth:`mne.Annotations.delete`).

    Parameters
    ----------
    raws : list
        List of `~mne.io.Raw` instances to concatenate (in order).
    %(preload_concatenate)s
    events_list : None | list
        The events to concatenate. Defaults to ``None``.
    %(on_mismatch_info)s
    %(verbose)s

    Returns
    -------
    raw : instance of Raw
        The result of the concatenation (first Raw instance passed in).
    events : ndarray of int, shape (n_events, 3)
        The events. Only returned if ``event_list`` is not None.
    r   N)r°   r   zraws[ú])Zinfo1Zinfo2rÆ  r5  z=`raws` and `event_list` are required to be of the same lengthc                 S   s   g | ]}|j |jf‘qS rc   )rê   rî   rk   rc   rc   rh   rs   ç	  s     z$concatenate_raws.<locals>.<listcomp>)r5  r   rr   r„   r�   r›   rT   re  )
rf  rƒ   Zevents_listr5  r?   rÊ   rm  r+  r,  r]  rc   rc   rh   Úconcatenate_rawsÃ	  s    
 ÿr7  c                 C   s8   d}| r$t | tƒr| dks4t|ƒ n|d7 }t|ƒ‚dS )zWarn or error about MaxShield.zÓThis file contains raw Internal Active Shielding data. It may be distorted. Elekta recommends it be run through MaxFilter to produce reliable results. Consider closing the file and running MaxFilter on the data.ÚyeszY Use allow_maxshield=True if you are sure you want to load the data despite this warning.N)r|   r˜   rA   r�   )Zallow_maxshieldr,  rc   rc   rh   Ú_check_maxshieldñ	  s    
ÿ
r9  )r   F)NN)}Ú
contextlibr   r  r   rÞ  r   r  Úos.pathrË  rÂ  r  Úcollectionsr   Únumpyrn   Ú	constantsr   Úutilsr	   r
   rÙ  r   r   r   r   r   Z	meas_infor   r   r   r«   r   r   r   r   Zchannels.channelsr   r   r   r   Zcompensatorr   r   Úwriter   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r×   r+   r,   r-   rJ  r.   r/   r0   r1   r2   r3   r7  r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   ÚdefaultsrN   ZvizrO   rP   rQ   rR   ÚeventrS   rT   rU   rV   rW   rX   rº   rü  r¹   r   r  ÚobjectrÅ   r  rw  r  r  r  r'  rÀ  r7  r9  rc   rc   rc   rh   Ú<module>   s‚   < l   ÿ               

,?<s
E0 ÿ-