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