U
    f»{jŸ¡  ã                   @   sŠ  d Z ddlmZmZ ddlmZmZ ddlmZm	Z
 ddlZddlmZ dd	lmZmZmZmZmZmZmZ dd
lmZmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddl!m"Z" ddlm#Z#m$Z$ ddl%m&Z&m'Z' ddl(m)Z) dZ*dZ+dZ,dd„ Z-G dd„ de.ƒZ/eG dd„ deƒƒZ0dd„ Z1dd „ Z2G d!d"„ d"eƒZ3d#d$„ Z4ed3d%d&„ƒZ5ed4d'd(„ƒZ6d5d)d*„Z7ed6d/d0„ƒZ8ed7d1d2„ƒZ9dS )8zhConversion tool from SQD to FIF.

RawKIT class is adapted from Denis Engemann et al.'s mne_bti2fiff.py.
é    )ÚdefaultdictÚOrderedDict)ÚsinÚcos)ÚSEEK_CURÚpathNé   ©Ú
pick_typesé   )ÚverboseÚloggerÚwarnÚfill_docÚ_check_optionÚ_stamp_to_dtÚ_check_fname)Úapply_transÚals_ras_trans)ÚBaseRaw)Ú_mult_cal_one)Ú
BaseEpochs)ÚFIFF)Ú_empty_infoé   )ÚKITÚLEGACY_AMP_PARAMS)Úread_mrkÚ_set_dig_kit)Úread_eventsz<f8z<u4z<i4c              	   C   sØ   |d kr<|d kr<|d kr<|  dd ¡}|  dd ¡}|  dd ¡}t|tƒrbdd„ |D ƒ}tj|dd�}|d k	r´|d k	r´|d k	r´|  ¡ �* t||||d ƒ\| d	< | d
< | d< W 5 Q R X n |d k	sÌ|d k	sÌ|d k	rÔtdƒ‚| S )NÚmrkÚelpÚhspc                 S   s"   g | ]}t |tƒrt|ƒn|‘qS © )Ú
isinstanceÚstrr   )Ú.0Úmarkerr#   r#   úM/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/io/kit/kit.pyÚ
<listcomp>.   s   ÿz&_call_digitization.<locals>.<listcomp>r   ©ZaxisÚeeg_digÚdigZ
dev_head_tZhpi_resultsz=mrk, elp and hsp need to be provided as a group (all or none))Úgetr$   ÚlistÚnpZmeanZ_unlockr   Ú
ValueError©Úinfor    r!   r"   Úkit_infor#   r#   r(   Ú_call_digitization%   s     
ÿ
ÿ r4   c                   @   s   e Zd ZdZdd„ ZdS )ÚUnsupportedKITFormatz4Our reader is not guaranteed to work with old files.c                 O   s   || _ tj| f|ž|Ž d S )N)Úsqd_versionr0   Ú__init__)Úselfr6   ÚargsÚkwargsr#   r#   r(   r7   A   s    zUnsupportedKITFormat.__init__N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r7   r#   r#   r#   r(   r5   >   s   r5   c                       sD   e Zd ZdZed‡ fdd	„	ƒZddd„Zedd„ ƒZdd„ Z	‡  Z
S )ÚRawKITaó	  Raw object from KIT SQD file.

    Parameters
    ----------
    input_fname : str
        Path to the sqd file.
    mrk : None | str | array_like, shape (5, 3) | list of str or array_like
        Marker points representing the location of the marker coils with
        respect to the MEG Sensors, or path to a marker file.
        If list, all of the markers will be averaged together.
    elp : None | str | array_like, shape (8, 3)
        Digitizer points representing the location of the fiducials and the
        marker coils with respect to the digitized head shape, or path to a
        file containing these points.
    hsp : None | str | array, shape (n_points, 3)
        Digitizer head shape points, or path to head shape file. If more than
        10,000 points are in the head shape, they are automatically decimated.
    stim : list of int | '<' | '>' | None
        Channel-value correspondence when converting KIT trigger channels to a
        Neuromag-style stim channel. For '<', the largest values are assigned
        to the first channel (default). For '>', the largest values are
        assigned to the last channel. Can also be specified as a list of
        trigger channel indexes. If None, no synthesized channel is generated.
    slope : '+' | '-'
        How to interpret values on KIT trigger channels when synthesizing a
        Neuromag-style stim channel. With '+', a positive slope (low-to-high)
        is interpreted as an event. With '-', a negative slope (high-to-low)
        is interpreted as an event.
    stimthresh : float
        The threshold level for accepting voltage changes in KIT trigger
        channels as a trigger event. If None, stim must also be set to None.
    %(preload)s
    stim_code : 'binary' | 'channel'
        How to decode trigger values from stim channels. 'binary' read stim
        channel events as binary code, 'channel' encodes channel number.
    allow_unknown_format : bool
        Force reading old data that is not officially supported. Alternatively,
        read and re-save the data with the KIT MEG Laboratory application.
    %(standardize_names)s
    %(verbose)s

    Notes
    -----
    ``elp`` and ``hsp`` are usually the exported text files (*.txt) from the
    Polhemus FastScan system. hsp refers to the headshape surface points. elp
    refers to the points in head-space that corresponds to the HPI points.
    Currently, '*.elp' and '*.hsp' files are NOT supported.

    See Also
    --------
    mne.io.Raw : Documentation of attribute and methods.
    Nú>ú-r   FÚbinaryc                    sÐ   t  d| ¡ t |¡}d| _t  d¡ t||
|ƒ\}}||d< ||d< |d tjkr^tdƒ‚t  d¡ |d	 d
 g}|g| _	|  
|||	¡ tt| ƒj||||g| j	|d� t| j||||d�| _t  d¡ d S )Nz$Extracting SQD Parameters from %s...FzCreating Raw.info structure...ÚslopeÚ
stimthreshÚacq_typez5SQD file contains epochs, not raw data. Wrong reader.zCreating Info structure...Ú	n_samplesr   )Ú
last_sampsÚ	filenamesZ
raw_extrasr   r1   úReady.)r   r2   ÚopÚabspathÚpreloadÚget_kit_infor   Ú
CONTINUOUSÚ	TypeErrorÚ_raw_extrasÚ_set_stimchannelsÚsuperr?   r7   r4   )r8   Úinput_fnamer    r!   r"   ÚstimrC   rD   rL   Ú	stim_codeÚallow_unknown_formatÚstandardize_namesr   r2   r3   rG   ©Ú	__class__r#   r(   r7   }   sB    

  ÿ

    þ    ÿzRawKIT.__init__ç     jø@c           	      C   s˜   t |ƒ}t | jƒ}t | jd ƒ}t| jdddg d�}tjd|ftjd�}t|||ƒD ]>}|| }| |||…f d }||dd…|||j	d  …f< qT|S )a  Read events from data.

        Parameter
        ---------
        buffer_size : int
            The size of chunk to by which the data are scanned.

        Returns
        -------
        events : array, [samples]
           The event vector (1 x samples).
        r   FT)ÚmegÚref_megrT   Úexclude©Údtyper   N)
ÚintZ
first_sampZ	last_sampr
   r2   r/   ÚemptyZint64ÚrangeÚshape)	r8   Úbuffer_sizeÚstartÚstopÚpickÚstim_chZb_startZb_stopÚxr#   r#   r(   Úread_stim_ch™   s    

 ÿ zRawKIT.read_stim_chc                 C   s&  | j rtdƒ‚td|ddgƒ |dk	�rt|tƒrrt|ƒ}|dkrR|ddd… }q®|dkr`|}q®td	t|ƒ ƒ‚n<t |t	¡}| 
¡ | jd
 d kr®td|| jd
 d f ƒ‚| jd
 d d }|d  ttj||dtjtjdtjt dtj¡tjtjd�¡ | ¡  || jd
 d< || jd
 d< dS )a²  Specify how the trigger channel is synthesized from analog channels.

        Has to be done before loading data. For a RawKIT instance that has been
        created with preload=True, this method will raise a
        NotImplementedError.

        Parameters
        ----------
        %(info_not_none)s
        stim : list of int | '<' | '>'
            Can be submitted as list of trigger channels.
            If a list is not specified, the default triggers extracted from
            misc channels will be used with specified directionality.
            '<' means that largest values assigned to the first channel
            in sequence.
            '>' means the largest trigger assigned to the last channel
            in sequence.
        stim_code : 'binary' | 'channel'
            How to decode trigger values from stim channels. 'binary' read stim
            channel events as binary code, 'channel' encodes channel number.
        z,Can't change stim channel after loading datarU   rB   ÚchannelNú<éÿÿÿÿr@   z0stim needs to be list of int, '>' or '<', not %rr   Únchanz.Got stim=%s, but sqd file only has %i channelsr   Úchsç      ð?zSTI 014é   )ÚcalÚlognoÚscannorb   ÚunitÚunit_mulÚch_nameÚ	coil_typeÚlocÚkindÚcoord_framerT   )rL   ÚNotImplementedErrorr   r$   r%   Ú_default_stim_chsr0   r/   Zasarrayr`   ÚmaxrP   ÚappendÚdictr   ÚCALIB_FACTORr   ZFIFF_UNIT_NONEZFIFF_UNITM_NONEZFIFFV_COIL_NONEÚfullÚnanZFIFFV_STIM_CHZFIFFV_COORD_UNKNOWNÚ_update_redundant)r8   r2   rT   rU   Zpicksrn   r#   r#   r(   rQ   ´   sJ    

ÿÿÿ
      ûzRawKIT._set_stimchannelsc              	   C   sv  | j | }|d }	|| |	 }
|d }|d j}|dks<t‚t|
d| |	 |	 ƒ}t| j| ddd���}||	 | }| |d	 tj d
 | ¡ |d }t	 
d|
|¡|	 D ]º}t||
||	  ƒ}t	j||d |d�}|j|	ddd� t¡}||jd  }|dd…||…f }||9 }|dk	�rVt||dd…f |d |d |d |ƒ}t	 ||f¡}t|||||ƒ q¬W 5 Q R X dS )zRead a chunk of raw data.rn   Úconv_factorr_   )r   é   i áõÚrbr   ©Ú	bufferingÚdirsÚoffsetrT   ©r_   Úcountrm   ÚF)Úorderr   NrC   rD   rU   )rP   ÚitemsizeÚAssertionErrorÚminÚopenÚ
_filenamesÚseekr   ÚDIR_INDEX_RAW_DATAr/   ÚarangeÚfromfileÚreshapeZastypeÚfloatrc   Ú_make_stim_channelÚvstackr   )r8   ÚdataÚidxÚfire   rf   ZcalsZmultÚsqdrn   Z	data_leftr…   Zn_bytesZblk_sizeÚfidZpointerrT   Z	blk_startÚblockZblk_stopZ	data_viewrh   r#   r#   r(   Ú_read_segment_fileî   s8    


   þzRawKIT._read_segment_file)NNNr@   rA   r   FrB   FNN)rZ   )r;   r<   r=   r>   r   r7   rj   r   rQ   r£   Ú__classcell__r#   r#   rX   r(   r?   F   s   5            ý

9r?   c                 C   s   t | dddg d�dd… S )z+Return default stim channels for SQD files.FT)r[   r\   Úmiscr]   Né   r	   )r2   r#   r#   r(   r}     s
    
ÿÿr}   c                 C   sŒ   |dkr| |k}n|dkr$| |k }nt dƒ‚|dkrHdt t| ƒ¡ }n|dkr`t dt|ƒ ƒ‚||dd…tjf  }tj|jd	d
�dd�S )z=Create synthetic stim channel from multiple trigger channels.ú+rA   zslope needs to be '+' or '-'rB   r   rk   z/stim_code must be 'binary' or 'channel', got %sNr   r*   )Zndmin)r0   r/   r—   ÚlenÚreprÚnewaxisÚarrayÚsum)Ztrigger_chsrC   Ú	thresholdrU   Ztrigger_valuesZtrig_chs_binZtrig_chsr#   r#   r(   r›     s    

ÿr›   c                       s.   e Zd ZdZed	‡ fdd„	ƒZdd„ Z‡  ZS )
Ú	EpochsKITa@  Epochs Array object from KIT SQD file.

    Parameters
    ----------
    input_fname : str
        Path to the sqd file.
    events : str | array, shape (n_events, 3)
        Path to events file. If array, it is the events typically returned
        by the read_events function. If some events don't match the events
        of interest as specified by event_id,they will be marked as 'IGNORED'
        in the drop log.
    event_id : int | list of int | dict | None
        The id of the event to consider. If dict,
        the keys can later be used to access associated events. Example:
        dict(auditory=1, visual=3). If int, a dict will be created with
        the id as string. If a list, all events with the IDs specified
        in the list are used. If None, all events will be used with
        and a dict is created with string integer names corresponding
        to the event id integers.
    tmin : float
        Start time before event.
    baseline : None or tuple of length 2 (default (None, 0))
        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.
        The baseline (a, b) includes both endpoints, i.e. all
        timepoints t such that a <= t <= b.
    reject : dict | None
        Rejection parameters based on peak-to-peak amplitude.
        Valid keys are 'grad' | 'mag' | 'eeg' | 'eog' | 'ecg'.
        If reject is None then no rejection is done. Example::

            reject = dict(grad=4000e-13, # T / m (gradiometers)
                          mag=4e-12, # T (magnetometers)
                          eeg=40e-6, # V (EEG channels)
                          eog=250e-6 # V (EOG channels)
                          )
    flat : dict | None
        Rejection parameters based on flatness of signal.
        Valid keys are 'grad' | 'mag' | 'eeg' | 'eog' | 'ecg', and values
        are floats that set the minimum acceptable peak-to-peak amplitude.
        If flat is None then no rejection is done.
    reject_tmin : scalar | None
        Start of the time window used to reject epochs (with the default None,
        the window will start with tmin).
    reject_tmax : scalar | None
        End of the time window used to reject epochs (with the default None,
        the window will end with tmax).
    mrk : None | str | array_like, shape = (5, 3) | list of str or array_like
        Marker points representing the location of the marker coils with
        respect to the MEG Sensors, or path to a marker file.
        If list, all of the markers will be averaged together.
    elp : None | str | array_like, shape = (8, 3)
        Digitizer points representing the location of the fiducials and the
        marker coils with respect to the digitized head shape, or path to a
        file containing these points.
    hsp : None | str | array, shape = (n_points, 3)
        Digitizer head shape points, or path to head shape file. If more than
        10`000 points are in the head shape, they are automatically decimated.
    allow_unknown_format : bool
        Force reading old data that is not officially supported. Alternatively,
        read and re-save the data with the KIT MEG Laboratory application.
    %(standardize_names)s
    %(verbose)s

    Notes
    -----
    ``elp`` and ``hsp`` are usually the exported text files (*.txt) from the
    Polhemus FastScan system. hsp refers to the headshape surface points. elp
    refers to the points in head-space that corresponds to the HPI points.
    Currently, '*.elp' and '*.hsp' files are NOT supported.

    See Also
    --------
    mne.Epochs : Documentation of attribute and methods.
    Nr   Fc                    s¨  t |tƒrt|ƒ}t|ddd�}t d| ¡ t|||ƒ\| _}|j|d� |g| _g | _	t
|ƒ| jd d krxtdƒ‚| jd d	 tjkržtj| jd d
< ntdƒ‚|d krÎdd„ t |d d …df ¡D ƒ}| ¡ D ],\}}||d d …df krÖtd||f ƒ‚qÖ|  ¡ }|j| jd d | jd | jd d fk�s<t‚|jd d | jd  | }tt| ƒj| j||||||||||	||d� t| j|
|||d�| _t d¡ d S )NTÚread)ÚfnameZ
must_existÚ	overwritez$Extracting KIT Parameters from %s...)rS   r   Ún_epochsz+Event list does not match number of epochs.rE   Zdata_lengthz@SQD file contains raw data, not epochs or average. Wrong reader.c                 S   s   i | ]}t |ƒt|ƒ“qS r#   )r%   r`   )r&   Úer#   r#   r(   Ú
<dictcomp>˜  s      z&EpochsKIT.__init__.<locals>.<dictcomp>r   z-No matching events found for %s (event id %i)rn   Úframe_lengthr   Úsfreq)ÚrejectÚflatÚreject_tminÚreject_tmaxÚfilenamer   r1   rI   )r$   r%   r   r   r   r2   rM   ÚupdaterP   r”   r¨   r0   r   ÚEPOCHSÚINTrO   r/   ÚuniqueÚitemsÚ_read_kit_datarc   r‘   rR   r®   r7   r4   )r8   rS   ÚeventsÚevent_idZtminZbaseliner·   r¸   r¹   rº   r    r!   r"   rV   rW   r   r3   ÚkeyÚvalr�   ZtmaxrX   r#   r(   r7   |  sn    
ÿ  ÿ
 ÿþ
          ý    ÿzEpochsKIT.__init__c              	   C   s¾   | j d }|d }|d }|d }|d }|d }|d }t|ddd	��6}| |d
 tj d ¡ || }	tj|||	d�}
W 5 Q R X |
 ||f¡j}
|
|d  }
|
 |||f¡}
|
 	d¡}
|
S )zúRead epochs data.

        Returns
        -------
        data : array, [channels x samples]
           the data matrix (channels x samples).
        times : array, [samples]
            returns the time values corresponding to the samples.
        r   rµ   r²   rF   rS   r_   rn   r‡   rˆ   rŠ   r‹   rŒ   r…   )r   r   r   )
rP   r“   r•   r   r–   r/   r˜   r™   ÚTZ	transpose)r8   r2   Zepoch_lengthr²   rF   rS   r_   rn   r¡   r�   r�   r#   r#   r(   rÁ   ¬  s     


zEpochsKIT._read_kit_data)Nr   NNNNNNNNFNN)r;   r<   r=   r>   r   r7   rÁ   r¤   r#   r#   rX   r(   r®   *  s    Q                   ü/r®   c              	   C   sH   t t | td¡d t | td¡d t | td¡d t | td¡d d�S )Nr   r   )r‹   ÚsizeÚ	max_countr�   )r€   r/   r˜   ÚUINT32ÚINT32)r¡   r#   r#   r(   Ú	_read_dirÊ  s
    ýrË   c                 C   st   t ƒ }| t| ƒ¡ t|d d d ƒD ],}t d|› d|  ¡ › �¡ | t| ƒ¡ q(t|ƒ|tj	 d kspt
‚|S )Nr   r�   r   z    KIT dir entry z @ )r.   r   rË   rb   r   ÚdebugÚtellr¨   r   ZDIR_INDEX_DIRr‘   )r¡   r   rŠ   Úiir#   r#   r(   Ú
_read_dirsÑ  s    rÏ   c           c      C   sÜ  t ƒ }| |d< d}t| ddd��
�:}t|ƒ |d< }| |tj d ¡ t |td¡\}}	|dk sr|dkr¤|	d	k r¤d
||	f }
|r”d}t	d|
 ƒ nt
|
d|
f ƒ‚t |td¡d }t|dd�}t|dd�}tt |td¡d ƒ |d< }t|dd�}t |td¡\}}| tjd	 t¡ t |td¡d }| tjd	 t¡ t |td¡d }| tjd	 t¡ t |td¡d }| tjd	 t¡ t |td¡d }| tjd t¡ |dk �sÊ|dk�râ|	d	k�râtt |td¡d ƒ}nt |td¡d }t |td	¡\}}}| dd¡}| ¡  dd¡}| dd¡}| ¡  dd¡}d|d›d|	d›�}t d¡ t d|¡ t d|¡ t d|¡ t d |¡ t d!|¡ t d"|¡ t d#|¡ t d$|¡ t d%|¡ t d&|¡ t d'|d( ¡ t d)|¡ t d*|¡ |› d+|› d,|› d-|› �}|d. dk�s*t‚t d/|d. › �¡|d0< |tjk�rŠttj ¡ ƒ}|t ||¡d  }t	d1|||||f ƒ |}|tj }|d |d2  }} g  |d3< }!tƒ }"t|ƒD �]r}#| || |#  ¡ t |td¡\}$|d4k�r|#d5k �r|$tjk�rtj}$|$tj k�rz|$tj!k�r2t"d6|$ ƒ‚|! #|$tj|td7d8�d9œ¡ |$tj$k�r2| d:t¡ t||$ƒ|!d; d<< n¸|$tj%k�r
t |td¡\}%| d=t¡ t||$ƒ}&|! #|$|%|&d>œ¡ |$tj&tj'fk�r2|$tj&k�ràd?nd.}'| |'t¡ |" #t |td¡d ¡ n(|$tjk�r&|! #d@|$i¡ nt(dA|$ ƒ‚�qÀt )|"¡}"| |tj* d ¡ tj|t|d d8�}(|df|(_+|(j,\})}*|)dk -¡ �sŽt‚| |tj. d ¡ t |td¡d }+|dBk�r&|+dC@ dD? },|+dE@ dF? }-|+dG@ dH? }.tj/|, tj/|-  tj/|.  }/|+dI@ d.? }0|+dJ@ d:? }1|+d	@ d? }2nP|+dK@ dL? }3|+dM@ d? }4tj/|3 tj/|4  }/|+dM@ d=? }0|+dI@ d.? }1|+dN@ dO? }2tj| \}5}6}7tj0|5 |0 |dP< tj1|6 |1 |dQ< tj2|7 |2 |dR< | |tj3 d ¡ t |td¡ \|dS< \}8t |td¡\|dT< |8tj4k�r.| tjt¡ t |td¡\|dU< n¦|8tj5k�sF|8tj6k�rÆt |td¡\|dV< t |td¡\|dW< t |td¡\|dX< t |td¡\|dY< |8tj5k�r°|dV |dU< n|dV |dY  |dU< nt(dZ|8f ƒ‚|tj7 }9|tj8 }:t ƒ };tƒ }<|9d[ dk�
rX|:d[ dk�
rX| |9d ¡ t|9d[ ƒD ]T}=t|d.d� ¡ }&|& 9¡ }&t |td	¡}>|&�rr|&|;k�sht‚|>|;|&< n
|< #|>¡ �q*g }?d\D ]4}@|@|;k�rˆt :|;|@ ¡ -¡ �rˆ|? #|; ;|@¡¡ �qˆt )|?¡}?t )|<t¡ <d;d	¡}<|?j+d]k�rþt=d^t>|?ƒd	 › �ƒ‚| |:d ¡ t ?|?j+d d	 d	f¡}Adgd7 }Bt|:d[ ƒD ]È}=t |td¡d }C| d:tj@ d:tj@  t¡ t |td¡d }D|C�	sˆ�	q:|Dt>|Aƒk�	sšt‚tt>|AƒƒD ]L}Et |td=¡\}F}G}H}ItA|Iƒ|B|E< | d	tj@ t¡ t |td	¡|A|E< �	q¦| dt¡ �	q:t-|Bƒ�
sHt Bd_tC|Bƒ› dt>|Bƒ› d`�¡ |?dgd	 |B  }?|A|B }A|jD|<|?|Ada� W 5 Q R X |�
rŒ|tEk�
r€t(db|f ƒ‚tE| \}}t )dcdd„ |!D ƒ¡}J|d(|  }K|K|/ |* }Lt F|J|L|K¡}Mdedd„ |!D ƒ}N|"d(|dO   }"|K|"|"dk< |"|M|N< |Mdfdf…tjGf |dg< tHt|dT ƒƒ}O|OjDtI|dfƒ|dQ |dP ||dh� t Bdi¡ g  |Odj< }PtJdkdl„ ƒ}QtKƒ |dm< tL|!dƒD �]J\}R}S|Sd@ tj k�rð|S Md<d¡}T|Tdk�s®|�r¶dn|R }Tt N|Sdo d	df… ¡\}U}VtO|UƒtP|Vƒ }WtO|UƒtO|Vƒ }XtP|Uƒ}Yt )|W|X|Yg¡}Z|ZtjQ R|Z¡ }Ztj?|ZjStjTdp�}[|Zd |Zd k �rb|Zd |Zd k �rXdq|[d< ndq|[d< n$|Zd |Zd k �r~dq|[d< ndq|[d< |[t C|[|Z ¡|Z 8 }[|[tjQ R|[¡ }[t U|Z|[¡}\t V|Sdo dfd	… |[|\|Zf¡}]tWtX|]ƒ}]tYjZ}^|] [¡ }_n’tj\|Sd@  }`|Q|`  d7  < |Q|` }a|S Md<d¡}T|T 9¡ }b|Tdrk�s:|�rFds|`|af }TtYj]}^t ?dD¡}_|b�r‚|b|;k�r‚|;|b  |_dfd	…< |dm |b< |P #t tj^|R|Rtj_|^tj`|TtYjatj!|Sd@  tjb|Sd@  |_dt�¡ �qxd|O_c|O d¡  |O|fS )uaâ  Extract all the information from the sqd/con file.

    Parameters
    ----------
    rawfile : str
        KIT file to be read.
    allow_unknown_format : bool
        Force reading old data that is not officially supported. Alternatively,
        read and re-save the data with the KIT MEG Laboratory application.
    %(standardize_names)s
    %(verbose)s

    Returns
    -------
    %(info_not_none)s
    sqd : dict
        A dict containing all the sqd parameter settings.
    ÚrawfileFr‡   r   rˆ   rŠ   r‹   r   r   zV%iR%03iTzForce loading KIT format %szaSQD file format %s is not officially supported. Set allow_unknown_format=True to load it anyways.r   é€   )Únrn   é   é   ú Ú Ú
ú/ÚVÚdÚRZ03dzSQD file basic information:zMeg160 version = %szSystem ID      = %izSystem name    = %szModel name     = %szChannel count  = %izComment        = %szDewar style    = %izFLL type       = %izTrigger type   = %izA/D board type = %izADC range      = +/-%s[V]g       @zADC allocate   = %i[bit]zADC bit        = %i[bit]z (z) ú r¦   z<ir_   z­Unknown site filter settings (FLL) for system "%s" model "%s" (ID %s), will assume FLL %d->%d, check your data for correctness, including channel scales and filter settings!rÇ   Úchannelsé4   é    zNKIT channel type %i can not be read. Please contact the mne-python developers.é   rŒ   )Útypery   é   rm   Únamer†   )rá   Únorã   é   rá   zUnknown KIT channel type: %iéd   i p  rq   i   pé   i   é   i   i   i   é   é   i À  é   ÚhighpassÚlowpassZnotchrE   r¶   rF   rµ   Zpretrigger_lengthZaverage_countr²   zOInvalid acquisition type: %i. Your file is neither continuous nor epoched data.r�   )ZfidnzZfidt9Zfidt10Zhpi_1Zhpi_2Zhpi_3Zhpi_4Zhpi_5))rå   r   )rê   r   )r¦   r   z"Fewer than 3 HPI coils found, got zKeeping z HPI coils that were digitized)r"   r!   r    z.Legacy parameters for system ID %i unavailablec                 S   s   g | ]}|d  t jk‘qS ©rá   )r   ÚCHANNELS_MEG©r&   Úchr#   r#   r(   r)      s     z get_kit_info.<locals>.<listcomp>c                 S   s    g | ]}|d  t jt jfk‘qS rî   )r   ÚCHANNEL_EEGÚCHANNEL_ECGrð   r#   r#   r(   r)   	  s   ÿNr…   )Z	meas_daterí   rì   Zkit_system_idÚdescriptionz!Setting channel info structure...ro   c                   S   s   dS )Nr   r#   r#   r#   r#   r(   Ú<lambda>  ó    zget_kit_info.<locals>.<lambda>r+   zMEG %03dry   r^   rp   )rÖ   ZEEGz%s %03i)rr   rs   rt   rb   ru   rv   rw   r{   rx   rz   ry   )er€   r“   rÏ   r•   r   ZDIR_INDEX_SYSTEMr/   r˜   rÊ   r   r5   Ú
_read_namer`   r¾   r   rš   ÚFLOAT64ÚreplaceÚstripr   rÌ   r‘   r_   ZFLL_SETTINGSÚsortedÚkeysZsearchsortedZDIR_INDEX_CHANNELSr.   rb   ZCHANNEL_NULLZCHANNEL_MAGNETOMETER_REFERENCErï   ZCH_TO_FIFF_COILr|   r   ÚCHANNEL_NAME_NCHARZCHANNELS_MISCrò   ró   ÚIOErrorr«   ZDIR_INDEX_CALIBRATIONrc   rÆ   ÚallZDIR_INDEX_AMP_FILTERZGAINSZHPFSZLPFSZBEFSZDIR_INDEX_ACQ_CONDrN   ZEVOKEDr½   ZDIR_INDEX_DIG_POINTSZDIR_INDEX_COREGÚlowerÚisfiniteÚpopr™   ÚRuntimeErrorr¨   ZzerosÚDOUBLEÚboolr2   r¬   r¼   r   Úwhererª   r   r   r   r   Ú	enumerater-   Úradiansr   r   ZlinalgZnormrÇ   Zfloat64Úcrossrœ   r   r   r   ZFIFF_UNIT_TZravelZCH_LABELZFIFF_UNIT_Vr�   ÚRANGEZUNIT_MULZFIFFV_COORD_DEVICEZCH_TO_FIFF_KINDZ	_unlockedr„   )crÐ   rV   rW   r   r    Zunsupported_formatr¡   rŠ   ÚversionÚrevisionÚversion_stringZsysidZsystem_nameZ
model_nameZchannel_countÚcommentZcreate_timeZlast_modified_timeZdewar_styleZfll_typeZtrigger_typeZadboard_typeZ	adc_rangeZadc_polarityZadc_allocatedZ
adc_storedZfull_versionrô   Z	fll_typesZuse_fll_typeZchan_dirZchan_offsetZ	chan_sizerÝ   Z	exg_gainsÚiZchannel_typeZ
channel_norã   r‹   ZsensitivityZchannel_offsetZchannel_gainZamp_dataZgain1Zgain2Zgain3Zamp_gainZhpfZlpfZbefZ
input_gainZoutput_gainZhpf_optionsZlpf_optionsZbef_optionsrE   Zdig_dirZcor_dirr,   r"   Ú_Zrrr!   rÄ   r    Zmeg_doneÚdoneZmarker_countÚmiZmri_typeZmeg_typeZmri_doneZthis_meg_doneZis_megZ
ad_to_voltZad_to_teslar…   Zis_exgr2   Zfiff_channelsZchannel_indexrž   rñ   rw   ÚthetaÚphiri   ÚyÚzZvec_zZvec_xZvec_yZvecsru   ry   Zch_type_labelZch_type_indexZeeg_namer#   r#   r(   rM   Ü  s4   þþ
ÿÿü
 ÿÿü
ý
	


ÿ



ÿ
ÿþÿ

 
ÿÿ ý







      ûrM   c                 C   s0   |d kr|nt j| }|  |¡ d¡d  d¡S )Nó    r   zutf-8)r   rý   r¯   ÚsplitÚdecode)r¡   Zch_typerÒ   r#   r#   r(   r÷   S  s    r÷   r@   rA   FrB   c                 C   s    t | |||||||||	|
|d�S )a[	  Reader function for Ricoh/KIT conversion to FIF.

    Parameters
    ----------
    input_fname : str
        Path to the sqd file.
    mrk : None | str | array_like, shape (5, 3) | list of str or array_like
        Marker points representing the location of the marker coils with
        respect to the MEG Sensors, or path to a marker file.
        If list, all of the markers will be averaged together.
    elp : None | str | array_like, shape (8, 3)
        Digitizer points representing the location of the fiducials and the
        marker coils with respect to the digitized head shape, or path to a
        file containing these points.
    hsp : None | str | array, shape (n_points, 3)
        Digitizer head shape points, or path to head shape file. If more than
        10,000 points are in the head shape, they are automatically decimated.
    stim : list of int | '<' | '>'
        Channel-value correspondence when converting KIT trigger channels to a
        Neuromag-style stim channel. For '<', the largest values are assigned
        to the first channel (default). For '>', the largest values are
        assigned to the last channel. Can also be specified as a list of
        trigger channel indexes.
    slope : '+' | '-'
        How to interpret values on KIT trigger channels when synthesizing a
        Neuromag-style stim channel. With '+', a positive slope (low-to-high)
        is interpreted as an event. With '-', a negative slope (high-to-low)
        is interpreted as an event.
    stimthresh : float
        The threshold level for accepting voltage changes in KIT trigger
        channels as a trigger event.
    %(preload)s
    stim_code : 'binary' | 'channel'
        How to decode trigger values from stim channels. 'binary' read stim
        channel events as binary code, 'channel' encodes channel number.
    allow_unknown_format : bool
        Force reading old data that is not officially supported. Alternatively,
        read and re-save the data with the KIT MEG Laboratory application.
    %(standardize_names)s
    %(verbose)s

    Returns
    -------
    raw : instance of RawKIT
        A Raw object containing KIT data.

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

    Notes
    -----
    If mrk, hsp or elp are array_like inputs, then the numbers in xyz
    coordinates should be in units of meters.
    ©rS   r    r!   r"   rT   rC   rD   rL   rU   rV   rW   r   )r?   r  r#   r#   r(   Úread_raw_kitX  s    <
    ür  c	           
      C   s   t | ||||||||d�	}	|	S )aÜ  Reader function for Ricoh/KIT epochs files.

    Parameters
    ----------
    input_fname : str
        Path to the sqd file.
    %(events_epochs)s
    %(event_id)s
    mrk : None | str | array_like, shape (5, 3) | list of str or array_like
        Marker points representing the location of the marker coils with
        respect to the MEG Sensors, or path to a marker file.
        If list, all of the markers will be averaged together.
    elp : None | str | array_like, shape (8, 3)
        Digitizer points representing the location of the fiducials and the
        marker coils with respect to the digitized head shape, or path to a
        file containing these points.
    hsp : None | str | array, shape (n_points, 3)
        Digitizer head shape points, or path to head shape file. If more than
        10,000 points are in the head shape, they are automatically decimated.
    allow_unknown_format : bool
        Force reading old data that is not officially supported. Alternatively,
        read and re-save the data with the KIT MEG Laboratory application.
    %(standardize_names)s
    %(verbose)s

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

    Notes
    -----
    .. versionadded:: 0.9.0
    )	rS   rÂ   rÃ   r    r!   r"   rV   rW   r   )r®   )
rS   rÂ   rÃ   r    r!   r"   rV   rW   r   Úepochsr#   r#   r(   Úread_epochs_kit›  s    &   ür  )N)NN)NN)NNNr@   rA   r   FrB   FFN)NNNNFFN):r>   Úcollectionsr   r   Úmathr   r   Úosr   r   rJ   Únumpyr/   rg   r
   Úutilsr   r   r   r   r   r   r   Z
transformsr   r   Úbaser   r   r  r   Ú	constantsr   Z	meas_infor   r   r   Zcoregr   r   Úeventr   rø   rÉ   rÊ   r4   r0   r5   r?   r}   r›   r®   rË   rÏ   rM   r÷   r  r  r#   r#   r#   r(   Ú<module>   sl   $ K !
  ÿ  x
            ýB       þ