Skip to content

Commit

Permalink
Re-instate visiblility via a property
Browse files Browse the repository at this point in the history
  • Loading branch information
joshmoore committed Sep 3, 2020
1 parent c0806ec commit 6cc1c25
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 39 deletions.
2 changes: 1 addition & 1 deletion ome_zarr/napari.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def f(*args: Any, **kwargs: Any) -> List[LayerData]:
if "colormap" in metadata:
del metadata["colormap"]

if shape[CHANNEL_DIMENSION] > 1:
elif shape[CHANNEL_DIMENSION] > 1:
metadata["channel_axis"] = CHANNEL_DIMENSION
else:
for x in ("name", "visible", "contrast_limits", "colormap"):
Expand Down
71 changes: 57 additions & 14 deletions ome_zarr/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ class Node:
hierarchy."""

def __init__(
self, zarr: BaseZarrLocation, root: Union["Node", "Reader", List[str]]
self,
zarr: BaseZarrLocation,
root: Union["Node", "Reader", List[str]],
visibility: bool = True,
):
self.zarr = zarr
self.root = root
Expand All @@ -28,7 +31,7 @@ def __init__(
self.seen = root.seen
else:
self.seen = cast(List[str], root)
self.visible = True
self.__visible = visibility

# Likely to be updated by specs
self.metadata: JSONDict = dict()
Expand All @@ -47,22 +50,64 @@ def __init__(
if OMERO.matches(zarr):
self.specs.append(OMERO(self))

@property
def visible(self) -> bool:
"""True if this node should be displayed by default.
An invisible node may have been requested by the instrument, by the
user, or by the ome_zarr library after determining that this node
is lower priority, e.g. to prevent too many nodes from being shown
at once.
"""
return self.__visible

@visible.setter
def visible(self, visibility: bool) -> bool:
"""
Set the visibility for this node, returning the previous value.
A change of the visibility will propagate to all subnodes.
"""
old = self.__visible
if old != visibility:
self.__visible = visibility
for node in self.pre_nodes + self.post_nodes:
node.visible = visibility
return old

def load(self, spec_type: Type["Spec"]) -> Optional["Spec"]:
for spec in self.specs:
if isinstance(spec, spec_type):
return spec
return None

def add(self, zarr: BaseZarrLocation, prepend: bool = False,) -> "Optional[Node]":
"""Create a child node if this location has not yet been seen; otherwise return
None."""
def add(
self,
zarr: BaseZarrLocation,
prepend: bool = False,
visibility: Optional[bool] = None,
) -> "Optional[Node]":
"""Create a child node if this location has not yet been seen.
Returns None if the node has already been processed.
By setting prepend, the addition will be considered as higher priority
node which will likely be turned into a lower layer for display.
By unsetting visible, the node (and in turn the layer) can be
deactivated for initial display. By default, the value of the current
node will be propagated.
"""

if zarr.zarr_path in self.seen:
LOGGER.debug(f"already seen {zarr}; stopping recursion")
return None

if visibility is None:
visibility = self.visible

self.seen.append(zarr.zarr_path)
node = Node(zarr, self)
node = Node(zarr, self, visibility=visibility)
if prepend:
self.pre_nodes.append(node)
else:
Expand All @@ -80,6 +125,8 @@ def __repr__(self) -> str:
suffix += " [zgroup]"
if self.zarr.zarray:
suffix += " [zarray]"
if not self.visible:
suffix += " (hidden)"
return f"{self.zarr.zarr_path}{suffix}"


Expand Down Expand Up @@ -137,7 +184,6 @@ def matches(zarr: BaseZarrLocation) -> bool:

def __init__(self, node: Node) -> None:
super().__init__(node)
node.visible = True

image = self.lookup("image", {}).get("array", None)
parent_zarr = None
Expand All @@ -146,9 +192,7 @@ def __init__(self, node: Node) -> None:
parent_zarr = self.zarr.create(image)
if parent_zarr.exists():
LOGGER.debug(f"delegating to parent image: {parent_zarr}")
parent_node = node.add(parent_zarr, prepend=True)
if parent_node is not None:
node.visible = False
node.add(parent_zarr, prepend=True, visibility=False)
else:
parent_zarr = None
if parent_zarr is None:
Expand All @@ -174,7 +218,7 @@ def __init__(self, node: Node) -> None:
name = self.zarr.zarr_path.split("/")[-1]
node.metadata.update(
{
"visible": False,
"visible": node.visible,
"name": name,
"color": colors,
"metadata": {"image": self.lookup("image", {}), "path": name},
Expand Down Expand Up @@ -219,7 +263,7 @@ def __init__(self, node: Node) -> None:
# Load possible node data
child_zarr = self.zarr.create("labels")
if child_zarr.exists():
node.add(child_zarr)
node.add(child_zarr, visibility=False)


class OMERO(Spec):
Expand Down Expand Up @@ -269,7 +313,7 @@ def __init__(self, node: Node) -> None:

visible = ch.get("active", None)
if visible is not None:
visibles[idx] = visible
visibles[idx] = visible and node.visible

window = ch.get("window", None)
if window is not None:
Expand Down Expand Up @@ -311,7 +355,6 @@ def __call__(self) -> Iterator[Node]:

# TODO: API thoughts for the Spec type
# - ask for recursion or not
# - ask for visible or invisible (?)
# - ask for "provides data", "overrides data"

elif self.zarr.zarray: # Nothing has matched
Expand Down
42 changes: 18 additions & 24 deletions tests/test_napari.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,47 +11,41 @@ def initdir(self, tmpdir):
self.path = tmpdir.mkdir("data")
create_zarr(str(self.path), astronaut, "astronaut")

def assert_layer(self, layer_data):
data, metadata, layer_type = layer_data
if not data or not metadata:
assert False, f"unknown layer: {layer_data}"
assert layer_type in ("image", "labels")
return data, metadata, layer_type
def assert_layers(self, layers, visible_1, visible_2):
# TODO: check name

def test_image(self):
layers = napari_get_reader(str(self.path))()
assert len(layers) == 2
image, label = layers

data, metadata, layer_type = self.assert_layer(image)
assert 1 == metadata["channel_axis"]
assert ["Red", "Green", "Blue"] == metadata["name"]
assert [[0, 1], [0, 1], [0, 1]] == metadata["contrast_limits"]
assert [True, True, True] == metadata["visible"]
assert [[0, 1]] * 3 == metadata["contrast_limits"]
assert [visible_1] * 3 == metadata["visible"]

data, metadata, layer_type = self.assert_layer(label)
assert visible_2 == metadata["visible"]

def assert_layer(self, layer_data):
data, metadata, layer_type = layer_data
if not data or not metadata:
assert False, f"unknown layer: {layer_data}"
assert layer_type in ("image", "labels")
return data, metadata, layer_type

def test_image(self):
layers = napari_get_reader(str(self.path))()
self.assert_layers(layers, True, False)

def test_labels(self):
filename = str(self.path.join("labels"))
layers = napari_get_reader(filename)()
assert layers
for layer_data in layers:
data, metadata, layer_type = self.assert_layer(layer_data)
self.assert_layers(layers, False, True)

def test_label(self):
filename = str(self.path.join("labels", "astronaut"))
layers = napari_get_reader(filename)()
assert layers
for layer_data in layers:
data, metadata, layer_type = self.assert_layer(layer_data)

def test_layers(self):
filename = str(self.path.join("labels", "astronaut"))
layers = napari_get_reader(filename)()
assert layers
# check order
# check name
# check visibility
self.assert_layers(layers, False, True)

def test_viewer(self, make_test_viewer):
"""example of testing the viewer."""
Expand Down

0 comments on commit 6cc1c25

Please sign in to comment.