
    9i}                     &   S r SSKJr  SSKrSSKrSSKJrJrJrJrJ	r	J
r
JrJrJrJr  SSKrSSKrSSKJrJrJr  SSKJrJr  \R2                  " \5      r " S S	5      r " S
 S5      r " S S\5      rS\R>                  S\	\\ \	\!   4      4S jr"g)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                   v   \ rS rSrSrSSSSSSS	.r0 S
S_SS\R                  " / SQ5      S4_SS_SS_SS_SS_SS_SS_SS_SS_S S!_S"S#_S$S%_S&S'_S(S)_S*S+_S,S-_0 S.S/_S0S1_S2S3_S4S5_S6S7_S8S9_S:S;_S<S=_S>S?_S@SA_SBSC_SDSE_SFSG_SHSI_SJSK_SLSM_SNSO_ESPSQSRSSSTSUSVSSWSXSYSZSS[.ErS\r	\R                  " \R                  5      \R                  " \R                  5      \R                  " \R                  5      \R                  " \R                  5      \R                  " \R                  5      S].r/ S^Qr/ S_QrS`/rSargb)cSpecA   a/  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)   rV   
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      r8   )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kineticsrn    N)__name__
__module____qualname____firstlineno____doc__basicnpdtypemetadata
data_startfloat32int32int16uint16uint32dtypescontrollersreadout_modes	no_decode__static_attributes__r       S/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/imageio/plugins/spe.pyr   r   A   s   $  (!'EB,B 	HH	 
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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j $! "!"#(%$#'CBHH J 88BJJ88BHH88BHH88BII88BIIFK" AM Ir   r   c                     ^  \ rS rSrSr0 SS_SS_SS_SS	_S
S	_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_rS S!S"S#S$.r " S% S&5      r0 S'\" S\" S(S)5      \	5      _S*\" S\" S)S+5      \	5      _S,\" S\" S-S5      \
5      _S.\" S\" S/S05      \S15      _S2\" S\" SS35      \
5      _S4\" S\" S5S65      \	5      _S7\" SS3S8 5      _S9\" SS:S; 5      _S<\" S\" S=S:5      \	5      _S>\" SS?S@ 5      _SA\" S\" SBS=5      \SC5      _SD\" S\" SS5      U 4SE j5      _SF\" S\" S6SB5      \S15      _SG\" S\" S-S5      \	5      _SH\" S\" SSI5      \SJ5      _SK\" S\" SS5      \	5      _SL\" S\" SIS=5      \S15      _\" S\" SS5      \	5      \" S\" S=SM5      \S15      \" S\" SS5      \	5      \" S\" S0SN5      \S15      \" S\" SMSO5      \S15      \" S\" SOSP5      \S15      \" S\" SPS/5      \S15      SQ.ESR\" S\" SSST5      SU 5      0SV.r\SW\\
   SX\\	\	4   4SY j5       r\SW\\
   SZ\\	\	4   SX\\
\4   4U 4S[ jj5       r\S\\
S]\
SX\\S^4   4U 4S_ jj5       r\SdS`\Sa\
4U 4Sb jjj5       rScrU =r$ )eSDTControlSpecr`   a  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änrx   JanFebr   u   Märry   MarAprr6   Mairg   MayJunr,   Jul   Augr8   Sep	   Oktr*   OctNov   Dez   DecstandardTOCCSLr   	arbitrary)SEQUSETOKINESEARc            
           \ rS rSr% Sr\\S'    \\S'    \\	/\
4   \S'    \S\4   \S'    \	S4S\S\S\\	/\
4   S\\   4S jjrS	rg)
SDTControlSpec.CommentDesc   z>Describe how to extract a metadata entry from a comment stringnslicecvtNscalec                 4    Xl         X l        X0l        X@l        g N)r   r   r   r   )selfr   r   r   r   s        r   __init__#SDTControlSpec.CommentDesc.__init__   s     FJHJr   )r   r   r   r   )r   r   r   r   r   int__annotations__r   r   strr   r   floatr
   r   r   r   r   r   CommentDescr      s    L7>seSj!!<T5[!!1 ),%)
	
	 
	 3%*%	
	
 E?
	 
	r   r   sdt_major_versionrS   D   sdt_minor_versionF   sdt_controller_namer   exposure_timerQ   I   gư>
color_coder0   detection_channels   r2   background_subtractionc                     U S:H  $ )NBr   xs    r   <lambda>SDTControlSpec.<lambda>  s    18r   	em_active    c                     U S:H  $ )NEr   r   s    r   r   r   	  s    a3hr   em_gain   modulation_active!   c                     U S:H  $ )NAr   r   s    r   r   r     s    a3hr   
pixel_size   g?sequence_typec                 "   > TR                   U    $ r   )sequence_types)r   	__class__s    r   r   r     s    9+C+CA+Fr   gridn_macrodelay_macro   gMbP?n_mini
delay_mini%   O   rC   7   )n_microdelay_micro	n_subpicsdelay_shutterdelay_prebleachbleach_timerecovery_timebleach_piezo_active"   #   c                     U S:H  $ )Nzr   r   s    r   r   r     s	    1PS8r   ))rg   r   )rg   rx   re   returnc                     U S   SS S:w  a  g [        U S   SS 5      [        U S   SS 5      4$ ! [         a     gf = f)zGet 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.
r6   r   L   COMVER)r   N   P   )r   
ValueError)re   s    r   get_comment_version"SDTControlSpec.get_comment_version"  s\     A;r")	x{2b)*CBr0B,CCC 		s   !1 
>>versionc           	        > 0 n[        US   S-   5       H{  n TR                  US   U4   nUR                  5        HO  u  pV UR	                  XR
                     UR                     5      nUR                  b  XvR                  -  nXrU'   MQ     M}     UTR                  ;  aM  SR                  [        S TR                  5      5      n	[        R                  " SUS    S	US   S
 SU	 S35        U S   U S   -   n
U
R                  5       US'   U$ ! [         a     GM
  f = f! [         a,  n[        R                  " SU SU 35        SX%'    SnAGM  SnAff = f)zExtract 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
rx   r   Nz-Failed to decode SDT-control metadata field `z`: z, c                     U S    SU S   S 3$ )Nr   .rx   02r   r   s    r   r   /SDTControlSpec.parse_comments.<locals>.<lambda>^  s    1a!Ry1r   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)re   r  sdt_mdminorcmtnamespecvesupported_verr
  r   s              r   parse_commentsSDTControlSpec.parse_comments6  sv   " 71:>*E
..wqz5/@A "iik
	(&&!1$**!=>Azz-ZZ#$4L * +( )222 II193K3KLM MM;GAJ<qQRTV X!!. 0CC
 1++#MMOy1   ! (MMGvSQRPST $(FLL	(s*   DA	D#
D D #
E- EEr:   timeNc                 "  >  TR                   U SS    n[        [        U SS 5      U[        U SS 5      [        USS 5      [        USS 5      [        USS 5      5      $ ! [         a#  n[        R                  SU S35         S	nAg	S	nAff = f)
a  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   rg   r   r   r6   r,   z1Failed to decode date from SDT-control metadata: r  N)monthsr   r   r  loggerinfo)r:   r  monthr  r   s       r   get_datetimeSDTControlSpec.get_datetimei  s    	R$$T!AY/ED1ID1ID1ID1ID1I   	RKKKA3aPQQ	Rs   AA! !
B+B		Bmetachar_encodingc                 f  > TR                  U S   5      n[        S U 5       5      (       a  [        R                  S5        gTR	                  U S   U5      nU R                  S5        U R                  U5        TR                  U S   U S   5      nU(       a&  X@S'   U R                  S5        U R                  S5        U S   n UR                  U5      U S	'   U R                  S5        U R                  S5        U R                  S5        g! [         a    [        R                  " S
5         NEf = f)a*  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.
re   c              3   *   #    U  H	  oS :  v   M     g7f)r   Nr   ).0cs     r   	<genexpr>2SDTControlSpec.extract_metadata.<locals>.<genexpr>  s     %f1ufs   zSDT-control comments not found.Nr:   rT   r   rn   modulation_scriptzHFailed to decode SDT-control laser modulation script. Bad char_encoding?rW   r9   )r  anyr"  debugr  popupdater%  decodeUnicodeDecodeErrorr  r  )r'  r(  comversdt_metadtsp4r   s         r   extract_metadataSDTControlSpec.extract_metadata  s    ..tJ/?@%f%%%LL:;++D,<fEH ##DL$|2DE!HHVHH\"9o	(+

=(AD$%HHY 	  " 	MM8	s   %D  D0/D0r   )latin1)r   r   r   r   r   r!  r   r   r   r   r   r   r  staticmethodr   r   r  r   r   r  r   r   r%  r	   r:  r   __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
Qb"s!C
 ";q%1+s#C
 [E"bM5&I	

 +ar2<
 !+ar2"D
 %k!R9K&L
 Q,>?
 {1eBmS9
  Q4F!G
 +ar2sC
 [5B<!F
 K5R=%@
  {1eAqk37!
" ;q%B-G#
$ k!U1a[#6%
& +ar2vF'
( #1eArlC8&q%B-G$Qac:(E"bM5&I*1eBmUFK&q%B-G(E"bM5&I5
: ";q%B-AS#T
; ND hsm c3h  & 03-0*/S/0	c3h0 0d R3 Rc ReHdN.C R R6 *!w *!s *! *!r   r   c                   X  ^  \ rS rSr   SS\S\S\\   S\\   SS4
U 4S jjjrS	S
.S\	S\
R                  4S jjrS\\
R                     4S jr    SS\	S\S\S\S\\\4   4
S jjrS\S\S\\\4   4S jrS\\\4   4S jrSS\	S\4S jjrS\\\4   S\S\\\4   4S jrSrU =r$ )	SpePlugini  Nrequestcheck_filesizer(  r7  r   c           	        > [         TU ]  U5        UR                  R                  [        R
                  :X  a  [        S5      eUb  [        R                  " S[        5        X0l
        Ub  [        R                  " S[        5        X@l        U R                  R                  5       U l         U R                  [         R"                  S5      nUS   U l        [         R&                  US      U l        US   US	   4U l        US
   U l        U(       Ga  US   S:  a  US   nODU R                  R/                  S[0        R2                  5        U R                  R5                  5       nU[         R6                  -
  nXpR*                  S   U R*                  S   -  U R(                  R8                  -  -  nXpR,                  :w  aX  [        R                  " SU R                  R:                   SU R,                   SU S35        [=        XpR,                  5      U l        U R                  R/                  [         R6                  5        g! [>         a    [        S5      ef = f)ai  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    ry   r   r   rx   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   r7   io_moder   writer   r  r  DeprecationWarning_char_encoding	_sdt_metarB  get_file_file_parse_headerr   r   _file_header_verr   _dtype_shape_lenseekosSEEK_ENDtellr   itemsizefilenameminr  )	r   rB  rC  r(  r7  r#  data_endliner   s	           r   r   SpePlugin.__init__  s   4 	!<<6<</%&>??$MM #	 ,MM #	 "\\**,
	S %%djj(;D$():$;D!++d:&67DK<f6DK[)DI
 )*a/#$78HJJOOAr{{3#zz0H$//1Q$++a.84;;;O;OOO99$MM-dll.C.C-DDV99+%EdV8U !$D)) 4DIJJOODOO, 	S%&QRR	Ss   ,FI I.indexr]  c                   U[         L aW  [        R                  nU R                  S   U R                  S   -  U R                  -  nU R                  /U R                  Q7nOUS:  a  [        SU S35      eXR                  :  a  [        SU SU R                   S35      e[        R                  XR                  S   -  U R                  S   -  U R                  R                  -  -   nU R                  S   U R                  S   -  nU R                  nU R                  R                  U5        [        R                  " U R                  U R                  US9nUR                  U5      $ )zRead 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   rx   zIndex `z` is smaller than 0.z5` exceeds the number of frames stored in this file (`z`).r   count)Ellipsisr   r   rP  rQ  
IndexErrorrO  rV  rL  rR  r   fromfilereshape)r   r]  read_offsetr`  	out_shapedatas         r   readSpePlugin.read  s8    H//KKKNT[[^3dii?E1T[[1IQYwug-ABCCii% UVZV_V_U``cd 
 ++a.(4;;q>9DKK<P<PPQ  KKNT[[^3EI

${{4::T[[F||I&&r   c                 B   ^  U 4S j[        T R                  5       5       $ )zRIterate over the frames in the file

Yields
------
A Numpy array of pixel values.
c              3   B   >#    U  H  nTR                  US 9v   M     g7f)r\  N)rh  )r+  ir   s     r   r-  !SpePlugin.iter.<locals>.<genexpr>1  s     =,<q			",<s   )r  rQ  )r   s   `r   iterSpePlugin.iter)  s     >E$)),<==r   exclude_appliedsdt_controlc                     U R                   S:  aC  U R                  b  U R                  nU R                  b  U R                  nU R                  X45      $ U R	                  5       $ )uq  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
ry   )rN  rI  rJ  _metadata_pre_v3_metadata_post_v3)r   r]  rp  r(  rq  s        r   r   SpePlugin.metadata3  s]    X   1$"". $ 3 3~~)"nn((DD%%''r   c                    U R                  [        R                  U5      nUR                  SS5      nUS:  a  SOUn[	        US   SU 5      US'   S Vs/ s H  oSR                  US5      PM     snUS'   S Vs/ s H  oSR                  US5      PM     snUS'   S	 Vs/ s H  oSR                  US5      PM     snUS
'   S Vs/ s H  oSR                  US5      PM     snUS'   US    Vs/ s H  n[        U5      PM     snUS'   / nUR                  SS5      nUS-  (       a  UR                  S5        US-  (       a  UR                  S5        US-  (       a  UR                  S5        XsS'   US   n	SU	s=::  a  [        [        R                  5      ::  a  O  O[        R                  U	S-
     US'   OSUS'   US   n
SU
s=::  a  [        [        R                  5      ::  a  O  O[        R                  U
S-
     US'   OSUS'   S H  n[        X5   5      X5'   M     U(       a  [        R                  X15        U$ s  snf s  snf s  snf s  snf s  snf )a  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"   Nrx   r#   )r+   r-   	chip_size)r/   r1   virt_chip_size)ro   rq   
pre_pixels)rp   rr   post_pixelsre   rh   r   rotater   reverser6   fliprt   rv   )rF   rJ   rL   rP   )rM  r   r   r2  roi_array_to_dictr   appendlenr   r   boolr   r:  )r   r(  rq  mnrkr,  gftrs              r   rs  SpePlugin._metadata_pre_v3  s'   " t}}m<UU8T"q&Qb%ain5&	 3II2HQ%%4.2HI+7QR7Q!uuQ~7QR
3OP3Oa55D>3OP,4RS4RqEE!TN4RS- *+:7AQ7* EE+q!q5HHXq5HHYq5HHV+ fI*S))**((Q/AfIAfIn,S++,, $ 2 21q5 9An $An
A :AD
 ++A=Y JRPS 8s   H<:III,Ic                     U R                  [        R                  S5      nU R                  R	                  US   5        U R                  R                  5       nSU0$ )zqExtract XML metadata from SPE v3 files

Returns
-------
dict with key `"__xml"`, whose value is the XML metadata
r<  r   __xml)rM  r   r   rL  rR  rh  )r   r#  xmls      r   rt  SpePlugin._metadata_post_v3M  sJ     !!$**h7

012jjoo~r   c                     U[         L a8  [        U R                  /U R                  Q7U R                  U R                  SS9$ [        U R                  U R                  SS9$ )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  )ra  r   rQ  rP  rO  )r   r]  s     r   
propertiesSpePlugin.propertiesZ  sV    " H"yy/4;;/kk	  T[[eTTr   r  c                 X  ^ 0 n[         R                  " U4S j5      nUR                  5        H  u  pVU R                  R	                  US   5        [        U5      S:  a  SOUS   n[         R                  " U R                  US   US9nUR                  R                  S:X  a  U[        R                  ;  a	   U" U5      n UR                  5       nXU'   M     U$ ! [         a    [        R                  " SU S	35         NAf = f! [         a    [         R                   " U5      n NVf = f)
aN  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                 &   > U R                  T5      $ r   )r4  )r   r(  s    r   r   )SpePlugin._parse_header.<locals>.<lambda>  s    (?r   r   ry   rx   r   r_  SzFailed to decode "z3" metadata string. Check `char_encoding` parameter.)r   	vectorizer  rL  rR  r  rc  r   kindr   r   r  r  r  itemr  squeeze)	r   r  r(  retr4  r  spcntr  s	     `      r   rM  SpePlugin._parse_headert  s   & ?@

HDJJOOBqE"2w{!1CDJJbe3?Aww||s"t4>>'Aq	A" FFH I) %* 
 ! MM,TF 3C C  "JJqM"s$   9CD$DD D)(D))rI  rO  rL  rN  rQ  rJ  rP  )TNN).Tr<  T).)r   r   r   r   r   r  r
   r   r   r   r   ndarrayrh  r   rn  r   r   r   rs  rt  r   r  r	   r   rM  r   r>  r?  s   @r   rA  rA    sh     $'+#'NSNS NS  }	NS
 4.NS 
NS NS` $' #'S #'2:: #'J>hrzz* >  $% R(R( R( 	R(
 R( 
c3hR(hDc D DcSVh DL4S> U Uo U4,CJ',8;,	c3h, ,r   rA  ar   c                     / nU / SQ   n U  HZ  u  p#pEpg[        U5      [        U5      /[        U5      [        U5      /[        U5      [        U5      /S.nUR                  U5        M\     U$ )a4  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   r  )	r  	dict_listsxsyexeygxgyroi_dicts	            r   r~  r~    st     I	
BCA"#R#b'* Wc"g.GSW%

 	" #$ r   )#r   r   loggingrS  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   rA  r  r   r   r~  r   r   r   <module>r     s   !F   	     ? ? : 
		8	$~ ~Bn! n!bm m` T#tCy.-A(B r   