Debian Codegraph @

ptufile/ptufile.py

raw
1 # ptufile.py
2
3 # Copyright (c) 2023-2026, Christoph Gohlke
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 #
16 # 3. Neither the name of the copyright holder nor the names of its
17 # contributors may be used to endorse or promote products derived from
18 # this software without specific prior written permission.
19 #
20 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 # POSSIBILITY OF SUCH DAMAGE.
31
32 """Read and write PicoQuant PTU and related files.
33
34 Ptufile is a Python library to
35
36 1. read data and metadata from PicoQuant PTU and related files
37 (PHU, PCK, PCO, PFS, PUS, PQRES, PQDAT, PQUNI, SPQR, and BIN), and
38 2. write TCSPC histograms to T3 image mode PTU files.
39
40 PTU files contain time correlated single photon counting (TCSPC)
41 measurement data and instrumentation parameters.
42
43 :Author: `Christoph Gohlke <https://www.cgohlke.com>`_
44 :License: BSD-3-Clause
45 :Version: 2026.8.8
46 :DOI: `10.5281/zenodo.10120021 <https://doi.org/10.5281/zenodo.10120021>`_
47
48 Quickstart
49 ----------
50
51 Install the ptufile package and all dependencies from the
52 `Python Package Index <https://pypi.org/project/ptufile/>`_::
53
54 python -m pip install -U "ptufile[all]"
55
56 See `Examples`_ for using the programming interface.
57
58 Source code and support are available on
59 `GitHub <https://github.com/cgohlke/ptufile>`_.
60
61 Requirements
62 ------------
63
64 This revision was tested with the following requirements and dependencies
65 (other versions may work):
66
67 - `CPython <https://www.python.org>`_ 3.12.10, 3.13.15, 3.14.7, 3.15.0rc 64-bit
68 - `Numpy <https://pypi.org/project/numpy>`_ 2.5.2
69 - `Xarray <https://pypi.org/project/xarray>`_ 2026.7.0 (recommended)
70 - `Matplotlib <https://pypi.org/project/matplotlib/>`_ 3.11.1 (optional)
71 - `Tifffile <https://pypi.org/project/tifffile/>`_ 2026.7.31 (optional)
72 - `Numcodecs <https://pypi.org/project/numcodecs/>`_ 0.16.5 (optional)
73 - `Python-dateutil <https://pypi.org/project/python-dateutil/>`_ 2.9.0
74 (optional)
75 - `Cython <https://pypi.org/project/cython/>`_ 3.2.9 (build)
76
77 Revisions
78 ---------
79
80 2026.8.8
81
82 - Add PQOVER file type.
83
84 2026.6.6
85
86 - Remove memmap parameter from PtuFile.read_records (breaking).
87 - Return copy of records from PtuFile.read_records by default (breaking).
88 - Add options for memory-mapping and locked reading to BinaryFile.
89 - Add option to memory-map PTU files.
90 - Drop support for numpy 2.0 (SPEC0).
91 - Support Python 3.15.
92
93 2026.3.21
94
95 - Add bounds checking to encode_t3_image function.
96 - Use format-dispatch in hot decode loops to allow compiler inlining.
97 - Build wheels on Windows with LLVM (30% faster decoding than MSVC).
98 - Drop support for Python 3.11.
99
100 2026.2.6
101
102 - Fix code review issues.
103
104 2026.1.14
105
106 - Improve code quality.
107
108 2025.12.12
109
110 - Add PQUNI file type.
111 - Add attrs properties and return with xarray DataSets.
112 - Improve code quality.
113
114 2025.11.8
115
116 - Fix reading files with negative TTResult_NumberOfRecords.
117 - Remove cache argument from PtuFile.read_records (breaking).
118 - Add cache_records property to PtuFile to control caching behavior.
119 - Derive PqFileError from ValueError.
120 - Factor out BinaryFile base class.
121 - Build ABI3 wheels.
122
123 2025.9.9
124
125 - Log error when decoding image with invalid line or frame masks.
126
127 2025.7.30
128
129 - Add option to specify pixel time for decoding images.
130 - Add functions to read and write PicoQuant BIN files.
131 - Drop support for Python 3.10.
132
133 2025.5.10
134
135 - Mark Cython extension free-threading compatible.
136 - Support Python 3.14.
137
138 2025.2.20
139
140 - …
141
142 Refer to the CHANGES file for older revisions.
143
144 Notes
145 -----
146
147 `PicoQuant GmbH <https://www.picoquant.com/>`_ is a manufacturer of photonic
148 components and instruments.
149
150 The PicoQuant unified file formats are documented at the
151 `PicoQuant-Time-Tagged-File-Format-Demos
152 <https://github.com/PicoQuant/PicoQuant-Time-Tagged-File-Format-Demos/tree/master/doc>`_.
153
154 All PicoQuant unified tagged formats use the same basic layout:
155 a file header followed by typed tags and an optional data block. PTU is
156 the main container for TTTR event streams, whereas related formats store
157 histograms, instrument settings, analysis results, or other auxiliary data.
158
159 The following features are currently not implemented due to the lack of
160 test files or documentation: PT2 and PT3 files, decoding images from
161 T2 and SPQR formats, bidirectional per frame, and deprecated image
162 reconstruction.
163
164 Compatibility with PTU files written by non-PicoQuant software (for example,
165 Leica LAS X or Abberior Imspector) is limited, as is decoding line,
166 bidirectional, and sinusoidal scanning.
167
168 Other modules for reading or writing PicoQuant files are
169 `Read_PTU.py
170 <https://github.com/PicoQuant/PicoQuant-Time-Tagged-File-Format-Demos/blob/master/PTU/Python/Read_PTU.py>`_,
171 `readPTU <https://github.com/qpl-public/readPTU>`_,
172 `readPTU_FLIM <https://github.com/SumeetRohilla/readPTU_FLIM>`_,
173 `fastFLIM <https://github.com/RobertMolenaar-UT/fastFLIM>`_,
174 `PyPTU <https://gitlab.inria.fr/jrye/pyptu>`_,
175 `PTU_Reader <https://github.com/UU-cellbiology/PTU_Reader>`_,
176 `PTU_Writer <https://github.com/ekatrukha/PTU_Writer>`_,
177 `FlimReader <https://github.com/flimfit/FlimReader>`_,
178 `tangy <https://github.com/Peter-Barrow/tangy>`_,
179 `tttrlib <https://github.com/Fluorescence-Tools/tttrlib>`_,
180 `picoquantio <https://github.com/tsbischof/picoquantio>`_,
181 `ptuparser <https://pypi.org/project/ptuparser/>`_,
182 `phconvert <https://github.com/Photon-HDF5/phconvert/>`_,
183 `trattoria <https://pypi.org/project/trattoria/>`_ (wrapper of
184 `trattoria-core <https://pypi.org/project/trattoria-core/>`_,
185 `tttr-toolbox <https://github.com/GCBallesteros/tttr-toolbox/>`_),
186 `PAM <https://gitlab.com/PAM-PIE/PAM/-/blob/master/functions/readin/Read_PTU.m>`_,
187 `FLOPA <https://github.com/IMCF-Biocev/FLOPA/tree/main/src/flopa/io/ptuio>`_,
188 `FLIMKit <https://github.com/alex1075/flim-native-decoders/tree/main/flim_native_decoders/ptu>`_,
189 and
190 `napari-flim-phasor-plotter
191 <https://github.com/zoccoler/napari-flim-phasor-plotter/blob/0.0.6/src/napari_flim_phasor_plotter/_io/readPTU_FLIM.py>`_.
192
193 Examples
194 --------
195
196 Import functions and classes used in these examples:
197
198 >>> from ptufile import PqFile, PtuFile, imwrite, imread
199
200 Read properties and tags from any type of PicoQuant unified tagged file:
201
202 >>> pq = PqFile('tests/data/Settings.pfs')
203 >>> pq.type
204 <PqFileType.PFS: ...>
205 >>> pq.guid
206 UUID('86d428e2-cb0b-4964-996c-04456ba6be7b')
207 >>> pq.tags
208 {...'CreatorSW_Name': 'SymPhoTime 64', 'CreatorSW_Version': '2.1'...}
209 >>> pq.close()
210
211 Read metadata from a PicoQuant PTU FLIM file:
212
213 >>> ptu = PtuFile('tests/data/FLIM.ptu')
214 >>> ptu.type
215 <PqFileType.PTU: ...>
216 >>> ptu.record_type
217 <PtuRecordType.PicoHarpT3: 66307>
218 >>> ptu.measurement_mode
219 <PtuMeasurementMode.T3: 3>
220 >>> ptu.measurement_submode
221 <PtuMeasurementSubMode.IMAGE: 3>
222
223 Decode TTTR records from the PTU file to ``numpy.recarray``:
224
225 >>> decoded = ptu.decode_records()
226 >>> decoded.dtype
227 dtype([('time', '<u8'), ('dtime', '<i2'), ('channel', 'i1'), ('marker', 'u1')])
228
229 Get global times of frame changes from markers:
230
231 >>> decoded['time'][(decoded['marker'] & ptu.frame_change_mask) > 0]
232 array([1571185680], dtype=uint64)
233
234 Decode TTTR records to overall delay-time histograms per channel:
235
236 >>> ptu.decode_histogram(dtype='uint8')
237 array([[ 5, 7, 7, ..., 10, 9, 2]], shape=(2, 3126), dtype=uint8)
238
239 Get information about the FLIM image histogram in the PTU file:
240
241 >>> ptu.shape
242 (1, 256, 256, 2, 3126)
243 >>> ptu.dims
244 ('T', 'Y', 'X', 'C', 'H')
245 >>> ptu.coords
246 {'T': ..., 'Y': ..., 'X': ..., 'H': ...}
247 >>> ptu.dtype
248 dtype('uint16')
249 >>> ptu.active_channels
250 (0, 1)
251
252 Decode parts of the image histogram to ``numpy.ndarray`` using slice notation.
253 Slice step sizes define binning, -1 being used to integrate along axis:
254
255 >>> ptu[:, ..., 0, ::-1]
256 array([[[103, ..., 38],
257 ...
258 [ 47, ..., 30]]],
259 shape=(1, 256, 256), dtype=uint16)
260
261 Alternatively, decode the first channel and integrate all histogram bins
262 into a ``xarray.DataArray``, keeping reduced axes:
263
264 >>> ptu.decode_image(channel=0, dtime=-1, asxarray=True)
265 <xarray.DataArray (T: 1, Y: 256, X: 256, C: 1, H: 1)> ...
266 array([[[[[103]],
267 ...
268 [[ 30]]]]], shape=(1, 256, 256, 1, 1), dtype=uint16)
269 Coordinates:
270 * T (T) float64... 0.05625
271 * Y (Y) float64... -0.0001304 ... 0.0001294
272 * X (X) float64... -0.0001304 ... 0.0001294
273 * C (C) uint8... 0
274 * H (H) float64... 0.0
275 Attributes...
276 name: FLIM.ptu
277 ...
278
279 Write the TCSPC histogram and metadata to a PicoHarpT3 image mode PTU file:
280
281 >>> imwrite(
282 ... '_test.ptu',
283 ... ptu[:],
284 ... ptu.global_resolution,
285 ... ptu.tcspc_resolution,
286 ... # optional metadata
287 ... pixel_time=ptu.pixel_time,
288 ... record_type=PtuRecordType.PicoHarpT3,
289 ... comment='Written by ptufile.py',
290 ... tags={'File_RawData_GUID': [ptu.guid]},
291 ... )
292
293 Read back the TCSPC histogram from the file:
294
295 >>> tcspc_histogram = imread('_test.ptu')
296 >>> import numpy
297 >>> numpy.array_equal(tcspc_histogram, ptu[:])
298 True
299
300 Close the file handle:
301
302 >>> ptu.close()
303
304 Preview the image and metadata in a PTU file from the console::
305
306 python -m ptufile tests/data/FLIM.ptu
307
308 """
309
310 from __future__ import annotations
311
312 __version__ = '2026.8.8'
313
314 __all__ = [
315 'FILE_EXTENSIONS',
316 'T2_RECORD_DTYPE',
317 'T3_RECORD_DTYPE',
318 'PhuFile',
319 'PhuMeasurementMode',
320 'PhuMeasurementSubMode',
321 'PqFile',
322 'PqFileError',
323 'PqFileType',
324 'PtuFile',
325 'PtuHwFeatures',
326 'PtuMeasurementMode',
327 'PtuMeasurementSubMode',
328 'PtuMeasurementWarnings',
329 'PtuRecordType',
330 'PtuScanDirection',
331 'PtuScannerType',
332 'PtuStopReason',
333 'PtuWriter',
334 '__version__',
335 'binread',
336 'binwrite',
337 'imread',
338 'imwrite',
339 ]
340
341 import contextlib
342 import dataclasses
343 import enum
344 import io
345 import logging
346 import math
347 import mmap
348 import os
349 import struct
350 import sys
351 import threading
352 import uuid
353 from datetime import datetime, timedelta
354 from functools import cached_property
355 from typing import TYPE_CHECKING, final, overload, override
356
357 if TYPE_CHECKING:
358 from collections.abc import Iterable, Sequence
359 from types import EllipsisType, TracebackType
360 from typing import IO, Any, ClassVar, Literal, Self
361
362 from numpy.typing import ArrayLike, DTypeLike, NDArray
363 from xarray import DataArray
364
365 import numpy
366
367 type Dimension = Literal['T', 'C', 'H']
368 type OutputType = str | IO[bytes] | NDArray[Any] | None
369
370
371 @overload
372 def imread(
373 file: str | os.PathLike[str] | IO[bytes],
374 /,
375 selection: Sequence[int | slice | EllipsisType | None] | None = None,
376 *,
377 dtype: DTypeLike | None = None,
378 channel: int | None = None,
379 frame: int | None = None,
380 dtime: int | None = None,
381 pixel_time: float | None = None,
382 bishift: int | None = None,
383 trimdims: Sequence[Dimension] | str | None = None,
384 keepdims: bool = True,
385 memmap: bool = False,
386 asxarray: Literal[False] = ...,
387 out: OutputType = None,
388 ) -> NDArray[Any]: ...
389
390
391 @overload
392 def imread(
393 file: str | os.PathLike[str] | IO[bytes],
394 /,
395 selection: Sequence[int | slice | EllipsisType | None] | None = None,
396 *,
397 dtype: DTypeLike | None = None,
398 channel: int | None = None,
399 frame: int | None = None,
400 dtime: int | None = None,
401 pixel_time: float | None = None,
402 bishift: int | None = None,
403 trimdims: Sequence[Dimension] | str | None = None,
404 keepdims: bool = True,
405 memmap: bool = False,
406 asxarray: Literal[True] = ...,
407 out: OutputType = None,
408 ) -> DataArray: ...
409
410
411 @overload
412 def imread(
413 file: str | os.PathLike[str] | IO[bytes],
414 /,
415 selection: Sequence[int | slice | EllipsisType | None] | None = None,
416 *,
417 dtype: DTypeLike | None = None,
418 channel: int | None = None,
419 frame: int | None = None,
420 dtime: int | None = None,
421 pixel_time: float | None = None,
422 bishift: int | None = None,
423 trimdims: Sequence[Dimension] | str | None = None,
424 keepdims: bool = True,
425 memmap: bool = False,
426 asxarray: bool = False,
427 out: OutputType = None,
428 ) -> NDArray[Any] | DataArray: ...
429
430
431 def imread(
432 file: str | os.PathLike[str] | IO[bytes],
433 /,
434 selection: Sequence[int | slice | EllipsisType | None] | None = None,
435 *,
436 dtype: DTypeLike | None = None,
437 channel: int | None = None,
438 frame: int | None = None,
439 dtime: int | None = None,
440 pixel_time: float | None = None,
441 bishift: int | None = None,
442 trimdims: Sequence[Dimension] | str | None = None,
443 keepdims: bool = True,
444 memmap: bool = False,
445 asxarray: bool = False,
446 out: OutputType = None,
447 ) -> NDArray[Any] | DataArray:
448 """Return decoded image histogram from T3 mode PTU file.
449
450 Parameters:
451 file:
452 File name or seekable binary stream.
453 selection, dtype, channel, frame, dtime, pixel_time, bishift,\
454 keepdims, asxarray, out:
455 Passed to :py:meth:`PtuFile.decode_image`.
456 trimdims, memmap:
457 Passed to :py:class:`PtuFile`.
458
459 Returns:
460 image:
461 Decoded TTTR T3 records as up to 5-dimensional image array.
462
463 """
464 with PtuFile(file, trimdims=trimdims, memmap=memmap) as ptu:
465 return ptu.decode_image(
466 selection,
467 dtype=dtype,
468 channel=channel,
469 frame=frame,
470 dtime=dtime,
471 bishift=bishift,
472 pixel_time=pixel_time,
473 keepdims=keepdims,
474 asxarray=asxarray,
475 out=out,
476 )
477
478
479 def imwrite(
480 file: str | os.PathLike[str] | IO[bytes],
481 data: ArrayLike,
482 /,
483 global_resolution: float,
484 tcspc_resolution: float,
485 pixel_time: float | None = None,
486 *,
487 has_frames: bool | None = None,
488 record_type: PtuRecordType | None = None,
489 pixel_resolution: float | None = None,
490 guid: str | uuid.UUID | None = None,
491 comment: str | None = None,
492 datetime: datetime | None = None,
493 tags: dict[str, Any] | None = None,
494 mode: Literal['w', 'wb', 'x', 'xb'] | None = None,
495 ) -> None:
496 """Write TCSPC histogram to T3 image mode PTU file.
497
498 Parameters:
499 file:
500 File name or writable binary stream.
501 data:
502 TCSPC histogram image stack.
503 The order of dimensions must be 'TYXCH', 'YXH', 'YXCH',
504 or 'TYXH' (with ``has_frames=True``).
505 The dtype must be unsigned integer.
506 global_resolution:
507 Resolution of time tags in s, typically in ns range.
508 The inverse of the synctime or laser frequency.
509 One photon is encoded per time tag.
510 tcspc_resolution:
511 Resolution of TCSPC in s, typically in ps range.
512 The width of a histogram bin.
513 pixel_time:
514 Time per pixel in s, typically in μs range.
515 Photons that cannot be encoded within pixel_time are omitted.
516 By default, pixel_time is set just large enough to encode all
517 photons.
518 has_frames:
519 4-dimensional data have frames in first axis ('TYXH'), no channels.
520 By default, true if data contains metadata specifying the first
521 dimension is 'T', else false.
522 record_type, pixel_resolution, guid, comment, datetime, tags, mode:
523 Optional parameters passed to :py:class:`PtuWriter`.
524
525 """
526 if hasattr(data, 'dims'):
527 has_frames = 'T' in data.dims and data.dims[0] == 'T'
528
529 data = numpy.asarray(data)
530
531 if pixel_time is None:
532 data = data.reshape(
533 PtuWriter.normalize_shape(data.shape, has_frames=has_frames)
534 )
535 pixel_time = global_resolution * max(
536 1, float(numpy.max(data.sum(axis=(3, 4), dtype=numpy.uint64)))
537 )
538
539 with PtuWriter(
540 file,
541 data.shape,
542 global_resolution,
543 tcspc_resolution,
544 pixel_time,
545 record_type=record_type,
546 pixel_resolution=pixel_resolution,
547 has_frames=has_frames,
548 guid=guid,
549 comment=comment,
550 datetime=datetime,
551 tags=tags,
552 mode=mode,
553 ) as ptu:
554 ptu.write(data)
555
556
557 @final
558 class PtuWriter:
559 """Write TCSPC histogram to T3 image mode PTU file.
560
561 T3 TTTR records allow for a maximum of 63 channels and 32768 bins.
562 The TTTR records written can only be used to reconstruct the encoded
563 TCSPC histogram image stack, not for higher-than-pixel-time-resolution
564 intensity time-trace or correlation analysis.
565
566 Parameters:
567 file:
568 File name or writable binary stream.
569 File names typically end in '.PTU'.
570 shape:
571 Shape of TCSPC histogram image stack to write.
572 The order of dimensions must be 'TYXCH', 'YXH', 'YXCH',
573 or 'TYXH' (with ``has_frames=True``).
574 global_resolution:
575 Resolution of time tags in s, typically in ns range.
576 The inverse of the synctime or laser frequency.
577 One photon is encoded per time tag.
578 tcspc_resolution:
579 Resolution of TCSPC in s, typically in ps range.
580 The width of a histogram bin.
581 pixel_time:
582 Time per pixel in s, typically in μs range.
583 Photons that cannot be encoded within pixel_time are omitted.
584 record_type:
585 Type of TTTR T3 records to write.
586 By default, write ``PicoHarpT3`` records for up to two channels
587 and 4096 bins, else ``GenericT3``.
588 pixel_resolution:
589 Resolution of single pixel in μm. The default is 1 μm.
590 has_frames:
591 4-dimensional shape has frames in first axis ('TYXH'), no channels.
592 guid:
593 Windows formatted GUID used as global file identifier.
594 By default, a random GUID. Write to File_GUID tag.
595 comment:
596 File comment. Write to File_Comment tag.
597 datetime:
598 File creation date and time.
599 The default is time at function call.
600 Write to File_CreatingTime tag.
601 tags:
602 Additional tag Id and values to write.
603 Critical tags are automatically set and cannot be modified.
604 No validation is performed.
605 Refer to the "PicoQuant Unified Tag Dictionary" for valid Id and
606 values.
607 mode:
608 Binary file open mode if ``file`` is file name.
609 The default is 'w', which opens files for writing, truncating
610 existing files.
611 'x' opens files for exclusive creation, failing on existing files.
612
613 Raises:
614 ValueError
615 Not ``0 < tcspc_resolution <= global_resolution <= pixel_time``.
616
617 """
618
619 _fh: IO[bytes] | None
620 _shape: tuple[int, int, int, int, int]
621 _record_type: PtuRecordType
622 _number_records: int
623 _number_records_offset: int
624 _number_frames: int
625 _number_frames_offset: int
626 _global_resolution: float
627 _tcspc_resolution: float
628 _pixel_time: int
629
630 _line_start = 1
631 _line_stop = 2
632 _frame_change = 3
633
634 def __init__(
635 self,
636 file: str | os.PathLike[str] | IO[bytes],
637 /,
638 shape: tuple[int, ...],
639 global_resolution: float,
640 tcspc_resolution: float,
641 pixel_time: float,
642 *,
643 record_type: PtuRecordType | None = None,
644 pixel_resolution: float | None = None,
645 has_frames: bool | None = None,
646 guid: str | uuid.UUID | None = None,
647 comment: str | None = None,
648 datetime: datetime | None = None,
649 tags: dict[str, Any] | None = None,
650 mode: Literal['w', 'wb', 'x', 'xb'] | None = None,
651 ) -> None:
652 """Write PTU header to file."""
653 # 0 < tcspc_resolution <= global_resolution <= pixel_time
654 if tcspc_resolution <= 0.0:
655 msg = f'{tcspc_resolution=} <= 0.0'
656 raise ValueError(msg)
657 if tcspc_resolution > global_resolution:
658 msg = f'{tcspc_resolution=} > {global_resolution=}'
659 raise ValueError(msg)
660 if pixel_time < global_resolution:
661 msg = f'{pixel_time=} < {global_resolution=}'
662 raise ValueError(msg)
663
664 self._fh = None
665 self._number_records = 0
666 self._number_records_offset = 0
667 self._number_frames = 0
668 self._number_frames_offset = 0
669 self._global_resolution = global_resolution
670 self._tcspc_resolution = tcspc_resolution
671 self._pixel_time = round(pixel_time / global_resolution)
672 self._shape = shape = PtuWriter.normalize_shape(
673 shape, has_frames=has_frames
674 )
675
676 if record_type is None:
677 if shape[3] <= 2 and shape[4] <= 4096:
678 record_type = PtuRecordType.PicoHarpT3
679 else:
680 record_type = PtuRecordType.GenericT3
681
682 if record_type == PtuRecordType.PicoHarpT3:
683 if shape[3] > 4 or shape[4] > 4096:
684 msg = (
685 f'{record_type=} does not support '
686 f'{shape[3]} channels and {shape[4]} bins'
687 )
688 raise ValueError(msg)
689 self._record_type = PtuRecordType.PicoHarpT3
690 elif record_type in {
691 PtuRecordType.GenericT3,
692 PtuRecordType.HydraHarp2T3,
693 PtuRecordType.TimeHarp260NT3,
694 PtuRecordType.TimeHarp260PT3,
695 }:
696 if shape[3] > 63 or shape[4] > 32768:
697 msg = (
698 f'{record_type=} does not support '
699 f'{shape[3]} channels and {shape[4]} bins'
700 )
701 raise ValueError(msg)
702 self._record_type = PtuRecordType.GenericT3
703 else:
704 msg = f'{record_type=} not supported'
705 raise ValueError(msg)
706
707 if comment is None:
708 comment = ''
709
710 if guid is None:
711 guid = f'{{{uuid.uuid4()}}}'
712 elif isinstance(guid, uuid.UUID):
713 guid = f'{{{guid}}}'
714 elif len(guid) != 38 or guid[9] != '-':
715 msg = 'invalid GUID'
716 raise ValueError(msg)
717
718 if pixel_resolution is None:
719 pixel_resolution = 1.0
720 elif pixel_resolution <= 0.0:
721 msg = f'{pixel_resolution=} <= 0.0'
722 raise ValueError(msg)
723
724 if datetime is None:
725 datetime = now()
726
727 critical_tags = {
728 # tags not to be overwritten by user
729 'Measurement_Mode': PtuMeasurementMode.T3,
730 'Measurement_SubMode': PtuMeasurementSubMode.IMAGE,
731 'MeasDesc_GlobalResolution': float(self._global_resolution),
732 'MeasDesc_Resolution': float(self._tcspc_resolution),
733 'MeasDesc_BinningFactor': 1,
734 'TTResult_NumberOfRecords': self._number_records,
735 'TTResult_SyncRate': round(1.0 / self._global_resolution),
736 'TTResultFormat_TTTRRecType': self._record_type,
737 'TTResultFormat_BitsPerRecord': 32,
738 'ImgHdr_Dimensions': 3,
739 'ImgHdr_Ident': PtuScannerType.LSM,
740 'ImgHdr_LineStart': self._line_start,
741 'ImgHdr_LineStop': self._line_stop,
742 'ImgHdr_Frame': self._frame_change,
743 'ImgHdr_MaxFrames': 0,
744 'ImgHdr_TimePerPixel': pixel_time * 1e3, # ms
745 'ImgHdr_PixX': int(self._shape[2]),
746 'ImgHdr_PixY': int(self._shape[1]),
747 'ImgHdr_BiDirect': False,
748 'ImgHdr_SinCorrection': 0,
749 }
750 pqtags = {
751 # required tags written first, allowed to be overwritten by user
752 'File_GUID': guid,
753 'File_Comment': comment,
754 'File_CreatingTime': datetime,
755 'CreatorSW_Name': 'ptufile.py',
756 'CreatorSW_Version': __version__,
757 }
758 pqtags.update(critical_tags)
759 pqtags.update(
760 # other tags allowed to be overwritten by user
761 {
762 'ImgHdr_PixResol': float(pixel_resolution),
763 'HW_InpChannels': self._shape[3] + 1, # used by FlimReader
764 # 'TTResult_StopReason': PtuStopReason(0)
765 }
766 )
767 if tags is not None:
768 # add user tags but do not overwrite critical tags
769 pqtags.update(
770 {k: v for k, v in tags.items() if k not in critical_tags}
771 )
772
773 header_list = [b'PQTTTR\x00\x001.0.00\x00\x00'] # magic and version
774 for tagid, value in pqtags.items():
775 if isinstance(value, (list, tuple)):
776 for index, item in enumerate(value):
777 header_list.append(encode_tag(tagid, item, index))
778 else:
779 header_list.append(encode_tag(tagid, value))
780 header_list.append(encode_tag('Header_End', None))
781
782 header = b''.join(header_list)
783 offset = header.find(b'TTResult_NumberOfRecords')
784 if offset < 0:
785 msg = 'TTResult_NumberOfRecords tag not found in header'
786 raise RuntimeError(msg)
787 self._number_records_offset = offset + 40
788
789 offset = header.find(b'ImgHdr_MaxFrames')
790 if offset < 0:
791 msg = 'ImgHdr_MaxFrames tag not found in header'
792 raise RuntimeError(msg)
793 self._number_frames_offset = offset + 40
794
795 if isinstance(file, (str, os.PathLike)):
796 if mode is None:
797 mode = 'wb'
798 elif mode[-1] != 'b':
799 mode += 'b' # type: ignore[assignment]
800 self._fh = open(file, mode) # noqa: SIM115
801 self._close = True
802 elif hasattr(file, 'write') and hasattr(file, 'seek'):
803 self._fh = file
804 self._close = False
805 else:
806 msg = f'cannot write to {type(file)=}'
807 raise ValueError(msg)
808
809 self._fh.write(header)
810
811 def write(self, data: ArrayLike, /) -> None:
812 """Append T3 encoded TCSPC histogram to file.
813
814 Parameters:
815 data:
816 TCSPC histogram image stack.
817 The shape must be compatible with the shape passed to
818 PtuWriter(). The dtype must be unsigned integer.
819
820 """
821 from ._ptufile import encode_t3_image
822
823 data = numpy.asarray(data)
824 if data.dtype.kind != 'u':
825 msg = f'{data.dtype=} is not an unsigned integer'
826 raise ValueError(msg)
827 data = data.reshape(self._shape)
828
829 number_photons = int(data.sum(dtype=numpy.uint64))
830
831 if self._record_type == PtuRecordType.PicoHarpT3:
832 maxtime = 65536
833 else:
834 maxtime = 1024
835
836 shape = data.shape
837 number_records = (
838 number_photons
839 # overflows assuming all empty pixels
840 + (shape[0] * shape[1] * shape[2] * self._pixel_time) // maxtime
841 # line markers
842 + shape[0] * shape[1] * 2
843 # frame markers
844 + shape[0]
845 )
846 records = numpy.zeros(number_records, dtype=numpy.uint32)
847
848 number_records = encode_t3_image(
849 records,
850 data,
851 self._record_type,
852 self._pixel_time,
853 int(2 ** (self._line_start - 1)),
854 int(2 ** (self._line_stop - 1)),
855 int(2 ** (self._frame_change - 1)),
856 )
857 if number_records < 0:
858 msg = f'{number_records=} < 0'
859 raise ValueError(msg)
860
861 if self._fh is None:
862 msg = 'file handle is closed'
863 raise RuntimeError(msg)
864 self._fh.write(records[:number_records].tobytes())
865
866 self._number_records += number_records
867 self._number_frames += shape[0]
868
869 def close(self) -> None:
870 """Close file handle after writing final tag values."""
871 if self._fh is None:
872 return
873
874 if self._number_records_offset > 0:
875 self._fh.seek(self._number_records_offset)
876 self._fh.write(struct.pack('<q', self._number_records))
877 self._fh.seek(self._number_frames_offset)
878 self._fh.write(struct.pack('<q', self._number_frames))
879
880 if self._close:
881 with contextlib.suppress(Exception):
882 self._fh.close()
883 self._fh = None
884
885 def __enter__(self) -> Self:
886 return self
887
888 def __exit__(
889 self,
890 exc_type: type[BaseException] | None,
891 exc_value: BaseException | None,
892 traceback: TracebackType | None,
893 ) -> None:
894 self.close()
895
896 @staticmethod
897 def normalize_shape(
898 shape: tuple[int, ...],
899 /,
900 *,
901 has_frames: bool | None = None,
902 ) -> tuple[int, int, int, int, int]:
903 """Return TCSPC histogram shape normalized to 5D 'TYXCH'."""
904 ndim = len(shape)
905 if ndim == 5:
906 'TYXCH'
907 return shape # type: ignore[return-value]
908 if ndim == 3:
909 # 'YXH'
910 return (1, shape[0], shape[1], 1, shape[2])
911 if ndim == 4:
912 if has_frames:
913 # 'TYXH'
914 return (shape[0], shape[1], shape[2], 1, shape[3])
915 # 'YXCH'
916 return (1, shape[0], shape[1], shape[2], shape[3])
917
918 msg = f'invalid number of dimensions {len(shape)=}'
919 raise ValueError(msg)
920
921
922 class PqFileType(enum.Enum):
923 """PicoQuant file type identifiers."""
924
925 PTU = b'PQTTTR\0\0'
926 """TTTR file, PTU, contains raw data in unified TTTR-format."""
927
928 PHU = b'PQHISTO\0'
929 """Histogram file, PHU, contains TCSPC histograms."""
930
931 PCK = b'PQCHECK\0'
932 """Internal file, PCK, contains post-acquisition analysis results."""
933
934 PCO = b'PQCOMNT\0'
935 """Comment file, PCO, contains manually entered text."""
936
937 PFS = b'PQDEFLT\0'
938 """Settings file, PFS or PUS, contains factory or user setting defaults."""
939
940 PQRES = b'PQRESLT\0'
941 """Result file, PQRES, contains analysis generated during measurement."""
942
943 PQDAT = b'PQDATA\0\0'
944 """Data file, PQDAT, contains undocumented data."""
945
946 PQUNI = b'PQUNI\0\0\0'
947 """UniHarp file, PQUNI, contains memory and measured data."""
948
949 PQOVER = b'PQOVER\0\0'
950 """Unknown file, PQOVER, contains undocumented data."""
951
952 SPQR = b'PQSPQR\0\0'
953 """Unknown file, SPQR, contains undocumented data."""
954
955
956 class PqFileError(ValueError):
957 """Exception to indicate invalid PicoQuant tagged file structure."""
958
959
960 class BinaryFile:
961 """Binary file.
962
963 Parameters:
964 file:
965 File name or seekable binary stream.
966 mode:
967 File open mode if ``file`` is a file name.
968 If not specified, defaults to ``'r'``. Files are always opened
969 in binary mode.
970 memmap:
971 Map file into memory.
972 Ignored if memory mapping is not available or if the stream does
973 not support it.
974
975 Notes:
976 Memory mapping can improve random-access read performance on large
977 files or repeated reads of the same file regions by reducing syscall
978 overhead and data copying.
979 For sequential one-pass reads, regular buffered I/O may be faster.
980
981 Raises:
982 TypeError:
983 File is a text stream, or an unsupported type.
984 ValueError:
985 Invalid file name, extension, or stream.
986 File stream is not seekable.
987
988 """
989
990 _fh: IO[bytes]
991 _mm: mmap.mmap | None
992 _mv: memoryview | None # view of _mm
993 _path: str # absolute path of file
994 _name: str # name of file or handle
995 _close: bool # file needs to be closed
996 _closed: bool # file is closed
997 _memmap: bool # open companion files using memmap
998 _lock: contextlib.AbstractContextManager[Any]
999 _ext: ClassVar[set[str]] = set() # valid extensions, empty for any
1000
1001 def __init__(
1002 self,
1003 file: str | os.PathLike[str] | IO[bytes],
1004 /,
1005 *,
1006 mode: Literal['r', 'r+'] | None = None,
1007 memmap: bool = False,
1008 ) -> None:
1009
1010 self._mm = None
1011 self._mv = None
1012 self._path = ''
1013 self._name = 'Unnamed'
1014 self._close = False
1015 self._closed = False
1016 self._memmap = bool(memmap)
1017 self._lock = contextlib.nullcontext()
1018
1019 if isinstance(file, (str, os.PathLike)):
1020 ext = os.path.splitext(file)[-1].lower()
1021 if self._ext and ext not in self._ext:
1022 msg = f'invalid file extension: {ext!r} not in {self._ext!r}'
1023 raise ValueError(msg)
1024 if mode is None:
1025 mode = 'r'
1026 else:
1027 if mode[-1:] == 'b':
1028 # accept 'rb'/'r+b'
1029 mode = mode[:-1] # type: ignore[assignment]
1030 if mode not in {'r', 'r+'}:
1031 msg = f'invalid {mode=!r}'
1032 raise ValueError(msg)
1033 self._path = os.path.abspath(file)
1034 self._close = True
1035 self._fh = open(self._path, mode + 'b') # noqa: SIM115
1036
1037 elif hasattr(file, 'seek'):
1038 # binary stream: open file, BytesIO, fsspec LocalFileOpener
1039 if isinstance(file, io.TextIOBase): # type: ignore[unreachable]
1040 msg = ( # type: ignore[unreachable]
1041 f'{file=!r} is not open in binary mode'
1042 )
1043 raise TypeError(msg)
1044
1045 self._fh = file
1046 try:
1047 self._fh.tell()
1048 except Exception as exc:
1049 msg = f'{file=!r} is not seekable'
1050 raise ValueError(msg) from exc
1051 if hasattr(file, 'path'):
1052 self._path = os.path.abspath(file.path)
1053 elif hasattr(file, 'name'):
1054 self._path = os.path.abspath(file.name)
1055
1056 elif hasattr(file, 'open'):
1057 # fsspec OpenFile
1058 self._fh = file.open()
1059 self._close = True
1060 try:
1061 self._fh.tell()
1062 except Exception as exc:
1063 with contextlib.suppress(Exception):
1064 self._fh.close()
1065 msg = f'{file=!r} is not seekable'
1066 raise ValueError(msg) from exc
1067 if hasattr(file, 'path'):
1068 self._path = os.path.abspath(file.path)
1069
1070 else:
1071 msg = f'cannot handle {type(file)=}'
1072 raise TypeError(msg)
1073
1074 if hasattr(file, 'name') and file.name:
1075 self._name = os.path.basename(file.name)
1076 elif self._path:
1077 self._name = os.path.basename(self._path)
1078 else:
1079 self._name = type(file).__name__
1080
1081 if memmap:
1082 _fh: Any = self._fh
1083 if isinstance(_fh, mmap.mmap):
1084 self._mm = _fh
1085 self._mv = memoryview(self._mm)
1086 else:
1087 try:
1088 access = (
1089 mmap.ACCESS_WRITE
1090 if self._fh.writable()
1091 else mmap.ACCESS_READ
1092 )
1093 self._mm = mmap.mmap(self._fh.fileno(), 0, access=access)
1094 self._mv = memoryview(self._mm)
1095 except OSError:
1096 pass
1097
1098 @property
1099 def filehandle(self) -> IO[bytes]:
1100 """File handle."""
1101 return self._fh
1102
1103 @property
1104 def filepath(self) -> str:
1105 """Absolute path to file, or empty string if no path is available."""
1106 return self._path
1107
1108 @property
1109 def filename(self) -> str:
1110 """Basename of file path, or empty string if no path is available."""
1111 return os.path.basename(self._path)
1112
1113 @property
1114 def dirname(self) -> str:
1115 """Directory containing file, or empty string if no path available."""
1116 return os.path.dirname(self._path)
1117
1118 @property
1119 def name(self) -> str:
1120 """Display name of file."""
1121 return self._name
1122
1123 @name.setter
1124 def name(self, value: str) -> None:
1125 self._name = value
1126
1127 @property
1128 def attrs(self) -> dict[str, Any]:
1129 """Selected metadata as dict."""
1130 return {'name': self.name, 'filepath': self.filepath}
1131
1132 @property
1133 def lock(self) -> contextlib.AbstractContextManager[Any]:
1134 """Lock for thread-safe file access."""
1135 return self._lock
1136
1137 def set_lock(self, enabled: bool, /) -> None: # noqa: FBT001
1138 """Enable or disable thread-safe file access.
1139
1140 Parameters:
1141 enabled:
1142 If true, use a threading.RLock, else a no-op lock.
1143 Has no effect when memory-mapped I/O is active.
1144
1145 """
1146 if self._mm is not None:
1147 return
1148 self._lock = threading.RLock() if enabled else contextlib.nullcontext()
1149
1150 def _write_at(
1151 self, offset: int, data: bytes | bytearray | memoryview, /
1152 ) -> None:
1153 """Write bytes to file at given offset.
1154
1155 Parameters:
1156 offset: Byte offset from start of file.
1157 data: Data to write.
1158
1159 """
1160 if self._mm is not None and self.writable:
1161 # writable mmap: direct slice write, no cursor movement
1162 self._mm[offset : offset + len(data)] = data
1163 else:
1164 with self._lock:
1165 self._fh.seek(offset)
1166 self._fh.write(data)
1167
1168 def _read_at(self, offset: int, size: int, /) -> bytes | memoryview:
1169 """Read bytes from file at given offset.
1170
1171 For memory-mapped files, returned bytes are exposed as a
1172 ``memoryview`` of the mapping. Keeping that view alive may keep
1173 the memory map (and associated file resources/lock) alive.
1174
1175 Parameters:
1176 offset: Byte offset from start of file.
1177 size: Number of bytes to read.
1178
1179 """
1180 mv = self._mv
1181 if mv is not None:
1182 return mv[offset : offset + size]
1183 fh = self._fh
1184 with self._lock:
1185 fh.seek(offset)
1186 return fh.read(size)
1187
1188 def _read_into(self, offset: int, buffer: NDArray[numpy.uint8], /) -> int:
1189 """Read bytes from file at given offset into existing buffer.
1190
1191 Parameters:
1192 offset: Byte offset from start of file.
1193 buffer: Flat, writable uint8 numpy array to read into.
1194
1195 Returns:
1196 Number of bytes read.
1197
1198 """
1199 nbytes = len(buffer)
1200 mv = self._mv
1201 if mv is not None:
1202 n = min(nbytes, max(0, len(mv) - offset))
1203 buffer[:n] = numpy.frombuffer(mv[offset : offset + n], numpy.uint8)
1204 return n
1205
1206 fh = self._fh
1207 with self._lock:
1208 fh.seek(offset)
1209 try:
1210 return fh.readinto(buffer) # type: ignore[attr-defined, no-any-return]
1211 except (AttributeError, OSError):
1212 data = fh.read(nbytes)
1213 buffer[:] = numpy.frombuffer(data, numpy.uint8)
1214 return len(data)
1215
1216 def _read_array(
1217 self,
1218 offset: int,
1219 count: int,
1220 dtype: DTypeLike,
1221 *,
1222 copy: bool = False,
1223 writable: bool = False,
1224 truncate: bool | None = False,
1225 ) -> NDArray[Any]:
1226 """Read numpy array from file at given offset.
1227
1228 For memory-mapped files, returned data are exposed directly as a
1229 NumPy array view of the mapping (zero copy). Keeping that array alive
1230 may keep the memory map (and associated file resources/lock) alive.
1231
1232 Parameters:
1233 offset:
1234 Byte offset from start of file.
1235 count:
1236 Number of elements to read. If ``-1``, read to end of file.
1237 dtype:
1238 Array element type.
1239 copy:
1240 If true, always return a detached copy in main memory.
1241 For memory-mapped files, bypass the direct-view fast path.
1242 writable:
1243 By default, return read-only array from memory-mapped file.
1244 Prevents accidental modification of underlying writable file.
1245 Has no effect for non-memory-mapped files (always writable).
1246 truncate:
1247 Allow partial reads of array.
1248 If None, log error on partial read.
1249
1250 """
1251 dtype = numpy.dtype(dtype)
1252 itemsize = dtype.itemsize
1253 if offset < 0:
1254 msg = f'{offset=} < 0'
1255 raise ValueError(msg)
1256 if count < -1:
1257 msg = f'{count=} < -1'
1258 raise ValueError(msg)
1259
1260 mv = self._mv
1261 if mv is not None:
1262 if count == -1:
1263 count = max(0, (len(mv) - offset) // itemsize)
1264 nbytes = count * itemsize
1265 size = min(nbytes, max(0, len(mv) - offset))
1266 n = size - size % itemsize
1267 array = numpy.frombuffer(
1268 mv[offset : offset + n],
1269 dtype,
1270 )
1271 if copy:
1272 array = array.copy()
1273 elif not writable and array.flags.writeable:
1274 array.flags.writeable = False
1275 elif count > -1:
1276 fh = self._fh
1277 nbytes = count * itemsize
1278 array = numpy.empty(count, dtype)
1279 with self._lock:
1280 fh.seek(offset)
1281 n = fh.readinto(array.data) # type: ignore[attr-defined]
1282 else:
1283 fh = self._fh
1284 with self._lock:
1285 fh.seek(0, os.SEEK_END)
1286 size = fh.tell()
1287 count = max(0, (size - offset) // itemsize)
1288 nbytes = count * itemsize
1289 array = numpy.empty(count, dtype)
1290 fh.seek(offset)
1291 n = fh.readinto(array.data) # type: ignore[attr-defined]
1292
1293 if n != nbytes:
1294 array = array[: n // itemsize]
1295 msg = f'expected {count} items, got {n // itemsize}'
1296 if truncate is None:
1297 logging.getLogger(__name__.split('.', 1)[0]).error(msg)
1298 elif not truncate:
1299 raise ValueError(msg)
1300
1301 return array
1302
1303 @cached_property
1304 def filesize(self) -> int:
1305 """Size of file in bytes."""
1306 if self._mm is not None:
1307 return len(self._mm)
1308 fh = self._fh
1309 try:
1310 return os.fstat(fh.fileno()).st_size
1311 except (AttributeError, io.UnsupportedOperation, OSError):
1312 pass
1313 with self._lock:
1314 pos = fh.tell()
1315 fh.seek(0, os.SEEK_END)
1316 size = fh.tell()
1317 fh.seek(pos)
1318 return size
1319
1320 @property
1321 def writable(self) -> bool:
1322 """File is open for writing."""
1323 return self._fh.writable()
1324
1325 @property
1326 def memmapped(self) -> bool:
1327 """File is memory-mapped."""
1328 return self._mm is not None
1329
1330 @property
1331 def closed(self) -> bool:
1332 """File is closed."""
1333 return self._closed
1334
1335 def close(self) -> None:
1336 """Close file."""
1337 self._closed = True # always report file as closed
1338 self._mv = None # do not release(), threads may hold local refs
1339 if self._mm is not None and self._mm is not self._fh: # type: ignore[comparison-overlap]
1340 with contextlib.suppress(Exception):
1341 self._mm.close()
1342 if self._close:
1343 with contextlib.suppress(Exception):
1344 self._fh.close()
1345
1346 def __enter__(self) -> Self:
1347 return self
1348
1349 def __exit__(
1350 self,
1351 exc_type: type[BaseException] | None,
1352 exc_value: BaseException | None,
1353 traceback: TracebackType | None,
1354 ) -> None:
1355 self.close()
1356
1357 def __repr__(self) -> str:
1358 return f'<{self.__class__.__name__} {self._name!r}>'
1359
1360
1361 class PqFile(BinaryFile):
1362 """PicoQuant unified tagged file.
1363
1364 PTU, PHU, PCK, PCO, PFS, PUS, PQRES, PQDAT, PQUNI, and SPQR files contain
1365 measurement metadata and settings encoded as unified tags.
1366
1367 ``PqFile`` and subclass instances are not thread safe.
1368 All attributes are read-only.
1369
1370 ``PqFile`` and subclass instances must be closed with
1371 :py:meth:`PqFile.close`, which is automatically called when using the
1372 'with' context manager.
1373
1374 Parameters:
1375 file:
1376 File name or seekable binary stream.
1377 mode:
1378 File open mode if ``file`` is file name.
1379 The default is ``'r'``. Files are always opened in binary mode.
1380 memmap:
1381 Map file into memory.
1382 Ignored if memory mapping is not available or if the stream does
1383 not support it.
1384 fastload:
1385 If true, only read tags marked for fast loading,
1386 else read all tags.
1387
1388 Raises:
1389 PqFileError: File is not a PicoQuant tagged file or is corrupted.
1390
1391 """
1392
1393 type: PqFileType
1394 """PicoQuant file type identifier."""
1395
1396 version: str
1397 """File version."""
1398
1399 tags: dict[str, Any]
1400 """PicoQuant unified tags."""
1401
1402 _data_offset: int # position of raw data in file
1403 _number_records_offset: int # position of TTResult_NumberOfRecords value
1404
1405 _TYPE: ClassVar[set[PqFileType]] = set(PqFileType)
1406 _STR_: tuple[str, ...] = ('type', 'version') # attributes listed first
1407
1408 def __init__(
1409 self,
1410 file: str | os.PathLike[str] | IO[bytes],
1411 /,
1412 *,
1413 mode: Literal['r', 'r+'] | None = None,
1414 memmap: bool = False,
1415 fastload: bool = False,
1416 ) -> None:
1417 super().__init__(file, mode=mode, memmap=memmap)
1418
1419 self.version = ''
1420 self.tags = {}
1421
1422 try:
1423 self._init(fastload=fastload)
1424 except Exception:
1425 self.close()
1426 raise
1427
1428 def _init(self, *, fastload: bool) -> None:
1429 header = bytes(self._read_at(0, 16))
1430 offset = 16
1431 try:
1432 self.type = PqFileType(header[:8])
1433 except ValueError as exc:
1434 msg = (
1435 f'{self.filename!r} is not a {self.__class__.__name__} '
1436 f'{header[:8]!r}'
1437 )
1438 raise PqFileError(msg) from exc
1439 if self.type not in self._TYPE:
1440 msg = (
1441 f'{self.filename!r} type={self.type} is not in {self._TYPE!r}'
1442 )
1443 raise PqFileError(msg)
1444
1445 self.version = header[8:].strip(b'\0').decode()
1446 tags = self.tags
1447
1448 def errmsg(
1449 msg: str, tagid: str, index: int, typecode: int, value: Any
1450 ) -> str:
1451 return (
1452 f'{msg} @ {self.name!r} '
1453 f'{tagid=}, {index=}, {typecode=}, {value=!r}'
1454 )[:160]
1455
1456 tagid: str
1457 index: int
1458 typecode: int
1459 value: Any
1460 unpack = struct.unpack
1461 try:
1462 while True:
1463 tagid_, index, typecode, value = struct.unpack_from(
1464 '<32siI8s', self._read_at(offset, 48)
1465 )
1466 offset += 48
1467 # print(tagid.strip(b'\0'), index, typecode, value)
1468 tagid = tagid_.rstrip(b'\0').decode('ascii', errors='ignore')
1469
1470 # tags must start on positions divisible by 8
1471 # disabled for PQRES and PQDAT
1472 if offset % 8 and self.type not in {
1473 PqFileType.PQRES,
1474 PqFileType.PQDAT,
1475 }:
1476 logger().error(
1477 errmsg(
1478 f'tag offset={offset - 48} not divisible by 8',
1479 tagid,
1480 index,
1481 typecode,
1482 value,
1483 )
1484 )
1485 if tagid == 'Header_End':
1486 break
1487 if tagid == 'Fast_Load_End':
1488 if fastload:
1489 break
1490 continue
1491
1492 match typecode:
1493 # frequent typecodes
1494 case PqTagType.Int8:
1495 value = unpack('<q', value)[0]
1496 case PqTagType.Bool8:
1497 value = bool(unpack('<q', value)[0])
1498 case PqTagType.Float8:
1499 value = unpack('<d', value)[0]
1500 case PqTagType.AnsiString:
1501 size = unpack('<q', value)[0]
1502 value = (
1503 bytes(self._read_at(offset, size))
1504 .rstrip(b'\0')
1505 .decode('windows-1252', errors='ignore')
1506 )
1507 offset += size
1508 case PqTagType.Empty8:
1509 value = None
1510 case PqTagType.TDateTime:
1511 value = unpack('<d', value)[0]
1512 value = datetime(1899, 12, 30) + timedelta(days=value)
1513 # rarer typecodes
1514 case PqTagType.WideString:
1515 size = unpack('<q', value)[0]
1516 value = (
1517 bytes(self._read_at(offset, size))
1518 .decode('utf-16-le')
1519 .rstrip('\0')
1520 )
1521 offset += size
1522 case PqTagType.BinaryBlob:
1523 size = unpack('<q', value)[0]
1524 if tagid == 'ChkHistogram':
1525 value = self._read_array(
1526 offset, size // 8, numpy.int64, copy=True
1527 )
1528 else:
1529 value = bytes(self._read_at(offset, size))
1530 offset += size
1531 case PqTagType.BitSet64:
1532 value = unpack('<q', value)[0]
1533 case PqTagType.Color8:
1534 # TODO: unpack to RGB triple
1535 value = unpack('<q', value)[0]
1536 case PqTagType.Float8Array:
1537 size = unpack('<q', value)[0]
1538 value = unpack(
1539 f'<{size // 8}d', self._read_at(offset, size)
1540 )
1541 offset += size
1542 case _:
1543 logger().error(
1544 errmsg(
1545 'invalid tag type',
1546 tagid,
1547 index,
1548 typecode,
1549 value,
1550 )
1551 )
1552 break
1553
1554 # Although tagids can appear multiple times, later tags have
1555 # always found to either contain the same or more detailed
1556 # values. Hence a dict interface seems sufficient.
1557 if index < 0:
1558 if tagid in tags and tags[tagid] != value:
1559 logger().warning(
1560 errmsg(
1561 'duplicate tag', tagid, index, typecode, value
1562 )
1563 + f' != {tags[tagid]!r}'[:16]
1564 )
1565 tags[tagid] = value
1566 elif index == 0:
1567 if tagid in tags and tags[tagid][0] != value:
1568 logger().warning(
1569 errmsg(
1570 'duplicate tag', tagid, index, typecode, value
1571 )
1572 + f' != {tags[tagid][0]!r}'[:16]
1573 )
1574 tags[tagid] = [value]
1575 elif tagid not in tags:
1576 logger().error(
1577 errmsg(
1578 'tag with index not in tags',
1579 tagid,
1580 index,
1581 typecode,
1582 value,
1583 )
1584 )
1585 tags[tagid] = [value]
1586 elif index != len(tags[tagid]):
1587 logger().error(
1588 errmsg(
1589 'tag index out of order',
1590 tagid,
1591 index,
1592 typecode,
1593 value,
1594 )
1595 )
1596 tags[tagid].append(value)
1597 else:
1598 tags[tagid].append(value)
1599 except Exception as exc:
1600 raise PqFileError(
1601 errmsg('tag corrupted', tagid, index, typecode, value)
1602 ) from exc
1603 self._data_offset = offset
1604
1605 @property
1606 def guid(self) -> uuid.UUID:
1607 """Global identifier of file."""
1608 return uuid.UUID(self.tags['File_GUID'])
1609
1610 @property
1611 def comment(self) -> str | None:
1612 """File comment, if any."""
1613 return self.tags.get('File_Comment')
1614
1615 @property
1616 def datetime(self) -> datetime | None:
1617 """File creation date, if any."""
1618 if 'File_CreatingTime' not in self.tags:
1619 return None
1620 value = self.tags['File_CreatingTime']
1621 if isinstance(value, datetime):
1622 return value
1623 if isinstance(value, str):
1624 try:
1625 return datetime.fromisoformat(value)
1626 except ValueError:
1627 try:
1628 from dateutil import parser
1629
1630 return parser.parse(value)
1631 except Exception:
1632 return None
1633 if not isinstance(value, float):
1634 return None
1635 try:
1636 return datetime(1899, 12, 30) + timedelta(days=value)
1637 except Exception:
1638 return None
1639
1640 @override
1641 @property
1642 def attrs(self) -> dict[str, Any]:
1643 """Selected metadata as dict."""
1644 return {
1645 **super().attrs,
1646 'type': self.type.name,
1647 'version': self.version,
1648 'guid': str(self.guid),
1649 'comment': self.comment,
1650 'datetime': (
1651 None if self.datetime is None else self.datetime.isoformat()
1652 ),
1653 'tags': self.tags,
1654 }
1655
1656 @override
1657 def __enter__(self) -> Self:
1658 return self
1659
1660 def __str__(self) -> str:
1661 return indent(
1662 repr(self),
1663 *(
1664 f'{name}: {getattr(self, name)!r}'[:160]
1665 for name in self._STR_
1666 if getattr(self, name) is not None
1667 ),
1668 *(
1669 f'{name}: {getattr(self, name)!r}'[:160]
1670 for name in dir(self)
1671 if not (
1672 name in self._STR_
1673 or name
1674 in {'attrs', 'dirname', 'tags', 'name', 'filehandle'}
1675 or name.startswith('_')
1676 or callable(getattr(self, name))
1677 )
1678 ),
1679 indent(
1680 'tags:',
1681 *(
1682 f'{key}: {value!r}'[:160]
1683 for key, value in self.tags.items()
1684 ),
1685 ),
1686 )
1687
1688
1689 @final
1690 class PhuFile(PqFile):
1691 """PicoQuant histogram file.
1692
1693 PHU files contain a series of TCSPC histograms in addition to unified tags.
1694
1695 ``PhuFile`` instances are derived from :py:class:`PqFile`.
1696
1697 Parameters:
1698 file:
1699 File name or seekable binary stream.
1700 mode:
1701 File open mode if ``file`` is file name.
1702 The default is ``'r'``. Files are always opened in binary mode.
1703 memmap:
1704 Map file into memory.
1705 Ignored if memory mapping is not available or if the stream does
1706 not support it.
1707
1708 Raises:
1709 PqFileError: File is not a PicoQuant PHU file or is corrupted.
1710
1711 """
1712
1713 _TYPE: ClassVar[set[PqFileType]] = {PqFileType.PHU}
1714 _STR_ = ('type', 'version', 'measurement_mode', 'measurement_submode')
1715
1716 def __init__(
1717 self,
1718 file: str | os.PathLike[str] | IO[bytes],
1719 /,
1720 *,
1721 mode: Literal['r', 'r+'] | None = None,
1722 memmap: bool = False,
1723 ) -> None:
1724 super().__init__(file, mode=mode, memmap=memmap)
1725
1726 @override
1727 def __enter__(self) -> Self:
1728 return self
1729
1730 @property
1731 def measurement_mode(self) -> PhuMeasurementMode:
1732 """Kind of measurement: HISTOGRAM or CONTI."""
1733 return PhuMeasurementMode(self.tags['Measurement_Mode'])
1734
1735 @property
1736 def measurement_submode(self) -> PhuMeasurementSubMode:
1737 """Sub-kind of measurement: OSCILLOSCOPE, INTEGRATING, or TRES."""
1738 return PhuMeasurementSubMode(self.tags['Measurement_SubMode'])
1739
1740 @property
1741 def tcspc_resolution(self) -> float:
1742 """Resolution of TCSPC in s (BaseResolution * iBinningFactor)."""
1743 return float(self.tags.get('MeasDesc_Resolution', 0.0))
1744
1745 @property
1746 def histogram_resolutions(self) -> tuple[float, ...] | None:
1747 """Base resolution for each histogram."""
1748 ncurves = self.number_histograms
1749 if 'HistResDscr_HWBaseResolution' in self.tags:
1750 return tuple(self.tags['HistResDscr_HWBaseResolution'])
1751 if 'HW_BaseResolution' in self.tags:
1752 return tuple([float(self.tags['HW_BaseResolution'])] * ncurves)
1753 return None
1754
1755 @property
1756 def number_histograms(self) -> int:
1757 """Number of histograms stored in file."""
1758 return int(self.tags['HistoResult_NumberOfCurves'])
1759
1760 # @property
1761 # def bits_per_bin(self) -> int:
1762 # """Number of bits per histogram bin."""
1763 # return int(self.tags.get('HistoResult_BitsPerBin', 32))
1764
1765 @override
1766 @property
1767 def attrs(self) -> dict[str, Any]:
1768 """Selected metadata as dict."""
1769 return {
1770 **super().attrs,
1771 'measurement_mode': self.measurement_mode.name,
1772 'measurement_submode': self.measurement_submode.name,
1773 'tcspc_resolution': self.tcspc_resolution,
1774 }
1775
1776 @overload
1777 def histograms(
1778 self,
1779 index: int | slice | None = None,
1780 /,
1781 *,
1782 asxarray: Literal[False] = ...,
1783 ) -> tuple[NDArray[numpy.uint32], ...]: ...
1784
1785 @overload
1786 def histograms(
1787 self,
1788 index: int | slice | None = None,
1789 /,
1790 *,
1791 asxarray: Literal[True] = ...,
1792 ) -> tuple[DataArray, ...]: ...
1793
1794 @overload
1795 def histograms(
1796 self,
1797 index: int | slice | None = None,
1798 /,
1799 *,
1800 asxarray: bool = ...,
1801 ) -> tuple[NDArray[numpy.uint32] | DataArray, ...]: ...
1802
1803 def histograms(
1804 self, index: int | slice | None = None, /, *, asxarray: bool = False
1805 ) -> tuple[NDArray[numpy.uint32] | DataArray, ...]:
1806 """Return sequences of histograms from file.
1807
1808 Parameters:
1809 index:
1810 Index of histogram(s) to return.
1811 By default, all histograms are returned.
1812 asxarray:
1813 If true, return histograms as ``xarray.DataArray``,
1814 else ``numpy.ndarray`` (default).
1815
1816 """
1817 if index is None:
1818 index = slice(None)
1819 elif isinstance(index, int):
1820 index = slice(index, index + 1)
1821 ncurves = self.number_histograms
1822 if len(self.tags['HistResDscr_DataOffset']) != ncurves:
1823 msg = 'invalid HistResDscr_DataOffset tag'
1824 raise ValueError(msg)
1825 if len(self.tags['HistResDscr_HistogramBins']) != ncurves:
1826 msg = 'invalid HistResDscr_HistogramBins tag'
1827 raise ValueError(msg)
1828
1829 histograms: list[NDArray[numpy.uint32] | DataArray] = []
1830 for offset, nbins in zip(
1831 self.tags['HistResDscr_DataOffset'][index],
1832 self.tags['HistResDscr_HistogramBins'][index],
1833 strict=True,
1834 ):
1835 hist = self._read_array(
1836 offset,
1837 nbins,
1838 dtype=numpy.uint32,
1839 copy=False,
1840 writable=False,
1841 truncate=None,
1842 )
1843 histograms.append(hist)
1844 if asxarray:
1845 from xarray import DataArray
1846
1847 assert self.histogram_resolutions is not None
1848
1849 histograms = [
1850 DataArray(
1851 h,
1852 dims=('H',),
1853 coords={
1854 # TODO: is this correct?
1855 'H': numpy.linspace(
1856 0, h.size * r, h.size, endpoint=False
1857 )
1858 },
1859 attrs=self.attrs,
1860 # name=self.name,
1861 )
1862 for h, r in zip(
1863 histograms, self.histogram_resolutions, strict=True
1864 )
1865 ]
1866 # TODO: do not return tuple if index is integer?
1867 return tuple(histograms)
1868
1869 def plot(self, *, verbose: bool = False, show: bool = True) -> None:
1870 """Plot histograms using matplotlib.
1871
1872 Parameters:
1873 verbose:
1874 Print information about histogram arrays.
1875 show:
1876 If true (default), display all figures.
1877 Else, defer to user or environment to display figures.
1878
1879 """
1880 from matplotlib import pyplot
1881 from tifffile import Timer
1882
1883 t = Timer()
1884 histograms = self.histograms(asxarray=True)
1885 if verbose:
1886 t.print('decode histograms')
1887 print()
1888 for hist in histograms:
1889 print(hist)
1890
1891 for i, hist in enumerate(histograms):
1892 y = numpy.trim_zeros(hist.values, trim='b')
1893 x = hist.coords['H'].values[: y.size]
1894 pyplot.plot(x, y, label=f'ch {i}')
1895 pyplot.title(repr(self))
1896 pyplot.xlabel('delay time [s]')
1897 pyplot.ylabel('photon count')
1898 pyplot.legend()
1899 if show:
1900 pyplot.show()
1901
1902
1903 @final
1904 class PtuFile(PqFile):
1905 """PicoQuant time-tagged time-resolved (TTTR) file.
1906
1907 PTU files contain TTTR records in addition to unified tags.
1908
1909 ``PtuFile`` instances are not thread-safe. All attributes are read-only.
1910
1911 ``PtuFile`` is derived from :py:class:`PqFile`.
1912
1913 Parameters:
1914 file:
1915 File name or seekable binary stream.
1916 mode:
1917 File open mode if ``file`` is file name.
1918 The default is ``'r'``. Files are always opened in binary mode.
1919 memmap:
1920 Map file into memory.
1921 Ignored if memory mapping is not available or if the stream does
1922 not support it.
1923 trimdims:
1924 Axes to trim. The default is ``'TCH'``:
1925
1926 - ``'T'``: remove incomplete first or last frame.
1927 - ``'C'``: remove leading and trailing channels without photons.
1928 Else use record type's default :py:attr:`number_channels_max`.
1929 - ``'H'``: remove trailing delay-time bins without photons.
1930 Else use record type's default :py:attr:`number_bins_max`.
1931
1932 Raises:
1933 PqFileError: File is not a PicoQuant PTU file or is corrupted.
1934
1935 """
1936
1937 _trimdims: set[str]
1938 _cache: bool # cache records in memory
1939 _asxarray: bool # return DataArray from slicing and decode_ functions
1940 _dtype: numpy.dtype[Any]
1941 _records: NDArray[numpy.uint32] | None # cached records
1942
1943 _TYPE: ClassVar[set[PqFileType]] = {PqFileType.PTU}
1944 _STR_ = (
1945 'type',
1946 'version',
1947 'record_type',
1948 'measurement_mode',
1949 'measurement_submode',
1950 'scanner',
1951 'sizes',
1952 )
1953
1954 def __init__(
1955 self,
1956 file: str | os.PathLike[str] | IO[bytes],
1957 /,
1958 *,
1959 mode: Literal['r', 'r+'] | None = None,
1960 memmap: bool = False,
1961 trimdims: Sequence[Dimension] | str | None = None,
1962 ) -> None:
1963 self._records = None
1964 super().__init__(file, mode=mode, memmap=memmap)
1965
1966 try:
1967 if trimdims is None:
1968 self._trimdims = {'T', 'C', 'H'}
1969 else:
1970 self._trimdims = {ax.upper() for ax in trimdims}
1971 self._dtype = numpy.dtype(numpy.uint16)
1972 self._asxarray = False
1973 self._cache = not memmap # memmap takes care of caching
1974 except Exception:
1975 self.close()
1976 raise
1977
1978 @override
1979 def __enter__(self) -> Self:
1980 return self
1981
1982 def __getitem__(self, key: Any, /) -> NDArray[Any] | DataArray:
1983 return self.decode_image(key, keepdims=False)
1984
1985 @override
1986 def close(self) -> None:
1987 """Close file handle and free resources."""
1988 del self._records # close numpy.memmap file handle
1989 self._records = None
1990 super().close()
1991
1992 @property
1993 def record_offset(self) -> int:
1994 """Position of records in file."""
1995 return self._data_offset
1996
1997 @property
1998 def record_type(self) -> PtuRecordType:
1999 """Type of TTTR records.
2000
2001 Defines the TCSPC device and type of measurement that produced the
2002 records.
2003
2004 """
2005 return PtuRecordType(self.tags['TTResultFormat_TTTRRecType'])
2006
2007 @property
2008 def measurement_mode(self) -> PtuMeasurementMode:
2009 """Kind of TCSPC measurement: T2 or T3."""
2010 return PtuMeasurementMode(self.tags['Measurement_Mode'])
2011
2012 @property
2013 def measurement_submode(self) -> PtuMeasurementSubMode:
2014 """Sub-kind of measurement: Point, line, or image scan."""
2015 return PtuMeasurementSubMode(self.tags['Measurement_SubMode'])
2016
2017 @property
2018 def measurement_ndim(self) -> int:
2019 """Dimensionality of measurement."""
2020 # Measurement_SubMode is not always correct
2021 submode = self.tags['Measurement_SubMode']
2022 if (
2023 submode == 3
2024 and self.tags.get('ImgHdr_Dimensions', 3) == 3 # optional
2025 # and self.tags.get('ImgHdr_PixY', 1) > 1 # may be missing
2026 ):
2027 return 3
2028 if (
2029 submode == 2
2030 and self.tags.get('ImgHdr_Dimensions', 2) == 2 # optional
2031 # and self.tags.get('ImgHdr_PixX', 1) > 1 # may be missing
2032 ):
2033 # TODO: need linescan test file
2034 return 2
2035 return 1
2036
2037 @property
2038 def measurement_warnings(self) -> PtuMeasurementWarnings | None:
2039 """Warnings during measurement, or None if not specified."""
2040 if 'TTResult_MDescWarningFlags' in self.tags:
2041 return PtuMeasurementWarnings(
2042 self.tags['TTResult_MDescWarningFlags']
2043 )
2044 return None
2045
2046 @property
2047 def hardware_features(self) -> PtuHwFeatures | None:
2048 """Hardware features, or None if not specified."""
2049 if 'HW_Features' in self.tags:
2050 return PtuHwFeatures(self.tags['HW_Features'])
2051 return None
2052
2053 @property
2054 def stop_reason(self) -> PtuStopReason | None:
2055 """Reason for measurement end, or None if not specified."""
2056 if 'TTResult_StopReason' in self.tags:
2057 return PtuStopReason(self.tags['TTResult_StopReason'])
2058 return None
2059
2060 @property
2061 def scanner(self) -> PtuScannerType | None:
2062 """Scanner hardware, or None if not specified."""
2063 if 'ImgHdr_Ident' in self.tags:
2064 return PtuScannerType(self.tags['ImgHdr_Ident'])
2065 return None
2066
2067 @property
2068 def global_resolution(self) -> float:
2069 """Resolution of time tags in s."""
2070 return float(self.tags['MeasDesc_GlobalResolution'])
2071
2072 @property
2073 def tcspc_resolution(self) -> float:
2074 """Resolution of TCSPC in s (BaseResolution * iBinningFactor)."""
2075 return float(self.tags.get('MeasDesc_Resolution', 0.0))
2076
2077 @cached_property
2078 def number_records(self) -> int:
2079 """Number of TTTR records."""
2080 # NOTE: this does not catch invalid TTResult_NumberOfRecords > 0
2081 count = value = int(self.tags.get('TTResult_NumberOfRecords', 0))
2082 if count <= 0:
2083 count = (self.filesize - self._data_offset) // 4
2084 if count != 0:
2085 logger().warning(
2086 f'{self!r} invalid TTResult_NumberOfRecords={value}. '
2087 'Using remaining file content as records'
2088 )
2089 return count
2090
2091 @property
2092 def number_photons(self) -> int:
2093 """Number of photons counted."""
2094 return self._info.photons
2095
2096 @property
2097 def number_markers(self) -> int:
2098 """Number of marker events."""
2099 return self._info.markers
2100
2101 @property
2102 def number_images(self) -> int:
2103 """Number of images separated by frame change markers."""
2104 return self._info.frames
2105
2106 @property
2107 def number_lines(self) -> int:
2108 """Number of line marker pairs."""
2109 return self._info.lines
2110
2111 @property
2112 def number_channels_max(self) -> int:
2113 """Maximum number of channels for record type."""
2114 return self._info.channels
2115
2116 @property
2117 def number_channels(self) -> int:
2118 """Number of channels, without leading and trailing empty channels."""
2119 return (
2120 1
2121 + self._info.channels_active_last
2122 - self._info.channels_active_first
2123 )
2124
2125 @property
2126 def active_channels(self) -> tuple[int, ...]:
2127 """Indices of un-trimmed channels containing photons."""
2128 channels_active = self._info.channels_active
2129 return tuple(
2130 ch
2131 for ch in range(self._info.channels)
2132 if channels_active & (1 << ch)
2133 )
2134
2135 @property
2136 def number_bins_max(self) -> int:
2137 """Maximum number of delay-time bins for record type."""
2138 return self._info.bins
2139
2140 @property
2141 def number_bins(self) -> int:
2142 """Number of bins up to the largest occupied delay-time bin.
2143
2144 Not available for T2 records.
2145
2146 """
2147 return self._info.bins_used
2148
2149 @property
2150 def number_bins_in_period(self) -> int:
2151 """Delay time in one period. Not available for T2 records.
2152
2153 Same as ``global_resolution / tcspc_resolution``
2154
2155 """
2156 if self.tcspc_resolution < 1e-14:
2157 return 1
2158 nbins = math.floor(self.global_resolution / self.tcspc_resolution)
2159 return max(nbins, 1)
2160
2161 @property
2162 def line_start_mask(self) -> int:
2163 """Marker mask defining line start, or 0 if not defined."""
2164 value = self.tags.get('ImgHdr_LineStart', None)
2165 return int(2 ** (value - 1) if value is not None else 0)
2166
2167 @property
2168 def line_stop_mask(self) -> int:
2169 """Marker mask defining line end, or 0 if not defined."""
2170 value = self.tags.get('ImgHdr_LineStop', None)
2171 return int(2 ** (value - 1) if value is not None else 0)
2172
2173 @property
2174 def frame_change_mask(self) -> int:
2175 """Marker mask defining image frame change, or 0 if not defined."""
2176 value = self.tags.get('ImgHdr_Frame', None)
2177 return int(2 ** (value - 1) if value is not None else 0)
2178
2179 @property
2180 def global_pixel_time(self) -> int:
2181 """Global time per pixel.
2182
2183 Multiply with global resolution to get time in s.
2184
2185 """
2186 if self.tags.get('ImgHdr_TimePerPixel', 0.0) > 0.0:
2187 pixeltime = (
2188 float(self.tags['ImgHdr_TimePerPixel'])
2189 / float(self.tags['MeasDesc_GlobalResolution'])
2190 / 1e3
2191 )
2192 elif self._info.lines > 0:
2193 pixeltime = self._info.line_time / self.pixels_in_line
2194 else:
2195 pixeltime = 1e-3 / float(self.tags['MeasDesc_GlobalResolution'])
2196 return max(1, round(pixeltime))
2197
2198 @property
2199 def global_line_time(self) -> int:
2200 """Global time per line, excluding retrace.
2201
2202 Might be approximate. Multiply with global resolution to get time in s.
2203
2204 """
2205 if 'ImgHdr_TimePerPixel' in self.tags:
2206 linetime = self.pixels_in_line * self.global_pixel_time
2207 elif self._info.lines > 0:
2208 linetime = self._info.line_time
2209 else:
2210 # point scan: line of one pixel
2211 linetime = 1e-3 / self.tags['MeasDesc_GlobalResolution']
2212 return round(linetime)
2213
2214 @property
2215 def global_frame_time(self) -> int:
2216 """Global time per image, line, or point scan cycle.
2217
2218 Multiply with global resolution to get time in s.
2219
2220 """
2221 if self.tags['Measurement_SubMode'] == 3:
2222 # image, including retrace
2223 if self._info.frames == 0:
2224 return self._info.acquisition_time
2225 return self._info.acquisition_time // self._info.frames
2226 if self._info.lines > 0:
2227 # line scan
2228 return self._info.line_time
2229 # point scan
2230 return self.pixels_in_frame * self.global_pixel_time
2231
2232 @property
2233 def global_acquisition_time(self) -> int:
2234 """Global time of acquisition."""
2235 # MeasDesc_AcquisitionTime not reliable
2236 # aqt = self.tags.get('MeasDesc_AcquisitionTime', 0.0)
2237 # if aqt > 0:
2238 # return round(1e-3 * aqt / self.global_resolution)
2239 return self._info.acquisition_time
2240
2241 @property
2242 def pixels_in_frame(self) -> int:
2243 """Number of pixels in one scan cycle."""
2244 return self.lines_in_frame * self.pixels_in_line
2245
2246 @property
2247 def pixels_in_line(self) -> int:
2248 """Number of pixels in line."""
2249 ndim = self.measurement_ndim
2250 if ndim == 3:
2251 # image
2252 pixels = self.tags['ImgHdr_PixX']
2253 elif ndim == 2:
2254 # line scan
2255 time_per_pixel = self.tags['ImgHdr_TimePerPixel']
2256 line_frequency = self.tags['ImgHdr_LineFrequency']
2257 if time_per_pixel > 0.0 and line_frequency > 0.0:
2258 pixels = round(1e-3 / (time_per_pixel * line_frequency))
2259 else:
2260 pixels = 1
2261 else:
2262 pixels = 1
2263 return max(1, int(pixels))
2264
2265 @property
2266 def lines_in_frame(self) -> int:
2267 """Number of lines in frame."""
2268 if self.measurement_ndim == 3:
2269 # TODO: Warning from the PicoQuant documentation:
2270 # Attention, in some images one will find a different number
2271 # of lines than defined by PixY (less or more, even different
2272 # in every frame), so do not trust this value.
2273 return max(1, int(self.tags['ImgHdr_PixY']))
2274 return 1
2275
2276 @property
2277 def pixel_time(self) -> float:
2278 """Time per pixel in s."""
2279 pixel_time = float(self.tags.get('ImgHdr_TimePerPixel', 0.0))
2280 if pixel_time > 0.0:
2281 return pixel_time * 1e-3 # ms to s
2282 return self.global_pixel_time * self.global_resolution
2283
2284 @property
2285 def line_time(self) -> float:
2286 """Average time between line markers or ``pixel_time`` in s."""
2287 return self.global_line_time * self.global_resolution
2288
2289 @property
2290 def frame_time(self) -> float:
2291 """Time per image, line, or point scan cycle in s.
2292
2293 Image scan times include retrace.
2294
2295 """
2296 return self.global_frame_time * self.global_resolution
2297
2298 @property
2299 def acquisition_time(self) -> float:
2300 """Duration of acquisition in s."""
2301 # MeasDesc_AcquisitionTime not reliable
2302 # if 'MeasDesc_AcquisitionTime' in self.tags:
2303 # return self.tags['MeasDesc_AcquisitionTime'] * 1e-3
2304 return self._info.acquisition_time * self.global_resolution
2305
2306 @property
2307 def frequency(self) -> float:
2308 """Repetition frequency in Hz.
2309
2310 The inverse of :py:attr:`PtuFile.global_resolution`.
2311
2312 """
2313 period = float(self.tags.get('MeasDesc_GlobalResolution', 0.0))
2314 return 1.0 / period if period > 1e-14 else 0.0
2315
2316 @property
2317 def syncrate(self) -> int:
2318 """Sync events per s as recorded at beginning of measurement."""
2319 return int(self.tags['TTResult_SyncRate'])
2320
2321 @property
2322 def is_image(self) -> bool:
2323 """File contains image data."""
2324 return (
2325 self.tags['Measurement_SubMode'] == 3
2326 and self.tags.get('ImgHdr_Dimensions', 1) == 3
2327 and 'ImgHdr_PixX' in self.tags # some Leica PTU are missing this
2328 )
2329
2330 @property
2331 def is_t3(self) -> bool:
2332 """File contains T3 records."""
2333 return bool(self.tags['Measurement_Mode'] == 3)
2334 # return self.tags['TTResultFormat_TTTRRecType'] in {
2335 # 0x00010303, 0x00010304, 0x01010304,
2336 # 0x00010305, 0x00010306, 0x00010307,
2337 # }
2338
2339 @property
2340 def is_bidirectional(self) -> bool:
2341 """Bidirectional scan mode."""
2342 return bool(self.tags.get('ImgHdr_BiDirect', 0) > 0)
2343
2344 @property
2345 def is_sinusoidal(self) -> bool:
2346 """Sinusoidal scan mode."""
2347 return bool(self.tags.get('ImgHdr_SinCorrection', 0) != 0)
2348
2349 @property
2350 def use_xarray(self) -> bool:
2351 """Slicing and decode methods return ``xarray.DataArray``."""
2352 return self._asxarray
2353
2354 @use_xarray.setter
2355 def use_xarray(self, value: bool, /) -> None:
2356 self._asxarray = bool(value)
2357
2358 @property
2359 def cache_records(self) -> bool:
2360 """Cache records read from file in memory."""
2361 return self._cache
2362
2363 @cache_records.setter
2364 def cache_records(self, value: bool, /) -> None:
2365 self._cache = bool(value)
2366 if not self._cache:
2367 del self._records # close numpy.memmap file handle
2368 self._records = None
2369
2370 @property
2371 def dtype(self) -> numpy.dtype[Any]:
2372 """Data type of image histogram array."""
2373 return self._dtype
2374
2375 @dtype.setter
2376 def dtype(self, dtype: DTypeLike | None, /) -> None:
2377 dtype = numpy.dtype('uint16' if dtype is None else dtype)
2378 if dtype.kind != 'u':
2379 msg = f'{dtype=!r} not an unsigned integer'
2380 raise ValueError(msg)
2381 self._dtype = dtype
2382
2383 @cached_property
2384 def shape(self) -> tuple[int, ...]:
2385 """Shape of image histogram array."""
2386 if not self.is_t3:
2387 return ()
2388
2389 if 'C' in self._trimdims:
2390 nchannels = max(self.number_channels, 1)
2391 else:
2392 nchannels = self.number_channels_max
2393 if 'H' in self._trimdims:
2394 nbins = self.number_bins
2395 else:
2396 nbins = self.number_bins_max
2397
2398 ndim = self.measurement_ndim
2399 if ndim == 3:
2400 return (
2401 max(self._info.frames, 1),
2402 self.lines_in_frame,
2403 self.pixels_in_line,
2404 nchannels,
2405 nbins,
2406 )
2407 if ndim == 2:
2408 return (
2409 max(self._info.lines, 1),
2410 self.pixels_in_line,
2411 nchannels,
2412 nbins,
2413 )
2414 if ndim in {0, 1}:
2415 return (
2416 max(1, self._info.photons // self.global_pixel_time),
2417 nchannels,
2418 nbins,
2419 )
2420 return ()
2421
2422 @cached_property
2423 def dims(self) -> tuple[str, ...]:
2424 """Axes labels for each dimension in image histogram array."""
2425 if not self.shape:
2426 return ()
2427 ndim = self.measurement_ndim
2428 if ndim == 3:
2429 return ('T', 'Y', 'X', 'C', 'H')
2430 if ndim == 2:
2431 return ('T', 'X', 'C', 'H')
2432 return ('T', 'C', 'H')
2433
2434 @property
2435 def sizes(self) -> dict[str, int]:
2436 """Map dimension names to lengths."""
2437 return dict(zip(self.dims, self.shape, strict=True))
2438
2439 @property
2440 def ndims(self) -> int:
2441 """Number of dimensions in image histogram array."""
2442 return len(self.dims)
2443
2444 @property
2445 def nbytes(self) -> int:
2446 """Number of bytes consumed by image histogram."""
2447 size = 1
2448 for i in self.shape:
2449 size *= int(i)
2450 return size * self._dtype.itemsize
2451
2452 @property
2453 def size(self) -> int:
2454 """Number of elements in image histogram."""
2455 size = 1
2456 for i in self.shape:
2457 size *= int(i)
2458 return size
2459
2460 @property
2461 def itemsize(self) -> int:
2462 """Length of one array element in image histogram in bytes."""
2463 return self._dtype.itemsize
2464
2465 @property
2466 def _coords_c(self) -> NDArray[Any]:
2467 """Coordinate array labelling all channels."""
2468 if 'C' in self._trimdims:
2469 return numpy.arange(
2470 self._info.channels_active_first,
2471 self._info.channels_active_last + 1,
2472 dtype=numpy.uint8,
2473 )
2474 return numpy.arange(self._info.channels, dtype=numpy.uint8)
2475
2476 @property
2477 def _coords_h(self) -> NDArray[Any]:
2478 """Coordinate array labelling all delay-time bins."""
2479 if 'H' in self._trimdims:
2480 nbins = self.number_bins
2481 else:
2482 nbins = self.number_bins_max
2483 return numpy.linspace(
2484 0, nbins * self.tags['MeasDesc_Resolution'], nbins, endpoint=False
2485 )
2486
2487 @cached_property
2488 def coords(self) -> dict[str, NDArray[Any]]:
2489 """Coordinate arrays labelling each point in image histogram array.
2490
2491 Coordinates for the time axis are approximate. Exact coordinates are
2492 returned with :py:meth:`PtuFile.decode_image` as ``xarray.DataArray``.
2493
2494 """
2495 if not self.shape:
2496 return {}
2497 ndim = self.measurement_ndim
2498 coords = {}
2499 shape = self.shape
2500 # exact time coordinates must be decoded from records
2501 coords['T'] = numpy.linspace(
2502 0, shape[0] * self.frame_time, shape[0], endpoint=False
2503 )
2504 res = self.tags.get('ImgHdr_PixResol', None)
2505 if res is not None:
2506 res *= 1e-6 # um
2507 if ndim > 2:
2508 offset = self.tags.get('ImgHdr_Y0', 0.0) * 1e-6 # um
2509 coords['Y'] = numpy.linspace(
2510 offset, offset + shape[-4] * res, shape[-4], endpoint=False
2511 )
2512 if ndim > 1:
2513 offset = self.tags.get('ImgHdr_X0', 0.0) * 1e-6
2514 coords['X'] = numpy.linspace(
2515 offset, offset + shape[-3] * res, shape[-3], endpoint=False
2516 )
2517 coords['C'] = self._coords_c
2518 coords['H'] = self._coords_h
2519 return coords
2520
2521 @override
2522 @property
2523 def attrs(self) -> dict[str, Any]:
2524 """Selected metadata as dict."""
2525 return {
2526 **super().attrs,
2527 'acquisition_time': self.acquisition_time,
2528 'active_channels': self.active_channels,
2529 'frame_time': self.frame_time,
2530 'frequency': self.frequency,
2531 'global_acquisition_time': self.global_acquisition_time,
2532 'global_frame_time': self.global_frame_time,
2533 'global_line_time': self.global_line_time,
2534 'global_pixel_time': self.global_pixel_time,
2535 'global_resolution': self.global_resolution,
2536 'line_time': self.line_time,
2537 'max_delaytime': self.number_bins_max, # for PhasorPy
2538 'measurement_mode': self.measurement_mode.name,
2539 'measurement_submode': self.measurement_submode.name,
2540 'number_bins': self.number_bins,
2541 'number_bins_in_period': self.number_bins_in_period,
2542 'number_bins_max': self.number_bins_max,
2543 'pixel_time': self.pixel_time,
2544 'record_type': self.record_type.name,
2545 'scanner': None if self.scanner is None else self.scanner.name,
2546 'syncrate': self.syncrate,
2547 'tcspc_resolution': self.tcspc_resolution,
2548 }
2549
2550 @cached_property
2551 def _info(self) -> PtuInfo:
2552 """Information about decoded records."""
2553 from ._ptufile import decode_info
2554
2555 lines_in_frame = 0
2556 if (
2557 'T' in self._trimdims
2558 and 'ImgHdr_PixY' in self.tags
2559 and self.tags['Measurement_SubMode'] == 3
2560 ):
2561 lines_in_frame = max(1, self.tags['ImgHdr_PixY'])
2562
2563 return PtuInfo(
2564 *decode_info(
2565 self.read_records(copy=False),
2566 self.tags['TTResultFormat_TTTRRecType'],
2567 self.line_start_mask,
2568 self.line_stop_mask,
2569 self.frame_change_mask,
2570 lines_in_frame,
2571 )
2572 )
2573
2574 def read_records(self, *, copy: bool = True) -> NDArray[numpy.uint32]:
2575 """Return encoded TTTR records from file.
2576
2577 If copy is false for a memory-mapped file, records are exposed
2578 directly as a NumPy array view of the mapping. Keeping that array
2579 alive may keep the memory map (and associated file resources/lock)
2580 alive.
2581
2582 Records are cached according to :py:attr:`PtuFile.cache_records`:
2583 disabled by default for memory-mapped files, enabled otherwise.
2584
2585 Parameters:
2586 copy:
2587 If true, always return a detached copy in main memory.
2588 This avoids cache corruption and returning arrays that
2589 reference memory-mapped resources.
2590
2591 """
2592 if self._cache and self._records is not None:
2593 if copy:
2594 return self._records.copy()
2595 return self._records
2596 if self.tags['TTResultFormat_BitsPerRecord'] not in {0, 32}:
2597 msg = f"invalid {self.tags['TTResultFormat_BitsPerRecord']=}"
2598 raise ValueError(msg)
2599 records = self._read_array(
2600 self._data_offset,
2601 self.number_records,
2602 numpy.uint32,
2603 copy=copy,
2604 truncate=None, # log errors on partial reads
2605 )
2606 if self._cache:
2607 self._records = records
2608 if copy:
2609 return records.copy()
2610 return records
2611
2612 def decode_records(
2613 self,
2614 records: NDArray[numpy.uint32] | None = None,
2615 /,
2616 *,
2617 out: OutputType = None,
2618 ) -> NDArray[Any]:
2619 """Return decoded TTTR records.
2620
2621 Parameters:
2622 records:
2623 Encoded TTTR records. By default, read records from file.
2624 out:
2625 Array where decoded records are stored.
2626 If ``None``, create a new NumPy recarray in main memory.
2627 If ``'memmap'``, create a memory-mapped recarray in a
2628 temporary file.
2629 If a ``numpy.ndarray``, a writable recarray of compatible
2630 shape and dtype.
2631 If a ``file name`` or ``open file``, create a
2632 memory-mapped array in the specified file.
2633
2634 Returns:
2635 :
2636 ``numpy.recarray`` of size :py:attr:`number_records` and dtype
2637 :py:attr:`T3_RECORD_DTYPE` or :py:attr:`T2_RECORD_DTYPE`.
2638
2639 A channel >= 0 indicates that a record contains a photon.
2640 Otherwise, the record contains an overflow event or marker > 0.
2641
2642 """
2643 from ._ptufile import decode_t2_records, decode_t3_records
2644
2645 if records is None:
2646 records = self.read_records(copy=False)
2647 rectype = self.tags['TTResultFormat_TTTRRecType']
2648 if self.is_t3:
2649 result = create_output(
2650 out, (records.size,), T3_RECORD_DTYPE, fillvalue=0
2651 )
2652 decode_t3_records(result, records, rectype)
2653 else:
2654 result = create_output(
2655 out, (records.size,), T2_RECORD_DTYPE, fillvalue=0
2656 )
2657 decode_t2_records(result, records, rectype)
2658 return result
2659
2660 @overload
2661 def decode_histogram(
2662 self,
2663 /,
2664 *,
2665 records: NDArray[numpy.uint32] | None = None,
2666 dtype: DTypeLike | None = None,
2667 sampling_time: int | None = None,
2668 dtime: int | None = None,
2669 asxarray: Literal[False] = ...,
2670 out: OutputType = None,
2671 ) -> NDArray[Any]: ...
2672
2673 @overload
2674 def decode_histogram(
2675 self,
2676 /,
2677 *,
2678 records: NDArray[numpy.uint32] | None = None,
2679 dtype: DTypeLike | None = None,
2680 sampling_time: int | None = None,
2681 dtime: int | None = None,
2682 asxarray: Literal[True] = ...,
2683 out: OutputType = None,
2684 ) -> DataArray: ...
2685
2686 @overload
2687 def decode_histogram(
2688 self,
2689 /,
2690 *,
2691 records: NDArray[numpy.uint32] | None = None,
2692 dtype: DTypeLike | None = None,
2693 sampling_time: int | None = None,
2694 dtime: int | None = None,
2695 asxarray: bool = ...,
2696 out: OutputType = None,
2697 ) -> NDArray[Any] | DataArray: ...
2698
2699 def decode_histogram(
2700 self,
2701 /,
2702 *,
2703 records: NDArray[numpy.uint32] | None = None,
2704 dtype: DTypeLike | None = None,
2705 sampling_time: int | None = None,
2706 dtime: int | None = None,
2707 asxarray: bool = False,
2708 out: OutputType = None,
2709 ) -> NDArray[Any] | DataArray:
2710 """Return histogram of all photons by channel.
2711
2712 Parameters:
2713 records:
2714 Encoded TTTR records. By default, read records from file.
2715 dtype:
2716 Unsigned integer type of histogram array.
2717 The default is ``uint32`` for T3, else ``uint16``.
2718 Increase the bit depth to avoid overflows.
2719 sampling_time:
2720 Global time per sample for T2 mode.
2721 The default is :py:attr:`PtuFile.global_pixel_time`.
2722 dtime:
2723 Number of bins in histogram.
2724 If 0, return :py:attr:`number_bins_in_period` bins.
2725 If > 0, return up to specified bin.
2726 asxarray:
2727 If true, return ``xarray.DataArray``, else ``numpy.ndarray``
2728 (default).
2729 out:
2730 Array where decoded histogram is stored.
2731 If ``None``, create a new NumPy array in main memory.
2732 If ``'memmap'``, create a memory-mapped array in a
2733 temporary file.
2734 If a ``numpy.ndarray``, a writable, initialized array
2735 of :py:attr:`shape` and unsigned integer dtype.
2736 If a ``file name`` or ``open file``, create a
2737 memory-mapped array in the specified file.
2738
2739 Returns:
2740 :
2741 Decoded TTTR T3 records as 2-dimensional histogram array:
2742
2743 - ``'C'`` channel
2744 - ``'H'`` histogram bins
2745
2746 """
2747 from ._ptufile import decode_t2_histogram, decode_t3_histogram
2748
2749 if dtype is None:
2750 dtype = numpy.uint32 if self.is_t3 else numpy.uint16
2751 dtype = numpy.dtype(dtype)
2752 if dtype.kind != 'u':
2753 msg = f'not an unsigned integer {dtype=!r}'
2754 raise ValueError(msg)
2755
2756 if records is None:
2757 records = self.read_records(copy=False)
2758 rectype = self.tags['TTResultFormat_TTTRRecType']
2759
2760 if 'C' in self._trimdims:
2761 first_channel = self._info.channels_active_first
2762 else:
2763 first_channel = 0
2764
2765 if self.is_t3:
2766 if dtime is None:
2767 nbins = self.shape[-1]
2768 elif dtime == 0:
2769 nbins = self.number_bins_in_period
2770 elif dtime > 0:
2771 nbins = dtime
2772 else:
2773 msg = f'{dtime=} < 0'
2774 raise ValueError(msg)
2775 histogram = create_output(
2776 out, (self.shape[-2], nbins), dtype, fillvalue=0
2777 )
2778 decode_t3_histogram(histogram, records, rectype, first_channel)
2779 coords = numpy.linspace(
2780 0,
2781 histogram.shape[-1] * self.tags['MeasDesc_Resolution'],
2782 histogram.shape[-1],
2783 endpoint=False,
2784 )
2785 else:
2786 if sampling_time is None or sampling_time <= 0:
2787 sampling_time = self.global_pixel_time
2788 histogram = create_output(
2789 out,
2790 (
2791 self.number_channels,
2792 max(1, self.global_acquisition_time // sampling_time),
2793 ),
2794 dtype,
2795 fillvalue=0,
2796 )
2797 decode_t2_histogram(
2798 histogram, records, rectype, sampling_time, first_channel
2799 )
2800 coords = numpy.linspace(
2801 0, self.acquisition_time, histogram.shape[1], endpoint=False
2802 )
2803 if not self._asxarray and not asxarray:
2804 return histogram
2805
2806 from xarray import DataArray
2807
2808 return DataArray(
2809 histogram,
2810 dims=('C', 'H'),
2811 coords={'C': self._coords_c, 'H': coords}, # name=self.name
2812 attrs=self.attrs,
2813 )
2814
2815 @overload
2816 def decode_image(
2817 self,
2818 selection: Sequence[int | slice | EllipsisType | None] | None = None,
2819 /,
2820 *,
2821 records: NDArray[numpy.uint32] | None = None,
2822 dtype: DTypeLike | None = None,
2823 frame: int | None = None,
2824 channel: int | None = None,
2825 dtime: int | None = None,
2826 pixel_time: float | None = None,
2827 bishift: int | None = None,
2828 keepdims: bool = True,
2829 asxarray: Literal[False] = ...,
2830 out: OutputType = None,
2831 ) -> NDArray[Any]: ...
2832
2833 @overload
2834 def decode_image(
2835 self,
2836 selection: Sequence[int | slice | EllipsisType | None] | None = None,
2837 /,
2838 *,
2839 records: NDArray[numpy.uint32] | None = None,
2840 dtype: DTypeLike | None = None,
2841 frame: int | None = None,
2842 channel: int | None = None,
2843 dtime: int | None = None,
2844 pixel_time: float | None = None,
2845 bishift: int | None = None,
2846 keepdims: bool = True,
2847 asxarray: Literal[True] = ...,
2848 out: OutputType = None,
2849 ) -> DataArray: ...
2850
2851 @overload
2852 def decode_image(
2853 self,
2854 selection: Sequence[int | slice | EllipsisType | None] | None = None,
2855 /,
2856 *,
2857 records: NDArray[numpy.uint32] | None = None,
2858 dtype: DTypeLike | None = None,
2859 frame: int | None = None,
2860 channel: int | None = None,
2861 dtime: int | None = None,
2862 pixel_time: float | None = None,
2863 bishift: int | None = None,
2864 keepdims: bool = True,
2865 asxarray: bool = ...,
2866 out: OutputType = None,
2867 ) -> NDArray[Any] | DataArray: ...
2868
2869 def decode_image(
2870 self,
2871 selection: Sequence[int | slice | EllipsisType | None] | None = None,
2872 /,
2873 *,
2874 records: NDArray[numpy.uint32] | None = None,
2875 dtype: DTypeLike | None = None,
2876 frame: int | None = None,
2877 channel: int | None = None,
2878 dtime: int | None = None,
2879 pixel_time: float | None = None,
2880 bishift: int | None = None,
2881 keepdims: bool = True,
2882 asxarray: bool = False,
2883 out: OutputType = None,
2884 ) -> NDArray[Any] | DataArray:
2885 """Return T3 mode point, line, or image histogram.
2886
2887 The histogram may not include photons counted during incomplete frame
2888 scans or during line retraces.
2889
2890 Parameters:
2891 selection:
2892 Indices for all dimensions:
2893
2894 - ``None``: return all items along axis (default).
2895 - ``Ellipsis``: return all items along multiple axes.
2896 - ``int``: return single item along axis.
2897 - ``slice``: return chunk of axis.
2898 ``slice.step`` is binning factor.
2899 If ``slice.step=-1``, integrate all items along axis.
2900
2901 records:
2902 Encoded TTTR records. By default, read records from file.
2903 dtype:
2904 Unsigned integer type of image histogram array.
2905 The default is ``uint16``. Increase the bit depth to avoid
2906 overflows when integrating.
2907 frame:
2908 If < 0, integrate time axis, else return specified frame.
2909 Overrides ``selection`` for axis ``T``.
2910 channel:
2911 If < 0, integrate channel axis, else return specified channel.
2912 Overrides ``selection`` for axis ``C``.
2913 dtime:
2914 Number of bins in image histogram.
2915 If 0, return :py:attr:`number_bins_in_period` bins.
2916 If < 0, integrate delay time axis.
2917 If > 0, return up to specified bin.
2918 Overrides ``selection`` for axis ``H``.
2919 pixel_time: float, optional
2920 Time per pixel in s.
2921 If zero, determine pixel times per line from line scan markers
2922 (cannot be used with bidirectional or line scans).
2923 The default is :py:attr:`PtuFile.pixel_time`.
2924 bishift:
2925 Global time shift of odd vs. even lines in bidirectional mode.
2926 The default is zero.
2927 Positive shifts invalidate left odd columns, while
2928 negative shifts invalidate right odd columns.
2929 keepdims:
2930 If true (default), reduced axes are left as size-one dimension.
2931 asxarray:
2932 If true, return ``xarray.DataArray``, else ``numpy.ndarray``
2933 (default).
2934 out:
2935 Array where decoded image histogram is stored.
2936 If ``None``, create a new NumPy array in main memory.
2937 If ``'memmap'``, create a memory-mapped array in a
2938 temporary file.
2939 If a ``numpy.ndarray``, a writable, initialized array
2940 of :py:attr:`shape` and unsigned integer dtype.
2941 If a ``file name`` or ``open file``, create a
2942 memory-mapped array in the specified file.
2943
2944 Returns:
2945 image:
2946 Decoded TTTR T3 records as up to 5-dimensional image array:
2947
2948 - ``'T'`` time/frame
2949 - ``'Y'`` slow scan axis for image scans
2950 - ``'X'`` fast scan axis for line and image scans
2951 - ``'C'`` channel
2952 - ``'H'`` histogram bins
2953
2954 Raises:
2955 NotImplementedError:
2956 T2 images, bidirectional sinusoidal scanning, and deprecated
2957 image reconstruction are not supported.
2958 IndexError:
2959 Selection is out of bounds.
2960
2961 """
2962 # TODO: support ReqHdr_ScanningPattern = 1, bidirectional per frame
2963 if not self.is_t3:
2964 # TODO: T2 images
2965 msg = 'not a T3 image'
2966 raise NotImplementedError(msg)
2967 if self.is_bidirectional and not self.is_image:
2968 msg = 'bidirectional scanning only supported for images'
2969 raise NotImplementedError(msg)
2970 if self.is_image and 'ImgHdr_LineStart' not in self.tags:
2971 # TODO: deprecated image reconstruction using
2972 # ImgHdr_PixResol, ImgHdr_TStartTo, ImgHdr_TStopTo,
2973 # ImgHdr_TStartFro, ImgHdr_TStopFro
2974 msg = 'old-style image reconstruction'
2975 raise NotImplementedError(msg)
2976
2977 shape = list(self.shape)
2978 ndim = len(shape)
2979 keepaxes: list[slice | int] = [slice(None)] * ndim
2980
2981 if selection is None:
2982 selection = [None] * ndim
2983 else:
2984 try:
2985 len(selection)
2986 except TypeError:
2987 selection = [selection] # type: ignore[list-item]
2988
2989 if len(selection) > ndim:
2990 msg = f'too many indices in {selection=}'
2991 raise IndexError(msg)
2992 if len(selection) == ndim:
2993 selection = list(selection).copy()
2994 if Ellipsis in selection:
2995 selection[selection.index(Ellipsis)] = None
2996 # elif len(selection) < ndim:
2997 elif Ellipsis in selection:
2998 selection = list(selection).copy()
2999 i = selection.index(Ellipsis)
3000 selection = (
3001 selection[:i]
3002 + ([None] * (1 + ndim - len(selection)))
3003 + selection[i + 1 :]
3004 )
3005 else:
3006 selection = list(selection) + [None] * (ndim - len(selection))
3007 if Ellipsis in selection:
3008 msg = f'more than one Ellipsis in {selection=}'
3009 raise IndexError(msg)
3010
3011 if frame is not None:
3012 if frame >= shape[0]:
3013 msg = f'{frame=} out of range'
3014 raise IndexError(msg)
3015 selection[0] = frame if frame >= 0 else slice(None, None, -1)
3016 if channel is not None:
3017 if channel >= shape[-2]:
3018 msg = f'{channel=} out of range'
3019 raise IndexError(msg)
3020 selection[-2] = channel if channel >= 0 else slice(None, None, -1)
3021 if dtime is not None:
3022 if dtime == 0:
3023 dtime = self.number_bins_in_period
3024 if dtime > 0:
3025 if dtime > self.number_bins_max:
3026 msg = f'{dtime=} out of range {self.number_bins_max}'
3027 raise IndexError(msg)
3028 selection[-1] = slice(0, dtime, 1)
3029 shape[-1] = dtime
3030 else:
3031 selection[-1] = slice(None, None, -1)
3032
3033 start = [0] * ndim
3034 step = [1] * ndim
3035 for i, (index, size) in enumerate(
3036 zip(selection, self.shape, strict=True)
3037 ):
3038 if index is None:
3039 pass
3040 elif isinstance(index, int):
3041 idx = index
3042 if idx < 0:
3043 idx %= shape[i]
3044 if not 0 <= idx < size:
3045 msg = f'axis {i} {idx=} out of range [0, {size}]'
3046 raise IndexError(msg)
3047 start[i] = idx
3048 shape[i] = 1
3049 keepaxes[i] = 0
3050 elif isinstance(index, slice):
3051 istart = index.start
3052 if istart is not None:
3053 if istart < 0:
3054 istart %= shape[i]
3055 if not 0 <= istart < shape[i]:
3056 msg = f'axis {i} {index=} start out of range'
3057 raise IndexError(msg)
3058 start[i] = istart
3059 if index.stop is not None:
3060 istop = index.stop
3061 if istop < 0:
3062 istop %= shape[i]
3063 if not start[i] < istop <= shape[i]:
3064 msg = f'axis {i} {index=} stop out of range'
3065 raise IndexError(msg)
3066 shape[i] = istop
3067 shape[i] -= start[i]
3068 if index.step is not None:
3069 if index.step == 0:
3070 msg = f'axis {i} slice step cannot be zero'
3071 raise IndexError(msg)
3072 if index.step < 0:
3073 # negative step size -> integrate all
3074 step[i] = shape[i]
3075 keepaxes[i] = 0
3076 else:
3077 step[i] = min(index.step, shape[i])
3078 shape[i] = shape[i] // step[i] + min(1, shape[i] % step[i])
3079 else:
3080 msg = f'axis {i} index type {type(index)!r} invalid'
3081 raise IndexError(msg)
3082
3083 if self._info.channels_active_first > 0 and 'C' in self._trimdims:
3084 # set channel offset
3085 start[-2] += self._info.channels_active_first
3086
3087 if pixel_time is None:
3088 global_pixel_time = self.global_pixel_time
3089 global_line_time = self.global_line_time
3090 elif pixel_time <= 0.0:
3091 global_pixel_time = 0
3092 global_line_time = 0
3093 if self.is_sinusoidal:
3094 msg = f'cannot use sinusoidal correction with {pixel_time=}'
3095 raise ValueError(msg)
3096 if ndim == 4:
3097 msg = f'cannot decode line scan with {pixel_time=}'
3098 raise ValueError(msg)
3099 else:
3100 global_pixel_time = max(
3101 1, round(pixel_time / self.global_resolution)
3102 )
3103 global_line_time = global_pixel_time * self.pixels_in_line
3104
3105 if self.is_sinusoidal:
3106 pixel_at_time = sinusoidal_correction(
3107 self.tags['ImgHdr_SinCorrection'],
3108 global_line_time,
3109 self.pixels_in_line,
3110 dtype=numpy.uint16, # should be enough for pixels_in_line
3111 )
3112 else:
3113 pixel_at_time = None
3114
3115 if dtype is None:
3116 dtype = self._dtype
3117 else:
3118 dtype = numpy.dtype(dtype)
3119 if dtype.kind != 'u':
3120 msg = f'not an unsigned integer {dtype=!r}'
3121 raise ValueError(msg)
3122
3123 histogram = create_output(out, shape, dtype, fillvalue=0)
3124 times = numpy.zeros(shape[0], numpy.uint64)
3125
3126 from ._ptufile import decode_t3_image, decode_t3_line, decode_t3_point
3127
3128 if records is None:
3129 records = self.read_records(copy=False)
3130
3131 if ndim == 5:
3132 if (
3133 self.line_start_mask == 0 # noqa: PLR1714
3134 or self.line_stop_mask == 0
3135 or (self.frame_change_mask == 0 and shape[0] > 1)
3136 or self.line_stop_mask == self.line_start_mask
3137 or self.frame_change_mask == self.line_start_mask
3138 or self.frame_change_mask == self.line_stop_mask
3139 ):
3140 logger().error(
3141 'invalid line_start, line_stop, or frame_change masks ('
3142 f'0b{self.line_start_mask:b}, '
3143 f'0b{self.line_stop_mask:b}, '
3144 f'0b{self.frame_change_mask:b})'
3145 )
3146 decode_t3_image(
3147 histogram,
3148 times,
3149 records,
3150 self.tags['TTResultFormat_TTTRRecType'],
3151 self.pixels_in_line,
3152 global_pixel_time,
3153 global_line_time,
3154 pixel_at_time if self.is_sinusoidal else None,
3155 self.line_start_mask,
3156 self.line_stop_mask,
3157 self.frame_change_mask,
3158 *start,
3159 *step,
3160 0 if bishift is None else bishift,
3161 self.is_bidirectional,
3162 self.is_sinusoidal,
3163 self._info.skip_first_frame,
3164 )
3165 elif ndim == 4:
3166 # not tested
3167 if (
3168 self.line_start_mask == 0 # noqa: PLR1714
3169 or self.line_stop_mask == 0
3170 or self.line_stop_mask == self.line_start_mask
3171 ):
3172 logger().error(
3173 'invalid line_start or line_stop masks ('
3174 f'0b{self.line_start_mask:b}, 0b{self.line_stop_mask:b})'
3175 )
3176 decode_t3_line(
3177 histogram,
3178 times,
3179 records,
3180 self.tags['TTResultFormat_TTTRRecType'],
3181 global_pixel_time,
3182 self.line_start_mask,
3183 self.line_stop_mask,
3184 *start,
3185 *step,
3186 )
3187 elif ndim == 3:
3188 decode_t3_point(
3189 histogram,
3190 times,
3191 records,
3192 self.tags['TTResultFormat_TTTRRecType'],
3193 global_pixel_time,
3194 *start,
3195 *step,
3196 )
3197
3198 if not keepdims:
3199 histogram = histogram[tuple(keepaxes)]
3200
3201 if not self._asxarray and not asxarray:
3202 return histogram
3203
3204 from xarray import DataArray
3205
3206 if self._info.channels_active_first > 0 and 'C' in self._trimdims:
3207 # unset channel offset
3208 start[-2] -= self._info.channels_active_first
3209
3210 dims = []
3211 coords = self.coords.copy()
3212 for i, ax in enumerate(self.dims):
3213 if keepdims or keepaxes[i] != 0:
3214 dims.append(ax)
3215 if ax in coords:
3216 index = slice(
3217 start[i], start[i] + shape[i] * step[i], step[i]
3218 )
3219 coords[ax] = coords[ax][index]
3220 elif ax in coords:
3221 del coords[ax]
3222 if 'H' in dims and len(coords['H']) < shape[-1]:
3223 coords['H'] = numpy.linspace(
3224 0,
3225 shape[-1] * coords['H'][1],
3226 shape[-1],
3227 endpoint=False,
3228 )
3229 if 'T' in dims:
3230 coords['T'] = times * self.global_resolution
3231
3232 return DataArray(
3233 histogram,
3234 dims=dims,
3235 coords=coords,
3236 attrs=self.attrs,
3237 # name=self.name,
3238 )
3239
3240 def plot(
3241 self,
3242 *,
3243 samples: int | None = None,
3244 frame: int | None = None,
3245 channel: int | None = None,
3246 dtime: int | None = -1,
3247 verbose: bool = False,
3248 show: bool = True,
3249 **kwargs: Any,
3250 ) -> None:
3251 """Plot histograms using matplotlib.
3252
3253 Parameters:
3254 samples:
3255 Number of bins along measurement for T2 mode.
3256 The default is 1000.
3257 frame:
3258 If < 0, integrate time axis, else show specified frame.
3259 By default, all frames are shown. Applies to T3 images.
3260 channel:
3261 If < 0, integrate channel axis, else show specified channel.
3262 By default, all channels are shown. Applies to T3 images.
3263 dtime:
3264 Number of bins in T3 histograms.
3265 If < 0 (default), integrate delay time axis of images.
3266 If 0, show :py:attr:`number_bins_in_period` bins.
3267 If > 0, show histograms up to specified bin.
3268 If None, show all bins.
3269 verbose:
3270 Print information about histogram arrays.
3271 show:
3272 If true (default), display all figures.
3273 Else, defer to user or environment to display figures.
3274 **kwargs:
3275 Additional arguments passed to ``tifffile.imshow``.
3276
3277 """
3278 from matplotlib import pyplot
3279 from tifffile import Timer, imshow
3280
3281 t = Timer()
3282 if self.is_t3:
3283 if self.measurement_ndim > 1:
3284 t.start()
3285 histogram: Any = self.decode_image(
3286 frame=frame, channel=channel, dtime=dtime, asxarray=True
3287 )
3288 if verbose:
3289 print()
3290 t.print('decode_image')
3291 print()
3292 print(histogram.squeeze())
3293 imshow(
3294 numpy.transpose(
3295 histogram.values, (0, 3, 4, 1, 2)
3296 ).squeeze(),
3297 title=repr(self),
3298 photometric='minisblack',
3299 **kwargs,
3300 )
3301 pyplot.figure()
3302 t.start()
3303 # histogram = histogram.sum(axis=(0, 1, 2), dtype=numpy.uint32)
3304 dtime = None if dtime is None or dtime < 0 else dtime
3305 histogram = self.decode_histogram(asxarray=True, dtime=dtime)
3306 else:
3307 if samples is None or samples < 1:
3308 samples = 1000
3309 histogram = self.decode_histogram(
3310 sampling_time=self.global_acquisition_time // samples,
3311 asxarray=True,
3312 )
3313 if verbose:
3314 print()
3315 t.print('decode_histogram')
3316 print()
3317 print(histogram)
3318 channels = histogram.coords['C'].values
3319 for i, hist in enumerate(histogram):
3320 pyplot.plot(
3321 hist.coords['H'], hist.values, label=f'ch {channels[i]}'
3322 )
3323 if self.frequency > 0.0:
3324 pyplot.axvline(x=1 / self.frequency, color='0.5', ls=':', lw=0.75)
3325 pyplot.title(repr(self))
3326 pyplot.xlabel('delay time [s]' if self.is_t3 else 'time [s]')
3327 pyplot.ylabel('photon count')
3328 pyplot.legend()
3329 if show:
3330 pyplot.show()
3331
3332
3333 class PhuMeasurementMode(enum.IntEnum):
3334 """Kind of TCSPC measurement (Measurement_Mode tag)."""
3335
3336 UNKNOWN = -1
3337 """Unknown mode."""
3338
3339 HISTOGRAM = 0
3340 """Histogram mode."""
3341
3342 CONTI = 8
3343 """Conti mode."""
3344
3345 @classmethod
3346 def _missing_(cls, value: object) -> object:
3347 if not isinstance(value, int):
3348 return None
3349 obj = cls(-1) # Unknown
3350 obj._value_ = value
3351 return obj
3352
3353
3354 class PhuMeasurementSubMode(enum.IntEnum):
3355 """Kind of measurement (Measurement_SubMode tag)."""
3356
3357 UNKNOWN = -1
3358 """Unknown mode."""
3359
3360 OSCILLOSCOPE = 0
3361 """Oscilloscope mode."""
3362
3363 INTEGRATING = 1
3364 """Integrating mode."""
3365
3366 TRES = 2
3367 """Time-Resolved Emission Spectra mode."""
3368
3369 SEQ = 3
3370 """Sequence mode."""
3371
3372 @classmethod
3373 def _missing_(cls, value: object) -> object:
3374 if not isinstance(value, int):
3375 return None
3376 obj = cls(-1)
3377 obj._value_ = value
3378 return obj
3379
3380
3381 class PtuMeasurementMode(enum.IntEnum):
3382 """Kind of TCSPC Measurement (Measurement_Mode tag)."""
3383
3384 UNKNOWN = -1
3385 """Unknown mode."""
3386
3387 T2 = 2
3388 """T2 mode."""
3389
3390 T3 = 3
3391 """T3 mode."""
3392
3393 @classmethod
3394 def _missing_(cls, value: object) -> object:
3395 if not isinstance(value, int):
3396 return None
3397 obj = cls(-1) # Unknown
3398 obj._value_ = value
3399 return obj
3400
3401
3402 class PtuMeasurementSubMode(enum.IntEnum):
3403 """Kind of measurement (Measurement_SubMode tag)."""
3404
3405 UNKNOWN = -1
3406 """Unknown mode."""
3407
3408 POINT = 1
3409 """Point scan mode."""
3410
3411 LINE = 2
3412 """Line scan mode."""
3413
3414 IMAGE = 3
3415 """Image scan mode."""
3416
3417 @classmethod
3418 def _missing_(cls, value: object) -> object:
3419 if not isinstance(value, int):
3420 return None
3421 obj = cls(1 if value == 0 else -1)
3422 obj._value_ = value
3423 return obj
3424
3425
3426 class PtuScannerType(enum.IntEnum):
3427 """Scanner hardware (ImgHdr_Ident tag)."""
3428
3429 UNKNOWN = -1
3430 """Unknown scanner."""
3431
3432 PI_E710 = 1
3433 """PI E-710 scanner."""
3434
3435 LSM = 3
3436 """PicoQuant LSM scanner."""
3437
3438 PI_LINEWBS = 5
3439 """PI Line WB scanner."""
3440
3441 PI_E725 = 6
3442 """PI E-725 scanner."""
3443
3444 PI_E727 = 7
3445 """PI E-727 scanner."""
3446
3447 MCL = 8
3448 """MCL scanner."""
3449
3450 FLIMBEE = 9
3451 """PicoQuant FLIMBee scanner."""
3452
3453 SCANBOX = 10
3454 """Zeiss ScanBox scanner."""
3455
3456 @classmethod
3457 def _missing_(cls, value: object) -> object:
3458 if not isinstance(value, int):
3459 return None
3460 obj = cls(-1) # Unknown
3461 obj._value_ = value
3462 return obj
3463
3464
3465 class PtuScanDirection(enum.IntEnum):
3466 """Scan direction (ImgHdr_ScanDirection tag)."""
3467
3468 XY = 0
3469 """X-Y scan."""
3470
3471 XZ = 1
3472 """X-Z scan."""
3473
3474 YZ = 2
3475 """Y-Z scan."""
3476
3477 @classmethod
3478 def _missing_(cls, value: object) -> object:
3479 if not isinstance(value, int) or value != 0:
3480 return None
3481 obj = cls(0) # XY
3482 obj._value_ = value
3483 return obj
3484
3485
3486 class PtuStopReason(enum.IntEnum):
3487 """Reason for measurement end (TTResult_StopReason tag)."""
3488
3489 TIME_OVER = 0
3490 MANUAL = 1
3491 OVERFLOW = 2
3492 ERROR = 3
3493 UNKNOWN = -1
3494 FIFO_OVERRUN = -2
3495 LEGACY_ERROR = -3
3496 TCSPC_ERROR = -4
3497 FILE_ERROR = -5
3498 OUT_OF_MEMORY = -6
3499 SUSPENDED = -7
3500 SYS_ERROR = -8
3501 QUEUE_OVERRUN = -9
3502 DATA_XFER_FAIL = -10
3503 DATA_CHECK_FAIL = -11
3504 REF_CLK_LOST = -12
3505 SYNC_LOST = -13
3506
3507 @classmethod
3508 def _missing_(cls, value: object) -> object:
3509 if not isinstance(value, int):
3510 return None
3511 obj = cls(-1) # Unknown
3512 obj._value_ = value
3513 return obj
3514
3515
3516 class PtuMeasurementWarnings(enum.IntFlag):
3517 """Warnings during measurement (TTResult_MDescWarningFlags tag)."""
3518
3519 SYNC_RATE_ZERO = 0x1
3520 SYNC_RATE_TOO_LOW = 0x2
3521 SYNC_RATE_TOO_HIGH = 0x4
3522 INPT_RATE_ZERO = 0x10
3523 INPT_RATE_TOO_HIGH = 0x40
3524 EVENTS_DROPPED = 0x80
3525 INPT_RATE_RATIO = 0x100
3526 DIVIDER_GT_ONE = 0x200
3527 TIME_SPAN_TOO_SMALL = 0x400
3528 OFFSET_UNNECESSARY = 0x800
3529
3530
3531 class PtuHwFeatures(enum.IntFlag):
3532 """Hardware features (HW_Features tag)."""
3533
3534 DLL = 0x1
3535 TTTR = 0x2
3536 MARKERS = 0x4
3537 LOW_RES = 0x8
3538 TRIG_OUT = 0x10
3539 PROG_DEADTIME = 0x20
3540 EXT_FPGA = 0x40
3541 PROG_HYSTERESES = 0x80
3542 COINCIDENCE_FILTERING = 0x100
3543 INPUT_MODES = 0x200
3544
3545
3546 class PqTagType(enum.IntEnum):
3547 """Tag type definition."""
3548
3549 Empty8 = 0xFFFF0008
3550 Bool8 = 0x00000008
3551 Int8 = 0x10000008
3552 BitSet64 = 0x11000008
3553 Color8 = 0x12000008
3554 Float8 = 0x20000008
3555 TDateTime = 0x21000008
3556 Float8Array = 0x2001FFFF
3557 AnsiString = 0x4001FFFF
3558 WideString = 0x4002FFFF
3559 BinaryBlob = 0xFFFFFFFF
3560
3561
3562 class PtuRecordType(enum.IntEnum):
3563 """TTTR record type."""
3564
3565 PicoHarpT3 = 0x00010303
3566 """PicoHarp 300 T3."""
3567
3568 PicoHarpT2 = 0x00010203
3569 """PicoHarp 300 T2."""
3570
3571 HydraHarpT3 = 0x00010304
3572 """HydraHarp V1.x T3."""
3573
3574 HydraHarpT2 = 0x00010204
3575 """HydraHarp V1.x T2."""
3576
3577 HydraHarp2T3 = 0x01010304
3578 """HydraHarp V2.x T3."""
3579
3580 HydraHarp2T2 = 0x01010204
3581 """HydraHarp V2.x T2."""
3582
3583 TimeHarp260NT3 = 0x00010305
3584 """TimeHarp 260N T3."""
3585
3586 TimeHarp260NT2 = 0x00010205
3587 """TimeHarp 260N T2."""
3588
3589 TimeHarp260PT3 = 0x00010306
3590 """TimeHarp 260P T3."""
3591
3592 TimeHarp260PT2 = 0x00010206
3593 """TimeHarp 260P T2."""
3594
3595 GenericT2 = 0x00010207
3596 """MultiHarp and Picoharp 330 T2."""
3597
3598 GenericT3 = 0x00010307
3599 """MultiHarp and Picoharp 330 T3."""
3600
3601
3602 @dataclasses.dataclass
3603 class PtuInfo:
3604 """Information about decoded TTTR records.
3605
3606 Returned by ``_ptufile.decode_info``.
3607
3608 """
3609
3610 format: int
3611 """Type of records."""
3612
3613 records: int
3614 """Number of records."""
3615
3616 photons: int
3617 """Number of photons counted."""
3618
3619 markers: int
3620 """Number of marker events."""
3621
3622 frames: int
3623 """Number of frames detected. May exclude incomplete frames."""
3624
3625 lines: int
3626 """Number of lines between line markers."""
3627
3628 channels: int
3629 """Maximum number of channels for record type."""
3630
3631 channels_active: int
3632 """Bitfield identifying channels with photons."""
3633
3634 channels_active_first: int
3635 """First channel with photons."""
3636
3637 channels_active_last: int
3638 """Last channel with photons."""
3639
3640 bins: int
3641 """Maximum delay time for record type."""
3642
3643 bins_used: int
3644 """Number of bins up to the largest occupied delay-time bin."""
3645
3646 skip_first_frame: bool
3647 """First frame of multi-frame image is incomplete."""
3648
3649 skip_last_frame: bool
3650 """Last frame of multi-frame image is incomplete."""
3651
3652 line_time: int
3653 """Average global time between line markers."""
3654
3655 acquisition_time: int
3656 """Global time of last sync event."""
3657
3658 def __str__(self) -> str:
3659 return indent(
3660 f'{self.__class__.__name__}(',
3661 *(f'{key}={value},' for key, value in self.__dict__.items()),
3662 end='\n)',
3663 )
3664
3665
3666 T2_RECORD_DTYPE = numpy.dtype(
3667 [
3668 ('time', numpy.uint64),
3669 ('channel', numpy.int8),
3670 ('marker', numpy.uint8),
3671 ]
3672 )
3673 """Numpy dtype of decoded T2 records."""
3674
3675 T3_RECORD_DTYPE = numpy.dtype(
3676 [
3677 ('time', numpy.uint64),
3678 ('dtime', numpy.int16),
3679 ('channel', numpy.int8),
3680 ('marker', numpy.uint8),
3681 ]
3682 )
3683 """Numpy dtype of decoded T3 records."""
3684
3685 FILE_EXTENSIONS = {
3686 '.ptu': PqFileType.PTU,
3687 '.phu': PqFileType.PHU,
3688 '.pck': PqFileType.PCK,
3689 '.pco': PqFileType.PCO,
3690 '.pfs': PqFileType.PFS,
3691 '.pus': PqFileType.PFS,
3692 '.pqres': PqFileType.PQRES,
3693 '.pqdat': PqFileType.PQDAT,
3694 '.pquni': PqFileType.PQUNI,
3695 '.pqover': PqFileType.PQOVER,
3696 '.spqr': PqFileType.SPQR,
3697 }
3698 """File extensions of PicoQuant tagged files."""
3699
3700
3701 def binwrite(
3702 filename: str | os.PathLike[str],
3703 data: ArrayLike,
3704 /,
3705 tcspc_resolution: float,
3706 pixel_resolution: float,
3707 ) -> None:
3708 """Write TCSPC image histogram and metadata to PicoQuant BIN file.
3709
3710 Parameters:
3711 filename:
3712 Name of PicoQuant BIN file.
3713 data:
3714 TCSPC image histogram array of shape (length, width, bins).
3715 Must be compatible with dtype.uint32.
3716 tcspc_resolution:
3717 TCSPC resolution in s.
3718 pixel_resolution:
3719 Pixel resolution in μm.
3720
3721 """
3722 data = numpy.asarray(data, '<u4')
3723 if data.ndim != 3:
3724 msg = f'invalid {data.ndim=} != 3'
3725 raise ValueError(msg)
3726 with open(filename, 'wb') as fh:
3727 fh.write(
3728 struct.pack(
3729 '<IIfIf',
3730 data.shape[1], # size_x
3731 data.shape[0], # size_y
3732 pixel_resolution,
3733 data.shape[2], # size_h
3734 tcspc_resolution * 1e9,
3735 )
3736 )
3737 fh.write(data.tobytes())
3738
3739
3740 def binread(
3741 filename: str | os.PathLike[str], /, *, memmap: bool = False
3742 ) -> tuple[NDArray[Any], dict[str, Any]]:
3743 """Return TCSPC image histogram and metadata from PicoQuant BIN file.
3744
3745 Parameters:
3746 filename:
3747 Name of PicoQuant BIN file.
3748 memmap:
3749 If true, return a read-only memory-mapped array.
3750
3751 Returns:
3752 tuple:
3753 - histogram:
3754 TCSPC image histogram array of shape (length, width, bins).
3755 - metadata:
3756 Dictionary with metadata.
3757
3758 - 'shape': Shape of histogram array.
3759 - 'pixel_resolution': Pixel resolution in μm.
3760 - 'tcspc_resolution': TCSPC resolution in s.
3761
3762 """
3763 data: NDArray[Any]
3764 with open(filename, 'rb') as fh:
3765 size_x, size_y, pixel_resolution, size_h, tcspc_resolution = (
3766 struct.unpack('<IIfIf', fh.read(20))
3767 )
3768 shape = size_y, size_x, size_h
3769 if not memmap:
3770 data = numpy.empty(shape, '<u4')
3771 if fh.readinto(data) != size_y * size_x * size_h * 4:
3772 msg = 'file too short'
3773 raise ValueError(msg)
3774 if memmap:
3775 data = numpy.memmap(filename, '<u4', 'r', offset=20, shape=shape)
3776 return data, {
3777 'shape': shape,
3778 'pixel_resolution': pixel_resolution,
3779 'tcspc_resolution': tcspc_resolution * 1e-9,
3780 }
3781
3782
3783 def encode_tag(tagid: str, value: Any, index: int = -1, /) -> bytes:
3784 """Return encoded PicoQuant tag.
3785
3786 Parameters:
3787 tagid: Tag identifier string.
3788 value: Tag value to encode.
3789 index: Array index for tag values, -1 for single values.
3790
3791 Returns:
3792 Encoded tag as bytes.
3793
3794 """
3795 match value:
3796 case None:
3797 typecode = PqTagType.Empty8
3798 buffer = b'\x00\x00\x00\x00\x00\x00\x00\x00'
3799 case bool() as v:
3800 # must check bool before int
3801 typecode = PqTagType.Bool8
3802 buffer = struct.pack('<q', v)
3803 case enum.IntFlag() as v:
3804 # must check IntFlag before int
3805 typecode = PqTagType.BitSet64
3806 buffer = struct.pack('<q', v)
3807 case int() as v:
3808 typecode = PqTagType.Int8
3809 buffer = struct.pack('<q', v)
3810 case float() as v:
3811 typecode = PqTagType.Float8
3812 buffer = struct.pack('<d', v)
3813 case str() as v:
3814 if not v.endswith('\0'):
3815 v += '\0'
3816 try:
3817 typecode = PqTagType.AnsiString
3818 value_ = v.encode('windows-1252')
3819 except UnicodeEncodeError:
3820 typecode = PqTagType.WideString
3821 value_ = v.encode('utf-16-le')
3822 value_ += align_bytes(len(value_), 8)
3823 buffer = struct.pack('<q', len(value_)) + value_
3824 case datetime() as v:
3825 typecode = PqTagType.TDateTime
3826 v -= datetime(1899, 12, 30) # type: ignore[assignment]
3827 v /= timedelta(days=1) # type: ignore[operator]
3828 buffer = struct.pack('<d', v)
3829 case uuid.UUID() as v:
3830 typecode = PqTagType.AnsiString
3831 v = f'{{{v}}}'.encode('windows-1252')
3832 v += align_bytes(len(v), 8)
3833 buffer = struct.pack('<q', len(v)) + v
3834 case bytes() as v:
3835 typecode = PqTagType.BinaryBlob
3836 v += align_bytes(len(v), 8)
3837 buffer = struct.pack('<q', len(v)) + v
3838 case _:
3839 # TODO: support Color8 and Float8Array
3840 msg = f'{type(value)=} not supported'
3841 raise ValueError(msg)
3842
3843 # tags always have lengths divisible by 8
3844 assert len(buffer) % 8 == 0
3845 return struct.pack('<32siI', tagid.encode(), index, typecode) + buffer
3846
3847
3848 def sinusoidal_correction(
3849 sincorrect: float,
3850 /,
3851 global_line_time: int,
3852 pixels_in_line: int,
3853 *,
3854 dtype: DTypeLike | None = None,
3855 is_amplitude: bool = True,
3856 ) -> NDArray[Any]:
3857 """Return pixel indices of global times in line for sinusoidal scanning.
3858
3859 Parameters:
3860 sincorrect:
3861 Amount of sine wave used for measurement.
3862 Either percentage of amplitude (PicoQuant) or period (Leica)
3863 depending on ``is_amplitude``.
3864 The value of the ``ImgHdr_SinCorrection`` tag.
3865 global_line_time:
3866 Global time per line.
3867 pixels_in_line:
3868 Number of pixels in line.
3869 is_amplitude:
3870 Correction value is percentage of amplitude of sine wave.
3871 If false, correction value is percentage of period of sine wave.
3872
3873 Returns:
3874 Array of size ``global_line_time``, mapping global time in line to
3875 pixel index in line.
3876
3877 """
3878 dtype = numpy.dtype(numpy.uint16 if dtype is None else dtype)
3879 if sincorrect <= 0.0 or sincorrect > 100.0:
3880 msg = f'{sincorrect=} out of range'
3881 raise ValueError(msg)
3882 if global_line_time < 2:
3883 msg = f'{global_line_time=} out of range'
3884 raise ValueError(msg)
3885 if pixels_in_line < 2 or pixels_in_line >= numpy.iinfo(dtype).max:
3886 msg = f'{pixels_in_line=} out of range'
3887 raise ValueError(msg)
3888 if not is_amplitude:
3889 sincorrect = math.sin(sincorrect * math.pi / 200.0) * 100.0
3890 limit = math.asin(-sincorrect / 100.0)
3891 a = numpy.linspace(limit, -limit, global_line_time, endpoint=False)
3892 a = numpy.sin(a)
3893 a *= -0.5 * pixels_in_line / a[0]
3894 a -= a[0]
3895 return a.astype(dtype)
3896
3897
3898 def create_output(
3899 out: OutputType,
3900 /,
3901 shape: Sequence[int],
3902 dtype: DTypeLike | None,
3903 *,
3904 mode: Literal['r+', 'w+', 'r', 'c'] = 'w+',
3905 suffix: str | None = None,
3906 fillvalue: float | None = None,
3907 ) -> NDArray[Any] | numpy.memmap[Any, Any]:
3908 """Return NumPy array where data of shape and dtype can be copied.
3909
3910 Parameters:
3911 out:
3912 Specifies kind of array of ``shape`` and ``dtype`` to return:
3913
3914 ``None``:
3915 Return new array.
3916 ``numpy.ndarray``:
3917 Return view of existing array.
3918 ``'memmap'`` or ``'memmap:tempdir'``:
3919 Return memory-map to array stored in temporary binary file.
3920 ``str`` or open file:
3921 Return memory-map to array stored in specified binary file.
3922 shape:
3923 Shape of array to return.
3924 dtype:
3925 Data type of array to return.
3926 If ``out`` is an existing array, ``dtype`` must be castable to its
3927 data type.
3928 mode:
3929 File mode to create memory-mapped array.
3930 The default is 'w+' to create new, or overwrite existing file for
3931 reading and writing.
3932 suffix:
3933 Suffix of ``NamedTemporaryFile`` if ``out`` is ``'memmap'``.
3934 The default is '.memmap'.
3935 fillvalue:
3936 Value to initialize output array.
3937 By default, return uninitialized array.
3938
3939 Returns:
3940 NumPy array or memory-mapped array of ``shape`` and ``dtype``.
3941
3942 Raises:
3943 ValueError:
3944 Existing array cannot be reshaped to ``shape``
3945 or cast to ``dtype``.
3946
3947 """
3948 shape = tuple(shape)
3949 dtype = numpy.dtype(dtype)
3950 if out is None:
3951 if fillvalue is None:
3952 return numpy.empty(shape, dtype)
3953 if fillvalue:
3954 return numpy.full(shape, fillvalue, dtype)
3955 return numpy.zeros(shape, dtype)
3956 if isinstance(out, numpy.ndarray):
3957 if product(shape) != product(out.shape):
3958 msg = f'cannot reshape {shape} to {out.shape}'
3959 raise ValueError(msg)
3960 if not numpy.can_cast(dtype, out.dtype):
3961 msg = f'cannot cast {dtype} to {out.dtype}'
3962 raise ValueError(msg)
3963 if out.shape != shape:
3964 out = out.reshape(shape, copy=False)
3965 if fillvalue is not None:
3966 out.fill(fillvalue)
3967 return out
3968 if isinstance(out, str) and out[:6] == 'memmap':
3969 import tempfile
3970
3971 tempdir = out[7:] if len(out) > 7 else None
3972 if suffix is None:
3973 suffix = '.memmap'
3974 with tempfile.NamedTemporaryFile(dir=tempdir, suffix=suffix) as fh:
3975 out = numpy.memmap(fh, shape=shape, dtype=dtype, mode=mode)
3976 if fillvalue is not None:
3977 out.fill(fillvalue)
3978 return out
3979 out = numpy.memmap(out, shape=shape, dtype=dtype, mode=mode)
3980 if fillvalue is not None:
3981 out.fill(fillvalue)
3982 return out
3983
3984
3985 def product(iterable: Iterable[int], /) -> int:
3986 """Return product of integers.
3987
3988 Like math.prod, but does not overflow with numpy arrays.
3989
3990 """
3991 prod = 1
3992 for i in iterable:
3993 prod *= int(i)
3994 return prod
3995
3996
3997 def now() -> datetime:
3998 """Return current date and time."""
3999 return datetime.now()
4000
4001
4002 def align_bytes(size: int, align: int, /) -> bytes:
4003 """Return trailing bytes to align bytes of size."""
4004 size %= align
4005 return b'' if size == 0 else b'\0' * (align - size)
4006
4007
4008 def indent(*args: Any, sep: str = '', end: str = '') -> str:
4009 """Return joined string representations of objects with indented lines."""
4010 text = (sep + '\n').join(
4011 arg if isinstance(arg, str) else repr(arg) for arg in args
4012 )
4013 return (
4014 '\n'.join(
4015 (' ' + line if line else line)
4016 for line in text.splitlines()
4017 if line
4018 )[4:]
4019 + end
4020 )
4021
4022
4023 def logger() -> logging.Logger:
4024 """Return logger for ptufile module."""
4025 return logging.getLogger('ptufile')
4026
4027
4028 def askopenfilename(**kwargs: Any) -> str:
4029 """Return file name(s) from Tkinter's file open dialog."""
4030 from tkinter import Tk, filedialog
4031
4032 root = Tk()
4033 root.withdraw()
4034 root.update()
4035 filenames = filedialog.askopenfilename(**kwargs)
4036 root.destroy()
4037 return filenames
4038
4039
4040 def main(argv: list[str] | None = None) -> int:
4041 """Command line usage main function.
4042
4043 Preview image and metadata in specified files or all files in directory.
4044
4045 ``python -m ptufile file_or_directory``
4046
4047 """
4048 from glob import glob
4049
4050 from tifffile import Timer
4051
4052 if argv is None:
4053 argv = sys.argv
4054
4055 fltr = False
4056 if len(argv) == 1:
4057 path = askopenfilename(
4058 title='Select a PTU file',
4059 filetypes=[
4060 (f'{ext.upper()} files', f'*{ext}') for ext in FILE_EXTENSIONS
4061 ]
4062 + [('All files', '*')],
4063 )
4064 files = [path] if path else []
4065 elif '*' in argv[1]:
4066 files = glob(argv[1])
4067 elif os.path.isdir(argv[1]):
4068 files = glob(f'{argv[1]}/*.p*')
4069 fltr = True
4070 else:
4071 files = argv[1:]
4072
4073 for filename in files:
4074 if (
4075 fltr
4076 and os.path.splitext(filename)[-1].lower() not in FILE_EXTENSIONS
4077 ):
4078 continue
4079 try:
4080 with PqFile(filename) as pq:
4081 if pq.type == PqFileType.PTU:
4082 t = Timer()
4083 with PtuFile(filename, memmap=True) as ptu:
4084 t.print(' open file')
4085 t.start()
4086 ptu.read_records(copy=False)
4087 t.print('read records')
4088 t.start()
4089 ptu_info = ptu._info
4090 t.print('scan records')
4091 # t.start()
4092 # ptu.decode_records()
4093 # t.print('decode records')
4094 print()
4095 print(ptu)
4096 print(ptu_info)
4097 try:
4098 ptu.plot(verbose=True)
4099 except NotImplementedError as exc:
4100 print('NotImplementedError:', exc)
4101 elif pq.type == PqFileType.PHU:
4102 with PhuFile(filename, memmap=True) as phu:
4103 print(phu)
4104 phu.plot(verbose=True)
4105 else:
4106 print(pq)
4107 print()
4108 except Exception:
4109 import traceback
4110
4111 print('Failed to read', filename)
4112 traceback.print_exc()
4113 print()
4114 continue
4115
4116 return 0
4117
4118
4119 if __name__ == '__main__':
4120 sys.exit(main())