micro-reader 0.4.5__tar.gz → 0.5.1__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.
Files changed (76) hide show
  1. {micro_reader-0.4.5 → micro_reader-0.5.1}/.gitignore +1 -0
  2. {micro_reader-0.4.5 → micro_reader-0.5.1}/PKG-INFO +6 -5
  3. {micro_reader-0.4.5 → micro_reader-0.5.1}/README.md +4 -4
  4. {micro_reader-0.4.5 → micro_reader-0.5.1}/pyproject.toml +3 -2
  5. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/__init__.py +2 -1
  6. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_axes.py +57 -0
  7. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_base.py +72 -10
  8. micro_reader-0.5.1/src/micro_reader/_engine.py +255 -0
  9. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_fileset.py +43 -26
  10. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_io.py +73 -7
  11. micro_reader-0.5.1/src/micro_reader/_many.py +92 -0
  12. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_outline.py +21 -1
  13. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_registry.py +12 -6
  14. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_version.py +1 -1
  15. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/_nd2_legacy.py +10 -0
  16. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/bdv.py +49 -27
  17. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/companion.py +23 -11
  18. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/czi.py +117 -1
  19. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/dv.py +2 -0
  20. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/ics.py +5 -0
  21. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/lif.py +10 -0
  22. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/metamorph.py +39 -24
  23. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/mrc.py +2 -0
  24. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/nd2.py +91 -2
  25. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/omp2info.py +5 -0
  26. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/tiff.py +130 -14
  27. {micro_reader-0.4.5 → micro_reader-0.5.1}/LICENSE +0 -0
  28. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_cfb.py +0 -0
  29. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_codecs.py +0 -0
  30. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_errors.py +0 -0
  31. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_eubi_guard.py +0 -0
  32. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_groups.py +0 -0
  33. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_index.py +0 -0
  34. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_jpeg_restarts.py +0 -0
  35. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_lambda.py +0 -0
  36. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_memory.py +0 -0
  37. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_metadata.py +0 -0
  38. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_mosaic.py +0 -0
  39. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_naming.py +0 -0
  40. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_parts.py +0 -0
  41. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_plate.py +0 -0
  42. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_pool.py +0 -0
  43. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_spatial.py +0 -0
  44. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_stack.py +0 -0
  45. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/_stream.py +0 -0
  46. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/__init__.py +0 -0
  47. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/_czi_metadata.py +0 -0
  48. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/_ets.py +0 -0
  49. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/_hdf5.py +0 -0
  50. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/_lif_metadata.py +0 -0
  51. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/_nd2_metadata.py +0 -0
  52. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/_nd2_run.py +0 -0
  53. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/_nd2_structure.py +0 -0
  54. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/_tiff_metadata.py +0 -0
  55. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/_tiff_variants.py +0 -0
  56. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/_vsi_tree.py +0 -0
  57. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/cellomics.py +0 -0
  58. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/columbus.py +0 -0
  59. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/cv7000.py +0 -0
  60. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/flex.py +0 -0
  61. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/harmony.py +0 -0
  62. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/hdf5.py +0 -0
  63. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/ilastik.py +0 -0
  64. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/ims.py +0 -0
  65. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/incell.py +0 -0
  66. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/jdce.py +0 -0
  67. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/klb.py +0 -0
  68. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/luxendo.py +0 -0
  69. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/metaxpress.py +0 -0
  70. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/micromanager.py +0 -0
  71. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/ndpis.py +0 -0
  72. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/oif.py +0 -0
  73. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/oir.py +0 -0
  74. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/raster.py +0 -0
  75. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/scanr.py +0 -0
  76. {micro_reader-0.4.5 → micro_reader-0.5.1}/src/micro_reader/backends/vsi.py +0 -0
@@ -10,6 +10,7 @@ dist/
10
10
 
11
11
  # Rust / maturin
12
12
  codecs/target/
13
+ core/target/
13
14
 
14
15
  # editors and OS
15
16
  .vscode/
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: micro-reader
3
- Version: 0.4.5
3
+ Version: 0.5.1
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`, which is installed automatically. Prebuilt wheels are available for Linux (x86-64 and ARM), macOS (Intel and Apple silicon) and Windows (x86-64).
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
 
@@ -166,7 +167,7 @@ len(image.resolutions)
166
167
  overview = image.resolutions[-1].read()
167
168
  ```
168
169
 
169
- 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.
170
171
 
171
172
  ### Example: a high-content screening plate
172
173
 
@@ -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-codecs` are MIT licensed. The codec wheels 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).
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`, which is installed automatically. Prebuilt wheels are available for Linux (x86-64 and ARM), macOS (Intel and Apple silicon) and Windows (x86-64).
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
 
@@ -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
 
@@ -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-codecs` are MIT licensed. The codec wheels 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).
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.4.5"
9
+ version = "0.5.1"
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", "tifffile>=2025.5.21"]
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
@@ -243,6 +295,11 @@ class AxesImage(Image):
243
295
  return AxesImage(self.source, self.axes, samples=self._samples_policy,
244
296
  squeeze=axes or True, _select=dict(self._select))
245
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
+
246
303
  def close(self) -> None:
247
304
  self.source.close()
248
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.pyramid is 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
- """The pyramid this image belongs to: itself at level 0, the
251
- full-resolution image for a lower level."""
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, when one step alone spans more than
323
- fits (``[::16]`` of large planes), only the selected positions, one at a time; the
324
- next axis splits what is still too large. Each piece is read with the backend's own
325
- ``_read_block``. Within a row the columns are read and thinned (a read per pixel
326
- would cost more). Peak: *out* and one piece."""
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)
@@ -380,6 +417,23 @@ class Image:
380
417
  number of pixels actually read or decoded to produce it)."""
381
418
  raise NotImplementedError
382
419
 
420
+ @staticmethod
421
+ def read_many(requests) -> None:
422
+ """``micro_reader.read_many``, here too: libraries that join arrays (dyna's
423
+ concatenation) look for ``read_many`` on their sources' type, and read
424
+ the parts of a join of images in one call."""
425
+ from ._many import read_many
426
+ read_many(requests)
427
+
428
+ def _plan_into(self, block: tuple[slice, ...], out: np.ndarray, stack):
429
+ """The plans that fill *out* (a writable array shaped like *block*) once
430
+ run, ``[(image, plan), ...]`` for ``_engine.run_plans`` (``read_many``);
431
+ None when this image cannot plan a read into a given array, and is read
432
+ with ``_read_block`` and copied instead. *stack*, a
433
+ ``contextlib.ExitStack``, holds what must stay acquired until the plans
434
+ have run (a file set's members)."""
435
+ return None
436
+
383
437
  def close(self) -> None:
384
438
  """Release file handles; the image is unusable afterwards."""
385
439
 
@@ -719,6 +773,14 @@ class File:
719
773
  from ._outline import outline_lines
720
774
  return "\n".join([self._header()] + [" " + line for line in outline_lines(self)])
721
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
+
722
784
  def _header(self) -> str:
723
785
  plates = f" plates={len(self.plates)}" if self.plates else ""
724
786
  return (f"<micro_reader.File {self.path!r} backend={self.backend!r} "
@@ -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)