ptufile

Read and write PicoQuant PTU and related files.

Ptufile is a Python library to

  1. read data and metadata from PicoQuant PTU and related files (PHU, PCK, PCO, PFS, PUS, PQRES, PQDAT, PQUNI, SPQR, and BIN), and

  2. write TCSPC histograms to T3 image mode PTU files.

PTU files contain time correlated single photon counting (TCSPC) measurement data and instrumentation parameters.

Author:

Christoph Gohlke

License:

BSD-3-Clause

Version:

2026.3.21

DOI:

10.5281/zenodo.10120021

Quickstart

Install the ptufile package and all dependencies from the Python Package Index:

python -m pip install -U "ptufile[all]"

See Examples for using the programming interface.

Source code and support are available on GitHub.

Requirements

This revision was tested with the following requirements and dependencies (other versions may work):

Revisions

2026.3.21

  • Add bounds checking to encode_t3_image function.

  • Use format-dispatch in hot decode loops to allow compiler inlining.

  • Build wheels on Windows with LLVM (30% faster decoding than MSVC).

  • Drop support for Python 3.11.

2026.2.6

  • Fix code review issues.

2026.1.14

  • Improve code quality.

2025.12.12

  • Add PQUNI file type.

  • Add attrs properties and return with xarray DataSets.

  • Improve code quality.

2025.11.8

  • Fix reading files with negative TTResult_NumberOfRecords.

  • Remove cache argument from PtuFile.read_records (breaking).

  • Add cache_records property to PtuFile to control caching behavior.

  • Derive PqFileError from ValueError.

  • Factor out BinaryFile base class.

  • Build ABI3 wheels.

2025.9.9

  • Log error when decoding image with invalid line or frame masks.

2025.7.30

  • Add option to specify pixel time for decoding images.

  • Add functions to read and write PicoQuant BIN files.

  • Drop support for Python 3.10.

2025.5.10

  • Mark Cython extension free-threading compatible.

  • Support Python 3.14.

2025.2.20

Refer to the CHANGES file for older revisions.

Notes

PicoQuant GmbH is a manufacturer of photonic components and instruments.

The PicoQuant unified file formats are documented at the PicoQuant-Time-Tagged-File-Format-Demos.

The following features are currently not implemented due to the lack of test files or documentation: PT2 and PT3 files, decoding images from T2 and SPQR formats, bidirectional per frame, and deprecated image reconstruction.

Compatibility with PTU files written by non-PicoQuant software (for example, Leica LAS X or Abberior Imspector) is limited, as is decoding line, bidirectional, and sinusoidal scanning.

Other modules for reading or writing PicoQuant files are Read_PTU.py, readPTU, readPTU_FLIM, fastFLIM, PyPTU, PTU_Reader, PTU_Writer, FlimReader, tangy, tttrlib, picoquantio, ptuparser, phconvert, trattoria (wrapper of trattoria-core, tttr-toolbox), PAM, FLOPA, and napari-flim-phasor-plotter.

Examples

Read properties and tags from any type of PicoQuant unified tagged file:

>>> pq = PqFile('tests/data/Settings.pfs')
>>> pq.type
<PqFileType.PFS: ...>
>>> pq.guid
UUID('86d428e2-cb0b-4964-996c-04456ba6be7b')
>>> pq.tags
{...'CreatorSW_Name': 'SymPhoTime 64', 'CreatorSW_Version': '2.1'...}
>>> pq.close()

Read metadata from a PicoQuant PTU FLIM file:

>>> ptu = PtuFile('tests/data/FLIM.ptu')
>>> ptu.type
<PqFileType.PTU: ...>
>>> ptu.record_type
<PtuRecordType.PicoHarpT3: 66307>
>>> ptu.measurement_mode
<PtuMeasurementMode.T3: 3>
>>> ptu.measurement_submode
<PtuMeasurementSubMode.IMAGE: 3>

Decode TTTR records from the PTU file to numpy.recarray:

>>> decoded = ptu.decode_records()
>>> decoded.dtype
dtype([('time', '<u8'), ('dtime', '<i2'), ('channel', 'i1'), ('marker', 'u1')])

Get global times of frame changes from markers:

>>> decoded['time'][(decoded['marker'] & ptu.frame_change_mask) > 0]
array([1571185680], dtype=uint64)

Decode TTTR records to overall delay-time histograms per channel:

>>> ptu.decode_histogram(dtype='uint8')
array([[ 5,  7,  7, ..., 10,  9,  2]], shape=(2, 3126), dtype=uint8)

Get information about the FLIM image histogram in the PTU file:

>>> ptu.shape
(1, 256, 256, 2, 3126)
>>> ptu.dims
('T', 'Y', 'X', 'C', 'H')
>>> ptu.coords
{'T': ..., 'Y': ..., 'X': ..., 'H': ...}
>>> ptu.dtype
dtype('uint16')
>>> ptu.active_channels
(0, 1)

Decode parts of the image histogram to numpy.ndarray using slice notation. Slice step sizes define binning, -1 being used to integrate along axis:

>>> ptu[:, ..., 0, ::-1]
array([[[103, ..., 38],
              ...
        [ 47, ..., 30]]],
      shape=(1, 256, 256), dtype=uint16)

Alternatively, decode the first channel and integrate all histogram bins into a xarray.DataArray, keeping reduced axes:

>>> ptu.decode_image(channel=0, dtime=-1, asxarray=True)
<xarray.DataArray (T: 1, Y: 256, X: 256, C: 1, H: 1)> ...
array([[[[[103]],
           ...
         [[ 30]]]]], shape=(1, 256, 256, 1, 1), dtype=uint16)
Coordinates:
  * T        (T) float64... 0.05625
  * Y        (Y) float64... -0.0001304 ... 0.0001294
  * X        (X) float64... -0.0001304 ... 0.0001294
  * C        (C) uint8... 0
  * H        (H) float64... 0.0
Attributes...
    name:                     FLIM.ptu
...

Write the TCSPC histogram and metadata to a PicoHarpT3 image mode PTU file:

>>> imwrite(
...     '_test.ptu',
...     ptu[:],
...     ptu.global_resolution,
...     ptu.tcspc_resolution,
...     # optional metadata
...     pixel_time=ptu.pixel_time,
...     record_type=PtuRecordType.PicoHarpT3,
...     comment='Written by ptufile.py',
...     tags={'File_RawData_GUID': [ptu.guid]},
... )

Read back the TCSPC histogram from the file:

>>> tcspc_histogram = imread('_test.ptu')
>>> import numpy
>>> numpy.array_equal(tcspc_histogram, ptu[:])
True

Close the file handle:

>>> ptu.close()

Preview the image and metadata in a PTU file from the console:

python -m ptufile tests/data/FLIM.ptu

License

Copyright (c) 2023-2026, Christoph Gohlke
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

ptufile module

ptufile.__version__ = '2026.3.21'

Ptufile version string.

final class ptufile.PhuFile(file, /, *, mode=None)

Bases: PqFile

PicoQuant histogram file.

PHU files contain a series of TCSPC histograms in addition to unified tags.

PhuFile instances are derived from PqFile.

Parameters:
  • file (str | os.PathLike[str] | IO[bytes]) – File name or seekable binary stream.

  • mode (Literal['r', 'r+'] | None)

Raises:

PqFileError – File is not a PicoQuant PHU file or is corrupted.

__init__(file, /, *, mode=None)
Parameters:
  • file (str | os.PathLike[str] | IO[bytes])

  • mode (Literal['r', 'r+'] | None)

Return type:

None

property measurement_mode: PhuMeasurementMode

HISTOGRAM or CONTI.

Type:

Kind of measurement

property measurement_submode: PhuMeasurementSubMode

OSCILLOSCOPE, INTEGRATING, or TRES.

Type:

Sub-kind of measurement

property tcspc_resolution: float

Resolution of TCSPC in s (BaseResolution * iBinningFactor).

property histogram_resolutions: tuple[float, ...] | None

Base resolution for each histogram.

property number_histograms: int

Number of histograms stored in file.

property attrs: dict[str, Any]

Selected metadata as dict.

histograms(index: int | slice | None = None, /, *, asxarray: Literal[False] = False) tuple[NDArray[numpy.uint32], ...]
histograms(index: int | slice | None = None, /, *, asxarray: Literal[True] = False) tuple[DataArray, ...]
histograms(index: int | slice | None = None, /, *, asxarray: bool = False) tuple[NDArray[numpy.uint32] | DataArray, ...]

Return sequences of histograms from file.

Parameters:
  • index (int | slice | None) – Index of histogram(s) to return. By default, all histograms are returned.

  • asxarray (bool) – If true, return histograms as xarray.DataArray, else numpy.ndarray (default).

Return type:

tuple[NDArray[numpy.uint32] | DataArray, …]

plot(*, verbose=False, show=True)

Plot histograms using matplotlib.

Parameters:
  • verbose (bool) – Print information about histogram arrays.

  • show (bool) – If true (default), display all figures. Else, defer to user or environment to display figures.

Return type:

None

class ptufile.PhuMeasurementMode(*values)

Bases: IntEnum

Kind of TCSPC measurement (Measurement_Mode tag).

UNKNOWN = -1

Unknown mode.

HISTOGRAM = 0

Histogram mode.

CONTI = 8

Conti mode.

__format__(format_spec, /)

Convert to a string according to format_spec.

__new__(value)
class ptufile.PhuMeasurementSubMode(*values)

Bases: IntEnum

Kind of measurement (Measurement_SubMode tag).

UNKNOWN = -1

Unknown mode.

OSCILLOSCOPE = 0

Oscilloscope mode.

INTEGRATING = 1

Integrating mode.

TRES = 2

Time-Resolved Emission Spectra mode.

SEQ = 3

Sequence mode.

__format__(format_spec, /)

Convert to a string according to format_spec.

__new__(value)
class ptufile.PqFile(file, /, *, mode=None, fastload=False)

Bases: BinaryFile

PicoQuant unified tagged file.

PTU, PHU, PCK, PCO, PFS, PUS, PQRES, PQDAT, PQUNI, and SPQR files contain measurement metadata and settings encoded as unified tags.

PqFile and subclass instances are not thread safe. All attributes are read-only.

PqFile and subclass instances must be closed with PqFile.close(), which is automatically called when using the ‘with’ context manager.

Parameters:
  • file (str | os.PathLike[str] | IO[bytes]) – File name or seekable binary stream.

  • mode (Literal['r', 'r+'] | None) – File open mode if file is file name. The default is ‘r’. Files are always opened in binary mode.

  • fastload (bool) – If true, only read tags marked for fast loading, else read all tags.

Raises:

PqFileError – File is not a PicoQuant tagged file or is corrupted.

__init__(file, /, *, mode=None, fastload=False)
Parameters:
  • file (str | os.PathLike[str] | IO[bytes])

  • mode (Literal['r', 'r+'] | None)

  • fastload (bool)

Return type:

None

tags: dict[str, Any]

PicoQuant unified tags.

type: PqFileType

PicoQuant file type identifier.

version: str

File version.

property guid: UUID

Global identifier of file.

property comment: str | None

File comment, if any.

property datetime: datetime | None

File creation date, if any.

property attrs: dict[str, Any]

Selected metadata as dict.

__str__()

Return str(self).

Return type:

str

class ptufile.PqFileError

Bases: ValueError

Exception to indicate invalid PicoQuant tagged file structure.

__weakref__

list of weak references to the object

class ptufile.PqFileType(*values)

Bases: Enum

PicoQuant file type identifiers.

PTU = b'PQTTTR\x00\x00'

TTTR file, PTU, contains raw data in unified TTTR-format.

PHU = b'PQHISTO\x00'

Histogram file, PHU, contains TCSPC histograms.

PCK = b'PQCHECK\x00'

Internal file, PCK, contains post-acquisition analysis results.

PCO = b'PQCOMNT\x00'

Comment file, PCO, contains manually entered text.

PFS = b'PQDEFLT\x00'

Settings file, PFS or PUS, contains factory or user setting defaults.

PQRES = b'PQRESLT\x00'

Result file, PQRES, contains analysis generated during measurement.

PQDAT = b'PQDATA\x00\x00'

Data file, PQDAT, contains undocumented data.

PQUNI = b'PQUNI\x00\x00\x00'

UniHarp file, PQUNI, contains memory and measured data.

SPQR = b'PQSPQR\x00\x00'

Unknown file, SPQR, contains undocumented data.

final class ptufile.PtuFile(file, /, *, mode=None, trimdims=None)

Bases: PqFile

PicoQuant time-tagged time-resolved (TTTR) file.

PTU files contain TTTR records in addition to unified tags.

PtuFile instances are not thread-safe. All attributes are read-only.

PtuFile is derived from PqFile.

Parameters:
  • file (str | os.PathLike[str] | IO[bytes]) – File name or seekable binary stream.

  • trimdims (Sequence[Dimension] | str | None) –

    Axes to trim. The default is 'TCH':

    • 'T': remove incomplete first or last frame.

    • 'C': remove leading and trailing channels without photons. Else use record type’s default number_channels_max.

    • 'H': remove trailing delay-time bins without photons. Else use record type’s default number_bins_max.

  • mode (Literal['r', 'r+'] | None)

Raises:

PqFileError – File is not a PicoQuant PTU file or is corrupted.

__init__(file, /, *, mode=None, trimdims=None)
Parameters:
  • file (str | os.PathLike[str] | IO[bytes])

  • mode (Literal['r', 'r+'] | None)

  • trimdims (Sequence[Dimension] | str | None)

Return type:

None

close()

Close file handle and free resources.

Return type:

None

property record_offset: int

Position of records in file.

property record_type: PtuRecordType

Type of TTTR records.

Defines the TCSPC device and type of measurement that produced the records.

property measurement_mode: PtuMeasurementMode

T2 or T3.

Type:

Kind of TCSPC measurement

property measurement_submode: PtuMeasurementSubMode

Point, line, or image scan.

Type:

Sub-kind of measurement

property measurement_ndim: int

Dimensionality of measurement.

property measurement_warnings: PtuMeasurementWarnings | None

Warnings during measurement, or None if not specified.

property hardware_features: PtuHwFeatures | None

Hardware features, or None if not specified.

property stop_reason: PtuStopReason | None

Reason for measurement end, or None if not specified.

property scanner: PtuScannerType | None

Scanner hardware, or None if not specified.

property global_resolution: float

Resolution of time tags in s.

property tcspc_resolution: float

Resolution of TCSPC in s (BaseResolution * iBinningFactor).

property number_records: int

Number of TTTR records.

property number_photons: int

Number of photons counted.

property number_markers: int

Number of marker events.

property number_images: int

Number of images separated by frame change markers.

property number_lines: int

Number of line marker pairs.

property number_channels_max: int

Maximum number of channels for record type.

property number_channels: int

Number of channels, without leading and trailing empty channels.

property active_channels: tuple[int, ...]

Indices of un-trimmed channels containing photons.

property number_bins_max: int

Maximum number of delay-time bins for record type.

property number_bins: int

Number of bins up to the largest occupied delay-time bin.

Not available for T2 records.

property number_bins_in_period: int

Delay time in one period. Not available for T2 records.

Same as global_resolution / tcspc_resolution

property line_start_mask: int

Marker mask defining line start, or 0 if not defined.

property line_stop_mask: int

Marker mask defining line end, or 0 if not defined.

property frame_change_mask: int

Marker mask defining image frame change, or 0 if not defined.

property global_pixel_time: int

Global time per pixel.

Multiply with global resolution to get time in s.

property global_line_time: int

Global time per line, excluding retrace.

Might be approximate. Multiply with global resolution to get time in s.

property global_frame_time: int

Global time per image, line, or point scan cycle.

Multiply with global resolution to get time in s.

property global_acquisition_time: int

Global time of acquisition.

property pixels_in_frame: int

Number of pixels in one scan cycle.

property pixels_in_line: int

Number of pixels in line.

property lines_in_frame: int

Number of lines in frame.

property pixel_time: float

Time per pixel in s.

property line_time: float

Average time between line markers or pixel_time in s.

property frame_time: float

Time per image, line, or point scan cycle in s.

Image scan times include retrace.

property acquisition_time: float

Duration of acquisition in s.

property frequency: float

Repetition frequency in Hz.

The inverse of PtuFile.global_resolution.

property syncrate: int

Sync events per s as recorded at beginning of measurement.

property is_image: bool

File contains image data.

property is_t3: bool

File contains T3 records.

property is_bidirectional: bool

Bidirectional scan mode.

property is_sinusoidal: bool

Sinusoidal scan mode.

property use_xarray: bool

Slicing and decode methods return xarray.DataArray.

property cache_records: bool

Cache records read from file in memory.

property dtype: numpy.dtype[Any]

Data type of image histogram array.

property shape: tuple[int, ...]

Shape of image histogram array.

property dims: tuple[str, ...]

Axes labels for each dimension in image histogram array.

property sizes: dict[str, int]

Map dimension names to lengths.

property ndims: int

Number of dimensions in image histogram array.

property nbytes: int

Number of bytes consumed by image histogram.

property size: int

Number of elements in image histogram.

property itemsize: int

Length of one array element in image histogram in bytes.

property coords: dict[str, NDArray[Any]]

Coordinate arrays labelling each point in image histogram array.

Coordinates for the time axis are approximate. Exact coordinates are returned with PtuFile.decode_image() as xarray.DataArray.

property attrs: dict[str, Any]

Selected metadata as dict.

read_records(*, memmap=False)

Return encoded TTTR records from file.

Records are cached depending on the PtuFile.cache_records property.

Parameters:

memmap (bool | Literal['r', 'r+', 'c']) – Memory-map records in file using specified mode. If false (default), read records from file into main memory.

Return type:

NDArray[numpy.uint32]

decode_records(records=None, /, *, out=None)

Return decoded TTTR records.

Parameters:
  • records (NDArray[numpy.uint32] | None) – Encoded TTTR records. By default, read records from file.

  • out (OutputType) – Array where decoded records are stored. If None, create a new NumPy recarray in main memory. If 'memmap', create a memory-mapped recarray in a temporary file. If a numpy.ndarray, a writable recarray of compatible shape and dtype. If a file name or open file, create a memory-mapped array in the specified file.

Returns:

numpy.recarray of size number_records and dtype T3_RECORD_DTYPE or T2_RECORD_DTYPE.

A channel >= 0 indicates that a record contains a photon. Otherwise, the record contains an overflow event or marker > 0.

Return type:

NDArray[Any]

decode_histogram(*, records: NDArray[numpy.uint32] | None = None, dtype: DTypeLike | None = None, sampling_time: int | None = None, dtime: int | None = None, asxarray: Literal[False] = False, out: OutputType = None) NDArray[Any]
decode_histogram(*, records: NDArray[numpy.uint32] | None = None, dtype: DTypeLike | None = None, sampling_time: int | None = None, dtime: int | None = None, asxarray: Literal[True] = False, out: OutputType = None) DataArray
decode_histogram(*, records: NDArray[numpy.uint32] | None = None, dtype: DTypeLike | None = None, sampling_time: int | None = None, dtime: int | None = None, asxarray: bool = False, out: OutputType = None) NDArray[Any] | DataArray

Return histogram of all photons by channel.

Parameters:
  • records (NDArray[numpy.uint32] | None) – Encoded TTTR records. By default, read records from file.

  • dtype (DTypeLike | None) – Unsigned integer type of histogram array. The default is uint32 for T3, else uint16. Increase the bit depth to avoid overflows.

  • sampling_time (int | None) – Global time per sample for T2 mode. The default is PtuFile.global_pixel_time().

  • dtime (int | None) – Number of bins in histogram. If 0, return number_bins_in_period bins. If > 0, return up to specified bin.

  • asxarray (bool) – If true, return xarray.DataArray, else numpy.ndarray (default).

  • out (OutputType) – Array where decoded histogram is stored. If None, create a new NumPy array in main memory. If 'memmap', create a memory-mapped array in a temporary file. If a numpy.ndarray, a writable, initialized array of shape and unsigned integer dtype. If a file name or open file, create a memory-mapped array in the specified file.

Returns:

Decoded TTTR T3 records as 2-dimensional histogram array:

  • 'C' channel

  • 'H' histogram bins

Return type:

NDArray[Any] | DataArray

decode_image(selection: Sequence[int | slice | EllipsisType | None] | None = None, /, *, records: NDArray[numpy.uint32] | None = None, dtype: DTypeLike | None = None, frame: int | None = None, channel: int | None = None, dtime: int | None = None, pixel_time: float | None = None, bishift: int | None = None, keepdims: bool = True, asxarray: Literal[False] = False, out: OutputType = None) NDArray[Any]
decode_image(selection: Sequence[int | slice | EllipsisType | None] | None = None, /, *, records: NDArray[numpy.uint32] | None = None, dtype: DTypeLike | None = None, frame: int | None = None, channel: int | None = None, dtime: int | None = None, pixel_time: float | None = None, bishift: int | None = None, keepdims: bool = True, asxarray: Literal[True] = False, out: OutputType = None) DataArray
decode_image(selection: Sequence[int | slice | EllipsisType | None] | None = None, /, *, records: NDArray[numpy.uint32] | None = None, dtype: DTypeLike | None = None, frame: int | None = None, channel: int | None = None, dtime: int | None = None, pixel_time: float | None = None, bishift: int | None = None, keepdims: bool = True, asxarray: bool = False, out: OutputType = None) NDArray[Any] | DataArray

Return T3 mode point, line, or image histogram.

The histogram may not include photons counted during incomplete frame scans or during line retraces.

Parameters:
  • selection (Sequence[int | slice | EllipsisType | None] | None) –

    Indices for all dimensions:

    • None: return all items along axis (default).

    • Ellipsis: return all items along multiple axes.

    • int: return single item along axis.

    • slice: return chunk of axis. slice.step is binning factor. If slice.step=-1, integrate all items along axis.

  • records (NDArray[numpy.uint32] | None) – Encoded TTTR records. By default, read records from file.

  • dtype (DTypeLike | None) – Unsigned integer type of image histogram array. The default is uint16. Increase the bit depth to avoid overflows when integrating.

  • frame (int | None) – If < 0, integrate time axis, else return specified frame. Overrides selection for axis T.

  • channel (int | None) – If < 0, integrate channel axis, else return specified channel. Overrides selection for axis C.

  • dtime (int | None) – Number of bins in image histogram. If 0, return number_bins_in_period bins. If < 0, integrate delay time axis. If > 0, return up to specified bin. Overrides selection for axis H.

  • pixel_time (float | None) – float, optional Time per pixel in s. If zero, determine pixel times per line from line scan markers (cannot be used with bidirectional or line scans). The default is PtuFile.pixel_time.

  • bishift (int | None) – Global time shift of odd vs. even lines in bidirectional mode. The default is zero. Positive shifts invalidate left odd columns, while negative shifts invalidate right odd columns.

  • keepdims (bool) – If true (default), reduced axes are left as size-one dimension.

  • asxarray (bool) – If true, return xarray.DataArray, else numpy.ndarray (default).

  • out (OutputType) – Array where decoded image histogram is stored. If None, create a new NumPy array in main memory. If 'memmap', create a memory-mapped array in a temporary file. If a numpy.ndarray, a writable, initialized array of shape and unsigned integer dtype. If a file name or open file, create a memory-mapped array in the specified file.

Returns:

Decoded TTTR T3 records as up to 5-dimensional image array:

  • 'T' time/frame

  • 'Y' slow scan axis for image scans

  • 'X' fast scan axis for line and image scans

  • 'C' channel

  • 'H' histogram bins

Return type:

image

Raises:
  • NotImplementedError – T2 images, bidirectional sinusoidal scanning, and deprecated image reconstruction are not supported.

  • IndexError – Selection is out of bounds.

plot(*, samples=None, frame=None, channel=None, dtime=-1, verbose=False, show=True, **kwargs)

Plot histograms using matplotlib.

Parameters:
  • samples (int | None) – Number of bins along measurement for T2 mode. The default is 1000.

  • frame (int | None) – If < 0, integrate time axis, else show specified frame. By default, all frames are shown. Applies to T3 images.

  • channel (int | None) – If < 0, integrate channel axis, else show specified channel. By default, all channels are shown. Applies to T3 images.

  • dtime (int | None) – Number of bins in T3 histograms. If < 0 (default), integrate delay time axis of images. If 0, show number_bins_in_period bins. If > 0, show histograms up to specified bin. If None, show all bins.

  • verbose (bool) – Print information about histogram arrays.

  • show (bool) – If true (default), display all figures. Else, defer to user or environment to display figures.

  • **kwargs (Any) – Additional arguments passed to tifffile.imshow.

Return type:

None

class ptufile.PtuHwFeatures(*values)

Bases: IntFlag

Hardware features (HW_Features tag).

__format__(format_spec, /)

Convert to a string according to format_spec.

__or__(other)

Return self|value.

__and__(other)

Return self&value.

__xor__(other)

Return self^value.

__ror__(other)

Return value|self.

__rand__(other)

Return value&self.

__rxor__(other)

Return value^self.

__invert__()

~self

__new__(value)
class ptufile.PtuMeasurementMode(*values)

Bases: IntEnum

Kind of TCSPC Measurement (Measurement_Mode tag).

UNKNOWN = -1

Unknown mode.

T2 = 2

T2 mode.

T3 = 3

T3 mode.

__format__(format_spec, /)

Convert to a string according to format_spec.

__new__(value)
class ptufile.PtuMeasurementSubMode(*values)

Bases: IntEnum

Kind of measurement (Measurement_SubMode tag).

UNKNOWN = -1

Unknown mode.

POINT = 1

Point scan mode.

LINE = 2

Line scan mode.

IMAGE = 3

Image scan mode.

__format__(format_spec, /)

Convert to a string according to format_spec.

__new__(value)
class ptufile.PtuMeasurementWarnings(*values)

Bases: IntFlag

Warnings during measurement (TTResult_MDescWarningFlags tag).

__format__(format_spec, /)

Convert to a string according to format_spec.

__or__(other)

Return self|value.

__and__(other)

Return self&value.

__xor__(other)

Return self^value.

__ror__(other)

Return value|self.

__rand__(other)

Return value&self.

__rxor__(other)

Return value^self.

__invert__()

~self

__new__(value)
class ptufile.PtuRecordType(*values)

Bases: IntEnum

TTTR record type.

__format__(format_spec, /)

Convert to a string according to format_spec.

__new__(value)
PicoHarpT3 = 66307

PicoHarp 300 T3.

PicoHarpT2 = 66051

PicoHarp 300 T2.

HydraHarpT3 = 66308

HydraHarp V1.x T3.

HydraHarpT2 = 66052

HydraHarp V1.x T2.

HydraHarp2T3 = 16843524

HydraHarp V2.x T3.

HydraHarp2T2 = 16843268

HydraHarp V2.x T2.

TimeHarp260NT3 = 66309

TimeHarp 260N T3.

TimeHarp260NT2 = 66053

TimeHarp 260N T2.

TimeHarp260PT3 = 66310

TimeHarp 260P T3.

TimeHarp260PT2 = 66054

TimeHarp 260P T2.

GenericT2 = 66055

MultiHarp and Picoharp 330 T2.

GenericT3 = 66311

MultiHarp and Picoharp 330 T3.

class ptufile.PtuScanDirection(*values)

Bases: IntEnum

Scan direction (ImgHdr_ScanDirection tag).

XY = 0

X-Y scan.

XZ = 1

X-Z scan.

YZ = 2

Y-Z scan.

__format__(format_spec, /)

Convert to a string according to format_spec.

__new__(value)
class ptufile.PtuScannerType(*values)

Bases: IntEnum

Scanner hardware (ImgHdr_Ident tag).

UNKNOWN = -1

Unknown scanner.

PI_E710 = 1

PI E-710 scanner.

LSM = 3

PicoQuant LSM scanner.

PI_LINEWBS = 5

PI Line WB scanner.

PI_E725 = 6

PI E-725 scanner.

PI_E727 = 7

PI E-727 scanner.

MCL = 8

MCL scanner.

FLIMBEE = 9

PicoQuant FLIMBee scanner.

SCANBOX = 10

Zeiss ScanBox scanner.

__format__(format_spec, /)

Convert to a string according to format_spec.

__new__(value)
class ptufile.PtuStopReason(*values)

Bases: IntEnum

Reason for measurement end (TTResult_StopReason tag).

__format__(format_spec, /)

Convert to a string according to format_spec.

__new__(value)
final class ptufile.PtuWriter(file, /, shape, global_resolution, tcspc_resolution, pixel_time, *, record_type=None, pixel_resolution=None, has_frames=None, guid=None, comment=None, datetime=None, tags=None, mode=None)

Bases: object

Write TCSPC histogram to T3 image mode PTU file.

T3 TTTR records allow for a maximum of 63 channels and 32768 bins. The TTTR records written can only be used to reconstruct the encoded TCSPC histogram image stack, not for higher-than-pixel-time-resolution intensity time-trace or correlation analysis.

Parameters:
  • file (str | os.PathLike[str] | IO[bytes]) – File name or writable binary stream. File names typically end in ‘.PTU’.

  • shape (tuple[int, ...]) – Shape of TCSPC histogram image stack to write. The order of dimensions must be ‘TYXCH’, ‘YXH’, ‘YXCH’, or ‘TYXH’ (with has_frames=True).

  • global_resolution (float) – Resolution of time tags in s, typically in ns range. The inverse of the synctime or laser frequency. One photon is encoded per time tag.

  • tcspc_resolution (float) – Resolution of TCSPC in s, typically in ps range. The width of a histogram bin.

  • pixel_time (float) – Time per pixel in s, typically in μs range. Photons that cannot be encoded within pixel_time are omitted.

  • record_type (PtuRecordType | None) – Type of TTTR T3 records to write. By default, write PicoHarpT3 records for up to two channels and 4096 bins, else GenericT3.

  • pixel_resolution (float | None) – Resolution of single pixel in μm. The default is 1 μm.

  • has_frames (bool | None) – 4-dimensional shape has frames in first axis (‘TYXH’), no channels.

  • guid (str | uuid.UUID | None) – Windows formatted GUID used as global file identifier. By default, a random GUID. Write to File_GUID tag.

  • comment (str | None) – File comment. Write to File_Comment tag.

  • datetime (datetime | None) – File creation date and time. The default is time at function call. Write to File_CreatingTime tag.

  • tags (dict[str, Any] | None) – Additional tag Id and values to write. Critical tags are automatically set and cannot be modified. No validation is performed. Refer to the “PicoQuant Unified Tag Dictionary” for valid Id and values.

  • mode (Literal['w', 'wb', 'x', 'xb'] | None) – Binary file open mode if file is file name. The default is ‘w’, which opens files for writing, truncating existing files. ‘x’ opens files for exclusive creation, failing on existing files.

Raises:

ValueError – Not 0 < tcspc_resolution <= global_resolution <= pixel_time.

__init__(file, /, shape, global_resolution, tcspc_resolution, pixel_time, *, record_type=None, pixel_resolution=None, has_frames=None, guid=None, comment=None, datetime=None, tags=None, mode=None)

Write PTU header to file.

Parameters:
  • file (str | os.PathLike[str] | IO[bytes])

  • shape (tuple[int, ...])

  • global_resolution (float)

  • tcspc_resolution (float)

  • pixel_time (float)

  • record_type (PtuRecordType | None)

  • pixel_resolution (float | None)

  • has_frames (bool | None)

  • guid (str | uuid.UUID | None)

  • comment (str | None)

  • datetime (datetime | None)

  • tags (dict[str, Any] | None)

  • mode (Literal['w', 'wb', 'x', 'xb'] | None)

Return type:

None

write(data, /)

Append T3 encoded TCSPC histogram to file.

Parameters:

data (numpy.ArrayLike) – TCSPC histogram image stack. The shape must be compatible with the shape passed to PtuWriter(). The dtype must be unsigned integer.

Return type:

None

close()

Close file handle after writing final tag values.

Return type:

None

static normalize_shape(shape, /, *, has_frames=None)

Return TCSPC histogram shape normalized to 5D ‘TYXCH’.

Parameters:
  • shape (tuple[int, ...])

  • has_frames (bool | None)

Return type:

tuple[int, int, int, int, int]

__weakref__

list of weak references to the object

ptufile.binread(filename, /, *, memmap=False)

Return TCSPC image histogram and metadata from PicoQuant BIN file.

Parameters:
  • filename (str | os.PathLike[str]) – Name of PicoQuant BIN file.

  • memmap (bool) – If true, return a read-only memory-mapped array.

Returns:

  • histogram: TCSPC image histogram array of shape (length, width, bins).

  • metadata: Dictionary with metadata.

    • ’shape’: Shape of histogram array.

    • ’pixel_resolution’: Pixel resolution in μm.

    • ’tcspc_resolution’: TCSPC resolution in s.

Return type:

tuple

ptufile.binwrite(filename, data, /, tcspc_resolution, pixel_resolution)

Write TCSPC image histogram and metadata to PicoQuant BIN file.

Parameters:
  • filename (str | PathLike[str]) – Name of PicoQuant BIN file.

  • data (numpy.ArrayLike) – TCSPC image histogram array of shape (length, width, bins). Must be compatible with dtype.uint32.

  • tcspc_resolution (float) – TCSPC resolution in s.

  • pixel_resolution (float) – Pixel resolution in μm.

Return type:

None

ptufile.imread(file: str | os.PathLike[str] | IO[bytes], /, selection: Sequence[int | slice | EllipsisType | None] | None = None, *, dtype: DTypeLike | None = None, channel: int | None = None, frame: int | None = None, dtime: int | None = None, pixel_time: float | None = None, bishift: int | None = None, trimdims: Sequence[Dimension] | str | None = None, keepdims: bool = True, asxarray: Literal[False] = False, out: OutputType = None) NDArray[Any]
ptufile.imread(file: str | os.PathLike[str] | IO[bytes], /, selection: Sequence[int | slice | EllipsisType | None] | None = None, *, dtype: DTypeLike | None = None, channel: int | None = None, frame: int | None = None, dtime: int | None = None, pixel_time: float | None = None, bishift: int | None = None, trimdims: Sequence[Dimension] | str | None = None, keepdims: bool = True, asxarray: Literal[True] = False, out: OutputType = None) DataArray
ptufile.imread(file: str | os.PathLike[str] | IO[bytes], /, selection: Sequence[int | slice | EllipsisType | None] | None = None, *, dtype: DTypeLike | None = None, channel: int | None = None, frame: int | None = None, dtime: int | None = None, pixel_time: float | None = None, bishift: int | None = None, trimdims: Sequence[Dimension] | str | None = None, keepdims: bool = True, asxarray: bool = False, out: OutputType = None) NDArray[Any] | DataArray

Return decoded image histogram from T3 mode PTU file.

Parameters:
Returns:

Decoded TTTR T3 records as up to 5-dimensional image array.

Return type:

image

ptufile.imwrite(file, data, /, global_resolution, tcspc_resolution, pixel_time=None, *, has_frames=None, record_type=None, pixel_resolution=None, guid=None, comment=None, datetime=None, tags=None, mode=None)

Write TCSPC histogram to T3 image mode PTU file.

Parameters:
  • file (str | os.PathLike[str] | IO[bytes]) – File name or writable binary stream.

  • data (ArrayLike) – TCSPC histogram image stack. The order of dimensions must be ‘TYXCH’, ‘YXH’, ‘YXCH’, or ‘TYXH’ (with has_frames=True). The dtype must be unsigned integer.

  • global_resolution (float) – Resolution of time tags in s, typically in ns range. The inverse of the synctime or laser frequency. One photon is encoded per time tag.

  • tcspc_resolution (float) – Resolution of TCSPC in s, typically in ps range. The width of a histogram bin.

  • pixel_time (float | None) – Time per pixel in s, typically in μs range. Photons that cannot be encoded within pixel_time are omitted. By default, pixel_time is set just large enough to encode all photons.

  • has_frames (bool | None) – 4-dimensional data have frames in first axis (‘TYXH’), no channels. By default, true if data contains metadata specifying the first dimension is ‘T’, else false.

  • record_type (PtuRecordType | None) – Optional parameters passed to PtuWriter.

  • pixel_resolution (float | None) – Optional parameters passed to PtuWriter.

  • guid (str | uuid.UUID | None) – Optional parameters passed to PtuWriter.

  • comment (str | None) – Optional parameters passed to PtuWriter.

  • datetime (datetime | None) – Optional parameters passed to PtuWriter.

  • tags (dict[str, Any] | None) – Optional parameters passed to PtuWriter.

  • mode (Literal['w', 'wb', 'x', 'xb'] | None) – Optional parameters passed to PtuWriter.

Return type:

None

ptufile.FILE_EXTENSIONS
ptufile.T2_RECORD_DTYPE = dtype([('time', '<u8'), ('channel', 'i1'), ('marker', 'u1')])

Numpy dtype of decoded T2 records.

ptufile.T3_RECORD_DTYPE = dtype([('time', '<u8'), ('dtime', '<i2'), ('channel', 'i1'), ('marker', 'u1')])

Numpy dtype of decoded T3 records.

ptufile.numcodecs

class ptufile.numcodecs.Ptu(*, selection=None, dtype=None, channel=None, frame=None, dtime=None, pixel_time=None, trimdims=None, keepdims=True)

Bases: Codec

Ptu codec for Numcodecs.

Parameters:
  • selection (Sequence[int | slice | EllipsisType | None] | None)

  • dtype (DTypeLike | None)

  • channel (int | None)

  • frame (int | None)

  • dtime (int | None)

  • pixel_time (float | None)

  • trimdims (str | None)

  • keepdims (bool)

codec_id: str | None = 'ptufile'

Codec identifier.

__init__(*, selection=None, dtype=None, channel=None, frame=None, dtime=None, pixel_time=None, trimdims=None, keepdims=True)
Parameters:
  • selection (Sequence[int | slice | EllipsisType | None] | None)

  • dtype (DTypeLike | None)

  • channel (int | None)

  • frame (int | None)

  • dtime (int | None)

  • pixel_time (float | None)

  • trimdims (str | None)

  • keepdims (bool)

Return type:

None

encode(buf)

Return Ptu file as bytes.

Parameters:

buf (numpy.ArrayLike)

Return type:

None

decode(buf, out=None)

Return decoded image as NumPy array.

Parameters:
  • buf (bytes)

  • out (Any | None)

Return type:

NDArray[Any]

ptufile.numcodecs.register_codec(cls=Ptu, codec_id=None)

Register Ptu codec with Numcodecs.

Parameters:
  • cls (Codec)

  • codec_id (str | None)

Return type:

None