Skip to content

Commit 9e11b56

Browse files
committed
Validate attributes in prepare_label_group and override multiscale name if needed (close #619)
1 parent cb1201f commit 9e11b56

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

fractal_tasks_core/lib_write.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,12 @@
1919

2020
import zarr.hierarchy
2121
from anndata.experimental import write_elem
22+
from pydantic.error_wrappers import ValidationError
2223
from zarr.errors import ContainsGroupError
2324
from zarr.errors import GroupNotFoundError
2425

26+
from .lib_ngff import NgffImageMeta
27+
2528

2629
class OverwriteNotAllowedError(RuntimeError):
2730
pass
@@ -213,7 +216,8 @@ def prepare_label_group(
213216
image_group:
214217
The group to write to.
215218
label_name:
216-
The name of the new label.
219+
The name of the new label; this name also overrides the multiscale
220+
name in NGFF-image Zarr attributes, if needed.
217221
overwrite:
218222
If `False`, check that the new label does not exist (either in zarr
219223
attributes or as a zarr sub-group); if `True` propagate parameter
@@ -270,6 +274,26 @@ def prepare_label_group(
270274

271275
# Optionally update attributes of the new-table zarr group
272276
if label_attrs is not None:
277+
# Validate attrs against NGFF specs 0.4
278+
try:
279+
meta = NgffImageMeta(**label_attrs)
280+
except ValidationError as e:
281+
error_msg = (
282+
"Label attributes do not comply with NGFF image "
283+
"specifications, as encoded in fractal-tasks-core.\n"
284+
f"Original error:\nValidationError: {str(e)}"
285+
)
286+
logger.error(error_msg)
287+
raise ValueError(error_msg)
288+
# Replace multiscale name with label_name, if needed
289+
current_multiscale_name = meta.multiscale.name
290+
if current_multiscale_name != label_name:
291+
logger.warning(
292+
f"Setting multiscale name to '{label_name}' (old value: "
293+
f"'{current_multiscale_name}') in label-image NGFF "
294+
"attributes."
295+
)
296+
label_attrs["multiscales"][0]["name"] = label_name
273297
# Overwrite label_group attributes with label_attrs key/value pairs
274298
label_group.attrs.put(label_attrs)
275299

0 commit comments

Comments
 (0)