B
    •%Z\h9  ã               @   s˜   d Z ddlmZmZmZ ddlZddlZddlZddl	m
Z
 ddlmZ e e¡ZG dd„ dƒZG d	d
„ d
eƒZdd„ ZeddddƒZe
jedd dS )z SPE file reader
é    )Úabsolute_importÚprint_functionÚdivisionNé   )Úformats)ÚFormatc            /   @   sô   e Zd ZdZdddddœZdde d	d
ddddg¡df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-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<œ.Zd=Ze d>¡e d?¡e d@¡e dA¡e dB¡gZ	dCdDdEdFdGdHdIdJdKdLdMdNgZ
dOdPdQgZdRgZdSS )TÚSpecaW  SPE file specification data

    Tuples of (offset, datatype, count), where offset is the offset in the SPE
    file and datatype is the datatype as used in `numpy.fromfile`()

    `data_start` is the offset of actual image data.

    `dtypes` translates SPE datatypes (0...4) to numpy ones, e. g. dtypes[0]
    is dtype("<f") (which is np.float32).

    `controllers` maps the `type` metadata to a human readable name

    `readout_modes` maps the `readoutMode` metadata to something human readable
    although this may not be accurate since there is next to no documentation
    to be found.
    )él   z<h)é*   z<H)i  z<H)i¦  z<i)ÚdatatypeÚxdimÚydimÚ	NumFrames)iæ  z<hiè  )Ústartxz<H)Úendxz<H)Úgroupxz<H)Ústartyz<H)Úendyz<H)Úgroupyz<Hé
   )é   z<H)é   z<H)é   z<h)é   z<h)r   z<h)r   z<h)é   z<H)é   z<h)r   z<f)é   z<10S)é$   z<f)é(   z<h)é,   z<h)é.   z<f)é2   z<H)é4   z<h)é6   z<H)é8   z<h)é:   z<h)é<   z<f)é@   z<h)éB   z<f)é¬   z<7S)é³   z<7S)é¼   z<H)é¾   z<H)éÀ   z<H)éÂ   z<H)éÄ   z<H)éÆ   z<H)éÈ   z<80Sé   )iX  z<H)i°  z<16S)iæ  z<436S)éb   z<h)éd   z<h)éf   z<h)éh   z<h)i   z<f)iÀ  z<h)i”  z<f)iÈ  z<H)iÊ  z<H)iÈ  z<f).ÚNumROIÚROIsÚxDimDetÚyDimDetÚ	VChipXdimÚ	VChipYdimZcontroller_versionZlogic_outputZamp_high_cap_low_noiseÚmodeZexposure_secZdateZdetector_tempZdetector_typeZst_diodeZ
delay_timeZshutter_controlÚabsorb_liveZabsorb_modeÚcan_do_virtual_chipÚthreshold_min_liveZthreshold_min_valÚthreshold_max_liveZthreshold_max_valZ
time_localZtime_utcZ
adc_offsetZadc_rateZadc_typeZadc_resolutionZadc_bit_adjustZgainÚcommentsÚ	geometricZ
sw_versionÚspare_4Ú
XPrePixelsÚXPostPixelsÚ
YPrePixelsÚYPostPixelsZreadout_timeÚtypeZclockspeed_usÚreadout_modeZwindow_sizeZfile_header_veri  z<fz<iz<hz<Hz<Iznew120 (Type II)zold120 (Type I)ZST130ZST121ZST138zDC131 (PentaMax)zST133 (MicroMax/Roper)zST135 (GPIB)ZVTCCDzST116 (GPIB)zOMA3 (GPIB)ZOMA4z
full framezframe transferZkineticsrD   N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚbasicÚnpÚdtypeÚmetadataÚ
data_startÚdtypesÚcontrollersÚreadout_modesÚ	no_decode© rX   rX   ú2lib/python3.7/site-packages/imageio/plugins/spe.pyr      sž   
r   c               @   s2   e Zd ZdZdd„ Zdd„ ZG dd„ dejƒZdS )	Ú	SpeFormata   Some CCD camera software produces images in the Princeton Instruments
    SPE file format. This plugin supports reading such files.

    Parameters for reading
    ----------------------
    char_encoding : str
        Character encoding used to decode strings in the metadata. Defaults
        to "latin1".
    check_filesize : bool
        The number of frames in the file is stored in the file header. However,
        this number may be wrong for certain software. If this is `True`
        (default), derive the number of frames also from the file size and
        raise a warning if the two values do not match.

    Metadata for reading
    --------------------
    ROIs : list of dict
        Regions of interest used for recording images. Each dict has the
        "top_left" key containing x and y coordinates of the top left corner,
        the "bottom_right" key with x and y coordinates of the bottom right
        corner, and the "bin" key with number of binned pixels in x and y
        directions.
    comments : list of str
        The SPE format allows for 5 comment strings of 80 characters each.
    controller_version : int
        Hardware version
    logic_output : int
        Definition of output BNC
    amp_hi_cap_low_noise : int
        Amp switching mode
    mode : int
        Timing mode
    exp_sec : float
        Alternative exposure in seconds
    date : str
        Date string
    detector_temp : float
        Detector temperature
    detector_type : int
        CCD / diode array type
    st_diode : int
        Trigger diode
    delay_time : float
        Used with async mode
    shutter_control : int
        Normal, disabled open, or disabled closed
    absorb_live : bool
        on / off
    absorb_mode : int
        Reference strip or file
    can_do_virtual_chip : bool
        True or False whether chip can do virtual chip
    threshold_min_live : bool
        on / off
    threshold_min_val : float
        Threshold minimum value
    threshold_max_live : bool
        on / off
    threshold_max_val : float
        Threshold maximum value
    time_local : str
        Experiment local time
    time_utc : str
        Experiment UTC time
    adc_offset : int
        ADC offset
    adc_rate : int
        ADC rate
    adc_type : int
        ADC type
    adc_resolution : int
        ADC resolution
    adc_bit_adjust : int
        ADC bit adjust
    gain : int
        gain
    sw_version : str
        Version of software which created this file
    spare_4 : bytes
        Reserved space
    readout_time : float
        Experiment readout time
    type : str
        Controller type
    clockspeed_us : float
        Vertical clock speed in microseconds
    readout_mode : {"full frame", "frame transfer", "kinetics", ""}
        Readout mode. Empty string means that this was not set by the
        Software.
    window_size : int
        Window size for Kinetics mode
    file_header_ver : float
        File header version
    chip_size : [int, int]
        x and y dimensions of the camera chip
    virt_chip_size : [int, int]
        Virtual chip x and y dimensions
    pre_pixels : [int, int]
        Pre pixels in x and y dimensions
    post_pixels : [int, int],
        Post pixels in x and y dimensions
    geometric : list of {"rotate", "reverse", "flip"}
        Geometric operations
    c             C   s    |j d | jd ko|j| jkS )Né   ú?)r=   ZmodesÚ	extensionÚ
extensions)ÚselfÚrequestrX   rX   rY   Ú	_can_readý   s    zSpeFormat._can_readc             C   s   dS )NFrX   )r_   r`   rX   rX   rY   Ú
_can_write  s    zSpeFormat._can_writec               @   s>   e Zd Zddd„Zdd„ Zdd„ Zd	d
„ Zdd„ Zdd„ ZdS )zSpeFormat.ReaderÚlatin1Tc             C   s¾   | j  ¡ | _|| _|  tj¡}tj|d  | _|d |d f| _	|d | _
|r´tj | j  ¡ ¡}|tj }|| j	d | j	d  | jj  }|| j
kr´t d| j j ¡ t|| j
ƒ| _
d | _d S )Nr   r   r   r   r   r[   zMNumber of frames according to file header does not match the size of file %s.)r`   Zget_fileÚ_fileÚ_char_encodingÚ_parse_headerr   rO   rT   Ú_dtypeÚ_shapeÚ_lenÚosÚpathÚgetsizeZget_local_filenamerS   ÚitemsizeÚloggerÚwarningÚfilenameÚminÚ_meta)r_   Zchar_encodingZcheck_filesizeÚinfoZfszÚlrX   rX   rY   Ú_open  s     

 
zSpeFormat.Reader._openc             C   s  | j d kr|  tj¡| _ | j  dd ¡}|dk r4dn|}t| j d d |… ƒ| j d< | j  dd ¡| j  dd ¡g| j d< | j  dd ¡| j  dd ¡g| j d	< | j  d
d ¡| j  dd ¡g| j d< | j  dd ¡| j  dd ¡g| j d< dd„ | j d D ƒ| j d< g }| j  dd¡}|d@ r| d¡ |d@ r0| d¡ |d@ rD| d¡ || j d< | j d }d|  krvttjƒkrn ntj|d  | j d< n
d| j d< | j d }d|  krÂttj	ƒkrÜn ntj	|d  | j d< n
d| j d< x"dD ]}t
| j | ƒ| j |< qìW | j| j d< | j S )Nr7   r[   r8   r9   r:   Z	chip_sizer;   r<   Zvirt_chip_sizerE   rG   Z
pre_pixelsrF   rH   Zpost_pixelsc             S   s   g | ]}t |ƒ‘qS rX   )Ústr)Ú.0ÚcrX   rX   rY   ú
<listcomp>9  s    z3SpeFormat.Reader._get_meta_data.<locals>.<listcomp>rB   rC   r   Úrotater   Úreverser   ZfliprI   Ú rJ   )r>   r?   r@   rA   Zframe_shape)rr   rf   r   rR   ÚpopÚroi_array_to_dictÚappendÚlenrU   rV   Úboolrh   )r_   ÚindexZnrÚgÚfÚtÚmÚkrX   rX   rY   Ú_get_meta_data  sH    







"

"
zSpeFormat.Reader._get_meta_datac             C   s   d S )NrX   )r_   rX   rX   rY   Ú_close_  s    zSpeFormat.Reader._closec          	      sì   i }t  ‡ fdd„¡}xÐ| ¡ D ]Ä\}}ˆ j |d ¡ t|ƒdk rHdn|d }t jˆ j|d |d}|jjdkr®|t	j
kr®y||ƒ}W n$ tk
r¬   t d	 |¡¡ Y nX yt  |¡}W n tk
rÚ   t  |¡}Y nX |||< q W |S )
Nc                s   |   ˆ j¡S )N)Údecodere   )Úx)r_   rX   rY   Ú<lambda>f  s    z0SpeFormat.Reader._parse_header.<locals>.<lambda>r   é   r[   r   )rQ   ÚcountÚSzGFailed to decode "{}" metadata string. Check `char_encoding` parameter.)rP   Z	vectorizeÚitemsrd   Úseekr€   ÚfromfilerQ   Zkindr   rW   Ú	Exceptionrn   ro   ÚformatZasscalarÚ
ValueErrorZsqueeze)r_   ÚspecZretrŠ   ÚnameZspZcntÚvrX   )r_   rY   rf   c  s&    zSpeFormat.Reader._parse_headerc             C   s   | j jd dkrdS | jS d S )Nr[   ÚvV)r`   r=   ri   )r_   rX   rX   rY   Ú_get_length€  s    zSpeFormat.Reader._get_lengthc             C   s
  |dk rt d| ƒ‚|| jkr0t d|| jf ƒ‚| jjd dkrž|dkrPt dƒ‚| j tj¡ tj	| j| j
| jd | jd  | j d}| | jf| j ¡}n^| j tj|| jd  | jd  | j
j  ¡ tj	| j| j
| jd | jd  d}| | j¡}||  |¡fS )Nr   zImage index %i < 0zImage index %i > %ir[   r™   z"Index has to be 0 in v and V modes)rQ   rŽ   )Ú
IndexErrorri   r`   r=   rd   r‘   r   rS   rP   r’   rg   rh   Zreshaperm   rˆ   )r_   r‚   ÚdatarX   rX   rY   Ú	_get_data†  s(    
$ zSpeFormat.Reader._get_dataN)rc   T)	rK   rL   rM   ru   rˆ   r‰   rf   rš   r   rX   rX   rX   rY   ÚReader  s   
Arž   N)rK   rL   rM   rN   ra   rb   r   rž   rX   rX   rX   rY   rZ   “   s   hrZ   c       	      C   sp   g }| ddddddg } xR| D ]J\}}}}}}t |ƒt |ƒgt |ƒt |ƒgt |ƒt |ƒgdœ}| |¡ qW |S )a‰  Convert the `ROIs` structured arrays to :py:class:`dict`

    Parameters
    ----------
    a : numpy.ndarray
        Structured array containing ROI data

    Returns
    -------
    list of dict
        One dict per ROI. Keys are "top_left", "bottom_right", and "bin",
        values are tuples whose first element is the x axis value and the
        second element is the y axis value.
    r   r   r   r   r   r   )Ztop_leftZbottom_rightÚbin)Úintr   )	Úart   ZsxZsyÚexZeyZgxZgyÚdrX   rX   rY   r~   ¢  s    r~   ZspezSPE file formatz.speZiIvVT)Z	overwrite)rN   Z
__future__r   r   r   rj   ZloggingZnumpyrP   r|   r   Zcorer   Z	getLoggerrK   rn   r   rZ   r~   ZfmtZ
add_formatrX   rX   rX   rY   Ú<module>   s   
~  