spe.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. # -*- coding: utf-8 -*-
  2. # imageio is distributed under the terms of the (new) BSD License.
  3. """Read SPE files.
  4. This plugin supports reading files saved in the Princeton Instruments
  5. SPE file format.
  6. Parameters
  7. ----------
  8. check_filesize : bool
  9. The number of frames in the file is stored in the file header. However,
  10. this number may be wrong for certain software. If this is `True`
  11. (default), derive the number of frames also from the file size and
  12. raise a warning if the two values do not match.
  13. char_encoding : str
  14. Deprecated. Exists for backwards compatibility; use ``char_encoding`` of
  15. ``metadata`` instead.
  16. sdt_meta : bool
  17. Deprecated. Exists for backwards compatibility; use ``sdt_control`` of
  18. ``metadata`` instead.
  19. Methods
  20. -------
  21. .. note::
  22. Check the respective function for a list of supported kwargs and detailed
  23. documentation.
  24. .. autosummary::
  25. :toctree:
  26. SpePlugin.read
  27. SpePlugin.iter
  28. SpePlugin.properties
  29. SpePlugin.metadata
  30. """
  31. from datetime import datetime
  32. import logging
  33. import os
  34. from typing import (
  35. Any,
  36. Callable,
  37. Dict,
  38. Iterator,
  39. List,
  40. Mapping,
  41. Optional,
  42. Sequence,
  43. Tuple,
  44. Union,
  45. )
  46. import warnings
  47. import numpy as np
  48. from ..core.request import Request, IOMode, InitializationError
  49. from ..core.v3_plugin_api import PluginV3, ImageProperties
  50. logger = logging.getLogger(__name__)
  51. class Spec:
  52. """SPE file specification data
  53. Tuples of (offset, datatype, count), where offset is the offset in the SPE
  54. file and datatype is the datatype as used in `numpy.fromfile`()
  55. `data_start` is the offset of actual image data.
  56. `dtypes` translates SPE datatypes (0...4) to numpy ones, e. g. dtypes[0]
  57. is dtype("<f") (which is np.float32).
  58. `controllers` maps the `type` metadata to a human readable name
  59. `readout_modes` maps the `readoutMode` metadata to something human readable
  60. although this may not be accurate since there is next to no documentation
  61. to be found.
  62. """
  63. basic = {
  64. "datatype": (108, "<h"), # dtypes
  65. "xdim": (42, "<H"),
  66. "ydim": (656, "<H"),
  67. "xml_footer_offset": (678, "<Q"),
  68. "NumFrames": (1446, "<i"),
  69. "file_header_ver": (1992, "<f"),
  70. }
  71. metadata = {
  72. # ROI information
  73. "NumROI": (1510, "<h"),
  74. "ROIs": (
  75. 1512,
  76. np.dtype(
  77. [
  78. ("startx", "<H"),
  79. ("endx", "<H"),
  80. ("groupx", "<H"),
  81. ("starty", "<H"),
  82. ("endy", "<H"),
  83. ("groupy", "<H"),
  84. ]
  85. ),
  86. 10,
  87. ),
  88. # chip-related sizes
  89. "xDimDet": (6, "<H"),
  90. "yDimDet": (18, "<H"),
  91. "VChipXdim": (14, "<h"),
  92. "VChipYdim": (16, "<h"),
  93. # other stuff
  94. "controller_version": (0, "<h"),
  95. "logic_output": (2, "<h"),
  96. "amp_high_cap_low_noise": (4, "<H"), # enum?
  97. "mode": (8, "<h"), # enum?
  98. "exposure_sec": (10, "<f"),
  99. "date": (20, "<10S"),
  100. "detector_temp": (36, "<f"),
  101. "detector_type": (40, "<h"),
  102. "st_diode": (44, "<h"),
  103. "delay_time": (46, "<f"),
  104. # shutter_control: normal, disabled open, disabled closed
  105. # But which one is which?
  106. "shutter_control": (50, "<H"),
  107. "absorb_live": (52, "<h"),
  108. "absorb_mode": (54, "<H"),
  109. "can_do_virtual_chip": (56, "<h"),
  110. "threshold_min_live": (58, "<h"),
  111. "threshold_min_val": (60, "<f"),
  112. "threshold_max_live": (64, "<h"),
  113. "threshold_max_val": (66, "<f"),
  114. "time_local": (172, "<7S"),
  115. "time_utc": (179, "<7S"),
  116. "adc_offset": (188, "<H"),
  117. "adc_rate": (190, "<H"),
  118. "adc_type": (192, "<H"),
  119. "adc_resolution": (194, "<H"),
  120. "adc_bit_adjust": (196, "<H"),
  121. "gain": (198, "<H"),
  122. "comments": (200, "<80S", 5),
  123. "geometric": (600, "<H"), # flags
  124. "sw_version": (688, "<16S"),
  125. "spare_4": (742, "<436S"),
  126. "XPrePixels": (98, "<h"),
  127. "XPostPixels": (100, "<h"),
  128. "YPrePixels": (102, "<h"),
  129. "YPostPixels": (104, "<h"),
  130. "readout_time": (672, "<f"),
  131. "xml_footer_offset": (678, "<Q"),
  132. "type": (704, "<h"), # controllers
  133. "clockspeed_us": (1428, "<f"),
  134. "readout_mode": (1480, "<H"), # readout_modes
  135. "window_size": (1482, "<H"),
  136. "file_header_ver": (1992, "<f"),
  137. }
  138. data_start = 4100
  139. dtypes = {
  140. 0: np.dtype(np.float32),
  141. 1: np.dtype(np.int32),
  142. 2: np.dtype(np.int16),
  143. 3: np.dtype(np.uint16),
  144. 8: np.dtype(np.uint32),
  145. }
  146. controllers = [
  147. "new120 (Type II)",
  148. "old120 (Type I)",
  149. "ST130",
  150. "ST121",
  151. "ST138",
  152. "DC131 (PentaMax)",
  153. "ST133 (MicroMax/Roper)",
  154. "ST135 (GPIB)",
  155. "VTCCD",
  156. "ST116 (GPIB)",
  157. "OMA3 (GPIB)",
  158. "OMA4",
  159. ]
  160. # This was gathered from random places on the internet and own experiments
  161. # with the camera. May not be accurate.
  162. readout_modes = ["full frame", "frame transfer", "kinetics"]
  163. # Do not decode the following metadata keys into strings, but leave them
  164. # as byte arrays
  165. no_decode = ["spare_4"]
  166. class SDTControlSpec:
  167. """Extract metadata written by the SDT-control software
  168. Some of it is encoded in the comment strings
  169. (see :py:meth:`parse_comments`). Also, date and time are encoded in a
  170. peculiar way (see :py:meth:`get_datetime`). Use :py:meth:`extract_metadata`
  171. to update the metadata dict.
  172. """
  173. months = {
  174. # Convert SDT-control month strings to month numbers
  175. "Jän": 1,
  176. "Jan": 1,
  177. "Feb": 2,
  178. "Mär": 3,
  179. "Mar": 3,
  180. "Apr": 4,
  181. "Mai": 5,
  182. "May": 5,
  183. "Jun": 6,
  184. "Jul": 7,
  185. "Aug": 8,
  186. "Sep": 9,
  187. "Okt": 10,
  188. "Oct": 10,
  189. "Nov": 11,
  190. "Dez": 12,
  191. "Dec": 12,
  192. }
  193. sequence_types = {
  194. # TODO: complete
  195. "SEQU": "standard",
  196. "SETO": "TOCCSL",
  197. "KINE": "kinetics",
  198. "SEAR": "arbitrary",
  199. }
  200. class CommentDesc:
  201. """Describe how to extract a metadata entry from a comment string"""
  202. n: int
  203. """Which of the 5 SPE comment fields to use."""
  204. slice: slice
  205. """Which characters from the `n`-th comment to use."""
  206. cvt: Callable[[str], Any]
  207. """How to convert characters to something useful."""
  208. scale: Union[None, float]
  209. """Optional scaling factor for numbers"""
  210. def __init__(
  211. self,
  212. n: int,
  213. slice: slice,
  214. cvt: Callable[[str], Any] = str,
  215. scale: Optional[float] = None,
  216. ):
  217. self.n = n
  218. self.slice = slice
  219. self.cvt = cvt
  220. self.scale = scale
  221. comment_fields = {
  222. (5, 0): {
  223. "sdt_major_version": CommentDesc(4, slice(66, 68), int),
  224. "sdt_minor_version": CommentDesc(4, slice(68, 70), int),
  225. "sdt_controller_name": CommentDesc(4, slice(0, 6), str),
  226. "exposure_time": CommentDesc(1, slice(64, 73), float, 10**-6),
  227. "color_code": CommentDesc(4, slice(10, 14), str),
  228. "detection_channels": CommentDesc(4, slice(15, 16), int),
  229. "background_subtraction": CommentDesc(4, 14, lambda x: x == "B"),
  230. "em_active": CommentDesc(4, 32, lambda x: x == "E"),
  231. "em_gain": CommentDesc(4, slice(28, 32), int),
  232. "modulation_active": CommentDesc(4, 33, lambda x: x == "A"),
  233. "pixel_size": CommentDesc(4, slice(25, 28), float, 0.1),
  234. "sequence_type": CommentDesc(
  235. 4, slice(6, 10), lambda x: __class__.sequence_types[x]
  236. ),
  237. "grid": CommentDesc(4, slice(16, 25), float, 10**-6),
  238. "n_macro": CommentDesc(1, slice(0, 4), int),
  239. "delay_macro": CommentDesc(1, slice(10, 19), float, 10**-3),
  240. "n_mini": CommentDesc(1, slice(4, 7), int),
  241. "delay_mini": CommentDesc(1, slice(19, 28), float, 10**-6),
  242. "n_micro": CommentDesc(1, slice(7, 10), int),
  243. "delay_micro": CommentDesc(1, slice(28, 37), float, 10**-6),
  244. "n_subpics": CommentDesc(1, slice(7, 10), int),
  245. "delay_shutter": CommentDesc(1, slice(73, 79), float, 10**-6),
  246. "delay_prebleach": CommentDesc(1, slice(37, 46), float, 10**-6),
  247. "bleach_time": CommentDesc(1, slice(46, 55), float, 10**-6),
  248. "recovery_time": CommentDesc(1, slice(55, 64), float, 10**-6),
  249. },
  250. (5, 1): {
  251. "bleach_piezo_active": CommentDesc(4, slice(34, 35), lambda x: x == "z")
  252. },
  253. }
  254. @staticmethod
  255. def get_comment_version(comments: Sequence[str]) -> Tuple[int, int]:
  256. """Get the version of SDT-control metadata encoded in the comments
  257. Parameters
  258. ----------
  259. comments
  260. List of SPE file comments, typically ``metadata["comments"]``.
  261. Returns
  262. -------
  263. Major and minor version. ``-1, -1`` if detection failed.
  264. """
  265. if comments[4][70:76] != "COMVER":
  266. return -1, -1
  267. try:
  268. return int(comments[4][76:78]), int(comments[4][78:80])
  269. except ValueError:
  270. return -1, -1
  271. @staticmethod
  272. def parse_comments(
  273. comments: Sequence[str], version: Tuple[int, int]
  274. ) -> Dict[str, Any]:
  275. """Extract SDT-control metadata from comments
  276. Parameters
  277. ----------
  278. comments
  279. List of SPE file comments, typically ``metadata["comments"]``.
  280. version
  281. Major and minor version of SDT-control metadata format
  282. Returns
  283. -------
  284. Dict of metadata
  285. """
  286. sdt_md = {}
  287. for minor in range(version[1] + 1):
  288. # Metadata with same major version is backwards compatible.
  289. # Fields are specified incrementally in `comment_fields`.
  290. # E.g. if the file has version 5.01, `comment_fields[5, 0]` and
  291. # `comment_fields[5, 1]` need to be decoded.
  292. try:
  293. cmt = __class__.comment_fields[version[0], minor]
  294. except KeyError:
  295. continue
  296. for name, spec in cmt.items():
  297. try:
  298. v = spec.cvt(comments[spec.n][spec.slice])
  299. if spec.scale is not None:
  300. v *= spec.scale
  301. sdt_md[name] = v
  302. except Exception as e:
  303. warnings.warn(
  304. f"Failed to decode SDT-control metadata field `{name}`: {e}"
  305. )
  306. sdt_md[name] = None
  307. if version not in __class__.comment_fields:
  308. supported_ver = ", ".join(
  309. map(lambda x: f"{x[0]}.{x[1]:02}", __class__.comment_fields)
  310. )
  311. warnings.warn(
  312. f"Unsupported SDT-control metadata version {version[0]}.{version[1]:02}. "
  313. f"Only versions {supported_ver} are supported. "
  314. "Some or all SDT-control metadata may be missing."
  315. )
  316. comment = comments[0] + comments[2]
  317. sdt_md["comment"] = comment.strip()
  318. return sdt_md
  319. @staticmethod
  320. def get_datetime(date: str, time: str) -> Union[datetime, None]:
  321. """Turn date and time saved by SDT-control into proper datetime object
  322. Parameters
  323. ----------
  324. date
  325. SPE file date, typically ``metadata["date"]``.
  326. time
  327. SPE file date, typically ``metadata["time_local"]``.
  328. Returns
  329. -------
  330. File's datetime if parsing was succsessful, else None.
  331. """
  332. try:
  333. month = __class__.months[date[2:5]]
  334. return datetime(
  335. int(date[5:9]),
  336. month,
  337. int(date[0:2]),
  338. int(time[0:2]),
  339. int(time[2:4]),
  340. int(time[4:6]),
  341. )
  342. except Exception as e:
  343. logger.info(f"Failed to decode date from SDT-control metadata: {e}.")
  344. @staticmethod
  345. def extract_metadata(meta: Mapping, char_encoding: str = "latin1"):
  346. """Extract SDT-control metadata from SPE metadata
  347. SDT-control stores some metadata in comments and other fields.
  348. Extract them and remove unused entries.
  349. Parameters
  350. ----------
  351. meta
  352. SPE file metadata. Modified in place.
  353. char_encoding
  354. Character encoding used to decode strings in the metadata.
  355. """
  356. comver = __class__.get_comment_version(meta["comments"])
  357. if any(c < 0 for c in comver):
  358. # This file most likely was not created by SDT-control
  359. logger.debug("SDT-control comments not found.")
  360. return
  361. sdt_meta = __class__.parse_comments(meta["comments"], comver)
  362. meta.pop("comments")
  363. meta.update(sdt_meta)
  364. # Get date and time in a usable format
  365. dt = __class__.get_datetime(meta["date"], meta["time_local"])
  366. if dt:
  367. meta["datetime"] = dt
  368. meta.pop("date")
  369. meta.pop("time_local")
  370. sp4 = meta["spare_4"]
  371. try:
  372. meta["modulation_script"] = sp4.decode(char_encoding)
  373. meta.pop("spare_4")
  374. except UnicodeDecodeError:
  375. warnings.warn(
  376. "Failed to decode SDT-control laser "
  377. "modulation script. Bad char_encoding?"
  378. )
  379. # Get rid of unused data
  380. meta.pop("time_utc")
  381. meta.pop("exposure_sec")
  382. class SpePlugin(PluginV3):
  383. def __init__(
  384. self,
  385. request: Request,
  386. check_filesize: bool = True,
  387. char_encoding: Optional[str] = None,
  388. sdt_meta: Optional[bool] = None,
  389. ) -> None:
  390. """Instantiate a new SPE file plugin object
  391. Parameters
  392. ----------
  393. request : Request
  394. A request object representing the resource to be operated on.
  395. check_filesize : bool
  396. If True, compute the number of frames from the filesize, compare it
  397. to the frame count in the file header, and raise a warning if the
  398. counts don't match. (Certain software may create files with
  399. char_encoding : str
  400. Deprecated. Exists for backwards compatibility; use ``char_encoding`` of
  401. ``metadata`` instead.
  402. sdt_meta : bool
  403. Deprecated. Exists for backwards compatibility; use ``sdt_control`` of
  404. ``metadata`` instead.
  405. """
  406. super().__init__(request)
  407. if request.mode.io_mode == IOMode.write:
  408. raise InitializationError("cannot write SPE files")
  409. if char_encoding is not None:
  410. warnings.warn(
  411. "Passing `char_encoding` to the constructor is deprecated. "
  412. "Use `char_encoding` parameter of the `metadata()` method "
  413. "instead.",
  414. DeprecationWarning,
  415. )
  416. self._char_encoding = char_encoding
  417. if sdt_meta is not None:
  418. warnings.warn(
  419. "Passing `sdt_meta` to the constructor is deprecated. "
  420. "Use `sdt_control` parameter of the `metadata()` method "
  421. "instead.",
  422. DeprecationWarning,
  423. )
  424. self._sdt_meta = sdt_meta
  425. self._file = self.request.get_file()
  426. try:
  427. # Spec.basic contains no string, no need to worry about character
  428. # encoding.
  429. info = self._parse_header(Spec.basic, "latin1")
  430. self._file_header_ver = info["file_header_ver"]
  431. self._dtype = Spec.dtypes[info["datatype"]]
  432. self._shape = (info["ydim"], info["xdim"])
  433. self._len = info["NumFrames"]
  434. if check_filesize:
  435. # Some software writes incorrect `NumFrames` metadata.
  436. # To determine the number of frames, check the size of the data
  437. # segment -- until the end of the file for SPE<3, until the
  438. # xml footer for SPE>=3.
  439. if info["file_header_ver"] >= 3:
  440. data_end = info["xml_footer_offset"]
  441. else:
  442. self._file.seek(0, os.SEEK_END)
  443. data_end = self._file.tell()
  444. line = data_end - Spec.data_start
  445. line //= self._shape[0] * self._shape[1] * self._dtype.itemsize
  446. if line != self._len:
  447. warnings.warn(
  448. f"The file header of {self.request.filename} claims there are "
  449. f"{self._len} frames, but there are actually {line} frames."
  450. )
  451. self._len = min(line, self._len)
  452. self._file.seek(Spec.data_start)
  453. except Exception:
  454. raise InitializationError("SPE plugin cannot read the provided file.")
  455. def read(self, *, index: int = ...) -> np.ndarray:
  456. """Read a frame or all frames from the file
  457. Parameters
  458. ----------
  459. index : int
  460. Select the index-th frame from the file. If index is `...`,
  461. select all frames and stack them along a new axis.
  462. Returns
  463. -------
  464. A Numpy array of pixel values.
  465. """
  466. if index is Ellipsis:
  467. read_offset = Spec.data_start
  468. count = self._shape[0] * self._shape[1] * self._len
  469. out_shape = (self._len, *self._shape)
  470. elif index < 0:
  471. raise IndexError(f"Index `{index}` is smaller than 0.")
  472. elif index >= self._len:
  473. raise IndexError(
  474. f"Index `{index}` exceeds the number of frames stored in this file (`{self._len}`)."
  475. )
  476. else:
  477. read_offset = (
  478. Spec.data_start
  479. + index * self._shape[0] * self._shape[1] * self._dtype.itemsize
  480. )
  481. count = self._shape[0] * self._shape[1]
  482. out_shape = self._shape
  483. self._file.seek(read_offset)
  484. data = np.fromfile(self._file, dtype=self._dtype, count=count)
  485. return data.reshape(out_shape)
  486. def iter(self) -> Iterator[np.ndarray]:
  487. """Iterate over the frames in the file
  488. Yields
  489. ------
  490. A Numpy array of pixel values.
  491. """
  492. return (self.read(index=i) for i in range(self._len))
  493. def metadata(
  494. self,
  495. index: int = ...,
  496. exclude_applied: bool = True,
  497. char_encoding: str = "latin1",
  498. sdt_control: bool = True,
  499. ) -> Dict[str, Any]:
  500. """SPE specific metadata.
  501. Parameters
  502. ----------
  503. index : int
  504. Ignored as SPE files only store global metadata.
  505. exclude_applied : bool
  506. Ignored. Exists for API compatibility.
  507. char_encoding : str
  508. The encoding to use when parsing strings.
  509. sdt_control : bool
  510. If `True`, decode special metadata written by the
  511. SDT-control software if present.
  512. Returns
  513. -------
  514. metadata : dict
  515. Key-value pairs of metadata.
  516. Notes
  517. -----
  518. SPE v3 stores metadata as XML, whereas SPE v2 uses a binary format.
  519. .. rubric:: Supported SPE v2 Metadata fields
  520. ROIs : list of dict
  521. Regions of interest used for recording images. Each dict has the
  522. "top_left" key containing x and y coordinates of the top left corner,
  523. the "bottom_right" key with x and y coordinates of the bottom right
  524. corner, and the "bin" key with number of binned pixels in x and y
  525. directions.
  526. comments : list of str
  527. The SPE format allows for 5 comment strings of 80 characters each.
  528. controller_version : int
  529. Hardware version
  530. logic_output : int
  531. Definition of output BNC
  532. amp_hi_cap_low_noise : int
  533. Amp switching mode
  534. mode : int
  535. Timing mode
  536. exp_sec : float
  537. Alternative exposure in seconds
  538. date : str
  539. Date string
  540. detector_temp : float
  541. Detector temperature
  542. detector_type : int
  543. CCD / diode array type
  544. st_diode : int
  545. Trigger diode
  546. delay_time : float
  547. Used with async mode
  548. shutter_control : int
  549. Normal, disabled open, or disabled closed
  550. absorb_live : bool
  551. on / off
  552. absorb_mode : int
  553. Reference strip or file
  554. can_do_virtual_chip : bool
  555. True or False whether chip can do virtual chip
  556. threshold_min_live : bool
  557. on / off
  558. threshold_min_val : float
  559. Threshold minimum value
  560. threshold_max_live : bool
  561. on / off
  562. threshold_max_val : float
  563. Threshold maximum value
  564. time_local : str
  565. Experiment local time
  566. time_utc : str
  567. Experiment UTC time
  568. adc_offset : int
  569. ADC offset
  570. adc_rate : int
  571. ADC rate
  572. adc_type : int
  573. ADC type
  574. adc_resolution : int
  575. ADC resolution
  576. adc_bit_adjust : int
  577. ADC bit adjust
  578. gain : int
  579. gain
  580. sw_version : str
  581. Version of software which created this file
  582. spare_4 : bytes
  583. Reserved space
  584. readout_time : float
  585. Experiment readout time
  586. type : str
  587. Controller type
  588. clockspeed_us : float
  589. Vertical clock speed in microseconds
  590. readout_mode : ["full frame", "frame transfer", "kinetics", ""]
  591. Readout mode. Empty string means that this was not set by the
  592. Software.
  593. window_size : int
  594. Window size for Kinetics mode
  595. file_header_ver : float
  596. File header version
  597. chip_size : [int, int]
  598. x and y dimensions of the camera chip
  599. virt_chip_size : [int, int]
  600. Virtual chip x and y dimensions
  601. pre_pixels : [int, int]
  602. Pre pixels in x and y dimensions
  603. post_pixels : [int, int],
  604. Post pixels in x and y dimensions
  605. geometric : list of {"rotate", "reverse", "flip"}
  606. Geometric operations
  607. sdt_major_version : int
  608. (only for files created by SDT-control)
  609. Major version of SDT-control software
  610. sdt_minor_version : int
  611. (only for files created by SDT-control)
  612. Minor version of SDT-control software
  613. sdt_controller_name : str
  614. (only for files created by SDT-control)
  615. Controller name
  616. exposure_time : float
  617. (only for files created by SDT-control)
  618. Exposure time in seconds
  619. color_code : str
  620. (only for files created by SDT-control)
  621. Color channels used
  622. detection_channels : int
  623. (only for files created by SDT-control)
  624. Number of channels
  625. background_subtraction : bool
  626. (only for files created by SDT-control)
  627. Whether background subtraction war turned on
  628. em_active : bool
  629. (only for files created by SDT-control)
  630. Whether EM was turned on
  631. em_gain : int
  632. (only for files created by SDT-control)
  633. EM gain
  634. modulation_active : bool
  635. (only for files created by SDT-control)
  636. Whether laser modulation (“attenuate”) was turned on
  637. pixel_size : float
  638. (only for files created by SDT-control)
  639. Camera pixel size
  640. sequence_type : str
  641. (only for files created by SDT-control)
  642. Type of sequnce (standard, TOCCSL, arbitrary, …)
  643. grid : float
  644. (only for files created by SDT-control)
  645. Sequence time unit (“grid size”) in seconds
  646. n_macro : int
  647. (only for files created by SDT-control)
  648. Number of macro loops
  649. delay_macro : float
  650. (only for files created by SDT-control)
  651. Time between macro loops in seconds
  652. n_mini : int
  653. (only for files created by SDT-control)
  654. Number of mini loops
  655. delay_mini : float
  656. (only for files created by SDT-control)
  657. Time between mini loops in seconds
  658. n_micro : int (only for files created by SDT-control)
  659. Number of micro loops
  660. delay_micro : float (only for files created by SDT-control)
  661. Time between micro loops in seconds
  662. n_subpics : int
  663. (only for files created by SDT-control)
  664. Number of sub-pictures
  665. delay_shutter : float
  666. (only for files created by SDT-control)
  667. Camera shutter delay in seconds
  668. delay_prebleach : float
  669. (only for files created by SDT-control)
  670. Pre-bleach delay in seconds
  671. bleach_time : float
  672. (only for files created by SDT-control)
  673. Bleaching time in seconds
  674. recovery_time : float
  675. (only for files created by SDT-control)
  676. Recovery time in seconds
  677. comment : str
  678. (only for files created by SDT-control)
  679. User-entered comment. This replaces the "comments" field.
  680. datetime : datetime.datetime
  681. (only for files created by SDT-control)
  682. Combines the "date" and "time_local" keys. The latter two plus
  683. "time_utc" are removed.
  684. modulation_script : str
  685. (only for files created by SDT-control)
  686. Laser modulation script. Replaces the "spare_4" key.
  687. bleach_piezo_active : bool
  688. (only for files created by SDT-control)
  689. Whether piezo for bleaching was enabled
  690. """
  691. if self._file_header_ver < 3:
  692. if self._char_encoding is not None:
  693. char_encoding = self._char_encoding
  694. if self._sdt_meta is not None:
  695. sdt_control = self._sdt_meta
  696. return self._metadata_pre_v3(char_encoding, sdt_control)
  697. return self._metadata_post_v3()
  698. def _metadata_pre_v3(self, char_encoding: str, sdt_control: bool) -> Dict[str, Any]:
  699. """Extract metadata from SPE v2 files
  700. Parameters
  701. ----------
  702. char_encoding
  703. String character encoding
  704. sdt_control
  705. If `True`, try to decode special metadata written by the
  706. SDT-control software.
  707. Returns
  708. -------
  709. dict mapping metadata names to values.
  710. """
  711. m = self._parse_header(Spec.metadata, char_encoding)
  712. nr = m.pop("NumROI", None)
  713. nr = 1 if nr < 1 else nr
  714. m["ROIs"] = roi_array_to_dict(m["ROIs"][:nr])
  715. # chip sizes
  716. m["chip_size"] = [m.pop(k, None) for k in ("xDimDet", "yDimDet")]
  717. m["virt_chip_size"] = [m.pop(k, None) for k in ("VChipXdim", "VChipYdim")]
  718. m["pre_pixels"] = [m.pop(k, None) for k in ("XPrePixels", "YPrePixels")]
  719. m["post_pixels"] = [m.pop(k, None) for k in ("XPostPixels", "YPostPixels")]
  720. # convert comments from numpy.str_ to str
  721. m["comments"] = [str(c) for c in m["comments"]]
  722. # geometric operations
  723. g = []
  724. f = m.pop("geometric", 0)
  725. if f & 1:
  726. g.append("rotate")
  727. if f & 2:
  728. g.append("reverse")
  729. if f & 4:
  730. g.append("flip")
  731. m["geometric"] = g
  732. # Make some additional information more human-readable
  733. t = m["type"]
  734. if 1 <= t <= len(Spec.controllers):
  735. m["type"] = Spec.controllers[t - 1]
  736. else:
  737. m["type"] = None
  738. r = m["readout_mode"]
  739. if 1 <= r <= len(Spec.readout_modes):
  740. m["readout_mode"] = Spec.readout_modes[r - 1]
  741. else:
  742. m["readout_mode"] = None
  743. # bools
  744. for k in (
  745. "absorb_live",
  746. "can_do_virtual_chip",
  747. "threshold_min_live",
  748. "threshold_max_live",
  749. ):
  750. m[k] = bool(m[k])
  751. # Extract SDT-control metadata if desired
  752. if sdt_control:
  753. SDTControlSpec.extract_metadata(m, char_encoding)
  754. return m
  755. def _metadata_post_v3(self) -> Dict[str, Any]:
  756. """Extract XML metadata from SPE v3 files
  757. Returns
  758. -------
  759. dict with key `"__xml"`, whose value is the XML metadata
  760. """
  761. info = self._parse_header(Spec.basic, "latin1")
  762. self._file.seek(info["xml_footer_offset"])
  763. xml = self._file.read()
  764. return {"__xml": xml}
  765. def properties(self, index: int = ...) -> ImageProperties:
  766. """Standardized ndimage metadata.
  767. Parameters
  768. ----------
  769. index : int
  770. If the index is an integer, select the index-th frame and return
  771. its properties. If index is an Ellipsis (...), return the
  772. properties of all frames in the file stacked along a new batch
  773. dimension.
  774. Returns
  775. -------
  776. properties : ImageProperties
  777. A dataclass filled with standardized image metadata.
  778. """
  779. if index is Ellipsis:
  780. return ImageProperties(
  781. shape=(self._len, *self._shape),
  782. dtype=self._dtype,
  783. n_images=self._len,
  784. is_batch=True,
  785. )
  786. return ImageProperties(shape=self._shape, dtype=self._dtype, is_batch=False)
  787. def _parse_header(
  788. self, spec: Mapping[str, Tuple], char_encoding: str
  789. ) -> Dict[str, Any]:
  790. """Get information from SPE file header
  791. Parameters
  792. ----------
  793. spec
  794. Maps header entry name to its location, data type description and
  795. optionally number of entries. See :py:attr:`Spec.basic` and
  796. :py:attr:`Spec.metadata`.
  797. char_encoding
  798. String character encoding
  799. Returns
  800. -------
  801. Dict mapping header entry name to its value
  802. """
  803. ret = {}
  804. # Decode each string from the numpy array read by np.fromfile
  805. decode = np.vectorize(lambda x: x.decode(char_encoding))
  806. for name, sp in spec.items():
  807. self._file.seek(sp[0])
  808. cnt = 1 if len(sp) < 3 else sp[2]
  809. v = np.fromfile(self._file, dtype=sp[1], count=cnt)
  810. if v.dtype.kind == "S" and name not in Spec.no_decode:
  811. # Silently ignore string decoding failures
  812. try:
  813. v = decode(v)
  814. except Exception:
  815. warnings.warn(
  816. f'Failed to decode "{name}" metadata '
  817. "string. Check `char_encoding` parameter."
  818. )
  819. try:
  820. # For convenience, if the array contains only one single
  821. # entry, return this entry itself.
  822. v = v.item()
  823. except ValueError:
  824. v = np.squeeze(v)
  825. ret[name] = v
  826. return ret
  827. def roi_array_to_dict(a: np.ndarray) -> List[Dict[str, List[int]]]:
  828. """Convert the `ROIs` structured arrays to :py:class:`dict`
  829. Parameters
  830. ----------
  831. a
  832. Structured array containing ROI data
  833. Returns
  834. -------
  835. One dict per ROI. Keys are "top_left", "bottom_right", and "bin",
  836. values are tuples whose first element is the x axis value and the
  837. second element is the y axis value.
  838. """
  839. dict_list = []
  840. a = a[["startx", "starty", "endx", "endy", "groupx", "groupy"]]
  841. for sx, sy, ex, ey, gx, gy in a:
  842. roi_dict = {
  843. "top_left": [int(sx), int(sy)],
  844. "bottom_right": [int(ex), int(ey)],
  845. "bin": [int(gx), int(gy)],
  846. }
  847. dict_list.append(roi_dict)
  848. return dict_list