micro-reader 0.4.5__tar.gz → 0.5.0__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.4.5 → micro_reader-0.5.0}/.gitignore +1 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/PKG-INFO +5 -4
- {micro_reader-0.4.5 → micro_reader-0.5.0}/README.md +3 -3
- {micro_reader-0.4.5 → micro_reader-0.5.0}/pyproject.toml +3 -2
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/__init__.py +2 -1
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_axes.py +52 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_base.py +17 -0
- micro_reader-0.5.0/src/micro_reader/_engine.py +255 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_fileset.py +43 -26
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_io.py +73 -7
- micro_reader-0.5.0/src/micro_reader/_many.py +92 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_version.py +1 -1
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/czi.py +102 -1
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/metamorph.py +39 -24
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/tiff.py +82 -2
- {micro_reader-0.4.5 → micro_reader-0.5.0}/LICENSE +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_cfb.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_codecs.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_errors.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_eubi_guard.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_groups.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_index.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_jpeg_restarts.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_lambda.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_memory.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_metadata.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_mosaic.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_naming.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_outline.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_parts.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_plate.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_pool.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_registry.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_spatial.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_stack.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/_stream.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/__init__.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/_czi_metadata.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/_ets.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/_hdf5.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/_lif_metadata.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/_nd2_legacy.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/_nd2_metadata.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/_nd2_run.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/_nd2_structure.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/_tiff_metadata.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/_tiff_variants.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/_vsi_tree.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/bdv.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/cellomics.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/columbus.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/companion.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/cv7000.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/dv.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/flex.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/harmony.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/hdf5.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/ics.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/ilastik.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/ims.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/incell.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/jdce.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/klb.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/lif.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/luxendo.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/metaxpress.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/micromanager.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/mrc.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/nd2.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/ndpis.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/oif.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/oir.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/omp2info.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/raster.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/src/micro_reader/backends/scanr.py +0 -0
- {micro_reader-0.4.5 → micro_reader-0.5.0}/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.
|
|
3
|
+
Version: 0.5.0
|
|
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
|
|
@@ -19,6 +19,7 @@ Classifier: Programming Language :: Python :: 3.14
|
|
|
19
19
|
Classifier: Topic :: Scientific/Engineering :: Image Processing
|
|
20
20
|
Requires-Python: >=3.11
|
|
21
21
|
Requires-Dist: micro-reader-codecs<0.1,>=0.0.4
|
|
22
|
+
Requires-Dist: micro-reader-core<0.1,>=0.0.1
|
|
22
23
|
Requires-Dist: numpy>=1.24
|
|
23
24
|
Requires-Dist: tifffile>=2025.5.21
|
|
24
25
|
Provides-Extra: all
|
|
@@ -72,7 +73,7 @@ The library supports a wide range of microscopy formats through a common interfa
|
|
|
72
73
|
pip install micro-reader
|
|
73
74
|
```
|
|
74
75
|
|
|
75
|
-
Requires Python 3.11 or newer. The native image decoders are provided by `micro-reader-codecs
|
|
76
|
+
Requires Python 3.11 or newer. The native image decoders are provided by `micro-reader-codecs` and the native read engine by `micro-reader-core`. Both are installed automatically. Prebuilt wheels are available for Linux (x86-64 and ARM), macOS (Intel and Apple silicon) and Windows (x86-64).
|
|
76
77
|
|
|
77
78
|
Some formats and less common TIFF compression methods require optional dependencies:
|
|
78
79
|
|
|
@@ -222,7 +223,7 @@ See [Memory and threads](https://bugraoezdemir.github.io/micro-reader/guide/perf
|
|
|
222
223
|
|
|
223
224
|
`micro-reader` uses native decoding libraries provided by `micro-reader-codecs`. These include libjpeg-turbo, jxrlib, OpenJPEG, libdeflate and zstd.
|
|
224
225
|
|
|
225
|
-
Decoding is parallelised across CPU cores, and native decoding releases Python's global interpreter lock. A single read can therefore make use of multiple cores. Decoded blocks are also cached, so nearby region requests can reuse data that has already been decoded.
|
|
226
|
+
Decoding is parallelised across CPU cores, and native decoding releases Python's global interpreter lock. A single read can therefore make use of multiple cores. For TIFF and CZI files, the read engine in `micro-reader-core` reads, decodes and places all the pieces of a region in one call, on its own threads. Decoded blocks are also cached, so nearby region requests can reuse data that has already been decoded.
|
|
226
227
|
|
|
227
228
|
The benchmarks below show typical reading times for several microscopy formats.
|
|
228
229
|
|
|
@@ -310,4 +311,4 @@ The project has been developed with substantial AI assistance. Its functionality
|
|
|
310
311
|
|
|
311
312
|
## License
|
|
312
313
|
|
|
313
|
-
`micro-reader` and `micro-reader-
|
|
314
|
+
`micro-reader`, `micro-reader-codecs` and `micro-reader-core` are MIT licensed. The wheels of the two native packages include third-party libraries. Their notices are available in [`codecs/THIRD_PARTY_LICENSES.txt`](https://github.com/bugraoezdemir/micro-reader/blob/main/codecs/THIRD_PARTY_LICENSES.txt) and [`core/THIRD_PARTY_LICENSES.txt`](https://github.com/bugraoezdemir/micro-reader/blob/main/core/THIRD_PARTY_LICENSES.txt).
|
|
@@ -18,7 +18,7 @@ The library supports a wide range of microscopy formats through a common interfa
|
|
|
18
18
|
pip install micro-reader
|
|
19
19
|
```
|
|
20
20
|
|
|
21
|
-
Requires Python 3.11 or newer. The native image decoders are provided by `micro-reader-codecs
|
|
21
|
+
Requires Python 3.11 or newer. The native image decoders are provided by `micro-reader-codecs` and the native read engine by `micro-reader-core`. Both are installed automatically. Prebuilt wheels are available for Linux (x86-64 and ARM), macOS (Intel and Apple silicon) and Windows (x86-64).
|
|
22
22
|
|
|
23
23
|
Some formats and less common TIFF compression methods require optional dependencies:
|
|
24
24
|
|
|
@@ -168,7 +168,7 @@ See [Memory and threads](https://bugraoezdemir.github.io/micro-reader/guide/perf
|
|
|
168
168
|
|
|
169
169
|
`micro-reader` uses native decoding libraries provided by `micro-reader-codecs`. These include libjpeg-turbo, jxrlib, OpenJPEG, libdeflate and zstd.
|
|
170
170
|
|
|
171
|
-
Decoding is parallelised across CPU cores, and native decoding releases Python's global interpreter lock. A single read can therefore make use of multiple cores. Decoded blocks are also cached, so nearby region requests can reuse data that has already been decoded.
|
|
171
|
+
Decoding is parallelised across CPU cores, and native decoding releases Python's global interpreter lock. A single read can therefore make use of multiple cores. For TIFF and CZI files, the read engine in `micro-reader-core` reads, decodes and places all the pieces of a region in one call, on its own threads. Decoded blocks are also cached, so nearby region requests can reuse data that has already been decoded.
|
|
172
172
|
|
|
173
173
|
The benchmarks below show typical reading times for several microscopy formats.
|
|
174
174
|
|
|
@@ -256,4 +256,4 @@ The project has been developed with substantial AI assistance. Its functionality
|
|
|
256
256
|
|
|
257
257
|
## License
|
|
258
258
|
|
|
259
|
-
`micro-reader` and `micro-reader-
|
|
259
|
+
`micro-reader`, `micro-reader-codecs` and `micro-reader-core` are MIT licensed. The wheels of the two native packages include third-party libraries. Their notices are available in [`codecs/THIRD_PARTY_LICENSES.txt`](https://github.com/bugraoezdemir/micro-reader/blob/main/codecs/THIRD_PARTY_LICENSES.txt) and [`core/THIRD_PARTY_LICENSES.txt`](https://github.com/bugraoezdemir/micro-reader/blob/main/core/THIRD_PARTY_LICENSES.txt).
|
|
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
|
|
|
6
6
|
|
|
7
7
|
[project]
|
|
8
8
|
name = "micro-reader"
|
|
9
|
-
version = "0.
|
|
9
|
+
version = "0.5.0"
|
|
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,8 @@ 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.4,<0.1", "
|
|
32
|
+
dependencies = ["numpy>=1.24", "micro-reader-codecs>=0.0.4,<0.1", "micro-reader-core>=0.0.1,<0.1",
|
|
33
|
+
"tifffile>=2025.5.21"]
|
|
33
34
|
|
|
34
35
|
[project.urls]
|
|
35
36
|
Homepage = "https://github.com/bugraoezdemir/micro-reader"
|
|
@@ -19,10 +19,11 @@ from ._io import cache_limit, cached_bytes, set_cache_limit
|
|
|
19
19
|
from ._pool import decode_threads, set_decode_threads
|
|
20
20
|
from ._registry import BACKENDS, open # noqa: A004 - the public entry point
|
|
21
21
|
from ._groups import FileGroup, Grouping, group_files
|
|
22
|
+
from ._many import read_many
|
|
22
23
|
from .backends.czi import DamagedFileWarning
|
|
23
24
|
|
|
24
25
|
__all__ = [
|
|
25
|
-
"open", "group_files", "FileGroup", "Grouping", "File", "Image", "INDEX_NAMES", "PLATE_INDICES", "SAMPLED_INDICES", "ReadStats",
|
|
26
|
+
"open", "read_many", "group_files", "FileGroup", "Grouping", "File", "Image", "INDEX_NAMES", "PLATE_INDICES", "SAMPLED_INDICES", "ReadStats",
|
|
26
27
|
"BACKENDS", "Metadata", "Channel", "Quantity", "Plate", "Well", "Field", "Acquisition",
|
|
27
28
|
"Axis", "CoordinateSystem", "Transformation", "Collection",
|
|
28
29
|
"decode_threads", "set_decode_threads", "memory_limit", "set_memory_limit",
|
|
@@ -161,8 +161,60 @@ class AxesImage(Image):
|
|
|
161
161
|
select[a] = 0
|
|
162
162
|
return "".join(a for a in axes if a not in drop)
|
|
163
163
|
|
|
164
|
+
def _plan_into(self, block, out, stack):
|
|
165
|
+
"""The source's plans into a view of *out* laid out in the source's axes:
|
|
166
|
+
a squeezed axis is a size-1 axis, folded channels split into (channels,
|
|
167
|
+
samples), the axes this view adds are left out (size 1) and the order is
|
|
168
|
+
the source's. None when the folded channels asked for do not start and
|
|
169
|
+
end on a pixel's samples (they are read and copied instead)."""
|
|
170
|
+
names, select = self._names, self._select
|
|
171
|
+
want = dict(zip(self.axes, block))
|
|
172
|
+
size = dict(zip(self.axes, out.shape))
|
|
173
|
+
stride = dict(zip(self.axes, out.strides))
|
|
174
|
+
S = self._samples
|
|
175
|
+
native_key, shape, strides = [], [], []
|
|
176
|
+
for a in names:
|
|
177
|
+
if a in select:
|
|
178
|
+
native_key.append(slice(select[a], select[a] + 1))
|
|
179
|
+
shape.append(1)
|
|
180
|
+
strides.append(0)
|
|
181
|
+
elif self._fold and a in "cs":
|
|
182
|
+
k = want.get("c", slice(0, 1))
|
|
183
|
+
if k.start % S or k.stop % S:
|
|
184
|
+
return None
|
|
185
|
+
if a == "s":
|
|
186
|
+
native_key.append(slice(0, S))
|
|
187
|
+
shape.append(S)
|
|
188
|
+
strides.append(stride["c"])
|
|
189
|
+
else:
|
|
190
|
+
native_key.append(slice(k.start // S, k.stop // S))
|
|
191
|
+
shape.append(k.stop // S - k.start // S)
|
|
192
|
+
strides.append(stride["c"] * S)
|
|
193
|
+
else:
|
|
194
|
+
native_key.append(want[a])
|
|
195
|
+
shape.append(size[a])
|
|
196
|
+
strides.append(stride[a])
|
|
197
|
+
view = np.lib.stride_tricks.as_strided(out, tuple(shape), tuple(strides), writeable=True)
|
|
198
|
+
return self.source._plan_into(tuple(native_key), view, stack)
|
|
199
|
+
|
|
164
200
|
def _read_block(self, block):
|
|
165
201
|
names, select, axes = self._names, self._select, self.axes
|
|
202
|
+
kept = [a for a in names if a not in select]
|
|
203
|
+
if self._fold or kept != [a for a in axes if a in kept]:
|
|
204
|
+
# the source's array would be reordered into this view's axes (RGB
|
|
205
|
+
# samples folded into the channels: a copy of the whole read, on one
|
|
206
|
+
# thread). On the read engine, plan straight into the final array
|
|
207
|
+
# instead: each segment's samples go to their place on the engine's
|
|
208
|
+
# threads. (2026-11-17: an 8192 x 8192 RGB JPEG plane at 16 threads,
|
|
209
|
+
# 127 ms -> the engine's own 32 ms.)
|
|
210
|
+
from . import _engine
|
|
211
|
+
if _engine.engine() is not None:
|
|
212
|
+
import contextlib
|
|
213
|
+
out = np.empty(tuple(s.stop - s.start for s in block), dtype=self.dtype)
|
|
214
|
+
with contextlib.ExitStack() as stack:
|
|
215
|
+
plans = self._plan_into(block, out, stack)
|
|
216
|
+
if plans is not None:
|
|
217
|
+
return out, _engine.run_plans(plans, out)
|
|
166
218
|
want = dict(zip(axes, block))
|
|
167
219
|
S = self._samples
|
|
168
220
|
if self._fold: # folded channels k0:k1 -> channels, all samples
|
|
@@ -380,6 +380,23 @@ class Image:
|
|
|
380
380
|
number of pixels actually read or decoded to produce it)."""
|
|
381
381
|
raise NotImplementedError
|
|
382
382
|
|
|
383
|
+
@staticmethod
|
|
384
|
+
def read_many(requests) -> None:
|
|
385
|
+
"""``micro_reader.read_many``, here too: libraries that join arrays (dyna's
|
|
386
|
+
concatenation) look for ``read_many`` on their sources' type, and read
|
|
387
|
+
the parts of a join of images in one call."""
|
|
388
|
+
from ._many import read_many
|
|
389
|
+
read_many(requests)
|
|
390
|
+
|
|
391
|
+
def _plan_into(self, block: tuple[slice, ...], out: np.ndarray, stack):
|
|
392
|
+
"""The plans that fill *out* (a writable array shaped like *block*) once
|
|
393
|
+
run, ``[(image, plan), ...]`` for ``_engine.run_plans`` (``read_many``);
|
|
394
|
+
None when this image cannot plan a read into a given array, and is read
|
|
395
|
+
with ``_read_block`` and copied instead. *stack*, a
|
|
396
|
+
``contextlib.ExitStack``, holds what must stay acquired until the plans
|
|
397
|
+
have run (a file set's members)."""
|
|
398
|
+
return None
|
|
399
|
+
|
|
383
400
|
def close(self) -> None:
|
|
384
401
|
"""Release file handles; the image is unusable afterwards."""
|
|
385
402
|
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"""The native read engine (micro-reader-core, Workplan MR23), when installed.
|
|
2
|
+
|
|
3
|
+
A backend plans a read as before -- which stored segments, which of their rows,
|
|
4
|
+
columns and samples go where in the output array -- and hands the pieces it can
|
|
5
|
+
to a :class:`Batch` instead of making a pool task of each. The engine then
|
|
6
|
+
reads, decodes and places all of them in one call, on its own threads without
|
|
7
|
+
Python's lock: one handle per file, positional reads, each segment decoded once
|
|
8
|
+
however many pieces need it, a cache of decoded segments of its own. Whatever
|
|
9
|
+
a backend does not hand over (large segments decoded in parts, codecs the
|
|
10
|
+
engine lacks) runs on the decode pool as before, in the same call.
|
|
11
|
+
|
|
12
|
+
Off when micro-reader-core is not installed, with ``MICRO_READER_ENGINE=0``, with
|
|
13
|
+
``MICRO_READER_NO_NATIVE=1`` (no native code at all: the reference decoders on the
|
|
14
|
+
Python path), or after ``set_engine(False)``; the Python path is then the only one,
|
|
15
|
+
and stays the reference the tests compare the engine with.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import itertools
|
|
20
|
+
import os
|
|
21
|
+
import threading
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
|
|
25
|
+
from . import _memory, _pool
|
|
26
|
+
|
|
27
|
+
try:
|
|
28
|
+
import micro_reader_core as _core
|
|
29
|
+
except ImportError: # not installed: the Python path
|
|
30
|
+
_core = None
|
|
31
|
+
|
|
32
|
+
#: the columns of a plan row, as the engine numbers them
|
|
33
|
+
COLUMNS = tuple(_core.PIECE_COLUMNS) if _core is not None else ()
|
|
34
|
+
NCOL = len(COLUMNS)
|
|
35
|
+
|
|
36
|
+
_lock = threading.Lock()
|
|
37
|
+
_engine = None
|
|
38
|
+
_enabled = None
|
|
39
|
+
_cache_limit = None
|
|
40
|
+
_codecs: dict = {}
|
|
41
|
+
#: ids of the specs in ``_codecs`` that read uncompressed bytes ("raw")
|
|
42
|
+
_raw_specs: set = set()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def available() -> bool:
|
|
46
|
+
"""Whether micro-reader-core is installed (whatever ``set_engine`` says)."""
|
|
47
|
+
return _core is not None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def has(feature: str) -> bool:
|
|
51
|
+
"""Whether the installed micro-reader-core has *feature* (``HAS_JXRLIB``,
|
|
52
|
+
``HAS_LIBJPEG_TURBO``); False without it."""
|
|
53
|
+
return bool(getattr(_core, feature, False))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def enabled() -> bool:
|
|
57
|
+
"""Whether reads go through the engine."""
|
|
58
|
+
global _enabled
|
|
59
|
+
if _enabled is None:
|
|
60
|
+
_enabled = (_core is not None and os.environ.get("MICRO_READER_ENGINE", "1") != "0"
|
|
61
|
+
and not os.environ.get("MICRO_READER_NO_NATIVE"))
|
|
62
|
+
return _enabled
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def set_engine(on) -> None:
|
|
66
|
+
"""Read through the engine (True), on the Python path (False), or as the
|
|
67
|
+
``MICRO_READER_ENGINE`` environment variable says (None). True without
|
|
68
|
+
micro-reader-core installed is refused."""
|
|
69
|
+
global _enabled
|
|
70
|
+
if on and _core is None:
|
|
71
|
+
raise RuntimeError("set_engine(True): micro-reader-core is not installed "
|
|
72
|
+
"(pip install micro-reader-core)")
|
|
73
|
+
_enabled = None if on is None else bool(on)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def engine():
|
|
77
|
+
"""The process' engine (made on first use), or None when reads do not use it."""
|
|
78
|
+
global _engine, _cache_limit
|
|
79
|
+
if not enabled():
|
|
80
|
+
return None
|
|
81
|
+
if _engine is None:
|
|
82
|
+
with _lock:
|
|
83
|
+
if _engine is None:
|
|
84
|
+
_engine = _core.Engine()
|
|
85
|
+
from ._io import cache_limit, yield_to_engine
|
|
86
|
+
limit = cache_limit()
|
|
87
|
+
if limit != _cache_limit: # set_cache_limit() applies here too
|
|
88
|
+
_engine.set_cache_limit(limit)
|
|
89
|
+
_cache_limit = limit
|
|
90
|
+
# one limit for the engine's cache and the Python caches (_io): they give back
|
|
91
|
+
# down to half of it if they hold more, and the engine keeps at most the rest
|
|
92
|
+
yield_to_engine(_engine, limit)
|
|
93
|
+
return _engine
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def cached_bytes() -> int:
|
|
97
|
+
"""What the engine's cache holds (0 without an engine)."""
|
|
98
|
+
return _engine.cached_bytes() if _engine is not None else 0
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def codec(kind: str, itemsize: int, samples: int, **kwargs):
|
|
102
|
+
"""The engine's spec of a codec (made once per distinct spec)."""
|
|
103
|
+
key = (kind, itemsize, samples, tuple(sorted(kwargs.items())))
|
|
104
|
+
spec = _codecs.get(key)
|
|
105
|
+
if spec is None:
|
|
106
|
+
with _lock:
|
|
107
|
+
spec = _codecs.setdefault(key, _core.Codec(kind, itemsize, samples, **kwargs))
|
|
108
|
+
if kind == "raw":
|
|
109
|
+
_raw_specs.add(id(spec))
|
|
110
|
+
return spec
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class Batch:
|
|
114
|
+
"""The pieces of one read for the engine, from one image or many (a file
|
|
115
|
+
set's planes): rows of ``COLUMNS`` plus the codecs and tables they name."""
|
|
116
|
+
|
|
117
|
+
def __init__(self, engine_):
|
|
118
|
+
self.engine = engine_
|
|
119
|
+
self.rows: list = []
|
|
120
|
+
self.codecs: list = []
|
|
121
|
+
self._codec_at: dict = {}
|
|
122
|
+
self.tables: list = []
|
|
123
|
+
self._table_at: dict = {}
|
|
124
|
+
#: the largest decoded segment, for the memory budget
|
|
125
|
+
self.max_segment = 0
|
|
126
|
+
#: per row, the plan it came from (``run_plans`` with counts)
|
|
127
|
+
self.owners: list = []
|
|
128
|
+
self.owner = 0
|
|
129
|
+
|
|
130
|
+
def _codec(self, spec) -> int:
|
|
131
|
+
at = self._codec_at.get(id(spec))
|
|
132
|
+
if at is None:
|
|
133
|
+
at = self._codec_at[id(spec)] = len(self.codecs)
|
|
134
|
+
self.codecs.append(spec)
|
|
135
|
+
return at
|
|
136
|
+
|
|
137
|
+
def _table(self, data) -> int:
|
|
138
|
+
if not data:
|
|
139
|
+
return -1
|
|
140
|
+
data = bytes(data)
|
|
141
|
+
at = self._table_at.get(data)
|
|
142
|
+
if at is None:
|
|
143
|
+
at = self._table_at[data] = len(self.tables)
|
|
144
|
+
self.tables.append(data)
|
|
145
|
+
return at
|
|
146
|
+
|
|
147
|
+
def add(self, handles, offset: int, count: int, spec, table, seg_shape: tuple,
|
|
148
|
+
rows: tuple, cols: tuple, samples: tuple, dst: np.ndarray) -> None:
|
|
149
|
+
"""Rows, columns and samples (``(start, stop)`` each) of the segment of
|
|
150
|
+
*seg_shape* (rows, cols) stored at *offset* in *handles*' file, into
|
|
151
|
+
*dst* (rows, cols, samples: a view of the output array)."""
|
|
152
|
+
r0, r1 = rows
|
|
153
|
+
if r1 <= r0 or cols[1] <= cols[0] or samples[1] <= samples[0]:
|
|
154
|
+
return
|
|
155
|
+
s = dst.strides
|
|
156
|
+
self.owners.append(self.owner)
|
|
157
|
+
self.rows.append((handles.engine_file(self.engine), offset, count, self._codec(spec),
|
|
158
|
+
self._table(table), seg_shape[0], seg_shape[1], r0, r1, cols[0],
|
|
159
|
+
cols[1], samples[0], samples[1],
|
|
160
|
+
dst.__array_interface__["data"][0], s[0], s[1], s[2]))
|
|
161
|
+
|
|
162
|
+
def run(self, out: np.ndarray, counts=None) -> int:
|
|
163
|
+
"""Run the pieces into *out*, the array every destination is part of.
|
|
164
|
+
*counts*: a list that gets, per plan (``owner``), what its pieces read."""
|
|
165
|
+
if not self.rows:
|
|
166
|
+
return 0
|
|
167
|
+
pieces = np.array(self.rows, dtype=np.int64)
|
|
168
|
+
if counts is not None:
|
|
169
|
+
per_piece = np.zeros(len(self.rows), np.int64)
|
|
170
|
+
n = self._run(pieces, out, per_piece)
|
|
171
|
+
for owner, k in enumerate(np.bincount(self.owners, weights=per_piece,
|
|
172
|
+
minlength=len(counts))):
|
|
173
|
+
counts[owner] += int(k)
|
|
174
|
+
return n
|
|
175
|
+
return self._run(pieces, out)
|
|
176
|
+
|
|
177
|
+
def _run(self, pieces, out, per_piece=None) -> int:
|
|
178
|
+
threads = _pool.decode_threads()
|
|
179
|
+
# at most one decoded segment per thread at once, plus a raw read buffer each
|
|
180
|
+
hold = min(threads, len(self.rows)) * (self.max_segment + (4 << 20))
|
|
181
|
+
hold = min(hold, _memory.memory_limit())
|
|
182
|
+
with _memory.reserve(hold, "segments decoded by the read engine"):
|
|
183
|
+
if per_piece is None:
|
|
184
|
+
return self.engine.read(pieces, self.codecs, self.tables, out, threads)
|
|
185
|
+
return self.engine.read(pieces, self.codecs, self.tables, out, threads,
|
|
186
|
+
counts=per_piece)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _counted(tasks, log, k):
|
|
190
|
+
"""*tasks* (pool tasks returning what they read), each logging ``(k, read)``
|
|
191
|
+
to *log* (``list.append`` is atomic across threads; ``+=`` on an item is not)."""
|
|
192
|
+
for task in tasks:
|
|
193
|
+
def run(task=task):
|
|
194
|
+
n = task()
|
|
195
|
+
log.append((k, n))
|
|
196
|
+
return n
|
|
197
|
+
yield run
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _pool_counted(plans, counts) -> int:
|
|
201
|
+
"""The pool tasks of *plans*, run, with what each plan read added to *counts*."""
|
|
202
|
+
log: list = []
|
|
203
|
+
n = _pool.run(itertools.chain.from_iterable(
|
|
204
|
+
_counted(image._tasks(*plan), log, k) for k, (image, plan) in enumerate(plans)))
|
|
205
|
+
for k, read in log:
|
|
206
|
+
counts[k] += read
|
|
207
|
+
return n
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _one_read(batch) -> bool:
|
|
211
|
+
"""Whether *batch*'s only piece is uncompressed whole rows of its segment: one
|
|
212
|
+
contiguous read on the Python path, where it costs less than a call to the
|
|
213
|
+
engine (nothing to decode or spread; a viewer's 256 x 256 tile of an
|
|
214
|
+
uncompressed TIFF: about 15 us of 45). A few columns of wide rows (strips
|
|
215
|
+
joined into one run) stay on the engine, which reads them faster."""
|
|
216
|
+
row = batch.rows[0]
|
|
217
|
+
seg_cols, c0, c1 = row[6], row[9], row[10]
|
|
218
|
+
return id(batch.codecs[row[3]]) in _raw_specs and c0 == 0 and c1 == seg_cols
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def run_plans(plans, out: np.ndarray, counts=None) -> int:
|
|
222
|
+
"""Run the plans of images (``[(image, plan), ...]``, a backend's
|
|
223
|
+
``_plan_series``) into *out*: on the engine what each image hands it
|
|
224
|
+
(``image._engine_split(batch, *plan)``), the rest as the images' pool
|
|
225
|
+
tasks (``image._tasks``). Without the engine, all of it on the pool.
|
|
226
|
+
*counts*: a list of one 0 per plan, which gets what each plan read
|
|
227
|
+
(``read_many``: each image's ``stats``)."""
|
|
228
|
+
plans = list(plans)
|
|
229
|
+
eng = engine()
|
|
230
|
+
if eng is None:
|
|
231
|
+
if counts is None:
|
|
232
|
+
return _pool.run(itertools.chain.from_iterable(
|
|
233
|
+
image._tasks(*plan) for image, plan in plans))
|
|
234
|
+
return _pool_counted(plans, counts)
|
|
235
|
+
batch = Batch(eng)
|
|
236
|
+
rest = []
|
|
237
|
+
for k, (image, plan) in enumerate(plans):
|
|
238
|
+
split = getattr(image, "_engine_split", None)
|
|
239
|
+
batch.owner = k
|
|
240
|
+
rest.append((image, split(batch, *plan) if split is not None else plan))
|
|
241
|
+
if counts is None and len(batch.rows) == 1 and _one_read(batch):
|
|
242
|
+
return _pool.run(itertools.chain.from_iterable(
|
|
243
|
+
image._tasks(*plan) for image, plan in plans))
|
|
244
|
+
try:
|
|
245
|
+
n = batch.run(out, counts)
|
|
246
|
+
except ValueError as exc: # the engine's message names file and offset
|
|
247
|
+
from ._errors import CorruptFileError
|
|
248
|
+
raise CorruptFileError(str(exc)) from exc
|
|
249
|
+
except OSError as exc:
|
|
250
|
+
from ._errors import CorruptFileError
|
|
251
|
+
raise CorruptFileError(str(exc)) from exc
|
|
252
|
+
if counts is None:
|
|
253
|
+
return n + _pool.run(itertools.chain.from_iterable(
|
|
254
|
+
image._tasks(*plan) for image, plan in rest))
|
|
255
|
+
return n + _pool_counted(rest, counts)
|
|
@@ -20,7 +20,6 @@ separate 2-D files (Harmony, MetaXpress, ...), listed by an index file.
|
|
|
20
20
|
its parts."""
|
|
21
21
|
from __future__ import annotations
|
|
22
22
|
|
|
23
|
-
import itertools
|
|
24
23
|
import os
|
|
25
24
|
import threading
|
|
26
25
|
import warnings
|
|
@@ -219,38 +218,56 @@ class PlaneImage(Image):
|
|
|
219
218
|
read += n
|
|
220
219
|
return out, read
|
|
221
220
|
|
|
221
|
+
def _plan_into(self, block, out, stack):
|
|
222
|
+
if self._closed or not self._readable or not self._members._pages:
|
|
223
|
+
return None # read_many reads it with _read_block
|
|
224
|
+
entries: list = []
|
|
225
|
+
stack.callback(self._release, entries)
|
|
226
|
+
(t0, t1), (c0, c1), (z0, z1) = ((s.start, s.stop) for s in block[:3])
|
|
227
|
+
return self._plan_pages(out, (t0, t1), (c0, c1), (z0, z1), block[3], block[4],
|
|
228
|
+
tuple(block[5:]), entries)
|
|
229
|
+
|
|
230
|
+
def _release(self, entries) -> None:
|
|
231
|
+
for entry in entries:
|
|
232
|
+
self._members.release(entry)
|
|
233
|
+
|
|
222
234
|
def _read_pages(self, out, ts, cs, zs, ys, xs, extra=()) -> int:
|
|
223
235
|
"""Fill *out* from members opened as pages: every plane's reads are
|
|
224
236
|
planned straight into *out* first, then all of them run in one batch on
|
|
225
237
|
the decode pool, as a multi-page TIFF's pages do (no copy per plane, the
|
|
226
238
|
pool busy across planes). The members stay acquired until it is done."""
|
|
227
|
-
from . import
|
|
228
|
-
entries
|
|
239
|
+
from . import _engine
|
|
240
|
+
entries: list = []
|
|
229
241
|
try:
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
for z in range(*zs):
|
|
233
|
-
dest = out[t - ts[0], c - cs[0], z - zs[0]]
|
|
234
|
-
member = self._planes.get((t, c, z))
|
|
235
|
-
if member is None: # a missing plane reads as zeros
|
|
236
|
-
dest[...] = 0
|
|
237
|
-
continue
|
|
238
|
-
path, ifd = member
|
|
239
|
-
entry = self._members.acquire(path)
|
|
240
|
-
entries.append(entry)
|
|
241
|
-
image, k = _page(entry[0], ifd, path, self._samples)
|
|
242
|
-
self._fits(path, image, ifd)
|
|
243
|
-
if image.axes[0] != "z":
|
|
244
|
-
plan = image._plan_series((ys, xs) + extra, dest)
|
|
245
|
-
else:
|
|
246
|
-
plan = image._plan_series((slice(k, k + 1), ys, xs) + extra,
|
|
247
|
-
dest[None])
|
|
248
|
-
plans.append((image, plan))
|
|
249
|
-
return _pool.run(itertools.chain.from_iterable(
|
|
250
|
-
image._tasks(*plan) for image, plan in plans))
|
|
242
|
+
return _engine.run_plans(self._plan_pages(out, ts, cs, zs, ys, xs, extra, entries),
|
|
243
|
+
out)
|
|
251
244
|
finally:
|
|
252
|
-
|
|
253
|
-
|
|
245
|
+
self._release(entries)
|
|
246
|
+
|
|
247
|
+
def _plan_pages(self, out, ts, cs, zs, ys, xs, extra, entries) -> list:
|
|
248
|
+
"""The plans of ``_read_pages``; each member acquired is added to
|
|
249
|
+
*entries* (the caller releases them once the plans have run)."""
|
|
250
|
+
plans = []
|
|
251
|
+
for t in range(*ts):
|
|
252
|
+
for c in range(*cs):
|
|
253
|
+
for z in range(*zs):
|
|
254
|
+
dest = out[t - ts[0], c - cs[0], z - zs[0]]
|
|
255
|
+
member = self._planes.get((t, c, z))
|
|
256
|
+
if member is None: # a missing plane reads as zeros
|
|
257
|
+
dest[...] = 0
|
|
258
|
+
continue
|
|
259
|
+
path, ifd = member
|
|
260
|
+
entry = self._members.acquire(path)
|
|
261
|
+
entries.append(entry)
|
|
262
|
+
image, k = _page(entry[0], ifd, path, self._samples)
|
|
263
|
+
self._fits(path, image, ifd)
|
|
264
|
+
if image.axes[0] != "z":
|
|
265
|
+
plan = image._plan_series((ys, xs) + extra, dest)
|
|
266
|
+
else:
|
|
267
|
+
plan = image._plan_series((slice(k, k + 1), ys, xs) + extra,
|
|
268
|
+
dest[None])
|
|
269
|
+
plans.append((image, plan))
|
|
270
|
+
return plans
|
|
254
271
|
|
|
255
272
|
def _fits(self, path: str, image, ifd=None) -> None:
|
|
256
273
|
"""Raise unless member *path* (its first image, or page *ifd*) is one
|