
    0-Ph}                     <   d Z ddlmZ ddlZddlZddlmZmZmZmZm	Z	m
Z
mZmZmZmZ ddlZddlZddlmZmZmZ ddlmZmZ  ej        e          Z G d d	          Z G d
 d          Z G d de          Zdej        de	ee e	e!         f                  fdZ"dS )a   Read SPE files.

This plugin supports reading files saved in the Princeton Instruments
SPE file format.

Parameters
----------
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.
char_encoding : str
    Deprecated. Exists for backwards compatibility; use ``char_encoding`` of
    ``metadata`` instead.
sdt_meta : bool
    Deprecated. Exists for backwards compatibility; use ``sdt_control`` of
    ``metadata`` instead.

Methods
-------
.. note::
    Check the respective function for a list of supported kwargs and detailed
    documentation.

.. autosummary::
    :toctree:

    SpePlugin.read
    SpePlugin.iter
    SpePlugin.properties
    SpePlugin.metadata

    )datetimeN)
AnyCallableDictIteratorListMappingOptionalSequenceTupleUnion   )RequestIOModeInitializationError)PluginV3ImagePropertiesc                   &   e Zd ZdZdddddddZi d	d
dd ej        g d          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,i d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUddVdWdXdYddZZd[Z ej        ej	                   ej        ej
                   ej        ej                   ej        ej                   ej        ej                  d\Zg d]Zg d^Zd_gZd`S )a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   <h)*   <H)i  r   )i  z<Q)i  z<i)i  <f)datatypexdimydimxml_footer_offset	NumFramesfile_header_verNumROI)i  r   ROIsi  ))startxr   )endxr   )groupxr   )startyr   )endyr   )groupyr   
   xDimDet)   r   yDimDet)   r   	VChipXdim)   r   	VChipYdim)   r   controller_version)r   r   logic_output)r   r   amp_high_cap_low_noise)   r   mode)   r   exposure_sec)r)   r   date)   z<10Sdetector_temp)$   r   detector_type)(   r   st_diode),   r   
delay_time).   r   shutter_control)2   r   absorb_live)4   r   absorb_mode)6   r   can_do_virtual_chip)8   r   threshold_min_live):   r   threshold_min_val)<   r   threshold_max_live)@   r   threshold_max_val)B   r   
time_local)   <7Stime_utc)   rU   
adc_offset)   r   adc_rate)   r   adc_type)   r   adc_resolution)   r   adc_bit_adjust)   r   gain)   r   comments)   z<80S   	geometric)iX  r   )i  z<16S)i  z<436S)b   r   )d   r   )f   r   )h   r   )i  r   )i  r   )i  r   )i  r   )i  r   )
sw_versionspare_4
XPrePixelsXPostPixels
YPrePixelsYPostPixelsreadout_timer   typeclockspeed_usreadout_modewindow_sizer    i  )r      r      r7   )znew120 (Type II)zold120 (Type I)ST130ST121ST138zDC131 (PentaMax)zST133 (MicroMax/Roper)zST135 (GPIB)VTCCDzST116 (GPIB)zOMA3 (GPIB)OMA4)z
full framezframe transferkineticsrm   N)__name__
__module____qualname____doc__basicnpdtypemetadata
data_startfloat32int32int16uint16uint32dtypescontrollersreadout_modes	no_decode     S/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/imageio/plugins/spe.pyr   r   A   s&        $  (!' EB,B 	BH  	 	 
B$ 	9%B& 	:'B( 	Z)B* 	Z+B. 	i/B0 		1B2 	!)3B4 		5B6 	
7B8 	9B: 	;B< 	=B> 	J?B@ 	jABF 	:GB BH 	zIBJ 	zKBL 	zMBN 	jOBP 	ZQBR 	jSBT 	ZUBV 	lWBX 	LYBZ 	k[B\ 	K]B^ 	K_B` 	+aBb 	+cBd 	eBf 	$gBh 	[iB Bj $! "!"#(%$#'CB B BHH J 28BJ28BH28BH28BI28BI F  K" A@@M IIIr   r   c                        e Zd ZdZi 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ddZdd d!d"d#Z G d$ d%          Zi d& ed ed'd(          e          d) ed ed(d*          e          d+ ed ed,d          e	          d- ed ed.d/          e
d0          d1 ed edd2          e	          d3 ed ed4d5          e          d6 edd2d7           d8 edd9d:           d; ed ed<d9          e          d= edd>d?           d@ ed edAd<          e
dB          dC ed edd           fdD          dE ed ed5dA          e
d0          dF ed ed,d          e          dG ed eddH          e
dI          dJ ed edd          e          dK ed edHd<          e
d0           ed edd          e           ed ed<dL          e
d0           ed edd          e           ed ed/dM          e
d0           ed edLdN          e
d0           ed edNdO          e
d0           ed edOd.          e
d0          dPdQ ed edRdS          dT           idUZedVee	         dWeeef         fdX            ZedVee	         dYeeef         dWee	ef         f fdZ            Zed[e	d\e	dWeed]f         f fd^            Zedcd`edae	f fdb            Z xZS )dSDTControlSpeca&  Extract metadata written by the SDT-control software

    Some of it is encoded in the comment strings
    (see :py:meth:`parse_comments`). Also, date and time are encoded in a
    peculiar way (see :py:meth:`get_datetime`). Use :py:meth:`extract_metadata`
    to update the metadata dict.
    u   Jänrw   JanFebr   u   Märrx   MarAprr5   Mairf   MayJunr+   Jul   Augr7   Sep	   Oktr)   OctNov   Dez   DecstandardTOCCSLr~   	arbitrary)SEQUSETOKINESEARc            
           e Zd ZU dZeed<   	 eed<   	 eege	f         ed<   	 e
def         ed<   	 edfdededeege	f         dee         fdZdS )SDTControlSpec.CommentDescz>Describe how to extract a metadata entry from a comment stringnslicecvtNscalec                 >    || _         || _        || _        || _        d S N)r   r   r   r   )selfr   r   r   r   s        r   __init__z#SDTControlSpec.CommentDesc.__init__   s$     DFDJDHDJJJr   )r   r   r   r   int__annotations__r   r   strr   r   floatr
   r   r   r   r   CommentDescr      s         LL7>seSj!!!!<T5[!!!!1 ),%)
	 
	
	 
	 3%*%	
	
 E?
	 
	 
	 
	 
	 
	r   r   sdt_major_versionrR   D   sdt_minor_versionF   sdt_controller_namer   exposure_timerP   I   gư>
color_coder/   detection_channels   r1   background_subtractionc                     | dk    S )NBr   xs    r   <lambda>zSDTControlSpec.<lambda>  s
    18 r   	em_active    c                     | dk    S )NEr   r   s    r   r   zSDTControlSpec.<lambda>	  s
    a3h r   em_gain   modulation_active!   c                     | dk    S )NAr   r   s    r   r   zSDTControlSpec.<lambda>  s
    a3h r   
pixel_size   g?sequence_typec                     j         |          S r   )sequence_types)r   	__class__s    r   r   zSDTControlSpec.<lambda>  s    9+CA+F r   gridn_macrodelay_macro   gMbP?n_mini
delay_mini%   O   rB   7   )n_microdelay_micro	n_subpicsdelay_shutterdelay_prebleachbleach_timerecovery_timebleach_piezo_active"   #   c                     | dk    S )Nzr   r   s    r   r   zSDTControlSpec.<lambda>  s    1PS8 r   ))rf   r   )rf   rw   rd   returnc                     | d         dd         dk    rdS 	 t          | d         dd                   t          | d         dd                   fS # t          $ r Y dS w xY w)a-  Get the version of SDT-control metadata encoded in the comments

        Parameters
        ----------
        comments
            List of SPE file comments, typically ``metadata["comments"]``.

        Returns
        -------
        Major and minor version. ``-1, -1`` if detection failed.
        r5   r   L   COMVER)r   N   P   )r   
ValueError)rd   s    r   get_comment_versionz"SDTControlSpec.get_comment_version"  s}     A;r"u))6	x{2b5)**CBrE0B,C,CCC 	 	 	66	s   9A 
A A versionc           	         i }t          |d         dz             D ]}	 j        |d         |f         }n# t          $ r Y %w xY w|                                D ]}\  }}	 |                    | |j                 |j                           }|j        
||j        z  }|||<   H# t          $ r)}t          j
        d| d|            d||<   Y d}~vd}~ww xY w|j        vrTd                    t          d j                            }	t          j
        d|d          d	|d         d
d|	 d           | d         | d         z   }
|
                                |d<   |S )aC  Extract SDT-control metadata from comments

        Parameters
        ----------
        comments
            List of SPE file comments, typically ``metadata["comments"]``.
        version
            Major and minor version of SDT-control metadata format

        Returns
        -------
        Dict of metadata
        rw   r   Nz-Failed to decode SDT-control metadata field `z`: z, c                 *    | d          d| d         dS )Nr   .rw   02r   r   s    r   r   z/SDTControlSpec.parse_comments.<locals>.<lambda>^  s    111!111 r   z)Unsupported SDT-control metadata version r   r  z. Only versions z@ are supported. Some or all SDT-control metadata may be missing.r   comment)rangecomment_fieldsKeyErroritemsr   r   r   r   	Exceptionwarningswarnjoinmapstrip)rd   r   sdt_mdminorcmtnamespecvesupported_verr  r   s              r   parse_commentszSDTControlSpec.parse_comments6  s   " 71:>** 	( 	(E
.wqz5/@A   !iikk 
( 
(
d	($&!1$*!=>>Az-TZ#$F4LL  ( ( (MTTTQRTT   $(F4LLLLLL	(
( )222 II1193KLL M MCGAJ C CQRZ C C!.C C C  
 1++#MMOOys(   5
AAAB!!
C+CCr9   timeNc                    	 j         | dd                  }t          t          | dd                   |t          | dd                   t          |dd                   t          |dd                   t          |dd                             S # t          $ r)}t                              d| d           Y d	}~d	S d	}~ww xY w)
ai  Turn date and time saved by SDT-control into proper datetime object

        Parameters
        ----------
        date
            SPE file date, typically ``metadata["date"]``.
        time
            SPE file date, typically ``metadata["time_local"]``.

        Returns
        -------
        File's datetime if parsing was succsessful, else None.
        r   rf   r   r   r5   r+   z1Failed to decode date from SDT-control metadata: r   N)monthsr   r   r  loggerinfo)r9   r  monthr  r   s       r   get_datetimezSDTControlSpec.get_datetimei  s    	R$T!A#Y/ED1ID1ID1ID1ID1I    	R 	R 	RKKPAPPPQQQQQQQQQ	Rs   BB 
CCClatin1metachar_encodingc                                         | d                   }t          d |D                       rt                              d           dS                     | d         |          }|                     d           |                     |                               | d         | d                   }|r/|| d<   |                     d           |                     d           | d         }	 |                    |          | d	<   |                     d           n$# t          $ r t          j        d
           Y nw xY w|                     d           |                     d           dS )ar  Extract SDT-control metadata from SPE metadata

        SDT-control stores some metadata in comments and other fields.
        Extract them and remove unused entries.

        Parameters
        ----------
        meta
            SPE file metadata. Modified in place.
        char_encoding
            Character encoding used to decode strings in the metadata.
        rd   c              3   "   K   | ]
}|d k     V  dS )r   Nr   .0cs     r   	<genexpr>z2SDTControlSpec.extract_metadata.<locals>.<genexpr>  s&      %%q1u%%%%%%r   zSDT-control comments not found.Nr9   rS   r   rm   modulation_scriptzHFailed to decode SDT-control laser modulation script. Bad char_encoding?rV   r8   )r   anyr  debugr  popupdater  decodeUnicodeDecodeErrorr  r	  )r  r  comversdt_metadtsp4r   s         r   extract_metadatazSDTControlSpec.extract_metadata  s    ..tJ/?@@%%f%%%%% 	LL:;;;F++D,<fEEH ##DL$|2DEE 	#!DHHVHH\"""9o	(+

=(A(AD$%HHY! 	 	 	M8    	 	     s   4-D" "EE)r  )r   r   r   r   r  r   r   r   r   r   r   r  staticmethodr   r   r   r   r   r  r   r   r  r	   r1  __classcell__r   s   @r   r   r      s         	q 	q	
 	 	q 	q 	q 	q 	q 	q 	q 	q 	r 	r  	r!" 	r#$ 	r%F.  N       2
Qb"s!C!C
Qb"s!C!C
 ";;q%%1++s#C#C
 [[EE"bMM5&II	

 ++ar2<<
 !++ar2"D"D
 %kk!R9K9K&L&L
 Q,>,>??
 {{1eeBmmS99
  Q4F4F!G!G
 ++ar2sCC
 [[55B<<!F!F!F!F 
 KK55R==%@@
  {{1eeAqkk377!
" ;;q%%B--GG#
$ kk!UU1a[[#66%
& ++ar2vFF'
( #{1eeArllC88&;q%%B--GG$Qac::([EE"bMM5&II*{1eeBmmUFKK&;q%%B--GG([EE"bMM5&II5
 
 
: ";;q%%B--ASAS#T#T
;   ND hsm c3h    \& 03-0*/S/0	c3h0 0 0 0 0 \0d R3 Rc ReHdN.C R R R R R \R6 *! *!w *!s *! *! *! *! *! \*! *! *! *! *!r   r   c                   R    e Zd Z	 	 	 ddededee         dee         ddf
 fdZd	d
dede	j
        fdZdee	j
                 fdZ	 	 	 	 ddededededeeef         f
dZdededeeef         fdZdeeef         fdZddedefdZdeeef         dedeeef         fdZ xZS )	SpePluginTNrequestcheck_filesizer  r.  r   c           	         t                                          |           |j        j        t          j        k    rt          d          |t          j        dt                     || _
        |t          j        dt                     || _        | j                                        | _        	 |                     t           j        d          }|d         | _        t           j        |d                  | _        |d         |d	         f| _        |d
         | _        |r|d         dk    r	|d         }n>| j                            dt0          j                   | j                                        }|t           j        z
  }|| j        d         | j        d         z  | j        j        z  z  }|| j        k    rGt          j        d| j        j         d| j         d| d           t=          || j                  | _        | j                            t           j                   dS # t>          $ r t          d          w xY w)a  Instantiate a new SPE file plugin object

        Parameters
        ----------
        request : Request
            A request object representing the resource to be operated on.
        check_filesize : bool
            If True, compute the number of frames from the filesize, compare it
            to the frame count in the file header, and raise a warning if the
            counts don't match. (Certain software may create files with
        char_encoding : str
            Deprecated. Exists for backwards compatibility; use ``char_encoding`` of
            ``metadata`` instead.
        sdt_meta : bool
            Deprecated. Exists for backwards compatibility; use ``sdt_control`` of
            ``metadata`` instead.

        zcannot write SPE filesNz{Passing `char_encoding` to the constructor is deprecated. Use `char_encoding` parameter of the `metadata()` method instead.ztPassing `sdt_meta` to the constructor is deprecated. Use `sdt_control` parameter of the `metadata()` method instead.r  r    r   r   r   r   rx   r   r   rw   zThe file header of z claims there are z  frames, but there are actually z frames.z)SPE plugin cannot read the provided file.) superr   r6   io_moder   writer   r  r	  DeprecationWarning_char_encoding	_sdt_metar7  get_file_file_parse_headerr   r   _file_header_verr   _dtype_shape_lenseekosSEEK_ENDtellr   itemsizefilenameminr  )	r   r7  r8  r  r.  r  data_endliner   s	           r   r   zSpePlugin.__init__  sO   4 	!!!<6<//%&>???$M #	   ,M #	   "\**,,
	S %%dj(;;D$():$;D!+d:&67DK<f6DK[)DI 5
 )*a//#$78HHJOOAr{333#z00H$/1Q$+a.84;;OOO49$$MUdl.C U U9U UFJU U U   !$D$) 4 4DIJOODO,,,,, 	S 	S 	S%&QRRR	Ss   1E1H$ $H>.indexrQ  c                f   |t           u r@t          j        }| j        d         | j        d         z  | j        z  }| j        g| j        R }n|dk     rt          d| d          || j        k    rt          d| d| j         d          t          j        || j        d         z  | j        d         z  | j        j        z  z   }| j        d         | j        d         z  }| j        }| j        	                    |           t          j        | j        | j        |          }|                    |          S )a<  Read a frame or all frames from the file

        Parameters
        ----------
        index : int
            Select the index-th frame from the file. If index is `...`,
            select all frames and stack them along a new axis.

        Returns
        -------
        A Numpy array of pixel values.

        r   rw   zIndex `z` is smaller than 0.z5` exceeds the number of frames stored in this file (`z`).r   count)Ellipsisr   r   rE  rF  
IndexErrorrD  rK  rA  rG  r   fromfilereshape)r   rQ  read_offsetrT  	out_shapedatas         r   readzSpePlugin.read  s9    H/KKNT[^3di?E1T[11IIQYYBuBBBCCCdid%ddVZV_ddd  
 $+a.(4;q>9DK<PPQ  KNT[^3EI
$$${4:T[FFF||I&&&r   c                 D      fdt           j                  D             S )zrIterate over the frames in the file

        Yields
        ------
        A Numpy array of pixel values.
        c              3   D   K   | ]}                     |           V  dS )rP  N)r\  )r#  ir   s     r   r%  z!SpePlugin.iter.<locals>.<genexpr>1  s1      ==q			""======r   )r  rF  )r   s   `r   iterzSpePlugin.iter)  s)     >===E$),<,<====r   r  exclude_appliedsdt_controlc                     | j         dk     r2| j        | j        }| j        | j        }|                     ||          S |                                 S )ua  SPE specific metadata.

        Parameters
        ----------
        index : int
            Ignored as SPE files only store global metadata.
        exclude_applied : bool
            Ignored. Exists for API compatibility.
        char_encoding : str
            The encoding to use when parsing strings.
        sdt_control : bool
            If `True`, decode special metadata written by the
            SDT-control software if present.

        Returns
        -------
        metadata : dict
            Key-value pairs of metadata.

        Notes
        -----
        SPE v3 stores metadata as XML, whereas SPE v2 uses a binary format.

        .. rubric:: Supported SPE v2 Metadata fields

        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
        sdt_major_version : int
            (only for files created by SDT-control)
            Major version of SDT-control software
        sdt_minor_version : int
            (only for files created by SDT-control)
            Minor version of SDT-control software
        sdt_controller_name : str
            (only for files created by SDT-control)
            Controller name
        exposure_time : float
            (only for files created by SDT-control)
            Exposure time in seconds
        color_code : str
            (only for files created by SDT-control)
            Color channels used
        detection_channels : int
            (only for files created by SDT-control)
            Number of channels
        background_subtraction : bool
            (only for files created by SDT-control)
            Whether background subtraction war turned on
        em_active : bool
            (only for files created by SDT-control)
            Whether EM was turned on
        em_gain : int
            (only for files created by SDT-control)
            EM gain
        modulation_active : bool
            (only for files created by SDT-control)
            Whether laser modulation (“attenuate”) was turned on
        pixel_size : float
            (only for files created by SDT-control)
            Camera pixel size
        sequence_type : str
            (only for files created by SDT-control)
            Type of sequnce (standard, TOCCSL, arbitrary, …)
        grid : float
            (only for files created by SDT-control)
            Sequence time unit (“grid size”) in seconds
        n_macro : int
            (only for files created by SDT-control)
            Number of macro loops
        delay_macro : float
            (only for files created by SDT-control)
            Time between macro loops in seconds
        n_mini : int
            (only for files created by SDT-control)
            Number of mini loops
        delay_mini : float
            (only for files created by SDT-control)
            Time between mini loops in seconds
        n_micro : int (only for files created by SDT-control)
            Number of micro loops
        delay_micro : float (only for files created by SDT-control)
            Time between micro loops in seconds
        n_subpics : int
            (only for files created by SDT-control)
            Number of sub-pictures
        delay_shutter : float
            (only for files created by SDT-control)
            Camera shutter delay in seconds
        delay_prebleach : float
            (only for files created by SDT-control)
            Pre-bleach delay in seconds
        bleach_time : float
            (only for files created by SDT-control)
            Bleaching time in seconds
        recovery_time : float
            (only for files created by SDT-control)
            Recovery time in seconds
        comment : str
            (only for files created by SDT-control)
            User-entered comment. This replaces the "comments" field.
        datetime : datetime.datetime
            (only for files created by SDT-control)
            Combines the "date" and "time_local" keys. The latter two plus
            "time_utc" are removed.
        modulation_script : str
            (only for files created by SDT-control)
            Laser modulation script. Replaces the "spare_4" key.
        bleach_piezo_active : bool
            (only for files created by SDT-control)
            Whether piezo for bleaching was enabled
        rx   )rC  r>  r?  _metadata_pre_v3_metadata_post_v3)r   rQ  ra  r  rb  s        r   r   zSpePlugin.metadata3  s[    X  1$$". $ 3~)"n((DDD%%'''r   c                   	 |                      t          j        |          		                    dd          }|dk     rdn|}t	          	d         d|                   	d<   	fddD             	d<   	fdd	D             	d
<   	fddD             	d<   	fddD             	d<   d 	d         D             	d<   g }	                    dd          }|dz  r|                    d           |dz  r|                    d           |dz  r|                    d           |	d<   	d         }d|cxk    rt          t          j                  k    rn nt          j        |dz
           	d<   nd	d<   	d         }d|cxk    rt          t          j                  k    rn nt          j        |dz
           	d<   nd	d<   dD ]}t          	|                   	|<   |rt                              	|           	S )aZ  Extract metadata from SPE v2 files

        Parameters
        ----------
        char_encoding
            String character encoding
        sdt_control
            If `True`, try to decode special metadata written by the
            SDT-control software.

        Returns
        -------
        dict mapping metadata names to values.

        r!   Nrw   r"   c                 <    g | ]}                     |d           S r   r)  r#  kms     r   
<listcomp>z.SpePlugin._metadata_pre_v3.<locals>.<listcomp>  s%    IIIQ!%%4..IIIr   )r*   r,   	chip_sizec                 <    g | ]}                     |d           S r   rh  ri  s     r   rl  z.SpePlugin._metadata_pre_v3.<locals>.<listcomp>   s%    RRR!quuQ~~RRRr   )r.   r0   virt_chip_sizec                 <    g | ]}                     |d           S r   rh  ri  s     r   rl  z.SpePlugin._metadata_pre_v3.<locals>.<listcomp>!  s%    PPPa155D>>PPPr   )rn   rp   
pre_pixelsc                 <    g | ]}                     |d           S r   rh  ri  s     r   rl  z.SpePlugin._metadata_pre_v3.<locals>.<listcomp>"  s%    SSSqAEE!TNNSSSr   )ro   rq   post_pixelsc                 ,    g | ]}t          |          S r   )r   r"  s     r   rl  z.SpePlugin._metadata_pre_v3.<locals>.<listcomp>%  s    777AQ777r   rd   rg   r   rotater   reverser5   fliprs   ru   )rE   rI   rK   rO   )rB  r   r   r)  roi_array_to_dictappendlenr   r   boolr   r1  )
r   r  rb  nrgftrrj  rk  s
            @r   rd  zSpePlugin._metadata_pre_v3  st   " t}m<<UU8T""q&&QQb%ain55&	 JIII2HIII+RRRR7QRRR
PPPP3OPPP,SSSS4RSSS- 87:777* EE+q!!q5 	HHXq5 	 HHYq5 	HHV+ fI****S)*******(Q/AfIIAfIn,,,,S+,,,,,,, $ 21q5 9An $An
 	 	A !::AaDD  	>++A}===r   c                     |                      t          j        d          }| j                            |d                    | j                                        }d|iS )zExtract XML metadata from SPE v3 files

        Returns
        -------
        dict with key `"__xml"`, whose value is the XML metadata
        r  r   __xml)rB  r   r   rA  rG  r\  )r   r  xmls      r   re  zSpePlugin._metadata_post_v3M  sP     !!$*h77
01222joo~r   c                     |t           u r+t          | j        g| j        R | j        | j        d          S t          | j        | j        d          S )a  Standardized ndimage metadata.

        Parameters
        ----------
        index : int
            If the index is an integer, select the index-th frame and return
            its properties. If index is an Ellipsis (...), return the
            properties of all frames in the file stacked along a new batch
            dimension.

        Returns
        -------
        properties : ImageProperties
            A dataclass filled with standardized image metadata.
        T)shaper   n_imagesis_batchF)r  r   r  )rU  r   rF  rE  rD  )r   rQ  s     r   
propertieszSpePlugin.propertiesZ  s`    " H"y/4;//k	    T[eTTTTr   r  c                 P   i }t          j        fd          }|                                D ]\  }}| j                            |d                    t          |          dk     rdn|d         }t          j        | j        |d         |          }|j        j        dk    rC|t          j
        vr5	  ||          }n(# t          $ r t          j        d| d	           Y nw xY w	 |                                }n$# t          $ r t          j        |          }Y nw xY w|||<   |S )
a  Get information from SPE file header

        Parameters
        ----------
        spec
            Maps header entry name to its location, data type description and
            optionally number of entries. See :py:attr:`Spec.basic` and
            :py:attr:`Spec.metadata`.
        char_encoding
            String character encoding

        Returns
        -------
        Dict mapping header entry name to its value
        c                 .    |                                S r   )r+  )r   r  s    r   r   z)SpePlugin._parse_header.<locals>.<lambda>  s    (?(? r   r   rx   rw   r   rS  SzFailed to decode "z3" metadata string. Check `char_encoding` parameter.)r   	vectorizer  rA  rG  rz  rW  r   kindr   r   r  r  r	  itemr   squeeze)	r   r  r  retr+  r  spcntr  s	     `      r   rB  zSpePlugin._parse_headert  sa   & ????@@

 	 	HD"JOOBqE"""2ww{{!!1CDJbe3???Aw|s""t4>'A'Aq		AA    MCT C C C    " FFHH " " "JqMM"CII
s$   2B>>"C#"C#'C<<DD)TNN).Tr  T).)r   r   r   r   r{  r
   r   r   r   r   ndarrayr\  r   r`  r   r   r   rd  re  r   r  r	   r   rB  r3  r4  s   @r   r6  r6    s&         $'+#'NS NSNS NS  }	NS
 4.NS 
NS NS NS NS NS NS` $' #' #' #'S #'2: #' #' #' #'J>hrz* > > > >  $% R( R(R( R( 	R(
 R( 
c3hR( R( R( R(hDc D DcSVh D D D DL4S>    U U Uo U U U U4,CJ',8;,	c3h, , , , , , , ,r   r6  ar   c                    g }| g d         } | D ]x\  }}}}}}t          |          t          |          gt          |          t          |          gt          |          t          |          gd}|                    |           y|S )a\  Convert the `ROIs` structured arrays to :py:class:`dict`

    Parameters
    ----------
    a
        Structured array containing ROI data

    Returns
    -------
    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(   )top_leftbottom_rightbin)r   ry  )	r  	dict_listsxsyexeygxgyroi_dicts	            r   rx  rx    s     I	
B
B
BCA"# # #BBBR#b''* WWc"gg.GGSWW%
 

 	""""r   )#r   r   loggingrH  typingr   r   r   r   r   r	   r
   r   r   r   r  numpyr   core.requestr   r   r   core.v3_plugin_apir   r   	getLoggerr   r  r   r   r6  r  r   r   rx  r   r   r   <module>r     s  ! !F        				                             ? ? ? ? ? ? ? ? ? ? : : : : : : : : 
	8	$	$~ ~ ~ ~ ~ ~ ~ ~Bn! n! n! n! n! n! n! n!bm m m m m m m m` T#tCy.-A(B      r   