micro-reader 0.5.0__tar.gz → 0.5.2__tar.gz
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.
- {micro_reader-0.5.0 → micro_reader-0.5.2}/PKG-INFO +3 -3
- {micro_reader-0.5.0 → micro_reader-0.5.2}/README.md +1 -1
- {micro_reader-0.5.0 → micro_reader-0.5.2}/pyproject.toml +2 -2
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_axes.py +5 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_base.py +55 -10
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_outline.py +21 -1
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_registry.py +12 -6
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_spatial.py +3 -3
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_version.py +1 -1
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/_nd2_legacy.py +10 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/bdv.py +49 -27
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/companion.py +23 -11
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/czi.py +15 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/dv.py +2 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/ics.py +5 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/lif.py +10 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/mrc.py +2 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/nd2.py +91 -2
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/omp2info.py +5 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/tiff.py +48 -12
- {micro_reader-0.5.0 → micro_reader-0.5.2}/.gitignore +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/LICENSE +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/__init__.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_cfb.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_codecs.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_engine.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_errors.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_eubi_guard.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_fileset.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_groups.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_index.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_io.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_jpeg_restarts.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_lambda.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_many.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_memory.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_metadata.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_mosaic.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_naming.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_parts.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_plate.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_pool.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_stack.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/_stream.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/__init__.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/_czi_metadata.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/_ets.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/_hdf5.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/_lif_metadata.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/_nd2_metadata.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/_nd2_run.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/_nd2_structure.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/_tiff_metadata.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/_tiff_variants.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/_vsi_tree.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/cellomics.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/columbus.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/cv7000.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/flex.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/harmony.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/hdf5.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/ilastik.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/ims.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/incell.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/jdce.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/klb.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/luxendo.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/metamorph.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/metaxpress.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/micromanager.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/ndpis.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/oif.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/oir.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/raster.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/scanr.py +0 -0
- {micro_reader-0.5.0 → micro_reader-0.5.2}/src/micro_reader/backends/vsi.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: micro-reader
|
|
3
|
-
Version: 0.5.
|
|
3
|
+
Version: 0.5.2
|
|
4
4
|
Summary: Low-level, memory-bounded pixel reading for microscopy formats: read exactly the rectangle you ask for.
|
|
5
5
|
Project-URL: Homepage, https://github.com/bugraoezdemir/micro-reader
|
|
6
6
|
Project-URL: Source, https://github.com/bugraoezdemir/micro-reader
|
|
@@ -18,7 +18,7 @@ Classifier: Programming Language :: Python :: 3.13
|
|
|
18
18
|
Classifier: Programming Language :: Python :: 3.14
|
|
19
19
|
Classifier: Topic :: Scientific/Engineering :: Image Processing
|
|
20
20
|
Requires-Python: >=3.11
|
|
21
|
-
Requires-Dist: micro-reader-codecs<0.1,>=0.0.
|
|
21
|
+
Requires-Dist: micro-reader-codecs<0.1,>=0.0.6
|
|
22
22
|
Requires-Dist: micro-reader-core<0.1,>=0.0.1
|
|
23
23
|
Requires-Dist: numpy>=1.24
|
|
24
24
|
Requires-Dist: tifffile>=2025.5.21
|
|
@@ -167,7 +167,7 @@ len(image.resolutions)
|
|
|
167
167
|
overview = image.resolutions[-1].read()
|
|
168
168
|
```
|
|
169
169
|
|
|
170
|
-
With `tiles="mosaic"`, tiles are placed at their recorded positions on a common canvas. They are not registered or blended. By default, tiles remain separate images with their own stage positions, which is useful when you want to perform registration or stitching yourself.
|
|
170
|
+
With `tiles="mosaic"`, tiles are placed at their recorded positions on a common canvas. They are not registered or blended. By default, tiles remain separate images with their own stage positions, which is useful when you want to perform registration or stitching yourself. Separate tiles are the default because they are what the file stores, for every format. Slide scans usually want `tiles="mosaic"`, and `print(f)` points to it on every series whose tiles it can place.
|
|
171
171
|
|
|
172
172
|
### Example: a high-content screening plate
|
|
173
173
|
|
|
@@ -112,7 +112,7 @@ len(image.resolutions)
|
|
|
112
112
|
overview = image.resolutions[-1].read()
|
|
113
113
|
```
|
|
114
114
|
|
|
115
|
-
With `tiles="mosaic"`, tiles are placed at their recorded positions on a common canvas. They are not registered or blended. By default, tiles remain separate images with their own stage positions, which is useful when you want to perform registration or stitching yourself.
|
|
115
|
+
With `tiles="mosaic"`, tiles are placed at their recorded positions on a common canvas. They are not registered or blended. By default, tiles remain separate images with their own stage positions, which is useful when you want to perform registration or stitching yourself. Separate tiles are the default because they are what the file stores, for every format. Slide scans usually want `tiles="mosaic"`, and `print(f)` points to it on every series whose tiles it can place.
|
|
116
116
|
|
|
117
117
|
### Example: a high-content screening plate
|
|
118
118
|
|
|
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
|
|
|
6
6
|
|
|
7
7
|
[project]
|
|
8
8
|
name = "micro-reader"
|
|
9
|
-
version = "0.5.
|
|
9
|
+
version = "0.5.2"
|
|
10
10
|
description = "Low-level, memory-bounded pixel reading for microscopy formats: read exactly the rectangle you ask for."
|
|
11
11
|
readme = "README.md"
|
|
12
12
|
requires-python = ">=3.11"
|
|
@@ -29,7 +29,7 @@ classifiers = [
|
|
|
29
29
|
# TIFF covers most microscopy images, so it is not an extra (Bugra,
|
|
30
30
|
# 2026-10-01) until micro-reader parses TIFF itself (post-0.0.1). The floor
|
|
31
31
|
# matches eubi-bridge's (tifffile>=2025.5.21), so both install together.
|
|
32
|
-
dependencies = ["numpy>=1.24", "micro-reader-codecs>=0.0.
|
|
32
|
+
dependencies = ["numpy>=1.24", "micro-reader-codecs>=0.0.6,<0.1", "micro-reader-core>=0.0.1,<0.1",
|
|
33
33
|
"tifffile>=2025.5.21"]
|
|
34
34
|
|
|
35
35
|
[project.urls]
|
|
@@ -295,6 +295,11 @@ class AxesImage(Image):
|
|
|
295
295
|
return AxesImage(self.source, self.axes, samples=self._samples_policy,
|
|
296
296
|
squeeze=axes or True, _select=dict(self._select))
|
|
297
297
|
|
|
298
|
+
@property
|
|
299
|
+
def exact_reads(self) -> bool:
|
|
300
|
+
"""The native image's: presenting other axes reads the same bytes."""
|
|
301
|
+
return self.source.exact_reads
|
|
302
|
+
|
|
298
303
|
def close(self) -> None:
|
|
299
304
|
self.source.close()
|
|
300
305
|
|
|
@@ -24,6 +24,11 @@ _RENAMED = "the image index 'scene' is now called 'series' (micro-reader 0.1.0);
|
|
|
24
24
|
#: 0.4.0 the whole span was read and then thinned (``image[::16]`` of a 6.8 GB MRC held
|
|
25
25
|
#: 6.8 GB). Smaller stepped reads keep one read of the span (fewer calls).
|
|
26
26
|
STEPPED_READ_BYTES = 64 << 20
|
|
27
|
+
#: the smallest step at which a stepped read takes only the selected positions, one at a
|
|
28
|
+
#: time, instead of runs of them (``Image._positions_alone``); measured 2026-11-20: from
|
|
29
|
+
#: step 4 the positions alone win on MRC, LIF, ICS and Micro-Manager TIFF (MRC [::64] of
|
|
30
|
+
#: 6.9 GB: 4.7 s -> 0.15 s), at 2 and 3 they lose on MRC and LIF
|
|
31
|
+
SKIP_READ_MIN_STEP = 4
|
|
27
32
|
|
|
28
33
|
|
|
29
34
|
class ImageIndex(dict):
|
|
@@ -152,6 +157,11 @@ class Image:
|
|
|
152
157
|
Results are always native-endian and never views into file-backed memory.
|
|
153
158
|
"""
|
|
154
159
|
|
|
160
|
+
#: True: any rectangle is read at exactly its own cost (uncompressed pixels), so a
|
|
161
|
+
#: stepped read takes only the selected positions (``_positions_alone``). False
|
|
162
|
+
#: (the default): not known, e.g. a compressed format that declares no ``read_unit``.
|
|
163
|
+
exact_reads = False
|
|
164
|
+
|
|
155
165
|
def __init__(self, position: int, axes: str, shape: Sequence[int], dtype,
|
|
156
166
|
name: Optional[str] = None,
|
|
157
167
|
read_unit: Optional[Sequence[int]] = None,
|
|
@@ -174,7 +184,9 @@ class Image:
|
|
|
174
184
|
self._whole: Optional["Image"] = None
|
|
175
185
|
self._metadata = None # backends set a _metadata.Metadata
|
|
176
186
|
#: None: any rectangle is read exactly. Otherwise the smallest block
|
|
177
|
-
#: the backend reads at once (e.g. a compressed tile or strip).
|
|
187
|
+
#: the backend reads at once (e.g. a compressed tile or strip). Not every
|
|
188
|
+
#: backend that leaves it None declares its tiles (CZI, VSI): ``exact_reads``
|
|
189
|
+
#: says when None is known to be exact.
|
|
178
190
|
self.read_unit = None if read_unit is None else tuple(int(n) for n in read_unit)
|
|
179
191
|
self.stats = ReadStats()
|
|
180
192
|
|
|
@@ -234,7 +246,7 @@ class Image:
|
|
|
234
246
|
warnings.warn("Image.is_pyramid is deprecated: it means level 0, also for an image "
|
|
235
247
|
"without lower levels. Use image.level == 0; image.is_pyramidal says "
|
|
236
248
|
"whether the file stores lower levels", DeprecationWarning, stacklevel=2)
|
|
237
|
-
return self.
|
|
249
|
+
return self.resolutions[0] is self # not through .pyramid: one warning
|
|
238
250
|
|
|
239
251
|
@property
|
|
240
252
|
def level(self) -> int:
|
|
@@ -247,8 +259,14 @@ class Image:
|
|
|
247
259
|
|
|
248
260
|
@property
|
|
249
261
|
def pyramid(self) -> "Image":
|
|
250
|
-
"""
|
|
251
|
-
|
|
262
|
+
"""Deprecated since 0.5.1: the name reads as "the whole pyramid", but it is one
|
|
263
|
+
image, the level-0 image of this image's pyramid. ``image.resolutions[0]`` says
|
|
264
|
+
what it does (``image.level == 0`` for a level-0 check). To go, with
|
|
265
|
+
``is_pyramid``, in a later minor release, once no supported eubi-bridge or
|
|
266
|
+
ome_zarr_pyramid release uses it (neither does)."""
|
|
267
|
+
warnings.warn("Image.pyramid is deprecated: it is the level-0 image, not the whole "
|
|
268
|
+
"pyramid. Use image.resolutions[0]; image.level == 0 checks for "
|
|
269
|
+
"level 0", DeprecationWarning, stacklevel=2)
|
|
252
270
|
return self.resolutions[0]
|
|
253
271
|
|
|
254
272
|
# A ragged image: its channels do not share one sampling (e.g. one channel
|
|
@@ -315,15 +333,34 @@ class Image:
|
|
|
315
333
|
out = out.squeeze(axis=squeeze)
|
|
316
334
|
return out
|
|
317
335
|
|
|
336
|
+
def _positions_alone(self, axis: int, step: int) -> bool:
|
|
337
|
+
"""Whether a stepped read along *axis* reads only its selected positions, one at a
|
|
338
|
+
time, rather than runs of positions (``_read_stepped``). Yes when the step is at
|
|
339
|
+
least twice the backend's read unit along *axis* (1 for an image that reads
|
|
340
|
+
exactly, ``exact_reads``) and at least SKIP_READ_MIN_STEP: every selected position
|
|
341
|
+
then lies in a unit of its own and at least every other unit is skipped, which the
|
|
342
|
+
runs read too ([::64] of a 6.9 GB MRC read the whole file). Measured 2026-11-20:
|
|
343
|
+
a step of one unit skips nothing and loses to the runs (an NDPI's 8-row JPEG unit
|
|
344
|
+
at [::8]: 3.3 s vs 2.2 s), and so do steps 2 and 3 of exact images (MRC, LIF: one
|
|
345
|
+
call per position costs more than the positions skipped). An image that declares
|
|
346
|
+
no unit and does not say it reads exactly (a compressed format whose tiles are not
|
|
347
|
+
declared) keeps the runs."""
|
|
348
|
+
if step < SKIP_READ_MIN_STEP:
|
|
349
|
+
return False
|
|
350
|
+
if self.read_unit is not None:
|
|
351
|
+
return step >= 2 * self.read_unit[axis]
|
|
352
|
+
return bool(self.exact_reads)
|
|
353
|
+
|
|
318
354
|
def _read_stepped(self, out: np.ndarray, spans: list, steps: list, axis: int) -> None:
|
|
319
355
|
"""A stepped read into *out*, a piece of at most STEPPED_READ_BYTES at a time: the
|
|
320
356
|
span is read whole once it fits; else, along *axis*, runs of positions that fit
|
|
321
357
|
(each starting at a selected position, read and thinned: a compressed tile or strip
|
|
322
|
-
is decoded once, as for the whole span), or
|
|
323
|
-
fits (``[::16]`` of large planes)
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
would cost more). Peak: *out*
|
|
358
|
+
is decoded once, as for the whole span), or only the selected positions, one at a
|
|
359
|
+
time, when one step alone spans more than fits (``[::16]`` of large planes) or no
|
|
360
|
+
unit holds two of them (``_positions_alone``); the next axis splits what is still
|
|
361
|
+
too large. Each piece is read with the backend's own ``_read_block``. Within a row
|
|
362
|
+
the columns are read and thinned (a read per pixel would cost more). Peak: *out*
|
|
363
|
+
and one piece."""
|
|
327
364
|
item = self.dtype.itemsize
|
|
328
365
|
size = int(np.prod([b - a for a, b in spans]))
|
|
329
366
|
if size * item <= STEPPED_READ_BYTES or axis == len(spans) - 1:
|
|
@@ -334,7 +371,7 @@ class Image:
|
|
|
334
371
|
lead = (slice(None),) * axis
|
|
335
372
|
(a, b), step = spans[axis], steps[axis]
|
|
336
373
|
per = max(1, STEPPED_READ_BYTES // (size // (b - a) * item)) # positions that fit
|
|
337
|
-
if per >= step:
|
|
374
|
+
if per >= step and not self._positions_alone(axis, step):
|
|
338
375
|
run = per - per % step # a whole number of steps
|
|
339
376
|
for j in range(a, b, run):
|
|
340
377
|
k = min(b, j + run)
|
|
@@ -736,6 +773,14 @@ class File:
|
|
|
736
773
|
from ._outline import outline_lines
|
|
737
774
|
return "\n".join([self._header()] + [" " + line for line in outline_lines(self)])
|
|
738
775
|
|
|
776
|
+
def _mosaic_levels(self, series: int, images: list):
|
|
777
|
+
"""For the summary (``_outline``, Workplan MR28): whether ``tiles="mosaic"``
|
|
778
|
+
would give the tile *images* of series *series* as one image. None when it
|
|
779
|
+
would not, or when that is not known from what opening read; else the number
|
|
780
|
+
of resolution levels that image would have, 0 meaning as many as one tile.
|
|
781
|
+
Backends that place tiles on one canvas override it; it never reads the file."""
|
|
782
|
+
return None
|
|
783
|
+
|
|
739
784
|
def _header(self) -> str:
|
|
740
785
|
plates = f" plates={len(self.plates)}" if self.plates else ""
|
|
741
786
|
return (f"<micro_reader.File {self.path!r} backend={self.backend!r} "
|
|
@@ -69,5 +69,25 @@ def outline_lines(f) -> list:
|
|
|
69
69
|
for image in rest:
|
|
70
70
|
by_series.setdefault(image.index.get("series", 0), []).append(image)
|
|
71
71
|
for series, members in sorted(by_series.items()):
|
|
72
|
-
|
|
72
|
+
line = f"series {series}: {_leaf(members)}"
|
|
73
|
+
if len({image.index.get("tile") for image in members}) > 1:
|
|
74
|
+
hint = _mosaic_hint(f, series, members)
|
|
75
|
+
if hint:
|
|
76
|
+
line += f" {hint}"
|
|
77
|
+
lines.append(line)
|
|
73
78
|
return lines
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _mosaic_hint(f, series: int, members: list) -> str:
|
|
82
|
+
"""Where a series is read as separate tiles (the default) and ``tiles="mosaic"``
|
|
83
|
+
would place them on one canvas, say so (Workplan MR28): a slide scan otherwise
|
|
84
|
+
shows thousands of tile images, and its stored pyramid is reached only through the
|
|
85
|
+
mosaic. Only where the mosaic would succeed (``File._mosaic_levels``)."""
|
|
86
|
+
try:
|
|
87
|
+
levels = f._mosaic_levels(series, members)
|
|
88
|
+
except Exception: # a summary never fails
|
|
89
|
+
return ""
|
|
90
|
+
if levels is None:
|
|
91
|
+
return ""
|
|
92
|
+
stored = f", with its {levels} stored levels" if levels > len(members[0].resolutions) else ""
|
|
93
|
+
return f'(tiles="mosaic": its tiles as one image{stored})'
|
|
@@ -72,8 +72,10 @@ def open(path, backend: Optional[str] = None, *, tiles: str = "separate", # noq
|
|
|
72
72
|
|
|
73
73
|
*rename* makes an index an array axis, for files that do not say what a
|
|
74
74
|
dimension is: ``rename={"sequence": "z"}`` reads a plain multi-page TIFF
|
|
75
|
-
as one z-stack. The target is ``t``, ``c`` or ``z
|
|
76
|
-
|
|
75
|
+
as one z-stack. The target is ``t``, ``c`` or ``z``, or one of them per
|
|
76
|
+
dimension of that index, outer first (``{"sequence": "tz"}`` for a TIFF whose
|
|
77
|
+
two dimensions are unnamed: one letter for two is refused, never guessed); a
|
|
78
|
+
format that cannot do it for that index raises.
|
|
77
79
|
|
|
78
80
|
*plates* (docs/HCS.md): ``True``, the default, reads a file that is a plate
|
|
79
81
|
as one: ``File.plates`` describes it, and its images are indexed by well and
|
|
@@ -201,10 +203,14 @@ def _check_rename(rename: Optional[dict]) -> dict:
|
|
|
201
203
|
if name not in SAMPLED_INDICES:
|
|
202
204
|
raise ValueError(f"rename: {name!r} is not an index that can become an axis "
|
|
203
205
|
f"(those are {SAMPLED_INDICES})")
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
206
|
+
# one letter per axis of the index: 'tz' for a file with two unnamed axes
|
|
207
|
+
if not axis or any(letter not in "tcz" for letter in axis):
|
|
208
|
+
raise ValueError(f"rename {name!r}: {axis!r} is not 't', 'c' or 'z' (or one "
|
|
209
|
+
"of them per axis of the index, such as 'tz')")
|
|
210
|
+
letters = "".join(rename.values())
|
|
211
|
+
if len(set(letters)) != len(letters):
|
|
212
|
+
raise ValueError(f"rename {rename}: two indices onto one axis (each axis is "
|
|
213
|
+
"given once)")
|
|
208
214
|
return rename
|
|
209
215
|
|
|
210
216
|
|
|
@@ -233,12 +233,12 @@ def file_stem(path) -> str:
|
|
|
233
233
|
"""A file's name without its extension, the root name of ``File.collection``
|
|
234
234
|
(3.17; the rule ozp's ``tree_from_file`` uses, decided 2026-10-21, M1-2):
|
|
235
235
|
``xyz.czi`` -> ``xyz``, ``cells.ome.tif`` / ``cells.ome.zarr`` -> ``cells``,
|
|
236
|
-
``Index.idx.xml`` -> ``Index.idx
|
|
237
|
-
``.zarr``."""
|
|
236
|
+
``Index.idx.xml`` -> ``Index.idx``, an OME companion ``set.companion.ome`` ->
|
|
237
|
+
``set``; a folder keeps its whole name, except ``.zarr``."""
|
|
238
238
|
import os
|
|
239
239
|
path = str(path).rstrip("/\\")
|
|
240
240
|
base = os.path.basename(path)
|
|
241
|
-
for pattern in (r"\.ome\.[A-Za-z0-9]+$", r"\.zarr$"):
|
|
241
|
+
for pattern in (r"\.companion\.ome$", r"\.ome\.[A-Za-z0-9]+$", r"\.zarr$"):
|
|
242
242
|
stem = re.sub(pattern, "", base, flags=re.IGNORECASE)
|
|
243
243
|
if stem != base:
|
|
244
244
|
return stem or base
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"""micro-reader's version, in one place (the package, the import guard)."""
|
|
2
|
-
__version__ = "0.5.
|
|
2
|
+
__version__ = "0.5.2"
|
|
@@ -29,6 +29,7 @@ import os
|
|
|
29
29
|
import re
|
|
30
30
|
import struct
|
|
31
31
|
import threading
|
|
32
|
+
import warnings
|
|
32
33
|
import xml.etree.ElementTree as ET
|
|
33
34
|
from collections import defaultdict
|
|
34
35
|
from functools import partial
|
|
@@ -191,6 +192,12 @@ class LegacyNd2Parser:
|
|
|
191
192
|
self.per_channel = components // self.channels
|
|
192
193
|
# RGB channels keep their samples (s); otherwise every component is a channel
|
|
193
194
|
self.samples = 3 if self.per_channel == 3 else 1
|
|
195
|
+
if self.samples > 1:
|
|
196
|
+
# bare JPEG 2000 codestreams (no colour box) and no camera block: nothing in
|
|
197
|
+
# the file says which sample is red (modern ND2 declares it, backends/nd2.py)
|
|
198
|
+
warnings.warn(f"{self.path!r}: the file does not state the order of its "
|
|
199
|
+
f"{self.samples} colour samples; they are read as stored and "
|
|
200
|
+
"named R, G, B", stacklevel=5)
|
|
194
201
|
self.c = self.channels if self.samples == 3 else components
|
|
195
202
|
self.loops = self._loops()
|
|
196
203
|
self.stored_frames = len(self.boxes.get(b"LUNK", [])) // max(1, self.channels)
|
|
@@ -285,6 +292,9 @@ class _LegacyNd2Image(Image):
|
|
|
285
292
|
read_unit=(1, 1, 1, nd2.height, nd2.width)
|
|
286
293
|
+ ((nd2.samples,) if self._rgb else ()))
|
|
287
294
|
|
|
295
|
+
#: legacy files never state the order of RGB samples (see LegacyNd2Parser)
|
|
296
|
+
sample_order = None
|
|
297
|
+
|
|
288
298
|
def _read_block(self, block):
|
|
289
299
|
if self._closed:
|
|
290
300
|
raise ValueError("this ND2 image has been closed: its file was closed "
|
|
@@ -493,6 +493,42 @@ class _PlacedViews:
|
|
|
493
493
|
return self._placement
|
|
494
494
|
|
|
495
495
|
|
|
496
|
+
def _groups_of_tiles(pyramids: list) -> dict:
|
|
497
|
+
"""Tile pyramids grouped by their index without the tile (one mosaic each)."""
|
|
498
|
+
groups: dict = {}
|
|
499
|
+
for pyramid in pyramids:
|
|
500
|
+
key = tuple((k, v) for k, v in pyramid[0].index.items() if k != "tile")
|
|
501
|
+
groups.setdefault(key, []).append(pyramid)
|
|
502
|
+
return groups
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def _mosaic_refusal(members: list, what: str) -> Optional[str]:
|
|
506
|
+
"""Why the tile pyramids *members* cannot be one mosaic (``_mosaics``), or None.
|
|
507
|
+
From the XML alone: the summary's hint asks it too (File._mosaic_levels, MR28)."""
|
|
508
|
+
placed = [pyramid[0]._views.placement().position for pyramid in members]
|
|
509
|
+
if any(not {"x", "y"} <= set(position) for position in placed):
|
|
510
|
+
return (f"{what}: a tile has no position on the acquisition grid (its views turn, "
|
|
511
|
+
f"shear or mirror, or disagree): read the tiles with tiles='separate'")
|
|
512
|
+
for axis in sorted(set().union(*placed) - {"x", "y"}):
|
|
513
|
+
values = {round(position[axis].to(placed[0][axis].unit).value, 9)
|
|
514
|
+
for position in placed if axis in position}
|
|
515
|
+
if len(values) > 1 or any(axis not in position for position in placed):
|
|
516
|
+
return (f"{what}: the tiles lie apart along {axis} ({sorted(values)}); a mosaic "
|
|
517
|
+
f"places tiles in y and x only: read them with tiles='separate'")
|
|
518
|
+
sizes = [pyramid[0].metadata.pixel_sizes for pyramid in members]
|
|
519
|
+
unit = placed[0]["x"].unit
|
|
520
|
+
for axis in "yx":
|
|
521
|
+
if any(axis not in size for size in sizes):
|
|
522
|
+
return f"{what}: a tile has no pixel size along {axis}"
|
|
523
|
+
values = {round(size[axis].to(unit).value, 12) for size in sizes}
|
|
524
|
+
if len(values) != 1:
|
|
525
|
+
return f"{what}: the tiles' pixel sizes along {axis} differ ({sorted(values)})"
|
|
526
|
+
if len({len(pyramid) for pyramid in members}) != 1:
|
|
527
|
+
return (f"{what}: the tiles store different numbers of levels "
|
|
528
|
+
f"{sorted({len(p) for p in members})}")
|
|
529
|
+
return None
|
|
530
|
+
|
|
531
|
+
|
|
496
532
|
def _mosaics(pyramids: list, where: str) -> list:
|
|
497
533
|
"""Each angle / illumination's tile pyramids as one pyramid of mosaics: every
|
|
498
534
|
level's tiles at their nominal positions (``_place``), in pixels of that level
|
|
@@ -500,41 +536,19 @@ def _mosaics(pyramids: list, where: str) -> list:
|
|
|
500
536
|
tile order, the later on top. Refused (UnsupportedFormatError, naming why) when a
|
|
501
537
|
tile has no position along y and x, the tiles lie apart along another axis (the
|
|
502
538
|
canvas is a y / x plane), or their pixel sizes or numbers of levels differ."""
|
|
503
|
-
groups
|
|
504
|
-
for pyramid in pyramids:
|
|
505
|
-
key = tuple((k, v) for k, v in pyramid[0].index.items() if k != "tile")
|
|
506
|
-
groups.setdefault(key, []).append(pyramid)
|
|
539
|
+
groups = _groups_of_tiles(pyramids)
|
|
507
540
|
out = []
|
|
508
541
|
for key, members in groups.items():
|
|
509
542
|
members.sort(key=lambda pyramid: pyramid[0].index["tile"])
|
|
510
543
|
label = " ".join(f"{k} {v}" for k, v in key if k != "series")
|
|
511
544
|
what = f"{where}: tiles='mosaic'{f' ({label})' if label else ''}"
|
|
545
|
+
refused = _mosaic_refusal(members, what)
|
|
546
|
+
if refused is not None:
|
|
547
|
+
raise UnsupportedFormatError(refused)
|
|
512
548
|
placed = [pyramid[0]._views.placement().position for pyramid in members]
|
|
513
|
-
if any(not {"x", "y"} <= set(position) for position in placed):
|
|
514
|
-
raise UnsupportedFormatError(
|
|
515
|
-
f"{what}: a tile has no position on the acquisition grid (its views turn, "
|
|
516
|
-
f"shear or mirror, or disagree): read the tiles with tiles='separate'")
|
|
517
|
-
for axis in sorted(set().union(*placed) - {"x", "y"}):
|
|
518
|
-
values = {round(position[axis].to(placed[0][axis].unit).value, 9)
|
|
519
|
-
for position in placed if axis in position}
|
|
520
|
-
if len(values) > 1 or any(axis not in position for position in placed):
|
|
521
|
-
raise UnsupportedFormatError(
|
|
522
|
-
f"{what}: the tiles lie apart along {axis} ({sorted(values)}); a mosaic "
|
|
523
|
-
f"places tiles in y and x only: read them with tiles='separate'")
|
|
524
549
|
sizes = [pyramid[0].metadata.pixel_sizes for pyramid in members]
|
|
525
550
|
unit = placed[0]["x"].unit
|
|
526
|
-
steps = []
|
|
527
|
-
for axis in "yx":
|
|
528
|
-
if any(axis not in size for size in sizes):
|
|
529
|
-
raise UnsupportedFormatError(f"{what}: a tile has no pixel size along {axis}")
|
|
530
|
-
values = {round(size[axis].to(unit).value, 12) for size in sizes}
|
|
531
|
-
if len(values) != 1:
|
|
532
|
-
raise UnsupportedFormatError(f"{what}: the tiles' pixel sizes along {axis} "
|
|
533
|
-
f"differ ({sorted(values)})")
|
|
534
|
-
steps.append(values.pop())
|
|
535
|
-
if len({len(pyramid) for pyramid in members}) != 1:
|
|
536
|
-
raise UnsupportedFormatError(f"{what}: the tiles store different numbers of "
|
|
537
|
-
f"levels {sorted({len(p) for p in members})}")
|
|
551
|
+
steps = [{round(size[axis].to(unit).value, 12) for size in sizes}.pop() for axis in "yx"]
|
|
538
552
|
y0 = min(position["y"].to(unit).value for position in placed)
|
|
539
553
|
x0 = min(position["x"].to(unit).value for position in placed)
|
|
540
554
|
offsets = [((position["y"].to(unit).value - y0) / steps[0],
|
|
@@ -968,6 +982,14 @@ class _BdvFile(File):
|
|
|
968
982
|
for image in images:
|
|
969
983
|
self._views.setdefault(image_key(image), image._views)
|
|
970
984
|
|
|
985
|
+
def _mosaic_levels(self, series: int, images: list):
|
|
986
|
+
# the same checks as tiles="mosaic" (_mosaic_refusal), on the native images
|
|
987
|
+
pyramids = [list(getattr(image, "source", image).resolutions) for image in images]
|
|
988
|
+
for members in _groups_of_tiles(pyramids).values():
|
|
989
|
+
if len(members) > 1 and _mosaic_refusal(members, "") is not None:
|
|
990
|
+
return None
|
|
991
|
+
return 0
|
|
992
|
+
|
|
971
993
|
def _declare_coordinate_systems(self):
|
|
972
994
|
# BigDataViewer's global space (plan 4.8), when an image is placed in
|
|
973
995
|
# it or has an edge into it, then its registered twin (3.7, 9.16);
|
|
@@ -178,8 +178,13 @@ class Core:
|
|
|
178
178
|
"""A companion file, parsed: its images (``series``), the UUID it lists
|
|
179
179
|
for each member and the IFDs it uses of it, the path notes."""
|
|
180
180
|
|
|
181
|
-
def __init__(self, path: str):
|
|
181
|
+
def __init__(self, path: str, own_planes: bool = False):
|
|
182
182
|
self.path = path
|
|
183
|
+
#: an OME-TIFF holding its own OME-XML: a TiffData that names no file refers to
|
|
184
|
+
#: this file, as the OME-TIFF specification has it (tifffile writes them so;
|
|
185
|
+
#: Workplan MR33). Off for companion files, which hold no pixels, and for every
|
|
186
|
+
#: route but plates=True on such a TIFF (backends/tiff.py _ome_plate)
|
|
187
|
+
self.own_planes = own_planes
|
|
183
188
|
try:
|
|
184
189
|
self.root = _ome_root(path)
|
|
185
190
|
except ET.ParseError as exc:
|
|
@@ -246,11 +251,17 @@ class Core:
|
|
|
246
251
|
def _tiffdata(self, series: _Series, data, where: str) -> None:
|
|
247
252
|
uuid = _children(data, "UUID")
|
|
248
253
|
name = uuid[0].get("FileName") if uuid else None
|
|
249
|
-
if not name:
|
|
254
|
+
if not name and self.own_planes:
|
|
255
|
+
# this file's own planes: its path, and the UUID the XML gives this file
|
|
256
|
+
name = os.path.basename(self.path)
|
|
257
|
+
listed = ((uuid[0].text or "").strip() if uuid else "") or self.uuid
|
|
258
|
+
member = os.path.normpath(os.path.abspath(self.path))
|
|
259
|
+
elif not name:
|
|
250
260
|
raise CorruptFileError(f"{where}: a TiffData names no file (a companion holds no "
|
|
251
261
|
"pixels of its own)")
|
|
252
|
-
|
|
253
|
-
|
|
262
|
+
else:
|
|
263
|
+
listed = (uuid[0].text or "").strip() or None
|
|
264
|
+
member = self._resolve(name)
|
|
254
265
|
try:
|
|
255
266
|
first = series.flat(int(data.get("FirstT", 0)), int(data.get("FirstC", 0)),
|
|
256
267
|
int(data.get("FirstZ", 0)))
|
|
@@ -488,22 +499,22 @@ _cores: "OrderedDict[tuple, Core]" = OrderedDict()
|
|
|
488
499
|
_cores_lock = threading.Lock()
|
|
489
500
|
|
|
490
501
|
|
|
491
|
-
def load(path: str) -> Core:
|
|
502
|
+
def load(path: str, own_planes: bool = False) -> Core:
|
|
492
503
|
"""The parsed companion at *path*, parsed once per process while it does not
|
|
493
504
|
change (by path, modification time and size); the CORE_CACHE most recently
|
|
494
|
-
used are kept."""
|
|
505
|
+
used are kept. *own_planes*: see ``Core``."""
|
|
495
506
|
path = os.path.abspath(path)
|
|
496
507
|
try:
|
|
497
508
|
stat = os.stat(path)
|
|
498
509
|
except OSError as exc:
|
|
499
510
|
raise CorruptFileError(f"{path!r}: {exc}") from None
|
|
500
|
-
key = (os.path.normcase(path), stat.st_mtime_ns, stat.st_size)
|
|
511
|
+
key = (os.path.normcase(path), stat.st_mtime_ns, stat.st_size, own_planes)
|
|
501
512
|
with _cores_lock:
|
|
502
513
|
core = _cores.get(key)
|
|
503
514
|
if core is not None:
|
|
504
515
|
_cores.move_to_end(key)
|
|
505
516
|
return core
|
|
506
|
-
core = Core(path)
|
|
517
|
+
core = Core(path, own_planes)
|
|
507
518
|
with _cores_lock:
|
|
508
519
|
_cores[key] = core
|
|
509
520
|
while len(_cores) > CORE_CACHE:
|
|
@@ -645,11 +656,12 @@ class _CompanionFile(File):
|
|
|
645
656
|
return (CoordinateSystem(STAGE),) # every Plane position (plan 4.6)
|
|
646
657
|
|
|
647
658
|
def __init__(self, path: str, plates: bool = False, *, companion: str = None,
|
|
648
|
-
plan: list = None):
|
|
659
|
+
plan: list = None, own_planes: bool = False):
|
|
649
660
|
"""*path* (``File.path``) reads the companion file *companion* (default:
|
|
650
661
|
*path*); *plan*: the plates as ``Core.plates`` gives them, from a backend
|
|
651
|
-
that knows them from elsewhere (ScanR: backends/scanr.py)
|
|
652
|
-
|
|
662
|
+
that knows them from elsewhere (ScanR: backends/scanr.py); *own_planes*: an
|
|
663
|
+
OME-TIFF whose TiffData without a file name are its own planes (``Core``)."""
|
|
664
|
+
core = load(companion or path, own_planes)
|
|
653
665
|
if core.moved:
|
|
654
666
|
written, used = core.moved[0]
|
|
655
667
|
warnings.warn(CompanionWarning(
|
|
@@ -1149,6 +1149,17 @@ class _CziFile(File):
|
|
|
1149
1149
|
per_series.setdefault(e.series, set()).add(e.mosaic)
|
|
1150
1150
|
#: some series has several mosaic tiles
|
|
1151
1151
|
self._tiled = any(len(m) > 1 for m in per_series.values())
|
|
1152
|
+
#: read as separate tiles: series of several tiles -> the resolution levels its
|
|
1153
|
+
#: mosaic has (1 + the stored zooms of its pyramid subblocks; not trusted in a
|
|
1154
|
+
#: repaired directory), for the summary's hint (File._mosaic_levels, MR28)
|
|
1155
|
+
self._mosaic_series = {}
|
|
1156
|
+
if self._tiled and tiles == "separate":
|
|
1157
|
+
for s, marks in per_series.items():
|
|
1158
|
+
if len(marks) > 1:
|
|
1159
|
+
zooms = set() if self.damage else {
|
|
1160
|
+
round(e.stored_width / e.width, 6) for e in pyramid
|
|
1161
|
+
if e.series == s and e.width}
|
|
1162
|
+
self._mosaic_series[s] = 1 + len(zooms)
|
|
1152
1163
|
#: indices this file has, besides "series"
|
|
1153
1164
|
self._levels = (["tile"] if self._tiled and tiles == "separate" else []) + \
|
|
1154
1165
|
[level for level, d in KEY_DIMS.items() if self._dim_sizes.get(d, 1) > 1]
|
|
@@ -1359,6 +1370,10 @@ class _CziFile(File):
|
|
|
1359
1370
|
values.append(e.plane.get(d, self._dim_starts[d]))
|
|
1360
1371
|
return tuple(values)
|
|
1361
1372
|
|
|
1373
|
+
def _mosaic_levels(self, series: int, images: list):
|
|
1374
|
+
# a CZI places any series' tiles by their stored positions
|
|
1375
|
+
return getattr(self, "_mosaic_series", {}).get(series)
|
|
1376
|
+
|
|
1362
1377
|
def canvas(self, **key) -> _CziImage:
|
|
1363
1378
|
"""All series composed on one canvas: the box around every level-0
|
|
1364
1379
|
tile of the file (libCZI's ``total_bounding_rectangle_no_pyramid``),
|
|
@@ -239,6 +239,8 @@ class _DvImage(Image):
|
|
|
239
239
|
"""All sections of a DeltaVision file as one image: the section axes in
|
|
240
240
|
the file's interleave order, then ``y x``."""
|
|
241
241
|
|
|
242
|
+
exact_reads = True # uncompressed: any rectangle is read exactly
|
|
243
|
+
|
|
242
244
|
def __init__(self, path: str, raw: bytes, head: dict, order: str, sizes: dict, ext: bytes):
|
|
243
245
|
self._order = SEQUENCES[head["sequence"]]
|
|
244
246
|
lead = tuple(sizes[a] for a in self._order)
|
|
@@ -343,6 +343,11 @@ class _IcsImage(Image):
|
|
|
343
343
|
#: gzip: the deflate stream (offset, length) inside the gzip member
|
|
344
344
|
self._deflate = _deflate_span(data, offset, layout) if layout.compression == "gzip" else None
|
|
345
345
|
|
|
346
|
+
@property
|
|
347
|
+
def exact_reads(self) -> bool:
|
|
348
|
+
"""Uncompressed pixels are read exactly; a gzip stream is inflated in order."""
|
|
349
|
+
return self._deflate is None
|
|
350
|
+
|
|
346
351
|
def _open(self):
|
|
347
352
|
if self._deflate is not None:
|
|
348
353
|
reader = _Inflated(self._data, *self._deflate, self._layout.nbytes)
|
|
@@ -506,6 +506,8 @@ def _mosaic(number: int, tiles: list, name: str, index: dict, path: str) -> "_Li
|
|
|
506
506
|
class _LifImage(Image):
|
|
507
507
|
"""One tile / rotation of one Leica image."""
|
|
508
508
|
|
|
509
|
+
exact_reads = True # LIF pixels are stored uncompressed
|
|
510
|
+
|
|
509
511
|
def __init__(self, index: int, element, name: str, block, layout: "_Layout", key: dict,
|
|
510
512
|
frames: _StageFrames):
|
|
511
513
|
self._layout = layout
|
|
@@ -651,6 +653,14 @@ class _LifFile(File):
|
|
|
651
653
|
raise
|
|
652
654
|
super().__init__(path, images)
|
|
653
655
|
|
|
656
|
+
def _mosaic_levels(self, series: int, images: list):
|
|
657
|
+
# tiles="mosaic" needs the tiles' stage positions and pixel sizes (``_mosaic``),
|
|
658
|
+
# which come from the XML opening parsed; a scan's flags are the same for all its
|
|
659
|
+
# tiles, so the first tells
|
|
660
|
+
md = getattr(images[0], "source", images[0]).metadata
|
|
661
|
+
placed = all(a in md.position and a in md.pixel_sizes for a in "xy")
|
|
662
|
+
return 0 if placed else None
|
|
663
|
+
|
|
654
664
|
def _declare_coordinate_systems(self):
|
|
655
665
|
# the systems the series' positions are in (plan 4.4, K1-2): one "stage",
|
|
656
666
|
# or one "stage-r<k>" per session ("stage-s<series>" for a series that
|
|
@@ -84,6 +84,8 @@ class _MrcImage(Image):
|
|
|
84
84
|
"""The whole MRC volume as one image, in its stored order (sections,
|
|
85
85
|
rows, columns), each axis named by the file's MAPS, MAPR, MAPC."""
|
|
86
86
|
|
|
87
|
+
exact_reads = True # uncompressed: any rectangle is read exactly
|
|
88
|
+
|
|
87
89
|
def __init__(self, path: str, offset: int, shape, file_dtype: np.dtype, sizes=None,
|
|
88
90
|
axes: str = "zyx"):
|
|
89
91
|
super().__init__(0, axes, shape, file_dtype, name=os.path.basename(path))
|
|
@@ -12,7 +12,9 @@ experiment loops, outermost first. Structure parsing is ported from nd2
|
|
|
12
12
|
- "Lossless" frames are one zlib stream each: decoded whole, cached.
|
|
13
13
|
|
|
14
14
|
Images are the XY positions, indexed by ``series`` (bioio-nd2 calls them scenes); axes ``tczyx``, plus ``s``
|
|
15
|
-
for RGB components
|
|
15
|
+
for RGB components, read in R, G, B(, A) order from the order the camera block declares
|
|
16
|
+
(``stored_sample_order``: Nikon colour cameras store B, G, R; a file that does not state it
|
|
17
|
+
is read as stored, with a warning). With ``plates=True``, a file whose every XY point is
|
|
16
18
|
named after a well as NIS-Elements names them (``A10_0000``, ``B02_0003``,
|
|
17
19
|
``E8.1``: JOBS and ND acquisitions over a well plate; a counter after the well
|
|
18
20
|
or a zero-padded column, ``NIS_WELL_POINT``, so that ``P1``, ``S2`` stay
|
|
@@ -35,6 +37,7 @@ import os
|
|
|
35
37
|
import re
|
|
36
38
|
import struct
|
|
37
39
|
import threading
|
|
40
|
+
import warnings
|
|
38
41
|
import zlib
|
|
39
42
|
|
|
40
43
|
import numpy as np
|
|
@@ -64,6 +67,60 @@ RAW_TASK_BYTES = 8 << 20 # uncompressed frames are read in row pieces o
|
|
|
64
67
|
SEPARATE_READ_BYTES = 32 << 10 # bytes worth skipping rather than issuing one more read
|
|
65
68
|
STREAM_PIECE_BYTES = 8 << 20 # rows of a streamed "lossless" frame decoded at a time
|
|
66
69
|
TIMESTAMP_BYTES = 8 # each frame chunk starts with a float64 timestamp
|
|
70
|
+
#: a camera component's name -> (the sample it holds, its colour as NIS writes it,
|
|
71
|
+
#: 0x00BBGGRR; None: not checked)
|
|
72
|
+
SAMPLE_NAMES = {"red": ("R", 0x0000FF), "green": ("G", 0x00FF00), "blue": ("B", 0xFF0000),
|
|
73
|
+
"alpha": ("A", None)}
|
|
74
|
+
#: the order samples are read in, by their count
|
|
75
|
+
READ_ORDER = {3: ("R", "G", "B"), 4: ("R", "G", "B", "A")}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def stored_sample_order(picture: dict, samples: int):
|
|
79
|
+
"""The order the file stores each pixel's RGB samples in, as letters (Nikon
|
|
80
|
+
colour cameras: ``("B", "G", "R")``), or None when the file does not settle it.
|
|
81
|
+
|
|
82
|
+
The order comes from the camera block of each channel's sample setting
|
|
83
|
+
(``sPicturePlanes/sSampleSetting/a<k>/pCameraSetting/Metadata/Channels/Channel_<i>``):
|
|
84
|
+
each component's ``Name`` (Blue, Green, Red) gives its sample, and its ``Color``
|
|
85
|
+
must agree. Not settled: no such block, a name or colour that does not fit, not
|
|
86
|
+
one of each sample, a count other than 3 or 4, or channels that disagree."""
|
|
87
|
+
if samples not in READ_ORDER:
|
|
88
|
+
return None
|
|
89
|
+
settings = ((picture.get("sPicturePlanes") or {}).get("sSampleSetting") or {})
|
|
90
|
+
orders = set()
|
|
91
|
+
for setting in (settings.values() if isinstance(settings, dict) else ()):
|
|
92
|
+
meta = ((setting or {}).get("pCameraSetting") or {}).get("Metadata") or {}
|
|
93
|
+
components = meta.get("Channels") or {}
|
|
94
|
+
if not isinstance(components, dict) or len(components) != samples:
|
|
95
|
+
return None
|
|
96
|
+
order = []
|
|
97
|
+
for i in range(samples):
|
|
98
|
+
component = components.get(f"Channel_{i}") or {}
|
|
99
|
+
known = SAMPLE_NAMES.get(str(component.get("Name", "")).strip().lower())
|
|
100
|
+
if known is None:
|
|
101
|
+
return None
|
|
102
|
+
letter, colour = known
|
|
103
|
+
if colour is not None and component.get("Color") != colour:
|
|
104
|
+
return None
|
|
105
|
+
order.append(letter)
|
|
106
|
+
if sorted(order) != sorted(READ_ORDER[samples]):
|
|
107
|
+
return None
|
|
108
|
+
orders.add(tuple(order))
|
|
109
|
+
return orders.pop() if len(orders) == 1 else None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _sample_index(stored: np.ndarray):
|
|
113
|
+
"""Stored sample positions as a slice when they are evenly spaced (a view, no
|
|
114
|
+
copy: B, G, R reversed is ``slice(2, None, -1)``), else as the array itself."""
|
|
115
|
+
if len(stored) == 0:
|
|
116
|
+
return slice(0, 0)
|
|
117
|
+
if len(stored) == 1:
|
|
118
|
+
return slice(int(stored[0]), int(stored[0]) + 1)
|
|
119
|
+
steps = np.diff(stored)
|
|
120
|
+
if steps[0] != 0 and (steps == steps[0]).all():
|
|
121
|
+
stop = int(stored[-1] + steps[0])
|
|
122
|
+
return slice(int(stored[0]), None if stop < 0 else stop, int(steps[0]))
|
|
123
|
+
return stored
|
|
67
124
|
|
|
68
125
|
|
|
69
126
|
def sniff(head: bytes, path: str) -> bool:
|
|
@@ -114,6 +171,21 @@ class Nd2Parser:
|
|
|
114
171
|
raise UnsupportedFormatError(f"{path!r}: {a.components} components "
|
|
115
172
|
f"for {a.channels} channels")
|
|
116
173
|
self.samples = a.components // a.channels
|
|
174
|
+
#: the order the file stores RGB samples in, e.g. ("B", "G", "R"); None when
|
|
175
|
+
#: the file does not state it (or for one sample). Reads give R, G, B(, A).
|
|
176
|
+
self.sample_order = None
|
|
177
|
+
#: read sample i -> its stored position, or None: read as stored
|
|
178
|
+
self._stored = None
|
|
179
|
+
if self.samples > 1:
|
|
180
|
+
self.sample_order = stored_sample_order(self.picture, self.samples)
|
|
181
|
+
if self.sample_order is None:
|
|
182
|
+
warnings.warn(f"{path!r}: the file does not state the order of its "
|
|
183
|
+
f"{self.samples} colour samples; they are read as stored and "
|
|
184
|
+
"named R, G, B", stacklevel=4)
|
|
185
|
+
else:
|
|
186
|
+
stored = [self.sample_order.index(s) for s in READ_ORDER[self.samples]]
|
|
187
|
+
if stored != list(range(self.samples)):
|
|
188
|
+
self._stored = np.array(stored)
|
|
117
189
|
self.dtype = np.dtype(a.dtype)
|
|
118
190
|
self.pixel_bytes = a.components * self.dtype.itemsize
|
|
119
191
|
if a.width_bytes < a.width * self.pixel_bytes:
|
|
@@ -132,6 +204,14 @@ class Nd2Parser:
|
|
|
132
204
|
def size(self, kind: str) -> int:
|
|
133
205
|
return next((loop.count for loop in self.loops if loop.kind == kind), 1)
|
|
134
206
|
|
|
207
|
+
def stored_samples(self, ss: slice):
|
|
208
|
+
"""The stored positions of read samples *ss* (R, G, B order): *ss* itself
|
|
209
|
+
when the file stores them in that order, else a slice or index array into
|
|
210
|
+
the stored samples."""
|
|
211
|
+
if self._stored is None:
|
|
212
|
+
return ss
|
|
213
|
+
return _sample_index(self._stored[ss])
|
|
214
|
+
|
|
135
215
|
def frame_number(self, t: int, p: int, z: int) -> int:
|
|
136
216
|
index = {"T": t, "P": p, "Z": z}
|
|
137
217
|
number = 0
|
|
@@ -195,13 +275,22 @@ class _Nd2Image(Image):
|
|
|
195
275
|
name=f"{os.path.basename(nd2.path)} position {position}",
|
|
196
276
|
read_unit=unit, index=index)
|
|
197
277
|
|
|
278
|
+
@property
|
|
279
|
+
def sample_order(self):
|
|
280
|
+
"""The order the file stores the RGB samples in, e.g. ``("B", "G", "R")``
|
|
281
|
+
(Nikon colour cameras); None when the file does not state it or the image
|
|
282
|
+
has one sample. Reads always give R, G, B(, A) on the ``s`` axis."""
|
|
283
|
+
return self._f.sample_order
|
|
284
|
+
|
|
198
285
|
def _read_block(self, block):
|
|
199
286
|
if self._closed:
|
|
200
287
|
raise ValueError("this ND2 image has been closed: its file was closed "
|
|
201
288
|
"(File.close() or the end of a with block)")
|
|
202
289
|
ts, cs, zs, ys, xs = block[:5]
|
|
203
290
|
ss = block[5] if self._rgb else slice(0, 1)
|
|
204
|
-
|
|
291
|
+
out_shape = tuple(s.stop - s.start for s in block)
|
|
292
|
+
ss = self._f.stored_samples(ss) # read R, G, B from the stored order
|
|
293
|
+
out = np.empty(out_shape, dtype=self.dtype)
|
|
205
294
|
view = out if self._rgb else out[..., None] # always (..., s)
|
|
206
295
|
tasks = []
|
|
207
296
|
for t, z in itertools.product(range(ts.start, ts.stop), range(zs.start, zs.stop)):
|
|
@@ -229,6 +229,8 @@ class _TilingFile(File):
|
|
|
229
229
|
px = like.metadata.pixel_sizes
|
|
230
230
|
if tiles == "mosaic" and not ("x" in px and "y" in px):
|
|
231
231
|
raise UnsupportedFormatError(f"{path!r}: tiles='mosaic': its tiles have no pixel size")
|
|
232
|
+
#: tiles="mosaic" would place the tiles (the summary's hint, File._mosaic_levels)
|
|
233
|
+
self._can_mosaic = "x" in px and "y" in px
|
|
232
234
|
|
|
233
235
|
images = []
|
|
234
236
|
for g, (areas, info) in enumerate(groups):
|
|
@@ -253,6 +255,9 @@ class _TilingFile(File):
|
|
|
253
255
|
f"{where} group {g}", {"series": g}, corner))
|
|
254
256
|
super().__init__(path, images)
|
|
255
257
|
|
|
258
|
+
def _mosaic_levels(self, series: int, images: list):
|
|
259
|
+
return 0 if getattr(self, "_can_mosaic", False) else None
|
|
260
|
+
|
|
256
261
|
def _declare_coordinate_systems(self):
|
|
257
262
|
# one stage for the whole protocol (plan 4.10): every group's grid is
|
|
258
263
|
# in its stage coordinates, known from the index alone
|
|
@@ -260,12 +260,18 @@ POSITION_KINDS = ("mmstack", "ndtiff")
|
|
|
260
260
|
|
|
261
261
|
|
|
262
262
|
def translate_axes(axes: str, *, lsm: bool = False, eer: bool = False, where: str = "",
|
|
263
|
-
rename: dict = None, positions: bool = False):
|
|
263
|
+
rename: dict = None, positions: bool = False, shape=None):
|
|
264
264
|
"""tifffile series axes -> (array axis letter or None per axis, image
|
|
265
265
|
index or None per axis); *rename* makes an index an axis instead;
|
|
266
|
-
*positions*: ``R`` is a stage position (``POSITION_KINDS``).
|
|
266
|
+
*positions*: ``R`` is a stage position (``POSITION_KINDS``).
|
|
267
|
+
|
|
268
|
+
A renamed index gives one letter per axis of that index, in file order (outer
|
|
269
|
+
first): QQYX with ``rename={'sequence': 'tz'}`` reads the first Q as t, the
|
|
270
|
+
second as z. Nothing is assumed about what unnamed axes are, so the number of
|
|
271
|
+
letters must match; an axis of size 1 (*shape*) needs none and stays a fixed
|
|
272
|
+
index. Workplan MR36."""
|
|
267
273
|
rename = rename or {}
|
|
268
|
-
letters, levels = [], []
|
|
274
|
+
letters, levels, renamed = [], [], set()
|
|
269
275
|
for a in axes.upper():
|
|
270
276
|
if a in AXIS_LETTERS:
|
|
271
277
|
level, letter = None, AXIS_LETTERS[a]
|
|
@@ -275,15 +281,39 @@ def translate_axes(axes: str, *, lsm: bool = False, eer: bool = False, where: st
|
|
|
275
281
|
position = (a == "P" and lsm) or (a == "R" and positions)
|
|
276
282
|
level = "series" if position else INDEX_LETTERS.get(a, "sequence")
|
|
277
283
|
letter = None
|
|
278
|
-
if level in rename:
|
|
279
|
-
level, letter = None, rename[level]
|
|
280
284
|
levels.append(level)
|
|
281
285
|
letters.append(letter)
|
|
286
|
+
for name, wanted in rename.items():
|
|
287
|
+
found = [p for p, level in enumerate(levels) if level == name]
|
|
288
|
+
varying = [p for p in found if shape is None or int(shape[p]) > 1]
|
|
289
|
+
if not varying:
|
|
290
|
+
continue # the index is absent here: nothing to do
|
|
291
|
+
if len(wanted) != len(varying):
|
|
292
|
+
n = len(varying)
|
|
293
|
+
sizes = (" (sizes " + ", ".join(str(int(shape[p])) for p in varying) + ")"
|
|
294
|
+
if shape is not None else "")
|
|
295
|
+
how = (f"give one letter (t, c or z) per axis, outer first, as in "
|
|
296
|
+
f"rename={{{name!r}: {'tcz'[:n]!r}}}, or open"
|
|
297
|
+
if n <= 3 else "only t, c and z can be given, so open")
|
|
298
|
+
raise UnsupportedFormatError(
|
|
299
|
+
f"rename: {where}: series axes {axes!r} have {n} {name} axes{sizes}, "
|
|
300
|
+
f"and rename={{{name!r}: {wanted!r}}} gives {len(wanted)} "
|
|
301
|
+
f"letter{'s' if len(wanted) != 1 else ''}. The file does not say what "
|
|
302
|
+
f"these axes are: {how} the file without rename to keep {name!r} as an "
|
|
303
|
+
f"index")
|
|
304
|
+
for p, letter in zip(varying, wanted):
|
|
305
|
+
levels[p], letters[p] = None, letter
|
|
306
|
+
renamed.add(letter)
|
|
282
307
|
used = [x for x in letters if x]
|
|
283
308
|
doubled = sorted({x for x in used if used.count(x) > 1})
|
|
284
309
|
if doubled:
|
|
310
|
+
# Doubled BY the rename (QZYX with rename={'sequence': 'z'}: the unnamed axis
|
|
311
|
+
# would be a second z): the message starts with "rename:", as the registry's
|
|
312
|
+
# refusals of a rename do, so a caller can open the file again without the
|
|
313
|
+
# rename and keep the index (eubi's open_renamed does). Workplan MR36.
|
|
314
|
+
prefix = "rename: " if doubled[0] in renamed else ""
|
|
285
315
|
raise UnsupportedFormatError(
|
|
286
|
-
f"{where}: series axes {axes!r} give axis {doubled[0]!r} twice"
|
|
316
|
+
f"{prefix}{where}: series axes {axes!r} give axis {doubled[0]!r} twice"
|
|
287
317
|
+ (f" (with rename={rename})" if rename else ""))
|
|
288
318
|
return letters, levels
|
|
289
319
|
|
|
@@ -640,6 +670,11 @@ class _TiffImage(Image):
|
|
|
640
670
|
|
|
641
671
|
# -- reading --------------------------------------------------------------
|
|
642
672
|
|
|
673
|
+
@property
|
|
674
|
+
def exact_reads(self) -> bool:
|
|
675
|
+
"""Uncompressed pages (no ``read_unit``) are read exactly."""
|
|
676
|
+
return self._raw
|
|
677
|
+
|
|
643
678
|
def _read_block(self, block):
|
|
644
679
|
if self._closed:
|
|
645
680
|
raise ValueError("this TIFF image has been closed: its file was closed "
|
|
@@ -1258,7 +1293,7 @@ def _images(tif, series: list, path: str, tiles: str, resolutions: str = "base",
|
|
|
1258
1293
|
where = f"{os.path.basename(path)!r} series {i}"
|
|
1259
1294
|
letters, frame = translate_axes(s.axes, lsm=bool(tif.is_lsm),
|
|
1260
1295
|
eer=bool(getattr(s.keyframe, "is_eer", False)),
|
|
1261
|
-
where=where, rename=rename,
|
|
1296
|
+
where=where, rename=rename, shape=s.shape,
|
|
1262
1297
|
positions=s.kind in POSITION_KINDS)
|
|
1263
1298
|
# frame axes of more than one index make images; size 1 is just fixed
|
|
1264
1299
|
by_level: dict = {}
|
|
@@ -1595,19 +1630,20 @@ def _ome_plate(tif, path: str):
|
|
|
1595
1630
|
"""``plates=True`` on an OME-TIFF holding its own OME-XML with a ``Plate``
|
|
1596
1631
|
(CQ1's ``MeasurementResult.ome.tif``): the file read as the companion it is
|
|
1597
1632
|
(backends/companion.py: plates, wells, fields), when that reader can read
|
|
1598
|
-
it
|
|
1599
|
-
|
|
1633
|
+
it; else None, and it reads as before, without a plate. A plane that names no
|
|
1634
|
+
file is one of this file's own (as tifffile writes a one-file OME-TIFF; Workplan
|
|
1635
|
+
MR33). Takes over *tif* (closed) when it returns the file."""
|
|
1600
1636
|
if tif.is_micromanager or "<Plate" not in (tif.ome_metadata or ""):
|
|
1601
1637
|
return None
|
|
1602
1638
|
from . import companion as ome_set
|
|
1603
1639
|
try:
|
|
1604
|
-
core = ome_set.load(path)
|
|
1640
|
+
core = ome_set.load(path, own_planes=True)
|
|
1605
1641
|
except (CorruptFileError, UnsupportedFormatError):
|
|
1606
|
-
return None #
|
|
1642
|
+
return None # XML the companion route cannot read
|
|
1607
1643
|
if not any(plate["places"] for plate in core.plates()):
|
|
1608
1644
|
return None
|
|
1609
1645
|
try:
|
|
1610
|
-
found = ome_set._CompanionFile(path, plates=True)
|
|
1646
|
+
found = ome_set._CompanionFile(path, plates=True, own_planes=True)
|
|
1611
1647
|
except ome_set.NotInItsSet:
|
|
1612
1648
|
return None # a file its own OME-XML does not list (CQ1's MIP)
|
|
1613
1649
|
tif.close()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|