phasorpy 0.5__cp313-cp313-win_amd64.whl → 0.6__cp313-cp313-win_amd64.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.
@@ -0,0 +1,312 @@
1
+ """Experimental functions.
2
+
3
+ The ``phasorpy.experimental`` module provides functions related to phasor
4
+ analysis for evaluation.
5
+ The functions may be removed or moved to other modules in future releases.
6
+
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ __all__ = [
12
+ 'anscombe_transform',
13
+ 'anscombe_transform_inverse',
14
+ 'spectral_vector_denoise',
15
+ ]
16
+
17
+ import math
18
+ from typing import TYPE_CHECKING
19
+
20
+ if TYPE_CHECKING:
21
+ from ._typing import Any, NDArray, ArrayLike, DTypeLike, Literal, Sequence
22
+
23
+ import numpy
24
+
25
+ from ._phasorpy import (
26
+ _anscombe,
27
+ _anscombe_inverse,
28
+ _anscombe_inverse_approx,
29
+ _phasor_from_signal_vector,
30
+ _signal_denoise_vector,
31
+ )
32
+ from ._utils import parse_harmonic
33
+ from .utils import number_threads
34
+
35
+
36
+ def anscombe_transform(
37
+ data: ArrayLike,
38
+ /,
39
+ **kwargs: Any,
40
+ ) -> NDArray[Any]:
41
+ r"""Return Anscombe variance-stabilizing transformation.
42
+
43
+ The Anscombe transformation normalizes the standard deviation of noisy,
44
+ Poisson-distributed data.
45
+ It can be used to transform un-normalized phasor coordinates to
46
+ approximate standard Gaussian distributions.
47
+
48
+ Parameters
49
+ ----------
50
+ data : array_like
51
+ Noisy Poisson-distributed data to be transformed.
52
+ **kwargs
53
+ Optional `arguments passed to numpy universal functions
54
+ <https://numpy.org/doc/stable/reference/ufuncs.html#ufuncs-kwargs>`_.
55
+
56
+ Returns
57
+ -------
58
+ ndarray
59
+ Anscombe-transformed data with variance of approximately 1.
60
+
61
+ Notes
62
+ -----
63
+ The Anscombe transformation according to [1]_:
64
+
65
+ .. math::
66
+
67
+ z = 2 \cdot \sqrt{x + 3 / 8}
68
+
69
+ References
70
+ ----------
71
+
72
+ .. [1] Anscombe FJ.
73
+ `The transformation of Poisson, binomial and negative-binomial data
74
+ <https://doi.org/10.2307/2332343>`_.
75
+ *Biometrika*, 35(3-4): 246-254 (1948)
76
+
77
+ Examples
78
+ --------
79
+
80
+ >>> z = anscombe_transform(numpy.random.poisson(10, 10000))
81
+ >>> numpy.allclose(numpy.std(z), 1.0, atol=0.1)
82
+ True
83
+
84
+ """
85
+ return _anscombe(data, **kwargs) # type: ignore[no-any-return]
86
+
87
+
88
+ def anscombe_transform_inverse(
89
+ data: ArrayLike,
90
+ /,
91
+ *,
92
+ approx: bool = False,
93
+ **kwargs: Any,
94
+ ) -> NDArray[Any]:
95
+ r"""Return inverse Anscombe transformation.
96
+
97
+ Parameters
98
+ ----------
99
+ data : array_like
100
+ Anscombe-transformed data.
101
+ approx : bool, default: False
102
+ If true, return approximation of exact unbiased inverse.
103
+ **kwargs
104
+ Optional `arguments passed to numpy universal functions
105
+ <https://numpy.org/doc/stable/reference/ufuncs.html#ufuncs-kwargs>`_.
106
+
107
+ Returns
108
+ -------
109
+ ndarray
110
+ Inverse Anscombe-transformed data.
111
+
112
+ Notes
113
+ -----
114
+ The inverse Anscombe transformation according to [1]_:
115
+
116
+ .. math::
117
+
118
+ x = (z / 2.0)^2 - 3 / 8
119
+
120
+ The approximate inverse Anscombe transformation according to [2]_ and [3]_:
121
+
122
+ .. math::
123
+
124
+ x = 1/4 \cdot z^2
125
+ + 1/4 \cdot \sqrt{3/2} \cdot z^{-1}
126
+ - 11/8 \cdot z^{-2}
127
+ + 5/8 \cdot \sqrt(3/2) \cdot z^{-3}
128
+ - 1/8
129
+
130
+ References
131
+ ----------
132
+
133
+ .. [2] Makitalo M, and Foi A.
134
+ `A closed-form approximation of the exact unbiased inverse of the
135
+ Anscombe variance-stabilizing transformation
136
+ <https://doi.org/10.1109/TIP.2011.2121085>`_.
137
+ *IEEE Trans Image Process*, 20(9): 2697-8 (2011).
138
+
139
+ .. [3] Makitalo M, and Foi A
140
+ `Optimal inversion of the generalized Anscombe transformation for
141
+ Poisson-Gaussian noise
142
+ <https://doi.org/10.1109/TIP.2012.2202675>`_,
143
+ *IEEE Trans Image Process*, 22(1): 91-103 (2013)
144
+
145
+ Examples
146
+ --------
147
+
148
+ >>> x = numpy.random.poisson(10, 100)
149
+ >>> x2 = anscombe_transform_inverse(anscombe_transform(x))
150
+ >>> numpy.allclose(x, x2, atol=1e-3)
151
+ True
152
+
153
+ """
154
+ if approx:
155
+ return _anscombe_inverse_approx( # type: ignore[no-any-return]
156
+ data, **kwargs
157
+ )
158
+ return _anscombe_inverse(data, **kwargs) # type: ignore[no-any-return]
159
+
160
+
161
+ def spectral_vector_denoise(
162
+ signal: ArrayLike,
163
+ /,
164
+ spectral_vector: ArrayLike | None = None,
165
+ *,
166
+ axis: int = -1,
167
+ harmonic: int | Sequence[int] | Literal['all'] | str | None = None,
168
+ sigma: float = 0.05,
169
+ vmin: float | None = None,
170
+ dtype: DTypeLike | None = None,
171
+ num_threads: int | None = None,
172
+ ) -> NDArray[Any]:
173
+ """Return spectral-vector-denoised signal.
174
+
175
+ The spectral vector denoising algorithm is based on a Gaussian weighted
176
+ average calculation, with weights obtained in n-dimensional Chebyshev or
177
+ Fourier space [4]_.
178
+
179
+ Parameters
180
+ ----------
181
+ signal : array_like
182
+ Hyperspectral data to be denoised.
183
+ A minimum of three samples are required along `axis`.
184
+ The samples must be uniformly spaced.
185
+ spectral_vector : array_like, optional
186
+ Spectral vector.
187
+ For example, phasor coordinates, PCA projected phasor coordinates,
188
+ or Chebyshev coefficients.
189
+ Must be of same shape as `signal` with `axis` removed and axis
190
+ containing spectral space appended.
191
+ If None (default), phasor coordinates are calculated at specified
192
+ `harmonic`.
193
+ axis : int, optional, default: -1
194
+ Axis over which `spectral_vector` is computed if not provided.
195
+ The default is the last axis (-1).
196
+ harmonic : int, sequence of int, or 'all', optional
197
+ Harmonics to include in calculating `spectral_vector`.
198
+ If `'all'`, include all harmonics for `signal` samples along `axis`.
199
+ Else, harmonics must be at least one and no larger than half the
200
+ number of `signal` samples along `axis`.
201
+ The default is the first harmonic (fundamental frequency).
202
+ A minimum of `harmonic * 2 + 1` samples are required along `axis`
203
+ to calculate correct phasor coordinates at `harmonic`.
204
+ sigma : float, default: 0.05
205
+ Width of Gaussian filter in spectral vector space.
206
+ Weighted averages are calculated using the spectra of signal items
207
+ within an spectral vector Euclidean distance of `3 * sigma` and
208
+ intensity above `vmin`.
209
+ vmin : float, optional
210
+ Signal intensity along `axis` below which not to include in denoising.
211
+ dtype : dtype_like, optional
212
+ Data type of output arrays. Either float32 or float64.
213
+ The default is float64 unless the `signal` is float32.
214
+ num_threads : int, optional
215
+ Number of OpenMP threads to use for parallelization.
216
+ By default, multi-threading is disabled.
217
+ If zero, up to half of logical CPUs are used.
218
+ OpenMP may not be available on all platforms.
219
+
220
+ Returns
221
+ -------
222
+ ndarray
223
+ Denoised signal of `dtype`.
224
+ Spectra with integrated intensity below `vmin` are unchanged.
225
+
226
+ References
227
+ ----------
228
+
229
+ .. [4] Harman RC, Lang RT, Kercher EM, Leven P, and Spring BQ.
230
+ `Denoising multiplexed microscopy images in n-dimensional spectral space
231
+ <https://doi.org/10.1364/BOE.463979>`_.
232
+ *Biomed Opt Express*, 13(8): 4298-4309 (2022)
233
+
234
+ Examples
235
+ --------
236
+ Denoise a hyperspectral image with a Gaussian filter width of 0.1 in
237
+ spectral vector space using first and second harmonic:
238
+
239
+ >>> signal = numpy.random.randint(0, 255, (8, 16, 16))
240
+ >>> spectral_vector_denoise(signal, axis=0, sigma=0.1, harmonic=[1, 2])
241
+ array([[[...]]])
242
+
243
+ """
244
+ num_threads = number_threads(num_threads)
245
+
246
+ signal = numpy.asarray(signal)
247
+ if axis == -1 or axis == signal.ndim - 1:
248
+ axis = -1
249
+ else:
250
+ signal = numpy.moveaxis(signal, axis, -1)
251
+ shape = signal.shape
252
+ samples = shape[-1]
253
+
254
+ if harmonic is None:
255
+ harmonic = 1
256
+ harmonic, _ = parse_harmonic(harmonic, samples // 2)
257
+ num_harmonics = len(harmonic)
258
+
259
+ if vmin is None or vmin < 0.0:
260
+ vmin = 0.0
261
+
262
+ sincos = numpy.empty((num_harmonics, samples, 2))
263
+ for i, h in enumerate(harmonic):
264
+ phase = numpy.linspace(
265
+ 0,
266
+ h * math.pi * 2.0,
267
+ samples,
268
+ endpoint=False,
269
+ dtype=numpy.float64,
270
+ )
271
+ sincos[i, :, 0] = numpy.cos(phase)
272
+ sincos[i, :, 1] = numpy.sin(phase)
273
+
274
+ signal = numpy.ascontiguousarray(signal).reshape(-1, samples)
275
+ size = signal.shape[0]
276
+
277
+ if dtype is None:
278
+ if signal.dtype.char == 'f':
279
+ dtype = signal.dtype
280
+ else:
281
+ dtype = numpy.float64
282
+ dtype = numpy.dtype(dtype)
283
+ if dtype.char not in {'d', 'f'}:
284
+ raise ValueError('dtype is not floating point')
285
+
286
+ if spectral_vector is None:
287
+ spectral_vector = numpy.zeros((size, num_harmonics * 2), dtype=dtype)
288
+ _phasor_from_signal_vector(
289
+ spectral_vector, signal, sincos, num_threads
290
+ )
291
+ else:
292
+ spectral_vector = numpy.ascontiguousarray(spectral_vector, dtype=dtype)
293
+ if spectral_vector.shape[:-1] != shape[:-1]:
294
+ raise ValueError('signal and spectral_vector shape mismatch')
295
+ spectral_vector = spectral_vector.reshape(
296
+ -1, spectral_vector.shape[-1]
297
+ )
298
+
299
+ if dtype == signal.dtype:
300
+ denoised = signal.copy()
301
+ else:
302
+ denoised = numpy.zeros(signal.shape, dtype=dtype)
303
+ denoised[:] = signal
304
+ integrated = numpy.zeros(size, dtype=dtype)
305
+ _signal_denoise_vector(
306
+ denoised, integrated, signal, spectral_vector, sigma, vmin, num_threads
307
+ )
308
+
309
+ denoised = denoised.reshape(shape)
310
+ if axis != -1:
311
+ denoised = numpy.moveaxis(denoised, -1, axis)
312
+ return denoised
@@ -0,0 +1,137 @@
1
+ """Read and write time-resolved and hyperspectral image file formats.
2
+
3
+ The ``phasorpy.io`` module provides functions to:
4
+
5
+ - read time-resolved and hyperspectral signals, as well as metadata from
6
+ many file formats used in bio-imaging:
7
+
8
+ - :py:func:`signal_from_lif` - Leica LIF and XLEF
9
+ - :py:func:`signal_from_lsm` - Zeiss LSM
10
+ - :py:func:`signal_from_ptu` - PicoQuant PTU
11
+ - :py:func:`signal_from_sdt` - Becker & Hickl SDT
12
+ - :py:func:`signal_from_fbd` - FLIMbox FBD
13
+ - :py:func:`signal_from_flimlabs_json` - FLIM LABS JSON
14
+ - :py:func:`signal_from_imspector_tiff` - ImSpector FLIM TIFF
15
+ - :py:func:`signal_from_flif` - FlimFast FLIF
16
+ - :py:func:`signal_from_b64` - SimFCS B64
17
+ - :py:func:`signal_from_z64` - SimFCS Z64
18
+ - :py:func:`signal_from_bhz` - SimFCS BHZ
19
+ - :py:func:`signal_from_bh` - SimFCS B&H
20
+
21
+ - read phasor coordinates, lifetime images, and metadata from
22
+ specialized file formats:
23
+
24
+ - :py:func:`phasor_from_ometiff` - PhasorPy OME-TIFF
25
+ - :py:func:`phasor_from_ifli` - ISS IFLI
26
+ - :py:func:`phasor_from_lif` - Leica LIF and XLEF
27
+ - :py:func:`phasor_from_flimlabs_json` - FLIM LABS JSON
28
+ - :py:func:`phasor_from_simfcs_referenced` - SimFCS REF and R64
29
+ - :py:func:`lifetime_from_lif` - Leica LIF and XLEF
30
+
31
+ - write phasor coordinate images to OME-TIFF and SimFCS file formats:
32
+
33
+ - :py:func:`phasor_to_ometiff`
34
+ - :py:func:`phasor_to_simfcs_referenced`
35
+
36
+ Support for other file formats is being considered:
37
+
38
+ - OME-TIFF
39
+ - Zeiss CZI
40
+ - Nikon ND2
41
+ - Olympus OIB/OIF
42
+ - Olympus OIR
43
+
44
+ The functions are implemented as minimal wrappers around specialized
45
+ third-party file reader libraries, currently
46
+ `tifffile <https://github.com/cgohlke/tifffile>`_,
47
+ `ptufile <https://github.com/cgohlke/ptufile>`_,
48
+ `liffile <https://github.com/cgohlke/liffile>`_,
49
+ `sdtfile <https://github.com/cgohlke/sdtfile>`_, and
50
+ `lfdfiles <https://github.com/cgohlke/lfdfiles>`_.
51
+ For advanced or unsupported use cases, consider using these libraries directly.
52
+
53
+ The signal-reading functions typically have the following signature::
54
+
55
+ signal_from_ext(
56
+ filename: str | PathLike,
57
+ /,
58
+ **kwargs
59
+ ): -> xarray.DataArray
60
+
61
+ where ``ext`` indicates the file format and ``kwargs`` are optional arguments
62
+ passed to the underlying file reader library or used to select which data is
63
+ returned. The returned `xarray.DataArray
64
+ <https://docs.xarray.dev/en/stable/user-guide/data-structures.html>`_
65
+ contains an N-dimensional array with labeled coordinates, dimensions, and
66
+ attributes:
67
+
68
+ - ``data`` or ``values`` (*array_like*)
69
+
70
+ Numpy array or array-like holding the array's values.
71
+
72
+ - ``dims`` (*tuple of str*)
73
+
74
+ :ref:`Axes character codes <axes>` for each dimension in ``data``.
75
+ For example, ``('T', 'C', 'Y', 'X')`` defines the dimension order in a
76
+ 4-dimensional array of a time-series of multi-channel images.
77
+
78
+ - ``coords`` (*dict_like[str, array_like]*)
79
+
80
+ Coordinate arrays labelling each point in the data array.
81
+ The keys are :ref:`axes character codes <axes>`.
82
+ Values are 1-dimensional arrays of numbers or strings.
83
+ For example, ``coords['C']`` could be an array of emission wavelengths.
84
+
85
+ - ``attrs`` (*dict[str, Any]*)
86
+
87
+ Arbitrary metadata such as measurement or calibration parameters required to
88
+ interpret the data values.
89
+ For example, the laser repetition frequency of a time-resolved measurement.
90
+
91
+ .. _axes:
92
+
93
+ Axes character codes from the OME model and tifffile library are used as
94
+ ``dims`` items and ``coords`` keys:
95
+
96
+ - ``'X'`` : width (OME)
97
+ - ``'Y'`` : height (OME)
98
+ - ``'Z'`` : depth (OME)
99
+ - ``'S'`` : sample (color components or phasor coordinates)
100
+ - ``'I'`` : sequence (of images, frames, or planes)
101
+ - ``'T'`` : time (OME)
102
+ - ``'C'`` : channel (OME. Acquisition path or emission wavelength)
103
+ - ``'A'`` : angle (OME)
104
+ - ``'P'`` : phase (OME. In LSM, ``'P'`` maps to position)
105
+ - ``'R'`` : tile (OME. Region, position, or mosaic)
106
+ - ``'H'`` : lifetime histogram (OME)
107
+ - ``'E'`` : lambda (OME. Excitation wavelength)
108
+ - ``'F'`` : frequency (ISS)
109
+ - ``'Q'`` : other (OME. Harmonics in PhasorPy TIFF)
110
+ - ``'L'`` : exposure (FluoView)
111
+ - ``'V'`` : event (FluoView)
112
+ - ``'M'`` : mosaic (LSM 6)
113
+ - ``'J'`` : column (NDTiff)
114
+ - ``'K'`` : row (NDTiff)
115
+
116
+ """
117
+
118
+ from __future__ import annotations
119
+
120
+ __all__: list[str] = []
121
+
122
+ from .._utils import init_module
123
+ from ._flimlabs import *
124
+ from ._leica import *
125
+ from ._ometiff import *
126
+ from ._other import *
127
+ from ._simfcs import *
128
+
129
+ # The `init_module()` function dynamically populates the `__all__` list with
130
+ # all public symbols imported from submodules or defined in this module.
131
+ # Any name not starting with an underscore will be automatically exported
132
+ # when using "from phasorpy.io import *"
133
+
134
+ init_module(globals())
135
+ del init_module
136
+
137
+ # flake8: noqa: F401, F403