-
Notifications
You must be signed in to change notification settings - Fork 89
restore option to compress raster #944
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+225
−8
Merged
Changes from 14 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
99acf82
replace asserts by proper errors
melonora 11d5249
correct for labels
melonora acda400
add compressor
melonora 977d0a9
add comrpessor to write_element
melonora 44761f1
minor corrections
melonora 25388b0
add tests
melonora eac6f3d
add tests
melonora b9be5d2
refactor of write_raster
melonora 93c6270
Merge branch 'main' into restore_storage_options
melonora 0b8d9e4
Merge branch 'main' into restore_storage_options
LucaMarconato ee34d7c
code edits for zarr v3; tests fail
LucaMarconato fac4cbc
Merge branch 'main' into restore_storage_options
LucaMarconato 0710fbf
Fix zarr v3 compression: use native codecs and bump min deps
LucaMarconato d3607f1
bump min dask test in ci
LucaMarconato 50d2623
chore: add request for issue for unsupported compression
melonora cdd4bc5
chore: remove unncessary assert
melonora 14c371c
Merge branch 'main' into restore_storage_options
melonora eea7a7f
refactor: change name of argument to account for other compressors
melonora File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,7 +2,7 @@ | |
|
|
||
| from collections.abc import Sequence | ||
| from pathlib import Path | ||
| from typing import Any, Literal, TypeGuard | ||
| from typing import Any, Literal, TypeGuard, cast | ||
|
|
||
| import dask.array as da | ||
| import numpy as np | ||
|
|
@@ -265,6 +265,7 @@ def _write_raster( | |
| name: str, | ||
| raster_format: RasterFormatType, | ||
| storage_options: JSONDict | list[JSONDict] | None = None, | ||
| compressor: dict[Literal["lz4", "zstd"], int] | None = None, | ||
| label_metadata: JSONDict | None = None, | ||
| **metadata: str | JSONDict | list[JSONDict], | ||
| ) -> None: | ||
|
|
@@ -284,6 +285,8 @@ def _write_raster( | |
| The format used to write the raster data. | ||
| storage_options | ||
| Additional options for writing the raster data, like chunks and compression. | ||
| compressor | ||
| Compression settings as a len-1 dictionary with a single key-value {compression: compression level} pair | ||
| label_metadata | ||
| Label metadata which can only be defined when writing 'labels'. | ||
| metadata | ||
|
|
@@ -313,6 +316,7 @@ def _write_raster( | |
| raster_data, | ||
| raster_format, | ||
| storage_options, | ||
| compressor=compressor, | ||
| **metadata, | ||
| ) | ||
| elif isinstance(raster_data, DataTree): | ||
|
|
@@ -323,6 +327,7 @@ def _write_raster( | |
| raster_data, | ||
| raster_format, | ||
| storage_options, | ||
| compressor=compressor, | ||
| **metadata, | ||
| ) | ||
| else: | ||
|
|
@@ -337,13 +342,94 @@ def _write_raster( | |
| group.attrs[ATTRS_KEY] = attrs | ||
|
|
||
|
|
||
| def _build_v3_codec( | ||
| compression: Literal["lz4", "zstd"], | ||
| compression_level: int, | ||
| ) -> Any: | ||
| """Return the appropriate zarr v3 codec for the given compression type and level.""" | ||
| if compression == "zstd": | ||
| from zarr.codecs import ZstdCodec | ||
|
|
||
| return ZstdCodec(level=compression_level) | ||
| # lz4: use the native zarr v3 BloscCodec | ||
| from zarr.codecs import BloscCodec | ||
|
|
||
| return BloscCodec(cname="lz4", clevel=compression_level) | ||
|
melonora marked this conversation as resolved.
|
||
|
|
||
|
|
||
| def _apply_compression( | ||
| storage_options: JSONDict | list[JSONDict], | ||
| compressor: dict[Literal["lz4", "zstd"], int] | None, | ||
| zarr_format: Literal[2, 3] = 3, | ||
| ) -> JSONDict | list[JSONDict]: | ||
| """Apply compression settings to storage options. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| storage_options | ||
| Storage options for zarr arrays | ||
| compressor | ||
| Compression settings as a dictionary with a single key-value pair | ||
| zarr_format | ||
| The zarr format version (2 or 3) | ||
|
|
||
| Returns | ||
| ------- | ||
| Updated storage options with compression settings | ||
| """ | ||
| if not compressor: | ||
| return storage_options | ||
|
|
||
| ((compression, compression_level),) = compressor.items() | ||
|
|
||
| if zarr_format == 2: | ||
| from numcodecs import Blosc as BloscV2 | ||
|
|
||
| assert BloscV2.SHUFFLE == 1 | ||
|
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why this assert if you hardcode shuffle to be 1 in any case? |
||
| codec_v2 = BloscV2(cname=compression, clevel=compression_level, shuffle=1) | ||
|
|
||
| def _update_dict(d: dict[str, Any]) -> None: | ||
| d["compressor"] = codec_v2 | ||
|
|
||
| if isinstance(storage_options, dict): | ||
| _update_dict(d=storage_options) | ||
| elif isinstance(storage_options, list): | ||
| for option in storage_options: | ||
| _update_dict(d=option) | ||
| elif storage_options is None: | ||
| return {"compressor": codec_v2} | ||
| else: | ||
| raise ValueError(f"storage_options must be a dict or list, not {type(storage_options)}") | ||
| else: | ||
| # zarr v3: use native codec objects via the "compressors" (plural) key. | ||
| # see https://github.com/ome/ome-zarr-py/blob/v0.16.0/ome_zarr/writer.py#L754 | ||
| # ome-zarr-py ≥ 0.16.0 with dask ≥ 2026.3.0 forwards this key to zarr_array_kwargs. | ||
| codec_v3 = _build_v3_codec(compression, compression_level) | ||
|
|
||
| def _update_dict_v3(d: dict[str, Any]) -> None: | ||
| d["compressors"] = [codec_v3] | ||
|
|
||
| if isinstance(storage_options, dict): | ||
| _update_dict_v3(d=storage_options) | ||
| elif isinstance(storage_options, list): | ||
| for option in storage_options: | ||
| _update_dict_v3(d=option) | ||
| elif storage_options is None: | ||
| return {"compressors": [codec_v3]} | ||
| else: | ||
| raise ValueError(f"storage_options must be a dict or list, not {type(storage_options)}") | ||
|
|
||
| return storage_options | ||
|
|
||
|
|
||
| def _write_raster_dataarray( | ||
| raster_type: Literal["image", "labels"], | ||
| group: zarr.Group, | ||
| element_name: str, | ||
| raster_data: DataArray, | ||
| raster_format: RasterFormatType, | ||
| storage_options: JSONDict | list[JSONDict] | None = None, | ||
| storage_options: JSONDict | list[JSONDict] | None, | ||
| compressor: dict[Literal["lz4", "zstd"], int] | None, | ||
| **metadata: str | JSONDict | list[JSONDict], | ||
| ) -> None: | ||
| """Write raster data of type DataArray to disk. | ||
|
|
@@ -362,6 +448,8 @@ def _write_raster_dataarray( | |
| The format used to write the raster data. | ||
| storage_options | ||
| Additional options for writing the raster data, like chunks and compression. | ||
| compressor | ||
| Compression settings as a len-1 dictionary with a single key-value {compression: compression level} pair | ||
| metadata | ||
| Additional metadata for the raster element | ||
| """ | ||
|
|
@@ -373,6 +461,11 @@ def _write_raster_dataarray( | |
| input_axes: tuple[str, ...] = tuple(raster_data.dims) | ||
| parsed_axes = _get_valid_axes(axes=list(input_axes), fmt=raster_format) | ||
| storage_options = _prepare_storage_options(storage_options) | ||
| # Apply compression if specified | ||
| storage_options = _apply_compression( | ||
| storage_options, compressor, zarr_format=cast(Literal[2, 3], raster_format.zarr_format) | ||
| ) | ||
|
|
||
| # Explicitly disable pyramid generation for single-scale rasters. Recent ome-zarr versions default | ||
| # write_image()/write_labels() to scale_factors=(2, 4, 8, 16), which would otherwise write s0, s1, ... | ||
| # even when the input is a plain DataArray. | ||
|
|
@@ -406,7 +499,8 @@ def _write_raster_datatree( | |
| element_name: str, | ||
| raster_data: DataTree, | ||
| raster_format: RasterFormatType, | ||
| storage_options: JSONDict | list[JSONDict] | None = None, | ||
| storage_options: JSONDict | list[JSONDict] | None, | ||
| compressor: dict[Literal["lz4", "zstd"], int] | None, | ||
| **metadata: str | JSONDict | list[JSONDict], | ||
| ) -> zarr.Group: | ||
| """Write raster data of type DataTree to disk. | ||
|
|
@@ -425,6 +519,8 @@ def _write_raster_datatree( | |
| The format used to write the raster data. | ||
| storage_options | ||
| Additional options for writing the raster data, like chunks and compression. | ||
| compressor | ||
| Compression settings as a len-1 dictionary with a single key-value {compression: compression level} pair | ||
| metadata | ||
| Additional metadata for the raster element | ||
| """ | ||
|
|
@@ -442,6 +538,10 @@ def _write_raster_datatree( | |
|
|
||
| parsed_axes = _get_valid_axes(axes=list(input_axes), fmt=raster_format) | ||
| storage_options = _prepare_storage_options(storage_options) | ||
|
|
||
| # Apply compression if specified | ||
| storage_options = _apply_compression(storage_options, compressor, zarr_format=raster_format.zarr_format) | ||
|
|
||
| ome_zarr_format = get_ome_zarr_format(raster_format) | ||
| dask_delayed = write_multi_scale_ngff( | ||
| pyramid=data, | ||
|
|
@@ -483,6 +583,7 @@ def write_image( | |
| name: str, | ||
| element_format: RasterFormatType = CurrentRasterFormat(), | ||
| storage_options: JSONDict | list[JSONDict] | None = None, | ||
| compressor: dict[Literal["lz4", "zstd"], int] | None = None, | ||
| **metadata: str | JSONDict | list[JSONDict], | ||
| ) -> None: | ||
| _write_raster( | ||
|
|
@@ -492,6 +593,7 @@ def write_image( | |
| name=name, | ||
| raster_format=element_format, | ||
| storage_options=storage_options, | ||
| compressor=compressor, | ||
| **metadata, | ||
| ) | ||
|
|
||
|
|
@@ -503,6 +605,7 @@ def write_labels( | |
| element_format: RasterFormatType = CurrentRasterFormat(), | ||
| storage_options: JSONDict | list[JSONDict] | None = None, | ||
| label_metadata: JSONDict | None = None, | ||
| compressor: dict[Literal["lz4", "zstd"], int] | None = None, | ||
| **metadata: JSONDict, | ||
| ) -> None: | ||
| _write_raster( | ||
|
|
@@ -512,6 +615,7 @@ def write_labels( | |
| name=name, | ||
| raster_format=element_format, | ||
| storage_options=storage_options, | ||
| compressor=compressor, | ||
| label_metadata=label_metadata, | ||
| **metadata, | ||
| ) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.