U
    f»{j~œ  ã                   @   sv  d 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ZddlmZmZ ddlmZmZmZmZmZmZ dd	lmZ dd
lmZ ddlmZmZmZ ddlm Z  ddl!m"Z"m#Z# ddl$m%Z% ddl!m&Z&m'Z'm(Z(m)Z)m*Z* ddl+m,Z, dZ-dd„ Z.G dd„ dej/ƒZ0dd„ Z1dd„ Z2dd„ Z3dd„ Z4e&d,d!d"„ƒZ5G d#d$„ d$eƒZ6e&d-d%d&„ƒZ7d.d'd(„Z8d/d*d+„Z9dS )0zEGI NetStation Load Function.é    )ÚOrderedDictN)Úparseé   )Ú_read_eventsÚ_combine_triggers)Ú_get_signalfnameÚ_get_ep_infoÚ_extractÚ_get_blocksÚ
_get_gainsÚ_block_ré   )ÚBaseRaw)ÚFIFF)Ú_empty_infoÚcreate_infoÚ_ensure_meas_date_none_or_dt)Ú
setup_proj)Ú_create_chsÚ_mult_cal_oneé   )ÚAnnotations)ÚverboseÚloggerÚwarnÚ_check_optionÚ_check_fname)ÚEvokedArray)ZVREFzVertex Referencec           6   
   C   s$  t | ƒ}|d d }|d d }t | d¡}ddg}t||d�}d}t|d ƒr\|d d	 }t | |¡}t|ƒ}	t| ƒ}
t||d
�}| |	¡ |d d	 }t	 
d|¡}|dkr¼td|f ƒ‚| ¡ d	 }t|ƒdkrætdd„ |D ƒƒsêt‚t|ƒdkrúdnd}dD ]Ô}t|
| ƒD ]6\}}|| d	k�r6td|f ƒ‚|| |
| |< �qt |
| tj¡|
|< |	d }d}t ||¡}|| }|| }tjdd�� |
|  |9  < W 5 Q R X |
|  |  < |
|  tj¡|
|< �q|	d  ¡ }|
d |
d   ¡ }||k�p>|
d |
d k  ¡  �p>|
d dd… |
d dd… k ¡  }|�rftdt|
d ƒt|
d ƒf ƒ‚| |
¡ t |
d d d¡}d	}t|
d |
d ƒD ]2\}}|| }t ||| ¡|||…< ||7 }�qš||d< t | d ¡}t|ƒ}| d!¡d	 jj |d"< | d#¡} tƒ }!tƒ }"d	}#tƒ }$| D ]f}%t!|% d$¡d	 jj ƒ}&|&d%k�r$|% d&¡d	 jj }'|' "¡ }'|$ #|'¡ |! #d'¡ |" #d(¡ |#d }#�q$|#|d) k�r®td*|#|d) f ƒ‚g }(d+|k�rt | |d+ d ¡})t|)ƒ}*|*d }+|	d },t $|+dd… |,dd… ¡�o|+d |,d t d,¡ k}-|-�s>td-t|+ƒt|,ƒf ƒ‚t | d.¡}.t|.ƒ}/|/ d#¡} g }0g }1| D ]~}%|% d!¡d	 jj }2|% d/¡d	 j}3d}4|3dk	�r¢|3j }4|2d0k�r²d1}5nd2|2k�rÂd3}5nd4}5|0 #|5¡ |1 #|4¡ |( #|2¡ �qh|j|0|1|d+ d |*d5� |j|(||d d	 |!|"|$d6� |S )7zRead mff header.ÚEEGÚsignalÚinfozinfo.xmlZ
mffVersionZ
recordTime)ÚfilepathÚ r   )Ú	eeg_fnameÚ
info_fnamezD\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.(\d{6}(?:\d{3})?)[+-]\d{2}:\d{2}NzCould not parse recordTime %r)é   é	   c                 s   s   | ]}|  ¡ V  qd S ©N)Ú	isnumeric)Ú.0Úf© r+   úP/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/io/egi/egimff.pyÚ	<genexpr>9   s     z#_read_mff_header.<locals>.<genexpr>r%   iè  i@B )Ú
last_sampsÚfirst_sampszCould not parse epoch time %sÚsfreqÚraise)ZoverÚsamples_blockr.   r/   r   éÿÿÿÿz5EGI epoch first/last samps could not be parsed:
%s
%sÚ
disk_sampszsensorLayout.xmlÚnameÚdeviceÚsensorÚtype)r   r   ÚnumberÚeegÚuVÚ
n_channelszHNumber of defined channels (%d) did not match the expected channels (%d)ZPNSr   z/PNS and signals samples did not match:
%s
vs
%sz
pnsSet.xmlÚunitZECGÚecgZEMGÚemgZbio)Ú	pns_typesÚ	pns_unitsÚ	pns_fnameÚpns_sample_blocks)Ú	pns_namesÚversionÚdateÚ	chan_typeÚ	chan_unitÚnumbers)%r   ÚopÚjoinr	   Úlenr
   r   ÚdictÚupdateÚreÚmatchÚRuntimeErrorÚgroupsÚallÚAssertionErrorÚ	enumerateÚnpÚarrayZuint64ÚmathÚgcdZerrstateZastypeZint64ÚsumÚlistÚfullÚzipÚaranger   ÚgetElementsByTagNameÚ
firstChildÚdataÚintÚencodeÚappendÚarray_equal)6r!   Ú	all_filesZeeg_fileZeeg_info_fileZinfo_filepathÚtagsZversion_and_daterE   ÚfnameZsignal_blocksÚepochsZsummaryinfoZrecord_timeÚgÚfracÚdivÚkeyÚeiÚeÚ	numeratorÚdenominatorZthis_gcdZn_samps_blockZn_samps_epochsÚbadr4   ÚoffsetÚfirstÚlastZn_thisZsensor_layout_fileZsensor_layout_objÚsensorsrG   rH   Zn_chansrI   r7   Z
sensortypeZsnrD   Z	pns_fpathZ
pns_blocksÚpns_samplesZsignal_samplesZsame_blocksZpns_fileZpns_objr@   rA   r5   Z	unit_elemr=   Úch_typer+   r+   r,   Ú_read_mff_header   s   ÿ
þ"	
ÿ$þ

ÿÿ
ÿ





þ

ÿþþ






þ
 ýry   c                   @   s0   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
S )Ú_FixedOffsetz`Fixed offset in minutes east from UTC.

    Adapted from the official Python documentation.
    c                 C   s   t j|d�| _d S )N)Úminutes)ÚdatetimeÚ	timedeltaÚ_offset)Úselfrs   r+   r+   r,   Ú__init__º   s    z_FixedOffset.__init__c                 C   s   | j S r'   )r~   ©r   Údtr+   r+   r,   Ú	utcoffset½   s    z_FixedOffset.utcoffsetc                 C   s   dS )NZMFFr+   r�   r+   r+   r,   ÚtznameÀ   s    z_FixedOffset.tznamec                 C   s
   t  d¡S )Nr   )r|   r}   r�   r+   r+   r,   ÚdstÃ   s    z_FixedOffset.dstN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r€   rƒ   r„   r…   r+   r+   r+   r,   rz   ´   s
   rz   c              	   C   sÈ   t | ƒ}t| d dƒ�}t |tjd¡d }W 5 Q R X t|d ƒdkrv|d dd… |d d	d… g\}}|| |d< tj |d d
¡}t||| 	d¡dddd�}|j
dddg g g dd� | 
|¡ |S )zÄObtain the headers from the file package mff.

    Parameters
    ----------
    input_fname : str
        Path for the file

    Returns
    -------
    info : dict
        Main headers set.
    z/signal1.binÚrbr   r   rF   é    Né   iúÿÿÿz%Y-%m-%dT%H:%M:%S.%f%zz%z)rE   Úmeas_dt_localÚ
utc_offsetZgainÚbitsÚvalue_range)Zn_categoriesZ
n_segmentsÚn_eventsÚevent_codesZcategory_namesZcategory_lengthsZpre_baseline)ry   ÚopenrV   ÚfromfileZint32rL   r|   ÚstrptimerM   ÚstrftimerN   )Úinput_fnameZmff_hdrÚfidrE   r‚   ÚtzZtime_nr    r+   r+   r,   Ú_read_headerÇ   s2    $ ÿú  ÿ
rš   c                    sˆ   t t | |d ¡ƒ}|d dkrP|d dkrP|d d|d   gt|d ƒ }n ddd	œ‰ ‡ fd
d„|d D ƒ}d|kr„||d 9 }|S )z,Calculate calibration info for EEG channels.r$   r�   r   r�   r   rG   ç�íµ ÷Æ°>r   )r;   ÚVc                    s   g | ]}ˆ | ‘qS r+   r+   )r)   Út©Z
cal_scalesr+   r,   Ú
<listcomp>ý   s     z-_get_eeg_calibration_info.<locals>.<listcomp>rH   Zgcal)r   rJ   rK   rL   )r!   Úegi_infoZgainsÚcalsr+   rž   r,   Ú_get_eeg_calibration_infoõ   s    
ÿ
r¢   c                    sp  ddl m} t | d¡}t |¡sNt d¡ ‡ fdd„t|d ƒD ƒ}|dfS d	d
ddœ}t 	|d ¡}t
|ƒ}| d¡}	tƒ }
tƒ }tƒ }tƒ }|	D ]¼‰ˆ d¡d j}ˆ d¡d j}|dkrÐˆ t|jƒ n|j}|j ¡ }‡fdd„dD ƒ}t 	|¡d }||k�r|||| < q–t ||k¡}t|ƒdk�r@| |¡ q–| |¡ ||
|< q–|f |
|dœ|—Ž}||fS )zRead channel locations.r   )Úmake_dig_montagezcoordinates.xmlz=File coordinates.xml not found, not setting channel locationsc                    s   g | ]}ˆ |d   ‘qS )r   r+   ©r)   Úi)Úchannel_namingr+   r,   rŸ   
  s     z_read_locs.<locals>.<listcomp>r<   NZlpaZrpaZnasion)zLeft periauricular pointzRight periauricular pointZNasionrI   r7   r5   r   r9   c                    s"   g | ]}t ˆ  |¡d  jjƒ‘qS )r   )Úfloatr_   r`   ra   )r)   Zcoord)r7   r+   r,   rŸ      s   ÿZxyzéd   )Úch_posÚhsp)Zchannels.montager£   rJ   rK   Úexistsr   r   ÚrangerV   rW   r   r_   r   r[   rM   r`   rb   ra   rc   ÚflatnonzerorL   rd   )r!   r    r¦   r£   rh   Úch_namesZdig_ident_maprI   Zcoordinatesrv   r©   rª   ZnlrZname_elementZnum_elementr5   ÚnrZcoordsÚlocZid_Úmonr+   )r¦   r7   r,   Ú
_read_locs  sR    
ÿ

ÿý
ÿ

ÿ


r²   c                 C   sˆ   t |d ƒD ]v\}}| |¡}|d | }tjtjdœ}| |tj¡}tj}	d}
|d | dkrjtj}	d}
| | j	|
|tj
|	d� q| S )	z/Add info for PNS channels to channel info dict.rD   r@   )r>   r?   r›   rA   r;   g      ð?)ÚcalÚkindÚ	coil_typer=   )rU   Úindexr   ÚFIFFV_ECG_CHÚFIFFV_EMG_CHÚgetÚFIFFV_BIO_CHZFIFF_UNIT_VÚFIFF_UNIT_NONErN   ÚFIFFV_COIL_NONE)Úchsr    r®   Zi_chÚch_nameÚidxrx   Ztype_to_kind_mapÚch_kindZch_unitZch_calr+   r+   r,   Ú_add_pns_channel_info4  s&    
ÿ  þrÁ   FúE%dc              	   C   s   t | |||||||ƒS )a-  Read EGI mff binary as raw object.

    .. note:: This function attempts to create a synthetic trigger channel.
              See notes below.

    Parameters
    ----------
    input_fname : str
        Path to the raw file.
    eog : list or tuple
        Names of channels or list of indices that should be designated
        EOG channels. Default is None.
    misc : list or tuple
        Names of channels or list of indices that should be designated
        MISC channels. Default is None.
    include : None | list
       The event channels to be ignored when creating the synthetic
       trigger. Defaults to None.
       Note. Overrides `exclude` parameter.
    exclude : None | list
       The event channels to be ignored when creating the synthetic
       trigger. Defaults to None. If None, channels that have more than
       one event and the ``sync`` and ``TREV`` channels will be
       ignored.
    %(preload)s
    channel_naming : str
        Channel naming convention for the data channels. Defaults to 'E%%d'
        (resulting in channel names 'E1', 'E2', 'E3'...). The effective default
        prior to 0.14.0 was 'EEG %%03d'.
    %(verbose)s

    Returns
    -------
    raw : instance of RawMff
        A Raw object containing EGI mff data.

    Notes
    -----
    The trigger channel names are based on the arbitrary user dependent event
    codes used. However this function will attempt to generate a synthetic
    trigger channel named ``STI 014`` in accordance with the general
    Neuromag / MNE naming pattern.

    The event_id assignment equals ``np.arange(n_events) + 1``. The resulting
    ``event_id`` mapping is stored as attribute to the resulting raw object but
    will be ignored when saving to a fiff. Note. The trigger channel is
    artificially constructed based on timestamps received by the Netstation.
    As a consequence, triggers have only short durations.

    This step will fail if events are not mutually exclusive.

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

    .. versionadded:: 0.15.0
    )ÚRawMff)r—   ÚeogÚmiscÚincludeÚexcludeÚpreloadr¦   r   r+   r+   r,   Ú_read_raw_egi_mffH  s
    =  ÿrÉ   c                       s.   e Zd ZdZed	‡ fdd„	ƒZdd„ Z‡  ZS )
rÃ   zRawMff class.NFrÂ   c	           +   
      sÀ  t |ddddd�}t d| ¡ t|ƒ}	|dkr4g }|dkr\t t |	d ¡dk¡d	  ¡ }t d
¡ t||	ƒ\}
}	t	||	ƒ}t d¡ |	d d	k�r´t
|	d ƒ‰ ˆdk�r€|dkr¼ddgn|‰‡fdd„tˆ ƒD ƒ‰g }|dk�rt|
ƒD ]&\}}| ¡ dkrìˆ | rì| |¡ qìtˆƒt|ƒ tˆ ƒk�r:tdtƒ n
ˆ |¡ ˆ ¡  ‡fdd„t |	d ¡D ƒ‰‡fdd„tˆ ƒD ƒ‰n‡fdd„tˆ ƒD ƒ‰ˆ‰dˆfd|ffD ]V\}}t|t
ƒ�rè|D ]"}|ˆ k�rÂtdt|ƒ› �ƒ‚�qÂn|dk	�rªtd| ƒ‚�qªt d¡ t dd ‡fdd„tˆ ƒD ƒ¡ ¡ t tˆƒ¡d }t|
ˆ |d�|	d < tt‡fd!d„ˆ D ƒ|ƒƒ| _|	d  dk	�r–t |
|	d  g¡}
|
jd |	d" d# k�sÆt‚nd| _d|	d < g ‰ |	d$  t j!j"¡}t#|	d% ƒ}t$|ƒ|d&< |	d' |d'< t|	d( d)�|d*< t%||	|ƒ\}}| t
|	d ƒ¡ |	d  dk	�rH| d+¡ t &|t 'dtˆ ƒd t|ƒ t|ƒ ¡g¡}| |	d, ¡ t &|t 'dt|	d, ƒ¡g¡}t(j)}t(j*}t+|||||d-d-|ƒ}‡ fd.d„t|ƒD ƒ}|D ],‰|ˆ  ,t(j-|ˆ t(j.t(j/t(j0d/œ¡ �qÞt1||	|ƒ}||d0< d1|_2| 3¡  |dk	�rF|j4|d2d3� t 5t 6|j7t8¡¡}t|ƒ�rä|d0 t9|ƒ d4 dd5… }|d0 D ]<}|d6 t(j*k}|d7 t8k}|�rˆ|�rˆ||d4 d5d8…< �qˆ| :¡ � t(j;|d9< W 5 Q R X t< ||	d: ¡} |
|	d;< d<}!tƒ ‰t d=d„ |D ƒ¡d	 ˆd< t d>d„ |D ƒ¡d	 ˆd?< t d@d„ |D ƒ¡d	 ˆdA< t =t &‡fdBd„|!D ƒ¡t t|ƒ¡¡�sŽtdCƒ‚d	g|	dD< |!D ]}"|	dD  tˆ|" ƒ¡ �qœt >|	dD ¡|	dD< |	dD d	 d	k�sât‚|	dD d# |dE k�süt‚d	g}#|	d" d# d g}$tt
ƒ t
ƒ t
ƒ dF�}%tˆdA ƒ�rÚt< ||	dG ¡|	dH< t |	dI dJ ¡}&t |	dJ ¡}'|&|'d k�rÀtdKƒ |%dL  |$d# |	d%  ¡ |%dM  d|	d%  ¡ |%dN  dO¡ n|&|'k�rÚt?dP|&|'f ƒ‚| g| _@|	g| _AtBtC| ƒjD||dQ| g|#|$|	g|dR� t|	dS dd… |	d" dd#… ƒD ]d\}(})|(|) }*|*d	k�sNt‚|*�r0|%dL  |)dT |	d%  ¡ |%dM  |*|	d%  ¡ |%dN  dU¡ �q0t|%dL ƒ�r¼|  EtFf |%dVdi—Ž¡ dS )WzInit the RawMff class.ÚreadTr—   )Úneed_dirz!Reading EGI MFF Header from %s...NrG   r:   r   z    Reading events ...z#    Assembling measurement info ...r‘   r’   ÚsyncZTREVc                    s   g | ]\}}|ˆ kr|‘qS r+   r+   ©r)   r¥   Úk)Úexclude_listr+   r,   rŸ   £  s
     ÿ z#RawMff.__init__.<locals>.<listcomp>r   z5Did not find any event code with more than one event.c                    s   g | ]}|ˆ kr|‘qS r+   r+   r¤   )Úexclude_indsr+   r,   rŸ   ±  s    ÿc                    s   g | ]\}}|ˆ kr|‘qS r+   r+   rÍ   ©Úinclude_r+   r,   rŸ   ³  s    ÿc                    s   g | ]\}}|ˆ kr|‘qS r+   r+   rÍ   )rÆ   r+   r,   rŸ   ¶  s    ÿrÆ   rÇ   zCould not find event named z!`%s` must be None or of type listz.    Synthesizing trigger channel "STI 014" ...z    Excluding events {%s} ...z, c                    s   g | ]\}}|ˆ kr|‘qS r+   r+   rÍ   rÑ   r+   r,   rŸ   Ä  s    ÿ)Z	remappingZnew_triggerc                    s   g | ]}|ˆ kr|‘qS r+   r+   )r)   ro   )Úinclude_namesr+   r,   rŸ   É  s
     ÿ r.   r3   r�   r0   Z	meas_daterŽ   r6   ©r8   Údevice_infozSTI 014rD   r+   c                    s&   g | ]\}}|  d ¡s|ˆ kr|‘qS )ZSTI)Ú
startswith)r)   r¥   r5   )r’   r+   r,   rŸ   î  s    
 ÿ)Zunit_mulr³   r´   rµ   r=   r½   FÚignore©Z
on_missingr°   r   r´   r¾   r%   Úcustom_ref_appliedr#   Ú
egi_events)r:   ÚstiÚpnsc                 S   s   g | ]}|d  t jk‘qS ©r´   )r   ÚFIFFV_EEG_CH©r)   Úchr+   r+   r,   rŸ     s     c                 S   s   g | ]}|d  t jk‘qS rÝ   )r   ÚFIFFV_STIM_CHrß   r+   r+   r,   rŸ     s     rÛ   c                 S   s$   g | ]}|d  t jt jt jfk‘qS rÝ   )r   r·   r¸   rº   rß   r+   r+   r,   rŸ     s   ÿÿrÜ   c                    s   g | ]}ˆ | ‘qS r+   r+   )r)   rm   )r¿   r+   r,   rŸ     s     z:Currently interlacing EEG and PNS channelsis not supportedÚkind_boundsÚnchan)ÚonsetÚdurationÚdescriptionrB   Úpns_filepathrC   r2   z$This file has the EGI PSG sample bugrä   rå   ræ   ZBAD_EGI_PSGz/PNS samples (%d) did not match EEG samples (%d)Zsingle)rÈ   Zorig_formatÚ	filenamesr/   r.   Z
raw_extrasr   r/   g      à?ZBAD_ACQ_SKIPZ	orig_time)Gr   r   r    rš   rV   ÚwhererW   Útolistr   r¢   r[   rU   rZ   rd   rL   r   ÚRuntimeWarningÚextendÚsortr^   Ú
isinstanceÚ
ValueErrorÚreprrK   r   rM   r]   Zevent_idÚvstackÚshaperT   Ú
astimezoner|   ÚtimezoneÚutcr   r   r²   ÚconcatenateÚrepeatr   ÚFIFFV_COIL_EEGrÞ   r   rN   ZFIFF_UNITM_NONErá   r¼   r»   rÁ   Z	_unlockedZ_update_redundantÚset_montager­   Zin1dr®   ÚREFERENCE_NAMESrb   Ú_unlockZFIFFV_MNE_CUSTOM_REF_ONrJ   re   ÚcumsumrQ   Ú
_filenamesÚ_raw_extrasÚsuperrÃ   r€   Zset_annotationsr   )+r   r—   rÄ   rÅ   rÆ   rÇ   rÈ   r¦   r   r    rÚ   r¡   Zmore_excludesÚiiÚeventÚkkÚvrÎ   Z
events_idsZmeas_dt_utcr    r®   r±   Úch_coilrÀ   r½   Z
sti_ch_idxZref_idxZ
ref_coordsZchanZis_eegZ
is_not_refZfile_binÚkeysrm   r/   r.   Zannotrw   Zeeg_samplesrt   Z	prev_lastÚgap©Ú	__class__)r’   rÐ   rÏ   r¿   rÆ   rÒ   rÓ   r,   r€   Œ  sz   
ÿÿÿÿ




ÿ

ÿ


ÿ ÿ
ÿÿ
&ÿÿü


ÿÿÿÿÿÿþþ
 ÿ
ÿ
ÿÿ
     ýÿzRawMff.__init__c           *   	   C   sŒ  t  d|d›d|d›d�¡ d}| j| }	t |	d d || f¡}
|	d }|	d	 }|	d }t|tƒrvt |j|j	¡}t 
||d
 k ¡d }||tjf }|| }t 
||d
 k||d k @ ¡d }|| }|| |d
  }t 
||d k||d k @ ¡d }|| |d  }||tjf }~~~|	d |||…f |
|dd…f< |	d ||… }t 
|dk¡d }t|ƒ�s‚t||
|||ƒ dS ||d  }||d  d
 }t|ƒ|| k�s´t‚t |¡}t ||k¡}||dk�rä||d
  nd }|| }t| j| ddd���x}d}d}d} ||k �rRt|ƒ}!|!dk	�r6|!}| |d d
¡ |d
7 }�q|dk�r|t  d|› �¡ t|ƒ}!|d
7 }|!dk	�rŠ|!}|d |d  }"t |||"¡}#|#j|ddd�}#|#jd
 }$t  d|$› d�¡ t  d|› d�¡ |dk�r|#dd…|d…f }#|$| }$d}||$k �r2|#dd…d|…f }#|}$t  d|$› d�¡ | }%|%|$ }&|#| |
|||%|&… f< ||$ }| |$ } �qRW 5 Q R X t|ƒdk�rx|	d }'|	d }(|(d }|(d	 }t |¡}t ||k ¡}||dk�rä||d
  nd }|| }t|'ddd���p}| dd¡ | ¡ })| d¡ d}d}d} ||k �rjt|ƒ}!|!dk	�rN|!}| |d d
¡ |d
7 }�q.|dk�rn|d
k�rœ| ¡ |)k�rœd|
|df< �qnt|ƒ}!|!dk	�r²|!}|d |d  }"t |||"¡}#|#j|ddd�}#|#jd
 }$|dk�r|#dd…|d…f }#|$| }$d}||$k �r6|#dd…d|…f }#|}$| }%|%|$ }&|#| |
|||%|&… f< ||$ }| |$ } �qjW 5 Q R X t||
|||ƒ dS )zRead a chunk of data.zReading MFF Z6dz ... ú ...z<f4râ   r3   r<   r2   r   r   r   r   rÚ   Nr4   rŠ   )Ú	bufferingÚ
block_sizez    Reading from block ZnsamplesÚncÚC)Úorderz        Read   z samplesz        Offset z        Keep   rç   rC   )r   Údebugrþ   rV   Zzerosrî   Úslicer^   ÚstartÚstopré   ZnewaxisrL   r   rT   rü   rZ   r“   rý   r   Úseekr”   Zreshaperò   Útell)*r   ra   r¿   Úfir  r  r¡   ZmultZdtyper    Úoner<   r2   ZboundsZeeg_outZeeg_oneZeeg_inZstim_outZstim_oneZstim_inZpns_outZpns_inZpns_oner4   Zdisk_use_idxZblock_samples_offsetZoffset_blocksZoffset_samplesZsamples_to_readr˜   Zcurrent_blockZcurrent_block_infoZcurrent_data_sampleZthis_block_infoZto_readZ
block_dataZsamples_readZs_startZs_endrç   Zpns_infoÚ	file_sizer+   r+   r,   Ú_read_segment_fileN  sü    

"" 

ÿÿ



ÿ



ÿÿ




ÿ


ÿzRawMff._read_segment_file)NNNNFrÂ   N)r†   r‡   rˆ   r‰   r   r€   r  Ú__classcell__r+   r+   r  r,   rÃ   ‰  s            þ BrÃ   c                    sü   t ƒ }ˆ d¡stdƒ‚| ˆ¡}z
|j}W n tk
rF   |j}Y nX |dkrdtˆ› d|› d�ƒ‚d|j ¡ kr‚tdˆ› d�ƒ‚d	}|d
kr¤|j	j	}	t
|	 ¡ ƒ}nt|t
ƒs¸|g}d}t dt|ƒ› dˆ› d�¡ ‡ ‡‡‡fdd„|D ƒ}
|rô|
S |
d S )a‹  Read averaged MFF file as EvokedArray or list of EvokedArray.

    Parameters
    ----------
    fname : str
        File path to averaged MFF file. Should end in .mff.
    condition : int or str | list of int or str | None
        The index (indices) or category (categories) from which to read in
        data. Averaged MFF files can contain separate averages for different
        categories. These can be indexed by the block number or the category
        name. If ``condition`` is a list or None, a list of EvokedArray objects
        is returned.
    channel_naming : str
        Channel naming convention for EEG channels. Defaults to 'E%%d'
        (resulting in channel names 'E1', 'E2', 'E3'...).
    baseline : None (default) or tuple of length 2
        The time interval to apply baseline correction. If None do not apply
        it. If baseline is (a, b) the interval is between "a (s)" and "b (s)".
        If a is None the beginning of the data is used and if b is None then b
        is set to the end of the interval. If baseline is equal to (None, None)
        all the time interval is used. Correction is applied by computing mean
        of the baseline period and subtracting it from the data. The baseline
        (a, b) includes both endpoints, i.e. all timepoints t such that
        a <= t <= b.
    %(verbose)s

    Returns
    -------
    evoked : EvokedArray or list of EvokedArray
        The evoked dataset(s); one EvokedArray if condition is int or str,
        or list of EvokedArray if condition is None or list.

    Raises
    ------
    ValueError
        If ``fname`` has file extension other than '.mff'.
    ValueError
        If the MFF file specified by ``fname`` is not averaged.
    ValueError
        If no categories.xml file in MFF directory specified by ``fname``.

    See Also
    --------
    Evoked, EvokedArray, create_info

    Notes
    -----
    .. versionadded:: 0.22
    z.mffz0fname must be an MFF file with extension ".mff".)ZaveragedZ	segmentedz is a z: MFF file. fname must be the path to an averaged MFF file.zcategories.xmlz+categories.xml not found in MFF directory. z! may not be an averaged MFF file.TNFzReading z evoked datasets from r	  c                    s"   g | ]}t ˆ|ˆˆd � ˆ ¡‘qS ))r¦   r   )Ú_read_evoked_mffZapply_baseline)r)   Úc©Úbaseliner¦   rh   r   r+   r,   rŸ   G  s   þÿÿz$read_evokeds_mff.<locals>.<listcomp>r   )Ú_import_mffpyÚendswithrï   ÚReaderZ
mff_flavorÚAttributeErrorÚflavorÚ	directoryÚlistdirÚ
categoriesr[   r  rî   r   r    rL   )rh   Ú	conditionr¦   r  r   ÚmffpyÚmffr"  Zreturn_listr%  Úoutputr+   r  r,   Úread_evokeds_mffú  s0    4



þr*  c              	   C   sÔ  ddl }t| ƒ}| | ¡}|jj}t|tƒrHtd||dd�}|j| }	nZt|tƒršz|j| }	W n0 t	k
r�   t
d|› dt|jƒ› d�ƒ‚Y nX |	j}ntd	ƒ‚| |	¡}
|
d
 \}}d|
krì|
d \}}t ||f¡}|d |d  }n|}|d }|d9 }t| ||ƒ\}}| |d ¡ t||jd
 |ƒ}| ¡ �* t|d d�|d< t|j ¡ ƒ|d< W 5 Q R X t| |ƒ}t |t dt|d ƒ¡g¡}tj}tj}t ||||ddddƒ}t!|||ƒ}| ¡ � ||d< W 5 Q R X |dk	�rò|j"|dd� ||d< z|| d d }W n. t#k
�r<   t$d|› d�t%d� d}Y nX g }|�rÈ|D ]z}|d dk�rL|d  dk�r�|d! D ]}| &||d  ¡ �qtn4|d  d"k�rL|d! D ]}| &|d |d  ¡ �q¦�qL||d#< | ¡ � d$|d%< W 5 Q R X z|j' (d&¡}W n t
t)fk
�r   Y n^X |� |j* +|¡}W 5 Q R X |j,D ]8}|d' d(k�r:d)|d* k�rht-|ƒ\}}nd+|d%< �q:z|| d d, d- d. }W n. t#k
�r¾   t$d/|› d0�t%d� d}Y nX t.||d1|||d2�S )3zRead evoked data from MFF file.r   Nr&  zprovided as category name)Úextraz"condition" parameter (zB), provided as epoch index, is out of range for available epochs (z).z0"condition" parameter must be either int or str.r   ZPNSDatarG   r@   r›   rD   r6   rÔ   rÕ   rã   r   r+   r½   r×   rØ   ræ   ZchannelStatusz,Channel status data not found for condition z$. No channels will be marked as bad.)ÚcategoryZ	exclusionZbadChannelsZ	signalBinZchannelsr   ÚbadsFrÙ   ÚhistoryÚmethodzMontage Operations ToolzAverage ReferenceÚsettingsTr  z#segra   z2Number of averaged epochs not found for condition z. nave will default to 1.g        )ZtminÚcommentÚnaver   )/r'  rš   r   r%  rî   Ústrr   ri   rb   Ú
IndexErrorrï   rL   r5   Ú	TypeErrorZget_physical_samples_from_epochrV   rñ   r²   rì   r   Zsampling_ratesrû   rM   rZ   Znum_channelsÚvaluesr¢   rö   r÷   r   rø   rÞ   r   rÁ   rù   ÚKeyErrorr   ÚUserWarningrd   r#  ZfilepointerÚFileNotFoundErrorÚXMLÚ	from_fileÚentriesr   r   )rh   r&  r¦   r   r'  r    r(  r%  r,  Úepochra   Zeeg_dataÚt0Zpns_dataZall_dataZch_typesr®   r±   r    r¡   r  rÀ   r½   Zchannel_statusr-  Úentryrà   Úfpr.  Z	projectorr2  r+   r+   r,   r  M  s¨    

ÿ
"




ÿ


ÿ

 ÿr  úread averaged .mff filesc              
   C   sL   zddl }W n: tk
rF } zd| › d|› �}t|ƒ‚W 5 d}~X Y nX |S )zImport and return module mffpy.r   Nzmffpy is required to z, got:
)r'  ÚImportError)Úwhyr'  ÚexpÚmsgr+   r+   r,   r  Á  s    r  )NNNNFrÂ   N)NrÂ   NN)rÂ   N)rA  ):r‰   Úcollectionsr   r|   rX   Úos.pathÚpathrJ   rO   Zxml.dom.minidomr   ÚnumpyrV   Úeventsr   r   Zgeneralr   r   r	   r
   r   r   Úbaser   Ú	constantsr   Z	meas_infor   r   r   Zprojr   Úutilsr   r   Úannotationsr   r   r   r   r   r   Zevokedr   rú   ry   Útzinforz   rš   r¢   r²   rÁ   rÉ   rÃ   r*  r  r  r+   r+   r+   r,   Ú<module>   sV     .1         þ@  s    ÿR
t