napari-zenapi-streaming 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- napari_zen_streaming/ZEN_config.py +268 -0
- napari_zen_streaming/ZEN_init.py +359 -0
- napari_zen_streaming/ZEN_omezarr.py +909 -0
- napari_zen_streaming/ZEN_pipeline.py +477 -0
- napari_zen_streaming/ZEN_stream2omezarr.py +2326 -0
- napari_zen_streaming/ZEN_ui.py +2991 -0
- napari_zen_streaming/ZEN_utils.py +170 -0
- napari_zen_streaming/__init__.py +5 -0
- napari_zen_streaming/_logging.py +100 -0
- napari_zen_streaming/_scene_geometry.py +202 -0
- napari_zen_streaming/_tests/__init__.py +0 -0
- napari_zen_streaming/_tests/test_config.py +139 -0
- napari_zen_streaming/_tests/test_display_completion.py +62 -0
- napari_zen_streaming/_tests/test_experiment_stream_filter.py +140 -0
- napari_zen_streaming/_tests/test_experiment_xml.py +220 -0
- napari_zen_streaming/_tests/test_hcs_ui_option.py +189 -0
- napari_zen_streaming/_tests/test_initial_experiment_selection.py +589 -0
- napari_zen_streaming/_tests/test_live_preview.py +287 -0
- napari_zen_streaming/_tests/test_logging.py +68 -0
- napari_zen_streaming/_tests/test_progress_reporting.py +178 -0
- napari_zen_streaming/_tests/test_runtime_pixel_type.py +105 -0
- napari_zen_streaming/_tests/test_scene_geometry.py +97 -0
- napari_zen_streaming/_tests/test_scene_mosaic.py +660 -0
- napari_zen_streaming/_widget.py +126 -0
- napari_zen_streaming/main.py +236 -0
- napari_zen_streaming/misc.py +65 -0
- napari_zen_streaming/napari.yaml +10 -0
- napari_zenapi_streaming-0.0.1.dist-info/METADATA +884 -0
- napari_zenapi_streaming-0.0.1.dist-info/RECORD +33 -0
- napari_zenapi_streaming-0.0.1.dist-info/WHEEL +5 -0
- napari_zenapi_streaming-0.0.1.dist-info/entry_points.txt +2 -0
- napari_zenapi_streaming-0.0.1.dist-info/licenses/LICENSE +27 -0
- napari_zenapi_streaming-0.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,909 @@
|
|
|
1
|
+
#################################################################
|
|
2
|
+
# File : zen_omezarr.py
|
|
3
|
+
# Author : SRh
|
|
4
|
+
# Institution : Carl Zeiss Microscopy GmbH
|
|
5
|
+
#
|
|
6
|
+
# Utility functions for the ZEN-API OME-ZARR streaming workflow:
|
|
7
|
+
# - ExperimentConfig dataclass & INI parser
|
|
8
|
+
# - start_experiment() helper (ZEN-API experiment control)
|
|
9
|
+
# - build_progress_bar() for console progress display
|
|
10
|
+
# - open_in_ndv_viewer() / open_in_napari_viewer() for viewing
|
|
11
|
+
# - read_omezarr_axis_names() for OME-ZARR 0.5 metadata
|
|
12
|
+
#
|
|
13
|
+
# Copyright(c) 2026 Carl Zeiss AG, Germany. All Rights Reserved.
|
|
14
|
+
#
|
|
15
|
+
# Permission is granted to use, modify and distribute this code,
|
|
16
|
+
# as long as this copyright notice remains part of the code.
|
|
17
|
+
#################################################################
|
|
18
|
+
|
|
19
|
+
import configparser
|
|
20
|
+
import json
|
|
21
|
+
import logging
|
|
22
|
+
import re
|
|
23
|
+
import xml.etree.ElementTree as ET
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import TYPE_CHECKING, Any
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
import napari
|
|
30
|
+
|
|
31
|
+
# ZEN API auto-generated stubs
|
|
32
|
+
from zen_api.acquisition.v1beta import (
|
|
33
|
+
ExperimentServiceExportRequest,
|
|
34
|
+
ExperimentServiceGetImageOutputPathRequest,
|
|
35
|
+
ExperimentServiceLoadRequest,
|
|
36
|
+
ExperimentServiceStartExperimentRequest,
|
|
37
|
+
ExperimentServiceStub,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
from napari_zen_streaming.misc import initialize_zenapi
|
|
41
|
+
from napari_zen_streaming.ZEN_config import resolve_gateway_config
|
|
42
|
+
|
|
43
|
+
logger = logging.getLogger(__name__)
|
|
44
|
+
|
|
45
|
+
# Plugin-only OME-ZARR defaults. Change these constants to alter plugin
|
|
46
|
+
# behavior that is intentionally not exposed as a UI setting. The standalone
|
|
47
|
+
# CLI continues to read the corresponding values from its experiment INI.
|
|
48
|
+
PLUGIN_DEFAULT_CZI_NAME = "zenapi_stream"
|
|
49
|
+
PLUGIN_DEFAULT_OVERWRITE_CZI = True
|
|
50
|
+
PLUGIN_DEFAULT_OVERWRITE_ZARR = True
|
|
51
|
+
PLUGIN_DEFAULT_SPATIAL_SHARD_SIZE_CHUNKS = 2
|
|
52
|
+
PLUGIN_DEFAULT_PYRAMID_LEVELS = 0
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class ExperimentConfig:
|
|
57
|
+
"""Parsed experiment configuration."""
|
|
58
|
+
|
|
59
|
+
experiment_name: str
|
|
60
|
+
czi_name: str
|
|
61
|
+
start_from_script: bool
|
|
62
|
+
overwrite_czi: bool
|
|
63
|
+
# dimensions
|
|
64
|
+
time_points: int
|
|
65
|
+
channels: int
|
|
66
|
+
z_planes: int
|
|
67
|
+
z_spacing: float
|
|
68
|
+
tiles: int
|
|
69
|
+
scenes: int
|
|
70
|
+
# output
|
|
71
|
+
output_dir: str
|
|
72
|
+
dtype: str
|
|
73
|
+
compression: str | None
|
|
74
|
+
overwrite_zarr: bool
|
|
75
|
+
# stream
|
|
76
|
+
channel_index: int | None
|
|
77
|
+
# zenapi
|
|
78
|
+
zenapi_config: str
|
|
79
|
+
# OME-ZARR layout
|
|
80
|
+
positions: list[dict[str, object]] = field(default_factory=list)
|
|
81
|
+
use_hcs_layout: bool = True
|
|
82
|
+
keep_source_tiles: bool = False
|
|
83
|
+
spatial_shard_size_chunks: int | None = 2
|
|
84
|
+
max_pending_frames: int = 4096
|
|
85
|
+
pyramid_levels: int = 0
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def create_plugin_experiment_config(
|
|
89
|
+
experiment_name: str,
|
|
90
|
+
output_dir: str,
|
|
91
|
+
dtype: str,
|
|
92
|
+
compression: str | None,
|
|
93
|
+
zenapi_config: str | Path,
|
|
94
|
+
start_from_script: bool,
|
|
95
|
+
use_hcs_layout: bool,
|
|
96
|
+
keep_source_tiles: bool,
|
|
97
|
+
pyramid_levels: int = PLUGIN_DEFAULT_PYRAMID_LEVELS,
|
|
98
|
+
) -> ExperimentConfig:
|
|
99
|
+
"""Create the plugin configuration without an experiment INI.
|
|
100
|
+
|
|
101
|
+
Acquisition dimensions and positions are placeholders replaced by the
|
|
102
|
+
selected ZEN experiment metadata before streaming starts.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
experiment_name: Selected ZEN experiment name.
|
|
106
|
+
output_dir: Destination directory selected in the plugin.
|
|
107
|
+
dtype: Compatibility fallback. The writer uses runtime PixelType.
|
|
108
|
+
compression: OME-ZARR compression selected in the plugin.
|
|
109
|
+
zenapi_config: Main ZEN API gateway configuration path.
|
|
110
|
+
start_from_script: Whether the plugin triggers the experiment.
|
|
111
|
+
use_hcs_layout: Whether explicit wells use an HCS plate layout.
|
|
112
|
+
keep_source_tiles: Keep generic raw tile groups after mosaicking.
|
|
113
|
+
pyramid_levels: Number of post-acquisition 2x Y/X pyramid levels.
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
Plugin OME-ZARR configuration with fixed advanced defaults.
|
|
117
|
+
"""
|
|
118
|
+
return ExperimentConfig(
|
|
119
|
+
experiment_name=experiment_name,
|
|
120
|
+
czi_name=PLUGIN_DEFAULT_CZI_NAME,
|
|
121
|
+
start_from_script=start_from_script,
|
|
122
|
+
overwrite_czi=PLUGIN_DEFAULT_OVERWRITE_CZI,
|
|
123
|
+
time_points=1,
|
|
124
|
+
channels=1,
|
|
125
|
+
z_planes=1,
|
|
126
|
+
z_spacing=1.0,
|
|
127
|
+
tiles=1,
|
|
128
|
+
scenes=1,
|
|
129
|
+
output_dir=output_dir,
|
|
130
|
+
dtype=dtype,
|
|
131
|
+
compression=compression,
|
|
132
|
+
overwrite_zarr=PLUGIN_DEFAULT_OVERWRITE_ZARR,
|
|
133
|
+
channel_index=None,
|
|
134
|
+
zenapi_config=str(zenapi_config),
|
|
135
|
+
use_hcs_layout=use_hcs_layout,
|
|
136
|
+
keep_source_tiles=keep_source_tiles,
|
|
137
|
+
spatial_shard_size_chunks=(PLUGIN_DEFAULT_SPATIAL_SHARD_SIZE_CHUNKS),
|
|
138
|
+
pyramid_levels=pyramid_levels,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@dataclass(frozen=True)
|
|
143
|
+
class ExperimentAcquisitionMetadata:
|
|
144
|
+
"""Acquisition dimensions and positions exported from a ZEN experiment."""
|
|
145
|
+
|
|
146
|
+
experiment_name: str
|
|
147
|
+
time_points: int
|
|
148
|
+
channels: int
|
|
149
|
+
z_planes: int
|
|
150
|
+
z_spacing: float
|
|
151
|
+
tiles: int
|
|
152
|
+
scenes: int
|
|
153
|
+
positions: tuple[dict[str, object], ...] = ()
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _xml_is_active(element: ET.Element | None, default: bool = True) -> bool:
|
|
157
|
+
"""Return whether an XML element is active according to ZEN metadata."""
|
|
158
|
+
if element is None:
|
|
159
|
+
return default
|
|
160
|
+
value = element.get("IsActivated")
|
|
161
|
+
return default if value is None else value.lower() == "true"
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _xml_text(
|
|
165
|
+
element: ET.Element | None,
|
|
166
|
+
path: str,
|
|
167
|
+
default: str | None = None,
|
|
168
|
+
) -> str | None:
|
|
169
|
+
"""Read non-empty text from a relative XML child path."""
|
|
170
|
+
if element is None:
|
|
171
|
+
return default
|
|
172
|
+
child = element.find(path)
|
|
173
|
+
if child is None or child.text is None or not child.text.strip():
|
|
174
|
+
return default
|
|
175
|
+
return child.text.strip()
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _xml_float(element: ET.Element | None, path: str) -> float | None:
|
|
179
|
+
"""Read a floating-point value from a relative XML child path."""
|
|
180
|
+
value = _xml_text(element, path)
|
|
181
|
+
try:
|
|
182
|
+
return float(value) if value is not None else None
|
|
183
|
+
except ValueError:
|
|
184
|
+
return None
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _xml_int(
|
|
188
|
+
element: ET.Element | None,
|
|
189
|
+
path: str,
|
|
190
|
+
default: int = 1,
|
|
191
|
+
) -> int:
|
|
192
|
+
"""Read an integer value from a relative XML child path."""
|
|
193
|
+
value = _xml_text(element, path)
|
|
194
|
+
try:
|
|
195
|
+
return int(value) if value is not None else default
|
|
196
|
+
except ValueError:
|
|
197
|
+
return default
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _find_active_dimension_setup(
|
|
201
|
+
block: ET.Element,
|
|
202
|
+
setup_name: str,
|
|
203
|
+
) -> ET.Element | None:
|
|
204
|
+
"""Find an active nested ZEN dimension setup."""
|
|
205
|
+
|
|
206
|
+
def find_in(container: ET.Element | None) -> ET.Element | None:
|
|
207
|
+
if container is None:
|
|
208
|
+
return None
|
|
209
|
+
for setup in container:
|
|
210
|
+
if not _xml_is_active(setup, default=False):
|
|
211
|
+
continue
|
|
212
|
+
if setup.tag == setup_name:
|
|
213
|
+
return setup
|
|
214
|
+
nested = setup.find("./SubDimensionSetups")
|
|
215
|
+
match = find_in(nested)
|
|
216
|
+
if match is not None:
|
|
217
|
+
return match
|
|
218
|
+
return None
|
|
219
|
+
|
|
220
|
+
return find_in(block.find("./SubDimensionSetups"))
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _parse_well_id(well_id: str) -> tuple[int | None, int | None]:
|
|
224
|
+
"""Convert a ZEN well name such as ``B03`` to one-based row/column."""
|
|
225
|
+
match = re.fullmatch(r"([A-Za-z]+)(\d+)", well_id)
|
|
226
|
+
if match is None:
|
|
227
|
+
return None, None
|
|
228
|
+
row = 0
|
|
229
|
+
for letter in match.group(1).upper():
|
|
230
|
+
row = row * 26 + ord(letter) - ord("A") + 1
|
|
231
|
+
return row, int(match.group(2))
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _xml_pair(
|
|
235
|
+
element: ET.Element,
|
|
236
|
+
path: str,
|
|
237
|
+
) -> tuple[float, float] | None:
|
|
238
|
+
"""Parse a comma-separated XML coordinate pair."""
|
|
239
|
+
value = _xml_text(element, path)
|
|
240
|
+
if value is None:
|
|
241
|
+
return None
|
|
242
|
+
try:
|
|
243
|
+
first, second = value.split(",", maxsplit=1)
|
|
244
|
+
return float(first), float(second)
|
|
245
|
+
except ValueError:
|
|
246
|
+
return None
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _well_id(row: int, column: int) -> str:
|
|
250
|
+
"""Return an Excel-style well identifier for one-based indices."""
|
|
251
|
+
letters = ""
|
|
252
|
+
value = row
|
|
253
|
+
while value > 0:
|
|
254
|
+
value, remainder = divmod(value - 1, 26)
|
|
255
|
+
letters = chr(ord("A") + remainder) + letters
|
|
256
|
+
return f"{letters}{column}"
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _tile_region_well(
|
|
260
|
+
region: ET.Element,
|
|
261
|
+
) -> tuple[int | None, int | None]:
|
|
262
|
+
"""Read an explicit well coordinate from one ZEN tile region."""
|
|
263
|
+
template_id = _xml_text(region, "TemplateShapeId", "") or ""
|
|
264
|
+
match = re.fullmatch(r"(\d+)-(\d+)", template_id)
|
|
265
|
+
if match is not None:
|
|
266
|
+
return int(match.group(1)), int(match.group(2))
|
|
267
|
+
return _parse_well_id(region.get("Name", ""))
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _extract_tile_region_positions(
|
|
271
|
+
sample_holder: ET.Element,
|
|
272
|
+
) -> tuple[dict[str, object], ...]:
|
|
273
|
+
"""Map active tile regions carrying explicit ZEN well identifiers."""
|
|
274
|
+
regions = [
|
|
275
|
+
region
|
|
276
|
+
for region in sample_holder.findall("./TileRegions/TileRegion")
|
|
277
|
+
if _xml_text(region, "IsUsedForAcquisition", "true") == "true"
|
|
278
|
+
]
|
|
279
|
+
if not regions:
|
|
280
|
+
return ()
|
|
281
|
+
|
|
282
|
+
field_counts: dict[tuple[int, int], int] = {}
|
|
283
|
+
positions: list[dict[str, object]] = []
|
|
284
|
+
for scene_index, region in enumerate(regions):
|
|
285
|
+
row, column = _tile_region_well(region)
|
|
286
|
+
center = _xml_pair(region, "CenterPosition")
|
|
287
|
+
if row is None or column is None:
|
|
288
|
+
return ()
|
|
289
|
+
|
|
290
|
+
well_key = (row, column)
|
|
291
|
+
field_counts[well_key] = field_counts.get(well_key, 0) + 1
|
|
292
|
+
positions.append(
|
|
293
|
+
{
|
|
294
|
+
"scene_index": scene_index,
|
|
295
|
+
"well_id": _well_id(row, column),
|
|
296
|
+
"well_row": row,
|
|
297
|
+
"well_column": column,
|
|
298
|
+
"field_index": field_counts[well_key],
|
|
299
|
+
"position_name": region.get("Name"),
|
|
300
|
+
"stage_position": {
|
|
301
|
+
"x": center[0] if center is not None else None,
|
|
302
|
+
"y": center[1] if center is not None else None,
|
|
303
|
+
"z": _xml_float(region, "Z"),
|
|
304
|
+
},
|
|
305
|
+
}
|
|
306
|
+
)
|
|
307
|
+
return tuple(positions)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _extract_xml_positions(block: ET.Element) -> tuple[dict[str, object], ...]:
|
|
311
|
+
"""Extract active sample-holder positions for optional HCS metadata."""
|
|
312
|
+
regions_setup = _find_active_dimension_setup(block, "RegionsSetup")
|
|
313
|
+
sample_holder = (
|
|
314
|
+
regions_setup.find("./SampleHolder")
|
|
315
|
+
if regions_setup is not None
|
|
316
|
+
else None
|
|
317
|
+
)
|
|
318
|
+
arrays = (
|
|
319
|
+
sample_holder.findall("./SingleTileRegionArrays/SingleTileRegionArray")
|
|
320
|
+
if sample_holder is not None
|
|
321
|
+
else []
|
|
322
|
+
)
|
|
323
|
+
positions: list[dict[str, object]] = []
|
|
324
|
+
scene_index = 0
|
|
325
|
+
for well in arrays:
|
|
326
|
+
if (
|
|
327
|
+
not _xml_is_active(well)
|
|
328
|
+
or _xml_text(well, "IsUsedForAcquisition", "true") != "true"
|
|
329
|
+
):
|
|
330
|
+
continue
|
|
331
|
+
well_id = well.get("Name", "")
|
|
332
|
+
row, column = _parse_well_id(well_id)
|
|
333
|
+
field_index = 0
|
|
334
|
+
for position in well.findall("./SingleTileRegions/SingleTileRegion"):
|
|
335
|
+
if _xml_text(position, "IsUsedForAcquisition", "true") != "true":
|
|
336
|
+
continue
|
|
337
|
+
field_index += 1
|
|
338
|
+
positions.append(
|
|
339
|
+
{
|
|
340
|
+
"scene_index": scene_index,
|
|
341
|
+
"well_id": well_id,
|
|
342
|
+
"well_row": row,
|
|
343
|
+
"well_column": column,
|
|
344
|
+
"field_index": field_index,
|
|
345
|
+
"position_name": position.get("Name"),
|
|
346
|
+
"stage_position": {
|
|
347
|
+
"x": _xml_float(position, "X"),
|
|
348
|
+
"y": _xml_float(position, "Y"),
|
|
349
|
+
"z": _xml_float(position, "Z"),
|
|
350
|
+
},
|
|
351
|
+
}
|
|
352
|
+
)
|
|
353
|
+
scene_index += 1
|
|
354
|
+
if positions:
|
|
355
|
+
return tuple(positions)
|
|
356
|
+
if sample_holder is None:
|
|
357
|
+
return ()
|
|
358
|
+
return _extract_tile_region_positions(sample_holder)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _parse_xml_tile_layout(block: ET.Element) -> tuple[int, int]:
|
|
362
|
+
"""Read per-scene M tiles from active ZEN ``TileRegion`` grids."""
|
|
363
|
+
regions_setup = _find_active_dimension_setup(block, "RegionsSetup")
|
|
364
|
+
sample_holder = (
|
|
365
|
+
regions_setup.find("./SampleHolder")
|
|
366
|
+
if regions_setup is not None
|
|
367
|
+
else None
|
|
368
|
+
)
|
|
369
|
+
if sample_holder is None:
|
|
370
|
+
return 1, 1
|
|
371
|
+
|
|
372
|
+
tile_regions = sample_holder.findall("./TileRegions/TileRegion")
|
|
373
|
+
active_regions = [
|
|
374
|
+
region
|
|
375
|
+
for region in tile_regions
|
|
376
|
+
if _xml_text(region, "IsUsedForAcquisition", "true") == "true"
|
|
377
|
+
]
|
|
378
|
+
if not active_regions:
|
|
379
|
+
return 1, 1
|
|
380
|
+
|
|
381
|
+
tile_counts: list[int] = []
|
|
382
|
+
for region in active_regions:
|
|
383
|
+
columns = max(1, _xml_int(region, "Columns"))
|
|
384
|
+
rows = max(1, _xml_int(region, "Rows"))
|
|
385
|
+
tile_counts.append(columns * rows)
|
|
386
|
+
return max(tile_counts), len(tile_counts)
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def parse_experiment_xml(
|
|
390
|
+
xml: str,
|
|
391
|
+
experiment_name: str = "<experiment-export>",
|
|
392
|
+
) -> ExperimentAcquisitionMetadata:
|
|
393
|
+
"""Parse acquisition dimensions from a ZEN ``.czexp`` XML document."""
|
|
394
|
+
root = ET.fromstring(xml)
|
|
395
|
+
blocks = root.findall("./ExperimentBlocks/AcquisitionBlock")
|
|
396
|
+
active_blocks = [block for block in blocks if _xml_is_active(block)]
|
|
397
|
+
if not active_blocks:
|
|
398
|
+
raise ValueError(
|
|
399
|
+
"The experiment contains no active acquisition blocks."
|
|
400
|
+
)
|
|
401
|
+
block = active_blocks[0]
|
|
402
|
+
|
|
403
|
+
time_setup = _find_active_dimension_setup(block, "TimeSeriesSetup")
|
|
404
|
+
time_points = max(1, _xml_int(time_setup, "Duration/Cycles"))
|
|
405
|
+
|
|
406
|
+
channels = sum(
|
|
407
|
+
1
|
|
408
|
+
for track in block.findall(".//MultiTrackSetup/Track")
|
|
409
|
+
if _xml_is_active(track)
|
|
410
|
+
for channel in track.findall("./Channels/Channel")
|
|
411
|
+
if _xml_is_active(channel)
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
z_setup = _find_active_dimension_setup(block, "ZStackSetup")
|
|
415
|
+
first = _xml_float(z_setup, "First/Distance/Value")
|
|
416
|
+
last = _xml_float(z_setup, "Last/Distance/Value")
|
|
417
|
+
interval = _xml_float(z_setup, "Interval/Distance/Value")
|
|
418
|
+
if first is not None and last is not None and interval:
|
|
419
|
+
z_planes = max(1, round(abs(last - first) / abs(interval)) + 1)
|
|
420
|
+
z_spacing = abs(interval) * 1e6
|
|
421
|
+
else:
|
|
422
|
+
z_planes = 1
|
|
423
|
+
z_spacing = 1.0
|
|
424
|
+
|
|
425
|
+
positions = _extract_xml_positions(block)
|
|
426
|
+
tiles, tile_scenes = _parse_xml_tile_layout(block)
|
|
427
|
+
scenes = max(1, len(positions)) if positions else tile_scenes
|
|
428
|
+
return ExperimentAcquisitionMetadata(
|
|
429
|
+
experiment_name=experiment_name,
|
|
430
|
+
time_points=time_points,
|
|
431
|
+
channels=max(1, channels),
|
|
432
|
+
z_planes=z_planes,
|
|
433
|
+
z_spacing=z_spacing,
|
|
434
|
+
tiles=tiles,
|
|
435
|
+
scenes=scenes,
|
|
436
|
+
positions=positions,
|
|
437
|
+
)
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def parse_experiment_file(
|
|
441
|
+
path: str | Path,
|
|
442
|
+
) -> ExperimentAcquisitionMetadata:
|
|
443
|
+
"""Parse acquisition metadata from a persisted ZEN experiment file."""
|
|
444
|
+
source = Path(path)
|
|
445
|
+
return parse_experiment_xml(
|
|
446
|
+
source.read_text(encoding="utf-8"),
|
|
447
|
+
experiment_name=source.stem,
|
|
448
|
+
)
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
async def load_experiment_acquisition(
|
|
452
|
+
experiment_service: Any,
|
|
453
|
+
experiment_name: str,
|
|
454
|
+
) -> ExperimentAcquisitionMetadata:
|
|
455
|
+
"""Load and export a ZEN experiment, then parse its acquisition XML."""
|
|
456
|
+
loaded = await experiment_service.load(
|
|
457
|
+
ExperimentServiceLoadRequest(experiment_name=experiment_name)
|
|
458
|
+
)
|
|
459
|
+
exported = await experiment_service.export(
|
|
460
|
+
ExperimentServiceExportRequest(experiment_id=loaded.experiment_id)
|
|
461
|
+
)
|
|
462
|
+
xml = getattr(exported, "xml", None)
|
|
463
|
+
if not isinstance(xml, str) or not xml.strip():
|
|
464
|
+
raise ValueError("ZEN returned an empty experiment XML export.")
|
|
465
|
+
return parse_experiment_xml(xml, experiment_name=experiment_name)
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def load_experiment_config(config_path: str | Path) -> ExperimentConfig:
|
|
469
|
+
"""Load experiment configuration from an INI file.
|
|
470
|
+
|
|
471
|
+
Args:
|
|
472
|
+
config_path: Path to the experiment config INI file.
|
|
473
|
+
|
|
474
|
+
Returns:
|
|
475
|
+
Populated ExperimentConfig dataclass.
|
|
476
|
+
"""
|
|
477
|
+
config_path = Path(config_path).resolve()
|
|
478
|
+
if not config_path.exists():
|
|
479
|
+
raise FileNotFoundError(f"Experiment config not found: {config_path}")
|
|
480
|
+
|
|
481
|
+
cfg = configparser.ConfigParser()
|
|
482
|
+
cfg.read(config_path)
|
|
483
|
+
|
|
484
|
+
zenapi_config = cfg.get("zenapi", "config", fallback="").strip()
|
|
485
|
+
if not zenapi_config:
|
|
486
|
+
zenapi_config = str(resolve_gateway_config())
|
|
487
|
+
|
|
488
|
+
# channel index: empty string means None (all channels)
|
|
489
|
+
ch_idx_raw = cfg.get("stream", "channel_index", fallback="").strip()
|
|
490
|
+
channel_index = int(ch_idx_raw) if ch_idx_raw else None
|
|
491
|
+
|
|
492
|
+
# compression: 'none' string -> None
|
|
493
|
+
compression_raw = cfg.get(
|
|
494
|
+
"output", "compression", fallback="blosc-zstd"
|
|
495
|
+
).strip()
|
|
496
|
+
compression = compression_raw if compression_raw != "none" else None
|
|
497
|
+
|
|
498
|
+
shard_raw = (
|
|
499
|
+
cfg.get("output", "spatial_shard_size_chunks", fallback="2")
|
|
500
|
+
.strip()
|
|
501
|
+
.lower()
|
|
502
|
+
)
|
|
503
|
+
spatial_shard_size_chunks = (
|
|
504
|
+
None if shard_raw in {"", "0", "none"} else int(shard_raw)
|
|
505
|
+
)
|
|
506
|
+
if spatial_shard_size_chunks is not None and spatial_shard_size_chunks < 1:
|
|
507
|
+
raise ValueError(
|
|
508
|
+
"spatial_shard_size_chunks must be a positive integer, 0, or none"
|
|
509
|
+
)
|
|
510
|
+
max_pending_frames = cfg.getint(
|
|
511
|
+
"stream",
|
|
512
|
+
"max_pending_frames",
|
|
513
|
+
fallback=4096,
|
|
514
|
+
)
|
|
515
|
+
if max_pending_frames < 1:
|
|
516
|
+
raise ValueError("max_pending_frames must be a positive integer")
|
|
517
|
+
pyramid_levels = cfg.getint("output", "pyramid_levels", fallback=0)
|
|
518
|
+
if pyramid_levels < 0:
|
|
519
|
+
raise ValueError("pyramid_levels must be non-negative")
|
|
520
|
+
|
|
521
|
+
return ExperimentConfig(
|
|
522
|
+
experiment_name=cfg.get("experiment", "name"),
|
|
523
|
+
czi_name=cfg.get("experiment", "czi_name", fallback="zenapi_stream"),
|
|
524
|
+
start_from_script=cfg.getboolean(
|
|
525
|
+
"experiment", "start_from_script", fallback=False
|
|
526
|
+
),
|
|
527
|
+
overwrite_czi=cfg.getboolean(
|
|
528
|
+
"experiment", "overwrite_czi", fallback=True
|
|
529
|
+
),
|
|
530
|
+
time_points=cfg.getint("dimensions", "time_points", fallback=1),
|
|
531
|
+
channels=cfg.getint("dimensions", "channels", fallback=1),
|
|
532
|
+
z_planes=cfg.getint("dimensions", "z_planes", fallback=1),
|
|
533
|
+
z_spacing=cfg.getfloat("dimensions", "z_spacing", fallback=1.0),
|
|
534
|
+
tiles=cfg.getint("dimensions", "tiles", fallback=1),
|
|
535
|
+
scenes=cfg.getint("dimensions", "scenes", fallback=1),
|
|
536
|
+
output_dir=cfg.get("output", "directory", fallback="."),
|
|
537
|
+
dtype=cfg.get("output", "dtype", fallback="uint16"),
|
|
538
|
+
compression=compression,
|
|
539
|
+
overwrite_zarr=cfg.getboolean("output", "overwrite", fallback=True),
|
|
540
|
+
channel_index=channel_index,
|
|
541
|
+
zenapi_config=zenapi_config,
|
|
542
|
+
use_hcs_layout=cfg.getboolean(
|
|
543
|
+
"output",
|
|
544
|
+
"use_hcs_layout",
|
|
545
|
+
fallback=True,
|
|
546
|
+
),
|
|
547
|
+
keep_source_tiles=cfg.getboolean(
|
|
548
|
+
"output",
|
|
549
|
+
"keep_source_tiles",
|
|
550
|
+
fallback=False,
|
|
551
|
+
),
|
|
552
|
+
spatial_shard_size_chunks=spatial_shard_size_chunks,
|
|
553
|
+
max_pending_frames=max_pending_frames,
|
|
554
|
+
pyramid_levels=pyramid_levels,
|
|
555
|
+
)
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
async def start_experiment(
|
|
559
|
+
exp_name: str,
|
|
560
|
+
czi_name: str,
|
|
561
|
+
overwrite: bool = False,
|
|
562
|
+
zenapi_config: str | Path = "config.ini",
|
|
563
|
+
) -> tuple[str, Path]:
|
|
564
|
+
"""Start a ZEN experiment via the ZEN-API.
|
|
565
|
+
|
|
566
|
+
Args:
|
|
567
|
+
exp_name: Experiment name (without .czexp extension).
|
|
568
|
+
czi_name: Desired CZI output name (without .czi extension).
|
|
569
|
+
overwrite: Allow overwriting an existing CZI.
|
|
570
|
+
zenapi_config: Path to the ZEN-API config file.
|
|
571
|
+
|
|
572
|
+
Returns:
|
|
573
|
+
Tuple of (experiment_id, czi_path).
|
|
574
|
+
"""
|
|
575
|
+
channel, metadata = initialize_zenapi(zenapi_config)
|
|
576
|
+
try:
|
|
577
|
+
exp_service = ExperimentServiceStub(channel=channel, metadata=metadata)
|
|
578
|
+
my_exp = await exp_service.load(
|
|
579
|
+
ExperimentServiceLoadRequest(experiment_name=exp_name)
|
|
580
|
+
)
|
|
581
|
+
logger.info(
|
|
582
|
+
f"Loaded experiment: {exp_name} (id={my_exp.experiment_id})"
|
|
583
|
+
)
|
|
584
|
+
|
|
585
|
+
save_path = await exp_service.get_image_output_path(
|
|
586
|
+
ExperimentServiceGetImageOutputPathRequest()
|
|
587
|
+
)
|
|
588
|
+
czi_path = Path(save_path.image_output_path) / f"{czi_name}.czi"
|
|
589
|
+
logger.info(f"CZI save location: {czi_path}")
|
|
590
|
+
|
|
591
|
+
if czi_path.exists():
|
|
592
|
+
if overwrite:
|
|
593
|
+
czi_path.unlink()
|
|
594
|
+
logger.info(f"Overwrote existing CZI: {czi_path.name}")
|
|
595
|
+
else:
|
|
596
|
+
raise FileExistsError(f"CZI file already exists: {czi_path}")
|
|
597
|
+
|
|
598
|
+
await exp_service.start_experiment(
|
|
599
|
+
ExperimentServiceStartExperimentRequest(
|
|
600
|
+
experiment_id=my_exp.experiment_id,
|
|
601
|
+
output_name=czi_name,
|
|
602
|
+
)
|
|
603
|
+
)
|
|
604
|
+
logger.info("Experiment execution started.")
|
|
605
|
+
return my_exp.experiment_id, czi_path
|
|
606
|
+
finally:
|
|
607
|
+
channel.close()
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def build_progress_bar(
|
|
611
|
+
current: int, total: int | None, width: int = 40
|
|
612
|
+
) -> str:
|
|
613
|
+
"""Render a text progress bar string.
|
|
614
|
+
|
|
615
|
+
Args:
|
|
616
|
+
current: Current frame number (1-based).
|
|
617
|
+
total: Total expected frames, or None if unknown.
|
|
618
|
+
width: Character width of the bar.
|
|
619
|
+
|
|
620
|
+
Returns:
|
|
621
|
+
Formatted progress bar string.
|
|
622
|
+
"""
|
|
623
|
+
if total is not None and total > 0:
|
|
624
|
+
frac = min(current / total, 1.0)
|
|
625
|
+
filled = int(width * frac)
|
|
626
|
+
bar = "█" * filled + "░" * (width - filled)
|
|
627
|
+
return f"\r [{bar}] {current}/{total} frames ({frac * 100:.1f}%)"
|
|
628
|
+
else:
|
|
629
|
+
# unknown total – show a spinner-style counter
|
|
630
|
+
return f"\r Frames written: {current}"
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
def open_in_ndv_viewer(zarr_path: Path) -> None:
|
|
634
|
+
"""Open an OME-ZARR dataset in the ndv viewer.
|
|
635
|
+
|
|
636
|
+
Reads axis names (T, C, Z, Y, X) and per-axis scales from the OME-ZARR
|
|
637
|
+
0.5 metadata stored in ``zarr.json`` and wraps the highest-resolution
|
|
638
|
+
array as a dask-backed ``xr.DataArray`` with physically-spaced
|
|
639
|
+
coordinates so that ndv shows correct proportions (including Z depth)
|
|
640
|
+
and labelled sliders.
|
|
641
|
+
|
|
642
|
+
Requires optional dependencies: ``ndv``, ``zarr``, ``dask``, ``xarray``.
|
|
643
|
+
If any are missing the function logs a warning and returns silently.
|
|
644
|
+
|
|
645
|
+
Args:
|
|
646
|
+
zarr_path: Path to the ``.ome.zarr`` directory.
|
|
647
|
+
"""
|
|
648
|
+
try:
|
|
649
|
+
import dask.array as da
|
|
650
|
+
import ndv
|
|
651
|
+
import numpy as np
|
|
652
|
+
import xarray as xr
|
|
653
|
+
import zarr
|
|
654
|
+
except ImportError as e:
|
|
655
|
+
logger.warning(
|
|
656
|
+
f"Cannot open viewer (missing dependency: {e}). Install with: pip install ndv zarr dask xarray"
|
|
657
|
+
)
|
|
658
|
+
return
|
|
659
|
+
|
|
660
|
+
try:
|
|
661
|
+
logger.info(f"Opening OME-ZARR in ndv viewer: {zarr_path}")
|
|
662
|
+
image_metadata = _read_first_image_metadata(zarr_path)
|
|
663
|
+
if image_metadata is None:
|
|
664
|
+
logger.error("No OME-ZARR multiscale image metadata found.")
|
|
665
|
+
return
|
|
666
|
+
image_path, _ = image_metadata
|
|
667
|
+
zarr_group = zarr.open(str(image_path), mode="r")
|
|
668
|
+
|
|
669
|
+
# OME-ZARR stores the image array under the "0" key (highest resolution).
|
|
670
|
+
# zarr.open() returns Array | Group; subscripting a Group with a string
|
|
671
|
+
# key returns a broad union. We narrow to Array here.
|
|
672
|
+
zarr_arr: zarr.Array = zarr_group["0"] # type: ignore[index,assignment]
|
|
673
|
+
if not hasattr(zarr_arr, "shape"):
|
|
674
|
+
logger.error(
|
|
675
|
+
"Expected a zarr Array at key '0', got: %s",
|
|
676
|
+
type(zarr_arr).__name__,
|
|
677
|
+
)
|
|
678
|
+
return
|
|
679
|
+
logger.info(f"Array shape: {zarr_arr.shape}, dtype: {zarr_arr.dtype}")
|
|
680
|
+
|
|
681
|
+
# Read axis names from OME-ZARR 0.5 metadata (zarr v3: zarr.json).
|
|
682
|
+
# ome-writers 0.3+ stores multiscales under attributes.ome.multiscales
|
|
683
|
+
axis_names = read_omezarr_axis_names(zarr_path)
|
|
684
|
+
axis_scales = read_omezarr_axis_scales(zarr_path)
|
|
685
|
+
|
|
686
|
+
if axis_names and len(axis_names) == len(zarr_arr.shape):
|
|
687
|
+
# Wrap zarr v3 array with dask for lazy chunk-aware loading,
|
|
688
|
+
# then label dimensions via xarray for the ndv viewer.
|
|
689
|
+
# Use physical coordinates (index * scale) so that the viewer
|
|
690
|
+
# renders the correct aspect ratio, especially for Z stacks
|
|
691
|
+
# where the z-spacing typically differs from the XY pixel size.
|
|
692
|
+
dask_arr = da.from_array(zarr_arr, chunks=zarr_arr.chunks) # type: ignore[arg-type]
|
|
693
|
+
coords = {}
|
|
694
|
+
for name, size in zip(axis_names, zarr_arr.shape, strict=True):
|
|
695
|
+
scale = axis_scales.get(name, 1.0) if axis_scales else 1.0
|
|
696
|
+
coords[name] = np.arange(size, dtype=np.float64) * scale
|
|
697
|
+
data = xr.DataArray(dask_arr, dims=axis_names, coords=coords)
|
|
698
|
+
logger.info(f"Viewer data: shape={data.shape}, dims={data.dims}")
|
|
699
|
+
if axis_scales:
|
|
700
|
+
logger.info(f"Applied axis scales: {axis_scales}")
|
|
701
|
+
ndv.imshow(data)
|
|
702
|
+
else:
|
|
703
|
+
logger.warning(
|
|
704
|
+
"Could not read axis names from OME-ZARR metadata, showing without labels."
|
|
705
|
+
)
|
|
706
|
+
ndv.imshow(zarr_arr)
|
|
707
|
+
except Exception as e:
|
|
708
|
+
logger.error(
|
|
709
|
+
f"Failed to open OME-ZARR in ndv viewer: {e}", exc_info=True
|
|
710
|
+
)
|
|
711
|
+
|
|
712
|
+
|
|
713
|
+
def open_in_napari_viewer(
|
|
714
|
+
zarr_path: Path,
|
|
715
|
+
viewer: "napari.Viewer | None" = None,
|
|
716
|
+
) -> None:
|
|
717
|
+
"""Open an OME-ZARR dataset in the napari viewer.
|
|
718
|
+
|
|
719
|
+
Uses the ``napari-ome-zarr`` plugin to read the dataset with full
|
|
720
|
+
OME-ZARR metadata support (channels, scales, axis labels).
|
|
721
|
+
|
|
722
|
+
When *viewer* is ``None`` (standalone mode) a new viewer is created
|
|
723
|
+
and ``napari.run()`` is called to start the Qt event loop. When an
|
|
724
|
+
existing *viewer* is supplied (plugin mode) the dataset is opened
|
|
725
|
+
into that viewer and the caller keeps control of the event loop.
|
|
726
|
+
|
|
727
|
+
Requires optional dependencies: ``napari`` and ``napari-ome-zarr``.
|
|
728
|
+
If any are missing the function logs a warning and returns silently.
|
|
729
|
+
|
|
730
|
+
Args:
|
|
731
|
+
zarr_path: Path to the ``.ome.zarr`` directory.
|
|
732
|
+
viewer: An existing napari ``Viewer`` instance to reuse.
|
|
733
|
+
If ``None``, a new viewer is created.
|
|
734
|
+
"""
|
|
735
|
+
try:
|
|
736
|
+
import napari # noqa: F811
|
|
737
|
+
|
|
738
|
+
except ImportError as e:
|
|
739
|
+
logger.warning(
|
|
740
|
+
f"Cannot open napari viewer (missing dependency: {e}). Install with: pip install napari[all]"
|
|
741
|
+
)
|
|
742
|
+
return
|
|
743
|
+
|
|
744
|
+
try:
|
|
745
|
+
import napari_ome_zarr # noqa: F401
|
|
746
|
+
except ImportError as e:
|
|
747
|
+
logger.warning(
|
|
748
|
+
f"Cannot open napari viewer (missing plugin: {e}). Install with: pip install napari-ome-zarr"
|
|
749
|
+
)
|
|
750
|
+
return
|
|
751
|
+
|
|
752
|
+
standalone = viewer is None
|
|
753
|
+
try:
|
|
754
|
+
logger.info(f"Opening OME-ZARR in napari viewer: {zarr_path}")
|
|
755
|
+
if viewer is None:
|
|
756
|
+
viewer = napari.Viewer()
|
|
757
|
+
viewer.open(str(zarr_path), plugin="napari-ome-zarr")
|
|
758
|
+
logger.info("napari viewer opened successfully.")
|
|
759
|
+
|
|
760
|
+
# Label viewer dimension sliders and layer names with
|
|
761
|
+
# OME-ZARR axis names (e.g. T, C, Z, Y, X).
|
|
762
|
+
axis_names = read_omezarr_axis_names(zarr_path)
|
|
763
|
+
if axis_names:
|
|
764
|
+
viewer.dims.axis_labels = axis_names
|
|
765
|
+
suffix = f" ({','.join(axis_names)})"
|
|
766
|
+
for layer in viewer.layers:
|
|
767
|
+
layer.name = f"{layer.name}{suffix}"
|
|
768
|
+
|
|
769
|
+
if standalone:
|
|
770
|
+
napari.run()
|
|
771
|
+
except Exception as e:
|
|
772
|
+
logger.error(
|
|
773
|
+
f"Failed to open OME-ZARR in napari viewer: {e}",
|
|
774
|
+
exc_info=True,
|
|
775
|
+
)
|
|
776
|
+
raise RuntimeError(
|
|
777
|
+
f"Could not display '{zarr_path.name}' in napari. "
|
|
778
|
+
f"Verify the file is a valid OME-ZARR and that "
|
|
779
|
+
f"napari-ome-zarr is up to date."
|
|
780
|
+
) from e
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
def read_omezarr_axis_names(zarr_path: Path) -> tuple[str, ...] | None:
|
|
784
|
+
"""Read axis names from the first OME-ZARR 0.5 image metadata.
|
|
785
|
+
|
|
786
|
+
OME-ZARR 0.5 (zarr v3) stores the multiscales metadata inside
|
|
787
|
+
``zarr.json → attributes.ome.multiscales``, unlike OME-ZARR 0.4
|
|
788
|
+
which used ``.zattrs``.
|
|
789
|
+
|
|
790
|
+
Args:
|
|
791
|
+
zarr_path: Path to the ``.ome.zarr`` directory.
|
|
792
|
+
|
|
793
|
+
Returns:
|
|
794
|
+
Tuple of uppercase axis names (e.g. ``('T', 'C', 'Z', 'Y', 'X')``),
|
|
795
|
+
or ``None`` if the metadata cannot be read.
|
|
796
|
+
"""
|
|
797
|
+
image_metadata = _read_first_image_metadata(zarr_path)
|
|
798
|
+
if image_metadata is None:
|
|
799
|
+
return None
|
|
800
|
+
|
|
801
|
+
_, root_meta = image_metadata
|
|
802
|
+
|
|
803
|
+
multiscales = (
|
|
804
|
+
root_meta.get("attributes", {}).get("ome", {}).get("multiscales", [])
|
|
805
|
+
)
|
|
806
|
+
if not isinstance(multiscales, list) or not multiscales:
|
|
807
|
+
return None
|
|
808
|
+
first_multiscale = multiscales[0]
|
|
809
|
+
if not isinstance(first_multiscale, dict):
|
|
810
|
+
return None
|
|
811
|
+
axes = first_multiscale.get("axes", [])
|
|
812
|
+
if not axes:
|
|
813
|
+
return None
|
|
814
|
+
|
|
815
|
+
try:
|
|
816
|
+
axis_names = tuple(str(axis["name"]).upper() for axis in axes)
|
|
817
|
+
except (KeyError, TypeError):
|
|
818
|
+
return None
|
|
819
|
+
logger.info(f"OME-ZARR axis names: {axis_names}")
|
|
820
|
+
return axis_names
|
|
821
|
+
|
|
822
|
+
|
|
823
|
+
def read_omezarr_axis_scales(zarr_path: Path) -> dict[str, float] | None:
|
|
824
|
+
"""Read scale factors from the first OME-ZARR 0.5 image metadata.
|
|
825
|
+
|
|
826
|
+
The scale transform is stored in
|
|
827
|
+
``zarr.json → attributes.ome.multiscales[0].datasets[0].coordinateTransformations``
|
|
828
|
+
as a list entry with ``{"type": "scale", "scale": [s0, s1, ...]}``.
|
|
829
|
+
The scale values are ordered to match the axes list.
|
|
830
|
+
|
|
831
|
+
Args:
|
|
832
|
+
zarr_path: Path to the ``.ome.zarr`` directory.
|
|
833
|
+
|
|
834
|
+
Returns:
|
|
835
|
+
Dict mapping uppercase axis name to its scale factor,
|
|
836
|
+
or ``None`` if the metadata cannot be read.
|
|
837
|
+
"""
|
|
838
|
+
image_metadata = _read_first_image_metadata(zarr_path)
|
|
839
|
+
if image_metadata is None:
|
|
840
|
+
return None
|
|
841
|
+
|
|
842
|
+
_, root_meta = image_metadata
|
|
843
|
+
|
|
844
|
+
multiscales = (
|
|
845
|
+
root_meta.get("attributes", {}).get("ome", {}).get("multiscales", [])
|
|
846
|
+
)
|
|
847
|
+
if not isinstance(multiscales, list) or not multiscales:
|
|
848
|
+
return None
|
|
849
|
+
first_multiscale = multiscales[0]
|
|
850
|
+
if not isinstance(first_multiscale, dict):
|
|
851
|
+
return None
|
|
852
|
+
axes = first_multiscale.get("axes", [])
|
|
853
|
+
datasets = first_multiscale.get("datasets", [])
|
|
854
|
+
if not axes or not datasets:
|
|
855
|
+
return None
|
|
856
|
+
|
|
857
|
+
# Find the scale transform for the highest-resolution dataset (index 0)
|
|
858
|
+
transforms = datasets[0].get("coordinateTransformations", [])
|
|
859
|
+
scale_values = None
|
|
860
|
+
for t in transforms:
|
|
861
|
+
if t.get("type") == "scale":
|
|
862
|
+
scale_values = t.get("scale")
|
|
863
|
+
break
|
|
864
|
+
|
|
865
|
+
if scale_values is None or len(scale_values) != len(axes):
|
|
866
|
+
return None
|
|
867
|
+
|
|
868
|
+
try:
|
|
869
|
+
axis_scales = {
|
|
870
|
+
str(axis["name"]).upper(): float(scale)
|
|
871
|
+
for axis, scale in zip(axes, scale_values, strict=True)
|
|
872
|
+
}
|
|
873
|
+
except (KeyError, TypeError, ValueError):
|
|
874
|
+
return None
|
|
875
|
+
logger.info(f"OME-ZARR axis scales: {axis_scales}")
|
|
876
|
+
return axis_scales
|
|
877
|
+
|
|
878
|
+
|
|
879
|
+
def _read_first_image_metadata(
|
|
880
|
+
zarr_path: Path,
|
|
881
|
+
) -> tuple[Path, dict[str, Any]] | None:
|
|
882
|
+
"""Return metadata for the root or first descendant multiscale image."""
|
|
883
|
+
root_metadata = zarr_path / "zarr.json"
|
|
884
|
+
candidates = [root_metadata]
|
|
885
|
+
if zarr_path.exists():
|
|
886
|
+
candidates.extend(
|
|
887
|
+
path
|
|
888
|
+
for path in sorted(zarr_path.rglob("zarr.json"))
|
|
889
|
+
if path != root_metadata
|
|
890
|
+
)
|
|
891
|
+
|
|
892
|
+
for metadata_path in candidates:
|
|
893
|
+
try:
|
|
894
|
+
with metadata_path.open(encoding="utf-8") as metadata_file:
|
|
895
|
+
metadata = json.load(metadata_file)
|
|
896
|
+
except (OSError, json.JSONDecodeError):
|
|
897
|
+
continue
|
|
898
|
+
if not isinstance(metadata, dict):
|
|
899
|
+
continue
|
|
900
|
+
attributes = metadata.get("attributes")
|
|
901
|
+
if not isinstance(attributes, dict):
|
|
902
|
+
continue
|
|
903
|
+
ome = attributes.get("ome")
|
|
904
|
+
if not isinstance(ome, dict):
|
|
905
|
+
continue
|
|
906
|
+
multiscales = ome.get("multiscales")
|
|
907
|
+
if multiscales:
|
|
908
|
+
return metadata_path.parent, metadata
|
|
909
|
+
return None
|