Skip to content
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

Axes v0.4 #93

Merged
merged 16 commits into from
Jan 31, 2022
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/omero_zarr/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from ._version import version as __version__

ngff_version = "0.3"
ngff_version = "0.4"
will-moore marked this conversation as resolved.
Show resolved Hide resolved

__all__ = [
"__version__",
Expand Down
4 changes: 2 additions & 2 deletions src/omero_zarr/masks.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ def save(self, masks: List[omero.model.Shape], name: str) -> None:
ignored_dimensions,
check_overlaps=True,
)
# For v0.3 ngff we want to reduce the number of dimensions to
# For v0.3+ ngff we want to reduce the number of dimensions to
# match the dims of the Image.
dims_to_squeeze = []
axes = []
Expand All @@ -326,7 +326,7 @@ def save(self, masks: List[omero.model.Shape], name: str) -> None:
image_label_colors: List[JSONDict] = []
label_properties: List[JSONDict] = []
image_label = {
"version": "0.3",
"version": "0.4",
will-moore marked this conversation as resolved.
Show resolved Hide resolved
"colors": image_label_colors,
"properties": label_properties,
"source": {"image": source_image_link},
Expand Down
99 changes: 79 additions & 20 deletions src/omero_zarr/raw_pixels.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,15 @@ def image_to_zarr(image: omero.gateway.ImageWrapper, args: argparse.Namespace) -
print(f"Exporting to {name} ({VERSION})")
store = open_store(name)
root = open_group(store)
n_levels, axes = add_image(image, root, cache_dir=cache_dir)
add_multiscales_metadata(root, axes, n_levels)
add_image(image, root, cache_dir=cache_dir)
add_omero_metadata(root, image)
add_toplevel_metadata(root)
print("Finished.")


def add_image(
image: omero.gateway.ImageWrapper, parent: Group, cache_dir: Optional[str] = None
) -> Tuple[int, List[str]]:
) -> Tuple[int, List[Dict[str, Any]]]:
"""Adds an OMERO image pixel data as array to the given parent zarr group.
Optionally caches the pixel data in the given cache_dir directory.
Returns the number of resolution levels generated for the image.
Expand All @@ -49,6 +48,41 @@ def get_cache_filename(z: int, c: int, t: int) -> str:
size_y = image.getSizeY()
size_t = image.getSizeT()
d_type = image.getPixelsType()
pixel_sizes = {}
pix_size_x = image.getPixelSizeX(units=True)
pix_size_y = image.getPixelSizeY(units=True)
pix_size_z = image.getPixelSizeZ(units=True)
# All OMERO units.lower() are valid UDUNITS-2 and therefore NGFF spec
if pix_size_x is not None:
pixel_sizes["x"] = {
"units": str(pix_size_x.getUnit()).lower(),
"value": pix_size_x.getValue(),
}
if pix_size_y is not None:
pixel_sizes["y"] = {
"units": str(pix_size_y.getUnit()).lower(),
"value": pix_size_y.getValue(),
}
if pix_size_z is not None:
pixel_sizes["z"] = {
"units": str(pix_size_z.getUnit()).lower(),
"value": pix_size_z.getValue(),
}

axes = []
if size_t > 1:
axes.append({"name": "t", "type": "time"})
if size_c > 1:
axes.append({"name": "c", "type": "channel"})
if size_z > 1:
axes.append({"name": "z", "type": "space"})
if pixel_sizes and "z" in pixel_sizes:
axes[-1]["units"] = pixel_sizes["z"]["units"]
# last 2 dimensions are always y and x
for dim in ("y", "x"):
axes.append({"name": dim, "type": "space"})
if pixel_sizes and dim in pixel_sizes:
axes[-1]["units"] = pixel_sizes[dim]["units"]

zct_list = []
for t in range(size_t):
Expand Down Expand Up @@ -79,7 +113,7 @@ def planeGen() -> np.ndarray:
longest = longest // 2
level_count += 1

return add_raw_image(
paths = add_raw_image(
planes=planes,
size_z=size_z,
size_c=size_c,
Expand All @@ -91,6 +125,29 @@ def planeGen() -> np.ndarray:
cache_file_name_func=get_cache_filename,
)

# Each path needs a transformations list...
transformations = []
zooms = {"x": 1, "y": 1, "z": 1}
for path in paths:
# {"type": "scale", "scale": [2.0, 2.0, 2.0], "axisIndices": [2, 3, 4]}
scales = []
axisIndices = []
for index, axis in enumerate(axes):
if axis["name"] in pixel_sizes:
scales.append(zooms[axis["name"]] * pixel_sizes[axis["name"]]["value"])
axisIndices.append(index)
# ...with a single 'scale' transformation each
transformations.append(
[{"type": "scale", "scale": scales, "axisIndices": axisIndices}]
)
# NB we rescale X and Y for each level, but not Z
zooms["x"] = zooms["x"] * 2
zooms["y"] = zooms["y"] * 2

add_multiscales_metadata(parent, axes, paths, transformations)

return (level_count, axes)


def add_raw_image(
*,
Expand All @@ -103,7 +160,7 @@ def add_raw_image(
level_count: int,
cache_dir: Optional[str] = None,
cache_file_name_func: Callable[[int, int, int], str] = None,
) -> Tuple[int, List[str]]:
) -> List[str]:
"""Adds the raw image pixel data as array to the given parent zarr group.
Optionally caches the pixel data in the given cache_dir directory.
Returns the number of resolution levels generated for the image.
Expand All @@ -121,14 +178,8 @@ def add_raw_image(
cache_dir = ""

dims = [dim for dim in [size_t, size_c, size_z] if dim != 1]
axes = []
if size_t > 1:
axes.append("t")
if size_c > 1:
axes.append("c")
if size_z > 1:
axes.append("z")

paths: List[str] = []
field_groups: List[Array] = []
for t in range(size_t):
for c in range(size_c):
Expand All @@ -151,9 +202,11 @@ def add_raw_image(
size_x = plane.shape[1]
# If on first plane, create a new group for this resolution level
if len(field_groups) <= level:
path = str(level)
paths.append(path)
field_groups.append(
parent.create(
str(level),
path,
shape=tuple(dims + [size_y, size_x]),
chunks=tuple([1] * len(dims) + [size_y, size_x]),
dtype=d_type,
Expand All @@ -179,7 +232,8 @@ def add_raw_image(
preserve_range=True,
anti_aliasing=False,
).astype(plane.dtype)
return (level_count, axes + ["y", "x"])

return paths


def marshal_acquisition(acquisition: omero.gateway._PlateAcquisitionWrapper) -> Dict:
Expand Down Expand Up @@ -256,8 +310,7 @@ def plate_to_zarr(plate: omero.gateway._PlateWrapper, args: argparse.Namespace)
row_group = root.require_group(row)
col_group = row_group.require_group(col)
field_group = col_group.require_group(field_name)
n_levels, axes = add_image(img, field_group, cache_dir=cache_dir)
add_multiscales_metadata(field_group, axes, n_levels)
add_image(img, field_group, cache_dir=cache_dir)
add_omero_metadata(field_group, img)
# Update Well metadata after each image
col_group.attrs["well"] = {"images": fields, "version": VERSION}
will-moore marked this conversation as resolved.
Show resolved Hide resolved
Expand All @@ -275,14 +328,20 @@ def plate_to_zarr(plate: omero.gateway._PlateWrapper, args: argparse.Namespace)

def add_multiscales_metadata(
will-moore marked this conversation as resolved.
Show resolved Hide resolved
zarr_root: Group,
axes: List[str],
resolutions: int = 1,
axes: List[Dict[str, str]],
paths: List[str],
transformations: List[List[Dict[str, Any]]] = None,
) -> None:
# transformations is a 2D list. For each path, we have a List of Dicts
datasets: List[Dict[str, Any]] = [{"path": path} for path in paths]
if transformations is not None:
for index, transform in enumerate(transformations):
datasets[index]["transformations"] = transform

multiscales = [
{
"version": "0.3",
"datasets": [{"path": str(r)} for r in range(resolutions)],
"version": "0.4",
"datasets": datasets,
"axes": axes,
}
]
Expand Down