phasorpy 0.1__cp313-cp313-macosx_10_13_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
phasorpy/io.py ADDED
@@ -0,0 +1,1671 @@
1
+ """Read and write time-resolved and hyperspectral image file formats.
2
+
3
+ The ``phasorpy.io`` module provides functions to:
4
+
5
+ - read and write phasor coordinate images in OME-TIFF format, which can be
6
+ imported in Bio-Formats and Fiji:
7
+
8
+ - :py:func:`phasor_to_ometiff`
9
+ - :py:func:`phasor_from_ometiff`
10
+
11
+ - read and write phasor coordinate images in SimFCS referenced R64 format:
12
+
13
+ - :py:func:`phasor_to_simfcs_referenced`
14
+ - :py:func:`phasor_from_simfcs_referenced`
15
+
16
+ - read time-resolved and hyperspectral image data and metadata (as relevant
17
+ to phasor analysis) from many file formats used in bio-imaging:
18
+
19
+ - :py:func:`read_lsm` - Zeiss LSM
20
+ - :py:func:`read_ifli` - ISS IFLI
21
+ - :py:func:`read_sdt` - Becker & Hickl SDT
22
+ - :py:func:`read_ptu` - PicoQuant PTU
23
+ - :py:func:`read_fbd` - FLIMbox FBD
24
+ - :py:func:`read_flif` - FlimFast FLIF
25
+ - :py:func:`read_b64` - SimFCS B64
26
+ - :py:func:`read_z64` - SimFCS Z64
27
+ - :py:func:`read_bhz` - SimFCS BHZ
28
+ - :py:func:`read_bh` - SimFCS B&H
29
+
30
+ Support for other file formats is being considered:
31
+
32
+ - OME-TIFF
33
+ - Zeiss CZI
34
+ - Leica LIF
35
+ - Nikon ND2
36
+ - Olympus OIB/OIF
37
+ - Olympus OIR
38
+
39
+ The functions are implemented as minimal wrappers around specialized
40
+ third-party file reader libraries, currently
41
+ `tifffile <https://github.com/cgohlke/tifffile>`_,
42
+ `ptufile <https://github.com/cgohlke/ptufile>`_,
43
+ `sdtfile <https://github.com/cgohlke/sdtfile>`_, and
44
+ `lfdfiles <https://github.com/cgohlke/lfdfiles>`_.
45
+ For advanced or unsupported use cases, consider using these libraries directly.
46
+
47
+ The read functions typically have the following signature::
48
+
49
+ read_ext(
50
+ filename: str | PathLike,
51
+ /,
52
+ **kwargs
53
+ ): -> xarray.DataArray
54
+
55
+ where ``ext`` indicates the file format and ``kwargs`` are optional arguments
56
+ passed to the underlying file reader library or used to select which data is
57
+ returned. The returned `xarray.DataArray
58
+ <https://docs.xarray.dev/en/stable/user-guide/data-structures.html>`_
59
+ contains an n-dimensional array with labeled coordinates, dimensions, and
60
+ attributes:
61
+
62
+ - ``data`` or ``values`` (*array_like*)
63
+
64
+ Numpy array or array-like holding the array's values.
65
+
66
+ - ``dims`` (*tuple of str*)
67
+
68
+ :ref:`Axes character codes <axes>` for each dimension in ``data``.
69
+ For example, ``('T', 'C', 'Y', 'X')`` defines the dimension order in a
70
+ 4-dimensional array of a time-series of multi-channel images.
71
+
72
+ - ``coords`` (*dict_like[str, array_like]*)
73
+
74
+ Coordinate arrays labelling each point in the data array.
75
+ The keys are :ref:`axes character codes <axes>`.
76
+ Values are 1-dimensional arrays of numbers or strings.
77
+ For example, ``coords['C']`` could be an array of emission wavelengths.
78
+
79
+ - ``attrs`` (*dict[str, Any]*)
80
+
81
+ Arbitrary metadata such as measurement or calibration parameters required to
82
+ interpret the data values.
83
+ For example, the laser repetition frequency of a time-resolved measurement.
84
+
85
+ .. _axes:
86
+
87
+ Axes character codes from the OME model and tifffile library are used as
88
+ ``dims`` items and ``coords`` keys:
89
+
90
+ - ``'X'`` : width (OME)
91
+ - ``'Y'`` : height (OME)
92
+ - ``'Z'`` : depth (OME)
93
+ - ``'S'`` : sample (color components or phasor coordinates)
94
+ - ``'I'`` : sequence (of images, frames, or planes)
95
+ - ``'T'`` : time (OME)
96
+ - ``'C'`` : channel (OME. Acquisition path or emission wavelength)
97
+ - ``'A'`` : angle (OME)
98
+ - ``'P'`` : phase (OME. In LSM, ``'P'`` maps to position)
99
+ - ``'R'`` : tile (OME. Region, position, or mosaic)
100
+ - ``'H'`` : lifetime histogram (OME)
101
+ - ``'E'`` : lambda (OME. Excitation wavelength)
102
+ - ``'F'`` : frequency (ISS)
103
+ - ``'Q'`` : other (OME. Harmonics in PhasorPy TIFF)
104
+ - ``'L'`` : exposure (FluoView)
105
+ - ``'V'`` : event (FluoView)
106
+ - ``'M'`` : mosaic (LSM 6)
107
+ - ``'J'`` : column (NDTiff)
108
+ - ``'K'`` : row (NDTiff)
109
+
110
+ """
111
+
112
+ from __future__ import annotations
113
+
114
+ __all__ = [
115
+ 'phasor_from_ometiff',
116
+ 'phasor_from_simfcs_referenced',
117
+ 'phasor_to_ometiff',
118
+ 'phasor_to_simfcs_referenced',
119
+ 'read_b64',
120
+ 'read_bh',
121
+ 'read_bhz',
122
+ # 'read_czi',
123
+ 'read_fbd',
124
+ 'read_flif',
125
+ 'read_ifli',
126
+ # 'read_lif',
127
+ 'read_lsm',
128
+ # 'read_nd2',
129
+ # 'read_oif',
130
+ # 'read_oir',
131
+ # 'read_ometiff',
132
+ 'read_ptu',
133
+ 'read_sdt',
134
+ 'read_z64',
135
+ '_squeeze_axes',
136
+ ]
137
+
138
+ import logging
139
+ import os
140
+ import re
141
+ import struct
142
+ import zlib
143
+ from typing import TYPE_CHECKING
144
+
145
+ from ._utils import chunk_iter, parse_harmonic
146
+ from .phasor import phasor_from_polar, phasor_to_polar
147
+
148
+ if TYPE_CHECKING:
149
+ from ._typing import (
150
+ Any,
151
+ ArrayLike,
152
+ DataArray,
153
+ DTypeLike,
154
+ EllipsisType,
155
+ Literal,
156
+ NDArray,
157
+ PathLike,
158
+ Sequence,
159
+ )
160
+
161
+ import numpy
162
+
163
+ logger = logging.getLogger(__name__)
164
+
165
+
166
+ def phasor_to_ometiff(
167
+ filename: str | PathLike[Any],
168
+ mean: ArrayLike,
169
+ real: ArrayLike,
170
+ imag: ArrayLike,
171
+ /,
172
+ *,
173
+ frequency: float | None = None,
174
+ harmonic: int | Sequence[int] | None = None,
175
+ axes: str | None = None,
176
+ dtype: DTypeLike | None = None,
177
+ description: str | None = None,
178
+ **kwargs: Any,
179
+ ) -> None:
180
+ """Write phasor coordinate images and metadata to OME-TIFF file.
181
+
182
+ The OME-TIFF format is compatible with Bio-Formats and Fiji.
183
+
184
+ By default, write phasor coordinates as single precision floating point
185
+ values to separate image series.
186
+ Write images larger than (1024, 1024) as (256, 256) tiles, datasets
187
+ larger than 2 GB as BigTIFF, and datasets larger than 8 KB zlib-compressed.
188
+
189
+ This file format is experimental and might be incompatible with future
190
+ versions of this library. It is intended for temporarily exchanging
191
+ phasor coordinates with other software, not as a long-term storage
192
+ solution.
193
+
194
+ Parameters
195
+ ----------
196
+ filename : str or Path
197
+ Name of OME-TIFF file to write.
198
+ mean : array_like
199
+ Average intensity image. Write to image series named 'Phasor mean'.
200
+ real : array_like
201
+ Image of real component of phasor coordinates.
202
+ Multiple harmonics, if any, must be in the first dimension.
203
+ Write to image series named 'Phasor real'.
204
+ imag : array_like
205
+ Image of imaginary component of phasor coordinates.
206
+ Multiple harmonics, if any, must be in the first dimension.
207
+ Write to image series named 'Phasor imag'.
208
+ frequency : float, optional
209
+ Fundamental frequency of time-resolved phasor coordinates.
210
+ Write to image series named 'Phasor frequency'.
211
+ harmonic : int or sequence of int, optional
212
+ Harmonics present in the first dimension of `real` and `imag`, if any.
213
+ Write to image series named 'Phasor harmonic'.
214
+ Only needed if harmonics are not starting at and increasing by one.
215
+ axes : str, optional
216
+ Character codes for `mean` image dimensions.
217
+ By default, the last dimensions are assumed to be 'TZCYX'.
218
+ If harmonics are present in `real` and `imag`, an "other" (``Q``)
219
+ dimension is prepended to axes for those arrays.
220
+ Refer to the OME-TIFF model for allowed axes and their order.
221
+ dtype : dtype-like, optional
222
+ Floating point data type used to store phasor coordinates.
223
+ The default is ``float32``, which has 6 digits of precision
224
+ and maximizes compatibility with other software.
225
+ description : str, optional
226
+ Plain-text description of dataset. Write as OME dataset description.
227
+ **kwargs
228
+ Additional arguments passed to :py:class:`tifffile.TiffWriter` and
229
+ :py:meth:`tifffile.TiffWriter.write`.
230
+ For example, ``compression=None`` writes image data uncompressed.
231
+
232
+ See Also
233
+ --------
234
+ phasorpy.io.phasor_from_ometiff
235
+
236
+ Notes
237
+ -----
238
+ Scalar or one-dimensional phasor coordinate arrays are written as images.
239
+
240
+ The OME-TIFF format is specified in the
241
+ `OME Data Model and File Formats Documentation
242
+ <https://ome-model.readthedocs.io/>`_.
243
+
244
+ The `6D, 7D and 8D storage
245
+ <https://ome-model.readthedocs.io/en/latest/developers/6d-7d-and-8d-storage.html>`_
246
+ extension is used to store multi-harmonic phasor coordinates.
247
+ The modulo type for the first, harmonic dimension is "other".
248
+
249
+ Examples
250
+ --------
251
+ >>> mean, real, imag = numpy.random.rand(3, 32, 32, 32)
252
+ >>> phasor_to_ometiff(
253
+ ... '_phasorpy.ome.tif', mean, real, imag, axes='ZYX', frequency=80.0
254
+ ... )
255
+
256
+ """
257
+ import tifffile
258
+
259
+ from .version import __version__
260
+
261
+ if dtype is None:
262
+ dtype = numpy.float32
263
+ dtype = numpy.dtype(dtype)
264
+ if dtype.kind != 'f':
265
+ raise ValueError(f'{dtype=} not a floating point type')
266
+
267
+ mean = numpy.asarray(mean, dtype)
268
+ real = numpy.asarray(real, dtype)
269
+ imag = numpy.asarray(imag, dtype)
270
+ datasize = mean.nbytes + real.nbytes + imag.nbytes
271
+
272
+ if real.shape != imag.shape:
273
+ raise ValueError(f'{real.shape=} != {imag.shape=}')
274
+ if mean.shape != real.shape[-mean.ndim :]:
275
+ raise ValueError(f'{mean.shape=} != {real.shape[-mean.ndim:]=}')
276
+ has_harmonic_dim = real.ndim == mean.ndim + 1
277
+ if mean.ndim == real.ndim or real.ndim == 0:
278
+ nharmonic = 1
279
+ else:
280
+ nharmonic = real.shape[0]
281
+
282
+ if mean.ndim < 2:
283
+ # not an image
284
+ mean = mean.reshape(1, -1)
285
+ if has_harmonic_dim:
286
+ real = real.reshape(real.shape[0], 1, -1)
287
+ imag = imag.reshape(imag.shape[0], 1, -1)
288
+ else:
289
+ real = real.reshape(1, -1)
290
+ imag = imag.reshape(1, -1)
291
+
292
+ if harmonic is not None:
293
+ harmonic_array = numpy.atleast_1d(harmonic)
294
+ if harmonic_array.ndim > 1 or harmonic_array.size != nharmonic:
295
+ raise ValueError('invalid harmonic')
296
+ samples = int(harmonic_array.max()) * 2 + 1
297
+ harmonic, _ = parse_harmonic(harmonic, samples)
298
+
299
+ if frequency is not None:
300
+ frequency_array = numpy.atleast_2d(frequency).astype(numpy.float64)
301
+ if frequency_array.size > 1:
302
+ raise ValueError('frequency must be scalar')
303
+
304
+ if axes is None:
305
+ axes = 'TZCYX'[-mean.ndim :]
306
+ else:
307
+ axes = ''.join(tuple(axes)) # accept dims tuple and str
308
+ if len(axes) != mean.ndim:
309
+ raise ValueError(f'{axes=} does not match {mean.ndim=}')
310
+ axes_phasor = axes if mean.ndim == real.ndim else 'Q' + axes
311
+
312
+ if 'photometric' not in kwargs:
313
+ kwargs['photometric'] = 'minisblack'
314
+ if 'compression' not in kwargs and datasize > 8192:
315
+ kwargs['compression'] = 'zlib'
316
+ if 'tile' not in kwargs and 'rowsperstrip' not in kwargs:
317
+ if (
318
+ axes.endswith('YX')
319
+ and mean.shape[-1] > 1024
320
+ and mean.shape[-2] > 1024
321
+ ):
322
+ kwargs['tile'] = (256, 256)
323
+
324
+ mode = kwargs.pop('mode', None)
325
+ bigtiff = kwargs.pop('bigtiff', None)
326
+ if bigtiff is None:
327
+ bigtiff = datasize > 2**31
328
+
329
+ metadata = kwargs.pop('metadata', {})
330
+ if 'Creator' not in metadata:
331
+ metadata['Creator'] = f'PhasorPy {__version__}'
332
+
333
+ dataset = metadata.pop('Dataset', {})
334
+ if 'Name' not in dataset:
335
+ dataset['Name'] = 'Phasor'
336
+ if description:
337
+ dataset['Description'] = description
338
+ metadata['Dataset'] = dataset
339
+
340
+ if has_harmonic_dim:
341
+ metadata['TypeDescription'] = {'Q': 'Phasor harmonics'}
342
+
343
+ with tifffile.TiffWriter(
344
+ filename, bigtiff=bigtiff, mode=mode, ome=True
345
+ ) as tif:
346
+ metadata['Name'] = 'Phasor mean'
347
+ metadata['axes'] = axes
348
+ tif.write(mean, metadata=metadata, **kwargs)
349
+ del metadata['Dataset']
350
+
351
+ metadata['Name'] = 'Phasor real'
352
+ metadata['axes'] = axes_phasor
353
+ tif.write(real, metadata=metadata, **kwargs)
354
+
355
+ metadata['Name'] = 'Phasor imag'
356
+ tif.write(imag, metadata=metadata, **kwargs)
357
+
358
+ if frequency is not None:
359
+ tif.write(frequency_array, metadata={'Name': 'Phasor frequency'})
360
+
361
+ if harmonic is not None:
362
+ tif.write(
363
+ numpy.atleast_2d(harmonic).astype(numpy.uint32),
364
+ metadata={'Name': 'Phasor harmonic'},
365
+ )
366
+
367
+
368
+ def phasor_from_ometiff(
369
+ filename: str | PathLike[Any],
370
+ /,
371
+ *,
372
+ harmonic: int | Sequence[int] | Literal['all'] | str | None = None,
373
+ ) -> tuple[NDArray[Any], NDArray[Any], NDArray[Any], dict[str, Any]]:
374
+ """Return phasor images and metadata from OME-TIFF written by PhasorPy.
375
+
376
+ Parameters
377
+ ----------
378
+ filename : str or Path
379
+ Name of OME-TIFF file to read.
380
+ harmonic : int, sequence of int, or 'all', optional
381
+ Harmonic(s) to return from file.
382
+ If None (default), return the first harmonic stored in the file.
383
+ If `'all'`, return all harmonics as stored in file.
384
+ If a list, the first axes of the returned `real` and `imag` arrays
385
+ contain specified harmonic(s).
386
+ If an integer, the returned `real` and `imag` arrays are single
387
+ harmonic and have the same shape as `mean`.
388
+
389
+ Returns
390
+ -------
391
+ mean : ndarray
392
+ Average intensity image.
393
+ real : ndarray
394
+ Image of real component of phasor coordinates.
395
+ imag : ndarray
396
+ Image of imaginary component of phasor coordinates.
397
+ attrs : dict
398
+ Select metadata:
399
+
400
+ - ``'axes'`` (str):
401
+ Character codes for `mean` image dimensions.
402
+ - ``'harmonic'`` (int or list of int):
403
+ Harmonic(s) present in `real` and `imag`.
404
+ If a scalar, `real` and `imag` are single harmonic and contain no
405
+ harmonic axes.
406
+ If a list, `real` and `imag` contain one or more harmonics in the
407
+ first axis.
408
+ - ``'frequency'`` (float, optional):
409
+ Fundamental frequency of time-resolved phasor coordinates.
410
+ - ``'description'`` (str, optional):
411
+ OME dataset plain-text description.
412
+
413
+ Raises
414
+ ------
415
+ tifffile.TiffFileError
416
+ File is not a TIFF file.
417
+ ValueError
418
+ File is not an OME-TIFF containing phasor coordinates.
419
+ IndexError
420
+ Requested harmonic is not found in file.
421
+
422
+ See Also
423
+ --------
424
+ phasorpy.io.phasor_to_ometiff
425
+
426
+ Notes
427
+ -----
428
+ Scalar or one-dimensional phasor coordinates stored in the file are
429
+ returned as two-dimensional images (three-dimensional if multiple
430
+ harmonics are present).
431
+
432
+ Examples
433
+ --------
434
+ >>> mean, real, imag = numpy.random.rand(3, 32, 32, 32)
435
+ >>> phasor_to_ometiff(
436
+ ... '_phasorpy.ome.tif', mean, real, imag, axes='ZYX', frequency=80.0
437
+ ... )
438
+ >>> mean, real, imag, attrs = phasor_from_ometiff('_phasorpy.ome.tif')
439
+ >>> mean
440
+ array(...)
441
+ >>> mean.dtype
442
+ dtype('float32')
443
+ >>> mean.shape
444
+ (32, 32, 32)
445
+ >>> attrs['axes']
446
+ 'ZYX'
447
+ >>> attrs['frequency']
448
+ 80.0
449
+ >>> attrs['harmonic']
450
+ 1
451
+
452
+ """
453
+ import tifffile
454
+
455
+ name = os.path.basename(filename)
456
+
457
+ with tifffile.TiffFile(filename) as tif:
458
+ if (
459
+ not tif.is_ome
460
+ or len(tif.series) < 3
461
+ or tif.series[0].name != 'Phasor mean'
462
+ or tif.series[1].name != 'Phasor real'
463
+ or tif.series[2].name != 'Phasor imag'
464
+ ):
465
+ raise ValueError(
466
+ f'{name!r} is not an OME-TIFF containing phasor images'
467
+ )
468
+
469
+ attrs: dict[str, Any] = {'axes': tif.series[0].axes}
470
+
471
+ # TODO: read coords from OME-XML
472
+ ome_xml = tif.ome_metadata
473
+ assert ome_xml is not None
474
+
475
+ # TODO: parse OME-XML
476
+ match = re.search(
477
+ r'><Description>(.*)</Description><',
478
+ ome_xml,
479
+ re.MULTILINE | re.DOTALL,
480
+ )
481
+ if match is not None:
482
+ attrs['description'] = (
483
+ match.group(1)
484
+ .replace('&amp;', '&')
485
+ .replace('&gt;', '>')
486
+ .replace('&lt;', '<')
487
+ )
488
+
489
+ has_harmonic_dim = tif.series[1].ndim > tif.series[0].ndim
490
+ nharmonics = tif.series[1].shape[0] if has_harmonic_dim else 1
491
+ maxharmonic = nharmonics
492
+ for i in (3, 4):
493
+ if len(tif.series) < i + 1:
494
+ break
495
+ series = tif.series[i]
496
+ data = series.asarray().squeeze()
497
+ if series.name == 'Phasor frequency':
498
+ attrs['frequency'] = float(data.item(0))
499
+ elif series.name == 'Phasor harmonic':
500
+ if not has_harmonic_dim and data.size == 1:
501
+ attrs['harmonic'] = int(data.item(0))
502
+ maxharmonic = attrs['harmonic']
503
+ elif has_harmonic_dim and data.size == nharmonics:
504
+ attrs['harmonic'] = data.tolist()
505
+ maxharmonic = max(attrs['harmonic'])
506
+ else:
507
+ logger.warning(
508
+ f'harmonic={data} does not match phasor '
509
+ f'shape={tif.series[1].shape}'
510
+ )
511
+
512
+ if 'harmonic' not in attrs:
513
+ if has_harmonic_dim:
514
+ attrs['harmonic'] = list(range(1, nharmonics + 1))
515
+ else:
516
+ attrs['harmonic'] = 1
517
+ harmonic_stored = attrs['harmonic']
518
+
519
+ mean = tif.series[0].asarray()
520
+ if harmonic is None:
521
+ # first harmonic in file
522
+ if isinstance(harmonic_stored, list):
523
+ attrs['harmonic'] = harmonic_stored[0]
524
+ else:
525
+ attrs['harmonic'] = harmonic_stored
526
+ real = tif.series[1].asarray()
527
+ if has_harmonic_dim:
528
+ real = real[0].copy()
529
+ imag = tif.series[2].asarray()
530
+ if has_harmonic_dim:
531
+ imag = imag[0].copy()
532
+ elif isinstance(harmonic, str) and harmonic == 'all':
533
+ # all harmonics as stored in file
534
+ real = tif.series[1].asarray()
535
+ imag = tif.series[2].asarray()
536
+ else:
537
+ # specified harmonics
538
+ harmonic, keepdims = parse_harmonic(harmonic, 2 * maxharmonic + 1)
539
+ try:
540
+ if isinstance(harmonic_stored, list):
541
+ index = [harmonic_stored.index(h) for h in harmonic]
542
+ else:
543
+ index = [[harmonic_stored].index(h) for h in harmonic]
544
+ except ValueError as exc:
545
+ raise IndexError('harmonic not found') from exc
546
+
547
+ if has_harmonic_dim:
548
+ if keepdims:
549
+ attrs['harmonic'] = [harmonic_stored[i] for i in index]
550
+ real = tif.series[1].asarray()[index].copy()
551
+ imag = tif.series[2].asarray()[index].copy()
552
+ else:
553
+ attrs['harmonic'] = harmonic_stored[index[0]]
554
+ real = tif.series[1].asarray()[index[0]].copy()
555
+ imag = tif.series[2].asarray()[index[0]].copy()
556
+ elif keepdims:
557
+ real = tif.series[1].asarray()
558
+ real = real.reshape(1, *real.shape)
559
+ imag = tif.series[2].asarray()
560
+ imag = imag.reshape(1, *imag.shape)
561
+ attrs['harmonic'] = [harmonic_stored]
562
+ else:
563
+ real = tif.series[1].asarray()
564
+ imag = tif.series[2].asarray()
565
+
566
+ if real.shape != imag.shape:
567
+ logger.warning(f'{real.shape=} != {imag.shape=}')
568
+ if real.shape[-mean.ndim :] != mean.shape:
569
+ logger.warning(f'{real.shape[-mean.ndim:]=} != {mean.shape=}')
570
+
571
+ return mean, real, imag, attrs
572
+
573
+
574
+ def phasor_to_simfcs_referenced(
575
+ filename: str | PathLike[Any],
576
+ mean: ArrayLike,
577
+ real: ArrayLike,
578
+ imag: ArrayLike,
579
+ /,
580
+ *,
581
+ size: int | None = None,
582
+ axes: str | None = None,
583
+ ) -> None:
584
+ """Write phasor coordinate images to SimFCS referenced R64 file(s).
585
+
586
+ SimFCS referenced R64 files store square-shaped (commonly 256x256)
587
+ images of the average intensity, and the calibrated phasor coordinates
588
+ (encoded as phase and modulation) of two harmonics as ZIP-compressed,
589
+ single precision floating point arrays.
590
+ The file format does not support any metadata.
591
+
592
+ Images with more than two dimensions or larger than square size are
593
+ chunked to square-sized images and saved to separate files with
594
+ a name pattern, for example, "filename_T099_Y256_X000.r64".
595
+ Images or chunks with less than two dimensions or smaller than square size
596
+ are padded with NaN values.
597
+
598
+ Parameters
599
+ ----------
600
+ filename : str or Path
601
+ Name of SimFCS referenced R64 file to write.
602
+ The file extension must be ``.r64``.
603
+ mean : array_like
604
+ Average intensity image.
605
+ real : array_like
606
+ Image of real component of calibrated phasor coordinates.
607
+ Multiple harmonics, if any, must be in the first dimension.
608
+ Harmonics must be starting at and increasing by one.
609
+ imag : array_like
610
+ Image of imaginary component of calibrated phasor coordinates.
611
+ Multiple harmonics, if any, must be in the first dimension.
612
+ Harmonics must be starting at and increasing by one.
613
+ size : int, optional
614
+ Size of X and Y dimensions of square-sized images stored in file.
615
+ By default, ``size = min(256, max(4, sizey, sizex))``.
616
+ axes : str, optional
617
+ Character codes for `mean` dimensions used to format file names.
618
+
619
+ See Also
620
+ --------
621
+ phasorpy.io.phasor_from_simfcs_referenced
622
+
623
+ Examples
624
+ --------
625
+ >>> mean, real, imag = numpy.random.rand(3, 32, 32)
626
+ >>> phasor_to_simfcs_referenced('_phasorpy.r64', mean, real, imag)
627
+
628
+ """
629
+ filename, ext = os.path.splitext(filename)
630
+ if ext.lower() != '.r64':
631
+ raise ValueError(f'file extension {ext} != .r64')
632
+
633
+ # TODO: delay conversions to numpy arrays to inner loop
634
+ mean = numpy.asarray(mean, numpy.float32)
635
+ phi, mod = phasor_to_polar(real, imag, dtype=numpy.float32)
636
+ del real
637
+ del imag
638
+ phi = numpy.rad2deg(phi)
639
+
640
+ if phi.shape != mod.shape:
641
+ raise ValueError(f'{phi.shape=} != {mod.shape=}')
642
+ if mean.shape != phi.shape[-mean.ndim :]:
643
+ raise ValueError(f'{mean.shape=} != {phi.shape[-mean.ndim:]=}')
644
+ if phi.ndim == mean.ndim:
645
+ phi = phi.reshape(1, *phi.shape)
646
+ mod = mod.reshape(1, *mod.shape)
647
+ nharmonic = phi.shape[0]
648
+
649
+ if mean.ndim < 2:
650
+ # not an image
651
+ mean = mean.reshape(1, -1)
652
+ phi = phi.reshape(nharmonic, 1, -1)
653
+ mod = mod.reshape(nharmonic, 1, -1)
654
+
655
+ # TODO: investigate actual size and harmonics limits of SimFCS
656
+ sizey, sizex = mean.shape[-2:]
657
+ if size is None:
658
+ size = min(256, max(4, sizey, sizex))
659
+ elif not 4 <= size <= 65535:
660
+ raise ValueError(f'{size=} out of range [4..65535]')
661
+
662
+ harmonics_per_file = 2 # TODO: make this a parameter?
663
+ chunk_shape = tuple(
664
+ [max(harmonics_per_file, 2)] + ([1] * (phi.ndim - 3)) + [size, size]
665
+ )
666
+ multi_file = any(i / j > 1 for i, j in zip(phi.shape, chunk_shape))
667
+
668
+ if axes is not None and len(axes) == phi.ndim - 1:
669
+ axes = 'h' + axes
670
+
671
+ chunk = numpy.empty((size, size), dtype=numpy.float32)
672
+
673
+ def rawdata_append(
674
+ rawdata: list[bytes], a: NDArray[Any] | None = None
675
+ ) -> None:
676
+ if a is None:
677
+ chunk[:] = numpy.nan
678
+ rawdata.append(chunk.tobytes())
679
+ else:
680
+ sizey, sizex = a.shape[-2:]
681
+ if sizey == size and sizex == size:
682
+ rawdata.append(a.tobytes())
683
+ elif sizey <= size and sizex <= size:
684
+ chunk[:sizey, :sizex] = a[..., :sizey, :sizex]
685
+ chunk[sizey:, sizex:] = numpy.nan
686
+ rawdata.append(chunk.tobytes())
687
+ else:
688
+ raise RuntimeError # should not be reached
689
+
690
+ for index, label, _ in chunk_iter(
691
+ phi.shape, chunk_shape, axes, squeeze=False, use_index=True
692
+ ):
693
+ rawdata = [struct.pack('I', size)]
694
+ rawdata_append(rawdata, mean[index[1:]])
695
+ phi_ = phi[index]
696
+ mod_ = mod[index]
697
+ for i in range(phi_.shape[0]):
698
+ rawdata_append(rawdata, phi_[i])
699
+ rawdata_append(rawdata, mod_[i])
700
+ if phi_.shape[0] == 1:
701
+ rawdata_append(rawdata)
702
+ rawdata_append(rawdata)
703
+
704
+ if not multi_file:
705
+ label = ''
706
+ with open(filename + label + ext, 'wb') as fh:
707
+ fh.write(zlib.compress(b''.join(rawdata)))
708
+
709
+
710
+ def phasor_from_simfcs_referenced(
711
+ filename: str | PathLike[Any],
712
+ /,
713
+ *,
714
+ harmonic: int | Sequence[int] | Literal['all'] | str | None = None,
715
+ ) -> tuple[NDArray[Any], NDArray[Any], NDArray[Any]]:
716
+ """Return phasor coordinate images from SimFCS referenced (REF, R64) file.
717
+
718
+ SimFCS referenced REF and R64 files contain phasor coordinate images
719
+ (encoded as phase and modulation) for two harmonics.
720
+ Phasor coordinates from lifetime-resolved signals are calibrated.
721
+
722
+ Parameters
723
+ ----------
724
+ filename : str or Path
725
+ Name of REF or R64 file to read.
726
+ harmonic : int or sequence of int, optional
727
+ Harmonic(s) to include in returned phasor coordinates.
728
+ By default, only the first harmonic is returned.
729
+
730
+ Returns
731
+ -------
732
+ mean : ndarray
733
+ Average intensity image.
734
+ real : ndarray
735
+ Image of real component of phasor coordinates.
736
+ Multiple harmonics, if any, are in the first axis.
737
+ imag : ndarray
738
+ Image of imaginary component of phasor coordinates.
739
+ Multiple harmonics, if any, are in the first axis.
740
+
741
+ Raises
742
+ ------
743
+ lfdfiles.LfdfileError
744
+ File is not a SimFCS REF or R64 file.
745
+
746
+ See Also
747
+ --------
748
+ phasorpy.io.phasor_to_simfcs_referenced
749
+
750
+ Examples
751
+ --------
752
+ >>> phasor_to_simfcs_referenced(
753
+ ... '_phasorpy.r64', *numpy.random.rand(3, 32, 32)
754
+ ... )
755
+ >>> mean, real, imag = phasor_from_simfcs_referenced('_phasorpy.r64')
756
+ >>> mean
757
+ array([[...]], dtype=float32)
758
+
759
+ """
760
+ import lfdfiles
761
+
762
+ ext = os.path.splitext(filename)[-1].lower()
763
+ if ext == '.r64':
764
+ with lfdfiles.SimfcsR64(filename) as r64:
765
+ data = r64.asarray()
766
+ elif ext == '.ref':
767
+ with lfdfiles.SimfcsRef(filename) as ref:
768
+ data = ref.asarray()
769
+ else:
770
+ raise ValueError(f'file extension must be .ref or .r64, not {ext!r}')
771
+
772
+ harmonic, keep_harmonic_dim = parse_harmonic(harmonic, data.shape[0])
773
+
774
+ mean = data[0].copy()
775
+ real = numpy.empty((len(harmonic),) + mean.shape, numpy.float32)
776
+ imag = numpy.empty_like(real)
777
+ for i, h in enumerate(harmonic):
778
+ h = (h - 1) * 2 + 1
779
+ re, im = phasor_from_polar(numpy.deg2rad(data[h]), data[h + 1])
780
+ real[i] = re
781
+ imag[i] = im
782
+ if not keep_harmonic_dim:
783
+ real = real.reshape(mean.shape)
784
+ imag = imag.reshape(mean.shape)
785
+
786
+ return mean, real, imag
787
+
788
+
789
+ def read_lsm(
790
+ filename: str | PathLike[Any],
791
+ /,
792
+ ) -> DataArray:
793
+ """Return hyperspectral image and metadata from Zeiss LSM file.
794
+
795
+ LSM files contain multi-dimensional images and metadata from laser
796
+ scanning microscopy measurements. The file format is based on TIFF.
797
+
798
+ Parameters
799
+ ----------
800
+ filename : str or Path
801
+ Name of OME-TIFF file to read.
802
+
803
+ Returns
804
+ -------
805
+ xarray.DataArray
806
+ Hyperspectral image data.
807
+ Usually, a 3-to-5-dimensional array of type ``uint8`` or ``uint16``.
808
+
809
+ Raises
810
+ ------
811
+ tifffile.TiffFileError
812
+ File is not a TIFF file.
813
+ ValueError
814
+ File is not an LSM file or does not contain hyperspectral image.
815
+
816
+ Examples
817
+ --------
818
+ >>> data = read_lsm(fetch('paramecium.lsm'))
819
+ >>> data.values
820
+ array(...)
821
+ >>> data.dtype
822
+ dtype('uint8')
823
+ >>> data.shape
824
+ (30, 512, 512)
825
+ >>> data.dims
826
+ ('C', 'Y', 'X')
827
+ >>> data.coords['C'].data # wavelengths
828
+ array(...)
829
+
830
+ """
831
+ import tifffile
832
+
833
+ with tifffile.TiffFile(filename) as tif:
834
+ if not tif.is_lsm:
835
+ raise ValueError(f'{tif.filename} is not an LSM file')
836
+
837
+ page = tif.pages.first
838
+ lsminfo = tif.lsm_metadata
839
+ channels = page.tags[258].count
840
+
841
+ if channels < 4 or lsminfo is None or lsminfo['SpectralScan'] != 1:
842
+ raise ValueError(
843
+ f'{tif.filename} does not contain hyperspectral image'
844
+ )
845
+
846
+ # TODO: contribute this to tifffile
847
+ series = tif.series[0]
848
+ data = series.asarray()
849
+ dims = tuple(series.axes)
850
+ coords = {}
851
+ # channel wavelengths
852
+ axis = dims.index('C')
853
+ wavelengths = lsminfo['ChannelWavelength'].mean(axis=1)
854
+ if wavelengths.size != data.shape[axis]:
855
+ raise ValueError(
856
+ f'{tif.filename} wavelengths do not match channel axis'
857
+ )
858
+ # stack may contain non-wavelength frame
859
+ indices = wavelengths > 0
860
+ wavelengths = wavelengths[indices]
861
+ if wavelengths.size < 3:
862
+ raise ValueError(
863
+ f'{tif.filename} does not contain hyperspectral image'
864
+ )
865
+ data = data.take(indices.nonzero()[0], axis=axis)
866
+ coords['C'] = wavelengths
867
+ # time stamps
868
+ if 'T' in dims:
869
+ coords['T'] = lsminfo['TimeStamps']
870
+ if coords['T'].size != data.shape[dims.index('T')]:
871
+ raise ValueError(
872
+ f'{tif.filename} timestamps do not match time axis'
873
+ )
874
+ # spatial coordinates
875
+ for ax in 'ZYX':
876
+ if ax in dims:
877
+ size = data.shape[dims.index(ax)]
878
+ coords[ax] = numpy.linspace(
879
+ lsminfo[f'Origin{ax}'],
880
+ size * lsminfo[f'VoxelSize{ax}'],
881
+ size,
882
+ endpoint=False,
883
+ dtype=numpy.float64,
884
+ )
885
+ metadata = _metadata(series.axes, data.shape, filename, **coords)
886
+
887
+ from xarray import DataArray
888
+
889
+ return DataArray(data, **metadata)
890
+
891
+
892
+ def read_ifli(
893
+ filename: str | PathLike[Any],
894
+ /,
895
+ *,
896
+ channel: int = 0,
897
+ **kwargs: Any,
898
+ ) -> DataArray:
899
+ """Return image and metadata from ISS IFLI file.
900
+
901
+ ISS VistaVision IFLI files contain phasor coordinates for several
902
+ positions, wavelengths, time points, channels, slices, and frequencies
903
+ from analog or digital frequency-domain fluorescence lifetime measurements.
904
+
905
+ Parameters
906
+ ----------
907
+ filename : str or Path
908
+ Name of ISS IFLI file to read.
909
+ channel : int, optional
910
+ Index of channel to return. The first channel is returned by default.
911
+ **kwargs
912
+ Additional arguments passed to :py:meth:`lfdfiles.VistaIfli.asarray`,
913
+ for example ``memmap=True``.
914
+
915
+ Returns
916
+ -------
917
+ xarray.DataArray
918
+ Average intensity and phasor coordinates.
919
+ An array of up to 8 dimensions with :ref:`axes codes <axes>`
920
+ ``'RCTZYXFS'`` and type ``float32``.
921
+ The last dimension contains `mean`, `real`, and `imag` phasor
922
+ coordinates.
923
+
924
+ - ``coords['F']``: modulation frequencies.
925
+ - ``coords['C']``: emission wavelengths, if any.
926
+ - ``attrs['ref_tau']``: reference lifetimes.
927
+ - ``attrs['ref_tau_frac']``: reference lifetime fractions.
928
+ - ``attrs['ref_phasor']``: reference phasor coordinates for all
929
+ frequencies.
930
+
931
+ Raises
932
+ ------
933
+ lfdfiles.LfdFileError
934
+ File is not an ISS IFLI file.
935
+
936
+ Examples
937
+ --------
938
+ >>> data = read_ifli(fetch('frequency_domain.ifli'))
939
+ >>> data.values
940
+ array(...)
941
+ >>> data.dtype
942
+ dtype('float32')
943
+ >>> data.shape
944
+ (256, 256, 4, 3)
945
+ >>> data.dims
946
+ ('Y', 'X', 'F', 'S')
947
+ >>> data.coords['F'].data
948
+ array([8.033...])
949
+ >>> data.coords['S'].data
950
+ array(['mean', 'real', 'imag'], dtype='<U4')
951
+ >>> data.attrs
952
+ {'ref_tau': (2.5, 0.0), 'ref_tau_frac': (1.0, 0.0), 'ref_phasor': array...}
953
+
954
+ """
955
+ import lfdfiles
956
+
957
+ with lfdfiles.VistaIfli(filename) as ifli:
958
+ assert ifli.axes is not None
959
+ # always return one acquisition channel to simplify metadata handling
960
+ data = ifli.asarray(**kwargs)[:, channel : channel + 1].copy()
961
+ shape, axes, _ = _squeeze_axes(data.shape, ifli.axes, skip='FYX')
962
+ axes = axes.replace('E', 'C') # spectral axis
963
+ data = data.reshape(shape)
964
+ header = ifli.header
965
+ coords: dict[str, Any] = {}
966
+ coords['S'] = ['mean', 'real', 'imag']
967
+ coords['F'] = numpy.array(header['ModFrequency'])
968
+ # TODO: how to distinguish time- from frequency-domain?
969
+ # TODO: how to extract spatial coordinates?
970
+ if 'T' in axes:
971
+ coords['T'] = numpy.array(header['TimeTags'])
972
+ if 'C' in axes:
973
+ coords['C'] = numpy.array(header['SpectrumInfo'])
974
+ # if 'Z' in axes:
975
+ # coords['Z'] = numpy.array(header[])
976
+ metadata = _metadata(axes, shape, filename, **coords)
977
+ attrs = metadata['attrs']
978
+ attrs['ref_tau'] = (
979
+ header['RefLifetime'][channel],
980
+ header['RefLifetime2'][channel],
981
+ )
982
+ attrs['ref_tau_frac'] = (
983
+ header['RefLifetimeFrac'][channel],
984
+ 1.0 - header['RefLifetimeFrac'][channel],
985
+ )
986
+ attrs['ref_phasor'] = numpy.array(header['RefDCPhasor'][channel])
987
+
988
+ from xarray import DataArray
989
+
990
+ return DataArray(data, **metadata)
991
+
992
+
993
+ def read_sdt(
994
+ filename: str | PathLike[Any],
995
+ /,
996
+ *,
997
+ index: int = 0,
998
+ ) -> DataArray:
999
+ """Return time-resolved image and metadata from Becker & Hickl SDT file.
1000
+
1001
+ SDT files contain time-correlated single photon counting measurement data
1002
+ and instrumentation parameters.
1003
+
1004
+ Parameters
1005
+ ----------
1006
+ filename : str or Path
1007
+ Name of SDT file to read.
1008
+ index : int, optional, default: 0
1009
+ Index of dataset to read in case the file contains multiple datasets.
1010
+
1011
+ Returns
1012
+ -------
1013
+ xarray.DataArray
1014
+ Time correlated single photon counting image data with
1015
+ :ref:`axes codes <axes>` ``'YXH'`` and type ``uint16``, ``uint32``,
1016
+ or ``float32``.
1017
+
1018
+ - ``coords['H']``: times of the histogram bins.
1019
+ - ``attrs['frequency']``: repetition frequency in MHz.
1020
+
1021
+ Raises
1022
+ ------
1023
+ ValueError
1024
+ File is not an SDT file containing time-correlated single photon
1025
+ counting data.
1026
+
1027
+ Examples
1028
+ --------
1029
+ >>> data = read_sdt(fetch('tcspc.sdt'))
1030
+ >>> data.values
1031
+ array(...)
1032
+ >>> data.dtype
1033
+ dtype('uint16')
1034
+ >>> data.shape
1035
+ (128, 128, 256)
1036
+ >>> data.dims
1037
+ ('Y', 'X', 'H')
1038
+ >>> data.coords['H'].data
1039
+ array(...)
1040
+ >>> data.attrs['frequency']
1041
+ 79...
1042
+
1043
+ """
1044
+ import sdtfile
1045
+
1046
+ with sdtfile.SdtFile(filename) as sdt:
1047
+ if (
1048
+ 'SPC Setup & Data File' not in sdt.info.id
1049
+ and 'SPC FCS Data File' not in sdt.info.id
1050
+ ):
1051
+ # skip DLL data
1052
+ raise ValueError(
1053
+ f'{os.path.basename(filename)!r} '
1054
+ 'is not an SDT file containing TCSPC data'
1055
+ )
1056
+ # filter block types?
1057
+ # sdtfile.BlockType(sdt.block_headers[index].block_type).contents
1058
+ # == 'PAGE_BLOCK'
1059
+ data = sdt.data[index]
1060
+ times = sdt.times[index]
1061
+
1062
+ # TODO: get spatial coordinates from scanner settings?
1063
+ metadata = _metadata('QYXH'[-data.ndim :], data.shape, filename, H=times)
1064
+ metadata['attrs']['frequency'] = 1e-6 / float(times[-1] + times[1])
1065
+
1066
+ from xarray import DataArray
1067
+
1068
+ return DataArray(data, **metadata)
1069
+
1070
+
1071
+ def read_ptu(
1072
+ filename: str | PathLike[Any],
1073
+ /,
1074
+ selection: Sequence[int | slice | EllipsisType | None] | None = None,
1075
+ *,
1076
+ trimdims: Sequence[Literal['T', 'C', 'H']] | str | None = None,
1077
+ dtype: DTypeLike | None = None,
1078
+ frame: int | None = None,
1079
+ channel: int | None = None,
1080
+ dtime: int | None = 0,
1081
+ keepdims: bool = True,
1082
+ ) -> DataArray:
1083
+ """Return image histogram and metadata from PicoQuant PTU T3 mode file.
1084
+
1085
+ PTU files contain time-correlated single photon counting measurement data
1086
+ and instrumentation parameters.
1087
+
1088
+ Parameters
1089
+ ----------
1090
+ filename : str or Path
1091
+ Name of PTU file to read.
1092
+ selection : sequence of index types, optional
1093
+ Indices for all dimensions:
1094
+
1095
+ - ``None``: return all items along axis (default).
1096
+ - ``Ellipsis``: return all items along multiple axes.
1097
+ - ``int``: return single item along axis.
1098
+ - ``slice``: return chunk of axis.
1099
+ ``slice.step`` is binning factor.
1100
+ If ``slice.step=-1``, integrate all items along axis.
1101
+
1102
+ trimdims : str, optional, default: 'TCH'
1103
+ Axes to trim.
1104
+ dtype : dtype-like, optional, default: uint16
1105
+ Unsigned integer type of image histogram array.
1106
+ Increase the bit depth to avoid overflows when integrating.
1107
+ frame : int, optional
1108
+ If < 0, integrate time axis, else return specified frame.
1109
+ Overrides `selection` for axis ``T``.
1110
+ channel : int, optional
1111
+ If < 0, integrate channel axis, else return specified channel.
1112
+ Overrides `selection` for axis ``C``.
1113
+ dtime : int, optional, default: 0
1114
+ Specifies number of bins in image histogram.
1115
+ If 0 (default), return number of bins in one period.
1116
+ If < 0, integrate delay time axis.
1117
+ If > 0, return up to specified bin.
1118
+ Overrides `selection` for axis ``H``.
1119
+ keepdims : bool, optional, default: True
1120
+ If true (default), reduced axes are left as size-one dimension.
1121
+
1122
+ Returns
1123
+ -------
1124
+ xarray.DataArray
1125
+ Decoded TTTR T3 records as up to 5-dimensional image array
1126
+ with :ref:`axes codes <axes>` ``'TYXCH'`` and type specified
1127
+ in ``dtype``:
1128
+
1129
+ - ``coords['H']``: times of the histogram bins.
1130
+ - ``attrs['frequency']``: repetition frequency in MHz.
1131
+
1132
+ Raises
1133
+ ------
1134
+ ptufile.PqFileError
1135
+ File is not a PicoQuant PTU file or is corrupted.
1136
+ ValueError
1137
+ File is not a PicoQuant PTU T3 mode file containing time-correlated
1138
+ single photon counting data.
1139
+
1140
+ Examples
1141
+ --------
1142
+ >>> data = read_ptu(fetch('hazelnut_FLIM_single_image.ptu'))
1143
+ >>> data.values
1144
+ array(...)
1145
+ >>> data.dtype
1146
+ dtype('uint16')
1147
+ >>> data.shape
1148
+ (5, 256, 256, 1, 132)
1149
+ >>> data.dims
1150
+ ('T', 'Y', 'X', 'C', 'H')
1151
+ >>> data.coords['H'].data
1152
+ array(...)
1153
+ >>> data.attrs['frequency']
1154
+ 78.02
1155
+
1156
+ """
1157
+ import ptufile
1158
+ from xarray import DataArray
1159
+
1160
+ with ptufile.PtuFile(filename, trimdims=trimdims) as ptu:
1161
+ if not ptu.is_t3 or not ptu.is_image:
1162
+ raise ValueError(
1163
+ f'{os.path.basename(filename)!r} '
1164
+ 'is not a PTU file containing a T3 mode image'
1165
+ )
1166
+ data = ptu.decode_image(
1167
+ selection,
1168
+ dtype=dtype,
1169
+ frame=frame,
1170
+ channel=channel,
1171
+ dtime=dtime,
1172
+ keepdims=keepdims,
1173
+ asxarray=True,
1174
+ )
1175
+ assert isinstance(data, DataArray)
1176
+ data.attrs['frequency'] = ptu.frequency * 1e-6 # MHz
1177
+
1178
+ return data
1179
+
1180
+
1181
+ def read_flif(
1182
+ filename: str | PathLike[Any],
1183
+ /,
1184
+ ) -> DataArray:
1185
+ """Return frequency-domain image and metadata from FlimFast FLIF file.
1186
+
1187
+ FlimFast FLIF files contain camera images and metadata from
1188
+ frequency-domain fluorescence lifetime measurements.
1189
+
1190
+ Parameters
1191
+ ----------
1192
+ filename : str or Path
1193
+ Name of FlimFast FLIF file to read.
1194
+
1195
+ Returns
1196
+ -------
1197
+ xarray.DataArray
1198
+ Frequency-domain phase images with :ref:`axes codes <axes>` ``'THYX'``
1199
+ and type ``uint16``:
1200
+
1201
+ - ``coords['H']``: phases in radians.
1202
+ - ``attrs['frequency']``: repetition frequency in MHz.
1203
+ - ``attrs['ref_phase']``: measured phase of reference.
1204
+ - ``attrs['ref_mod']``: measured modulation of reference.
1205
+ - ``attrs['ref_tauphase']``: lifetime from phase of reference.
1206
+ - ``attrs['ref_taumod']``: lifetime from modulation of reference.
1207
+
1208
+ Raises
1209
+ ------
1210
+ lfdfiles.LfdFileError
1211
+ File is not a FlimFast FLIF file.
1212
+
1213
+ Examples
1214
+ --------
1215
+ >>> data = read_flif(fetch('flimfast.flif'))
1216
+ >>> data.values
1217
+ array(...)
1218
+ >>> data.dtype
1219
+ dtype('uint16')
1220
+ >>> data.shape
1221
+ (32, 220, 300)
1222
+ >>> data.dims
1223
+ ('H', 'Y', 'X')
1224
+ >>> data.coords['H'].data
1225
+ array(...)
1226
+ >>> data.attrs['frequency']
1227
+ 80.65...
1228
+
1229
+ """
1230
+ import lfdfiles
1231
+
1232
+ with lfdfiles.FlimfastFlif(filename) as flif:
1233
+ nphases = int(flif.header.phases)
1234
+ data = flif.asarray()
1235
+ if data.shape[0] < nphases:
1236
+ raise ValueError(f'measured phases {data.shape[0]} < {nphases=}')
1237
+ if data.shape[0] % nphases != 0:
1238
+ data = data[: (data.shape[0] // nphases) * nphases]
1239
+ data = data.reshape(-1, nphases, data.shape[1], data.shape[2])
1240
+ if data.shape[0] == 1:
1241
+ data = data[0]
1242
+ axes = 'HYX'
1243
+ else:
1244
+ axes = 'THYX'
1245
+ # TODO: check if phases are ordered
1246
+ phases = numpy.radians(flif.records['phase'][:nphases])
1247
+ metadata = _metadata(axes, data.shape, H=phases)
1248
+ attrs = metadata['attrs']
1249
+ attrs['frequency'] = float(flif.header.frequency)
1250
+ attrs['ref_phase'] = float(flif.header.measured_phase)
1251
+ attrs['ref_mod'] = float(flif.header.measured_mod)
1252
+ attrs['ref_tauphase'] = float(flif.header.ref_tauphase)
1253
+ attrs['ref_taumod'] = float(flif.header.ref_taumod)
1254
+
1255
+ from xarray import DataArray
1256
+
1257
+ return DataArray(data, **metadata)
1258
+
1259
+
1260
+ def read_fbd(
1261
+ filename: str | PathLike[Any],
1262
+ /,
1263
+ *,
1264
+ frame: int | None = None,
1265
+ channel: int | None = None,
1266
+ keepdims: bool = True,
1267
+ laser_factor: float = -1.0,
1268
+ ) -> DataArray:
1269
+ """Return frequency-domain image and metadata from FLIMbox FBD file.
1270
+
1271
+ FDB files contain encoded data from the FLIMbox device, which can be
1272
+ decoded to photon arrival windows, channels, and global times.
1273
+ The encoding scheme depends on the FLIMbox device's firmware.
1274
+ The FBD file format is undocumented.
1275
+
1276
+ This function may fail to produce expected results when files use unknown
1277
+ firmware, do not contain image scans, settings were recorded incorrectly,
1278
+ scanner and FLIMbox frequencies were out of sync, or scanner settings were
1279
+ changed during acquisition.
1280
+
1281
+ Parameters
1282
+ ----------
1283
+ filename : str or Path
1284
+ Name of FLIMbox FBD file to read.
1285
+ frame : int, optional
1286
+ If None (default), return all frames.
1287
+ If < 0, integrate time axis, else return specified frame.
1288
+ channel : int, optional
1289
+ If None (default), return all channels, else return specified channel.
1290
+ keepdims : bool, optional
1291
+ If true (default), reduced axes are left as size-one dimension.
1292
+ laser_factor : float, optional
1293
+ Factor to correct dwell_time/laser_frequency.
1294
+
1295
+ Returns
1296
+ -------
1297
+ xarray.DataArray
1298
+ Frequency-domain image histogram with :ref:`axes codes <axes>`
1299
+ ``'TCYXH'`` and type ``uint16``:
1300
+
1301
+ - ``coords['H']``: phases in radians.
1302
+ - ``attrs['frequency']``: repetition frequency in MHz.
1303
+
1304
+ Raises
1305
+ ------
1306
+ lfdfiles.LfdFileError
1307
+ File is not a FLIMbox FBD file.
1308
+
1309
+ Examples
1310
+ --------
1311
+ >>> data = read_fbd(fetch('convallaria_000$EI0S.fbd')) # doctest: +SKIP
1312
+ >>> data.values # doctest: +SKIP
1313
+ array(...)
1314
+ >>> data.dtype # doctest: +SKIP
1315
+ dtype('uint16')
1316
+ >>> data.shape # doctest: +SKIP
1317
+ (9, 2, 256, 256, 64)
1318
+ >>> data.dims # doctest: +SKIP
1319
+ ('T', 'C', 'Y', 'X', 'H')
1320
+ >>> data.coords['H'].data # doctest: +SKIP
1321
+ array(...)
1322
+ >>> data.attrs['frequency'] # doctest: +SKIP
1323
+ 40.0
1324
+
1325
+ """
1326
+ import lfdfiles
1327
+
1328
+ integrate_frames = 0 if frame is None or frame >= 0 else 1
1329
+
1330
+ with lfdfiles.FlimboxFbd(filename, laser_factor=laser_factor) as fbd:
1331
+ data = fbd.asimage(None, None, integrate_frames=integrate_frames)
1332
+ if integrate_frames:
1333
+ frame = None
1334
+ copy = False
1335
+ axes = 'TCYXH'
1336
+ if channel is None:
1337
+ if not keepdims and data.shape[1] == 1:
1338
+ data = data[:, 0]
1339
+ axes = 'TYXH'
1340
+ else:
1341
+ if channel < 0 or channel >= data.shape[1]:
1342
+ raise IndexError(f'{channel=} out of bounds')
1343
+ if keepdims:
1344
+ data = data[:, channel : channel + 1]
1345
+ else:
1346
+ data = data[:, channel]
1347
+ axes = 'TYXH'
1348
+ copy = True
1349
+ if frame is None:
1350
+ if not keepdims and data.shape[0] == 1:
1351
+ data = data[0]
1352
+ axes = axes[1:]
1353
+ else:
1354
+ if frame < 0 or frame > data.shape[0]:
1355
+ raise IndexError(f'{frame=} out of bounds')
1356
+ if keepdims:
1357
+ data = data[frame : frame + 1]
1358
+ else:
1359
+ data = data[frame]
1360
+ axes = axes[1:]
1361
+ copy = True
1362
+ if copy:
1363
+ data = data.copy()
1364
+ # TODO: return arrival window indices or micro-times as H coords?
1365
+ phases = numpy.linspace(
1366
+ 0.0, numpy.pi * 2, data.shape[-1], endpoint=False
1367
+ )
1368
+ metadata = _metadata(axes, data.shape, H=phases)
1369
+ attrs = metadata['attrs']
1370
+ attrs['frequency'] = fbd.laser_frequency * 1e-6
1371
+
1372
+ from xarray import DataArray
1373
+
1374
+ return DataArray(data, **metadata)
1375
+
1376
+
1377
+ def read_b64(
1378
+ filename: str | PathLike[Any],
1379
+ /,
1380
+ ) -> DataArray:
1381
+ """Return intensity image and metadata from SimFCS B64 file.
1382
+
1383
+ B64 files contain one or more square intensity image(s), a carpet
1384
+ of lines, or a stream of intensity data. B64 files contain no metadata.
1385
+
1386
+ Parameters
1387
+ ----------
1388
+ filename : str or Path
1389
+ Name of SimFCS B64 file to read.
1390
+
1391
+ Returns
1392
+ -------
1393
+ xarray.DataArray
1394
+ Stack of square-sized intensity images of type ``int16``.
1395
+
1396
+ Raises
1397
+ ------
1398
+ lfdfiles.LfdFileError
1399
+ File is not a SimFCS B64 file.
1400
+ ValueError
1401
+ File does not contain an image stack.
1402
+
1403
+ Examples
1404
+ --------
1405
+ >>> data = read_b64(fetch('simfcs.b64'))
1406
+ >>> data.values
1407
+ array(...)
1408
+ >>> data.dtype
1409
+ dtype('int16')
1410
+ >>> data.shape
1411
+ (22, 1024, 1024)
1412
+ >>> data.dtype
1413
+ dtype('int16')
1414
+ >>> data.dims
1415
+ ('I', 'Y', 'X')
1416
+
1417
+ """
1418
+ import lfdfiles
1419
+
1420
+ with lfdfiles.SimfcsB64(filename) as b64:
1421
+ data = b64.asarray()
1422
+ if data.ndim != 3:
1423
+ raise ValueError(
1424
+ f'{os.path.basename(filename)!r} '
1425
+ 'does not contain an image stack'
1426
+ )
1427
+ metadata = _metadata(b64.axes, data.shape, filename)
1428
+
1429
+ from xarray import DataArray
1430
+
1431
+ return DataArray(data, **metadata)
1432
+
1433
+
1434
+ def read_z64(
1435
+ filename: str | PathLike[Any],
1436
+ /,
1437
+ ) -> DataArray:
1438
+ """Return image and metadata from SimFCS Z64 file.
1439
+
1440
+ Z64 files contain stacks of square images such as intensity volumes
1441
+ or time-domain fluorescence lifetime histograms acquired from
1442
+ Becker & Hickl(r) TCSPC cards. Z64 files contain no metadata.
1443
+
1444
+ Parameters
1445
+ ----------
1446
+ filename : str or Path
1447
+ Name of SimFCS Z64 file to read.
1448
+
1449
+ Returns
1450
+ -------
1451
+ xarray.DataArray
1452
+ Single or stack of square-sized images of type ``float32``.
1453
+
1454
+ Raises
1455
+ ------
1456
+ lfdfiles.LfdFileError
1457
+ File is not a SimFCS Z64 file.
1458
+
1459
+ Examples
1460
+ --------
1461
+ >>> data = read_z64(fetch('simfcs.z64'))
1462
+ >>> data.values
1463
+ array(...)
1464
+ >>> data.dtype
1465
+ dtype('float32')
1466
+ >>> data.shape
1467
+ (256, 256, 256)
1468
+ >>> data.dims
1469
+ ('Q', 'Y', 'X')
1470
+
1471
+ """
1472
+ import lfdfiles
1473
+
1474
+ with lfdfiles.SimfcsZ64(filename) as z64:
1475
+ data = z64.asarray()
1476
+ metadata = _metadata(z64.axes, data.shape, filename)
1477
+
1478
+ from xarray import DataArray
1479
+
1480
+ return DataArray(data, **metadata)
1481
+
1482
+
1483
+ def read_bh(
1484
+ filename: str | PathLike[Any],
1485
+ /,
1486
+ ) -> DataArray:
1487
+ """Return image and metadata from SimFCS B&H file.
1488
+
1489
+ B&H files contain time-domain fluorescence lifetime histogram data,
1490
+ acquired from Becker & Hickl(r) TCSPC cards, or converted from other
1491
+ data sources. B&H files contain no metadata.
1492
+
1493
+ Parameters
1494
+ ----------
1495
+ filename : str or Path
1496
+ Name of SimFCS B&H file to read.
1497
+
1498
+ Returns
1499
+ -------
1500
+ xarray.DataArray
1501
+ Time-domain fluorescence lifetime histogram with axes ``'HYX'``,
1502
+ shape ``(256, 256, 256)``, and type ``float32``.
1503
+
1504
+ Raises
1505
+ ------
1506
+ lfdfiles.LfdFileError
1507
+ File is not a SimFCS B&H file.
1508
+
1509
+ Examples
1510
+ --------
1511
+ >>> data = read_bh(fetch('simfcs.b&h'))
1512
+ >>> data.values
1513
+ array(...)
1514
+ >>> data.dtype
1515
+ dtype('float32')
1516
+ >>> data.shape
1517
+ (256, 256, 256)
1518
+ >>> data.dims
1519
+ ('H', 'Y', 'X')
1520
+
1521
+ """
1522
+ import lfdfiles
1523
+
1524
+ with lfdfiles.SimfcsBh(filename) as bnh:
1525
+ assert bnh.axes is not None
1526
+ data = bnh.asarray()
1527
+ metadata = _metadata(bnh.axes.replace('Q', 'H'), data.shape, filename)
1528
+
1529
+ from xarray import DataArray
1530
+
1531
+ return DataArray(data, **metadata)
1532
+
1533
+
1534
+ def read_bhz(
1535
+ filename: str | PathLike[Any],
1536
+ /,
1537
+ ) -> DataArray:
1538
+ """Return image and metadata from SimFCS BHZ file.
1539
+
1540
+ BHZ files contain time-domain fluorescence lifetime histogram data,
1541
+ acquired from Becker & Hickl(r) TCSPC cards, or converted from other
1542
+ data sources. BHZ files contain no metadata.
1543
+
1544
+ Parameters
1545
+ ----------
1546
+ filename : str or Path
1547
+ Name of SimFCS BHZ file to read.
1548
+
1549
+ Returns
1550
+ -------
1551
+ xarray.DataArray
1552
+ Time-domain fluorescence lifetime histogram with axes ``'HYX'``,
1553
+ shape ``(256, 256, 256)``, and type ``float32``.
1554
+
1555
+ Raises
1556
+ ------
1557
+ lfdfiles.LfdFileError
1558
+ File is not a SimFCS BHZ file.
1559
+
1560
+ Examples
1561
+ --------
1562
+ >>> data = read_bhz(fetch('simfcs.bhz'))
1563
+ >>> data.values
1564
+ array(...)
1565
+ >>> data.dtype
1566
+ dtype('float32')
1567
+ >>> data.shape
1568
+ (256, 256, 256)
1569
+ >>> data.dims
1570
+ ('H', 'Y', 'X')
1571
+
1572
+ """
1573
+ import lfdfiles
1574
+
1575
+ with lfdfiles.SimfcsBhz(filename) as bhz:
1576
+ assert bhz.axes is not None
1577
+ data = bhz.asarray()
1578
+ metadata = _metadata(bhz.axes.replace('Q', 'H'), data.shape, filename)
1579
+
1580
+ from xarray import DataArray
1581
+
1582
+ return DataArray(data, **metadata)
1583
+
1584
+
1585
+ def _metadata(
1586
+ dims: Sequence[str] | None,
1587
+ shape: tuple[int, ...],
1588
+ /,
1589
+ name: str | PathLike[Any] | None = None,
1590
+ attrs: dict[str, Any] | None = None,
1591
+ **coords: Any,
1592
+ ) -> dict[str, Any]:
1593
+ """Return xarray-style dims, coords, and attrs in a dict.
1594
+
1595
+ >>> _metadata('SYX', (3, 2, 1), S=['0', '1', '2'])
1596
+ {'dims': ('S', 'Y', 'X'), 'coords': {'S': ['0', '1', '2']}, 'attrs': {}}
1597
+
1598
+ """
1599
+ assert dims is not None
1600
+ dims = tuple(dims)
1601
+ if len(dims) != len(shape):
1602
+ raise ValueError(
1603
+ f'dims do not match shape {len(dims)} != {len(shape)}'
1604
+ )
1605
+ coords = {dim: coords[dim] for dim in dims if dim in coords}
1606
+ if attrs is None:
1607
+ attrs = {}
1608
+ metadata = {'dims': dims, 'coords': coords, 'attrs': attrs}
1609
+ if name:
1610
+ metadata['name'] = os.path.basename(name)
1611
+ return metadata
1612
+
1613
+
1614
+ def _squeeze_axes(
1615
+ shape: Sequence[int],
1616
+ axes: str,
1617
+ /,
1618
+ skip: str = 'XY',
1619
+ ) -> tuple[tuple[int, ...], str, tuple[bool, ...]]:
1620
+ """Return shape and axes with length-1 dimensions removed.
1621
+
1622
+ Remove unused dimensions unless their axes are listed in `skip`.
1623
+
1624
+ Adapted from the tifffile library.
1625
+
1626
+ Parameters
1627
+ ----------
1628
+ shape : tuple of ints
1629
+ Sequence of dimension sizes.
1630
+ axes : str
1631
+ Character codes for dimensions in `shape`.
1632
+ skip : str, optional
1633
+ Character codes for dimensions whose length-1 dimensions are
1634
+ not removed. The default is 'XY'.
1635
+
1636
+ Returns
1637
+ -------
1638
+ shape : tuple of ints
1639
+ Sequence of dimension sizes with length-1 dimensions removed.
1640
+ axes : str
1641
+ Character codes for dimensions in output `shape`.
1642
+ squeezed : str
1643
+ Dimensions were kept (True) or removed (False).
1644
+
1645
+ Examples
1646
+ --------
1647
+ >>> _squeeze_axes((5, 1, 2, 1, 1), 'TZYXC')
1648
+ ((5, 2, 1), 'TYX', (True, False, True, True, False))
1649
+ >>> _squeeze_axes((1,), 'Q')
1650
+ ((1,), 'Q', (True,))
1651
+
1652
+ """
1653
+ if len(shape) != len(axes):
1654
+ raise ValueError(f'{len(shape)=} != {len(axes)=}')
1655
+ if not axes:
1656
+ return tuple(shape), axes, ()
1657
+ squeezed: list[bool] = []
1658
+ shape_squeezed: list[int] = []
1659
+ axes_squeezed: list[str] = []
1660
+ for size, ax in zip(shape, axes):
1661
+ if size > 1 or ax in skip:
1662
+ squeezed.append(True)
1663
+ shape_squeezed.append(size)
1664
+ axes_squeezed.append(ax)
1665
+ else:
1666
+ squeezed.append(False)
1667
+ if len(shape_squeezed) == 0:
1668
+ squeezed[-1] = True
1669
+ shape_squeezed.append(shape[-1])
1670
+ axes_squeezed.append(axes[-1])
1671
+ return tuple(shape_squeezed), ''.join(axes_squeezed), tuple(squeezed)