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

Add methods to export plate to zarr #28

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
4 changes: 2 additions & 2 deletions .bumpversion.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ commit = True
tag = True
sign_tags = True
parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(\.(?P<release>[a-z]+)(?P<build>\d+))?
serialize =
serialize =
{major}.{minor}.{patch}.{release}{build}
{major}.{minor}.{patch}

[bumpversion:part:release]
optional_value = prod
first_value = dev
values =
values =
dev
prod

Expand Down
2 changes: 1 addition & 1 deletion .isort.cfg
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[settings]
known_third_party = numpy,ome_zarr,omero,omero_zarr,setuptools,zarr
known_third_party = natsort,numpy,ome_zarr,omero,omero_zarr,setuptools,zarr
7 changes: 5 additions & 2 deletions src/omero_zarr/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@

from omero.cli import CLI, BaseControl, Parser, ProxyStringType
from omero.gateway import BlitzGateway, BlitzObjectWrapper
from omero.model import ImageI
from omero.model import ImageI, PlateI

from .masks import MASK_DTYPE_SIZE, image_masks_to_zarr
from .raw_pixels import image_to_zarr
from .raw_pixels import image_to_zarr, plate_to_zarr

HELP = """Export data in zarr format.

Expand Down Expand Up @@ -181,6 +181,9 @@ def export(self, args: argparse.Namespace) -> None:
self._bf_export(repo_path / p, args)
else:
image_to_zarr(image, args)
elif isinstance(args.object, PlateI):
plate = self._lookup(self.gateway, "Plate", args.object.id)
plate_to_zarr(plate, args)

def _lookup(
self, gateway: BlitzGateway, otype: str, oid: int
Expand Down
90 changes: 90 additions & 0 deletions src/omero_zarr/raw_pixels.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import numpy
import numpy as np
import omero.clients # noqa
import time
from omero.rtypes import unwrap
from zarr.hierarchy import Group, open_group

Expand Down Expand Up @@ -74,6 +75,95 @@ def planeGen() -> np.ndarray:
print("Created", name)


def add_image(image: omero.gateway.Image, parent: Group, field_index="0") -> None:
"""Adds the image pixel data as array to the given parent zarr group."""
size_c = image.getSizeC()
size_z = image.getSizeZ()
size_x = image.getSizeX()
size_y = image.getSizeY()
size_t = image.getSizeT()
d_type = image.getPixelsType()

group = parent.create(
field_index,
shape=(size_t, size_c, size_z, size_y, size_x),
chunks=(1, 1, 1, size_y, size_x),
dtype=d_type,
)

zct_list = []
for t in range(size_t):
for c in range(size_c):
for z in range(size_z):
zct_list.append((z, c, t))

pixels = image.getPrimaryPixels()

def planeGen() -> np.ndarray:
planes = pixels.getPlanes(zct_list)
yield from planes

planes = planeGen()

for t in range(size_t):
for c in range(size_c):
for z in range(size_z):
plane = next(planes)
group[t, c, z, :, :] = plane

def print_status(t0, t, count, total):
""" Prints percent done and ETA """
percent_done = count * 100 / total
rate = count / (t - t0)
eta = (total - count) / rate
status = "{:.2f}% done, ETA: {}".format(
percent_done, time.strftime('%H:%M:%S', time.gmtime(eta))
)
print(status, end="\r", flush=True)

def plate_to_zarr(plate: omero.gateway._PlateWrapper, args: argparse.Namespace) -> None:
"""
Exports a plate to a zarr file using the hierarchy discussed here ('Option 3'):
https://github.com/ome/omero-ms-zarr/issues/73#issuecomment-706770955
"""
gs = plate.getGridSize()
n_rows = gs["rows"]
n_cols = gs["columns"]
n_fields = plate.getNumberOfFields()
total = n_rows * n_cols * (n_fields[1] - n_fields[0] + 1)
dominikl marked this conversation as resolved.
Show resolved Hide resolved

target_dir = args.output
name = os.path.join(target_dir, "%s.zarr" % plate.id)
print("Exporting to {}".format(name))
root = open_group(name, mode="w")
plate_metadata = {
"rows": n_rows,
"columns": n_cols
}
root.attrs["plate"] = plate_metadata

count = 0
t0 = time.time()

for well in plate.listChildren():
row = plate.getRowLabels()[well.row]
col = plate.getColumnLabels()[well.column]
for field in range(n_fields[0], n_fields[1] + 1):
ws = well.getWellSample(field)
field_name = "Field_{}".format(field + 1)
count += 1
if ws and ws.getImage():
img = ws.getImage()
ac = ws.getPlateAcquisition()
ac_name = ac.getName() if ac else "0"
ac_group = root.require_group(ac_name)
row_group = ac_group.require_group(row)
col_group = row_group.require_group(col)
add_image(img, col_group, field_name)
print_status(t0, time.time(), count, total)
print("Finished.")


def add_group_metadata(
zarr_root: Group, image: omero.gateway.Image, resolutions: int = 1
) -> None:
Expand Down