Skip to content
This repository has been archived by the owner on Jan 5, 2024. It is now read-only.

Make sure metadata is attached to loaded napari Layers #38

Merged
merged 7 commits into from
Jun 29, 2022
Merged
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
97 changes: 47 additions & 50 deletions brainreg_napari/register.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
import pathlib
from collections import namedtuple
from enum import Enum
from typing import Dict
from typing import Dict, List, Tuple

import napari
from fancylog import fancylog
from magicgui import magicgui
from napari.types import LayerDataTuple

import bg_space as bg
import brainreg as program_for_log
Expand All @@ -20,6 +21,37 @@
from brainreg_segment.atlas.utils import get_available_atlases


def add_registered_image_layers(
viewer: napari.Viewer, *, registration_directory: pathlib.Path
) -> Tuple[napari.layers.Image, napari.layers.Labels]:
"""
Read in saved registration data and add as layers to the
napari viewer.

Returns
-------
boundaries :
Registered boundaries.
labels :
Registered brain regions.
"""
layers: List[LayerDataTuple] = []

meta_file = (registration_directory / "brainreg.json").resolve()
if meta_file.exists():
with open(meta_file) as json_file:
metadata = json.load(json_file)
layers = load_registration(layers, registration_directory, metadata)
else:
raise FileNotFoundError(
f"'brainreg.json' file not found in {registration_directory}"
)

boundaries = viewer.add_layer(napari.layers.Layer.create(*layers[0]))
labels = viewer.add_layer(napari.layers.Layer.create(*layers[1]))
return boundaries, labels


def get_layer_labels(widget):
return [layer._name for layer in widget.viewer.value.layers]

Expand Down Expand Up @@ -252,33 +284,17 @@ def widget(
is set to `True` in the tests.
"""

def add_image_layers():
def load_registration_as_layers() -> None:
"""
Load the saved registration data into napari layers.
"""
viewer = getattr(widget, "viewer").value
registration_directory = pathlib.Path(
getattr(widget, "registration_output_folder").value
)
layers = []

if registration_directory.exists():
with open(
registration_directory / "brainreg.json"
) as json_file:
metadata = json.load(json_file)
layers = load_registration(
layers, registration_directory, metadata
)
viewer = getattr(widget, "viewer").value
atlas_layer = napari.layers.Labels(
layers[0][0],
scale=layers[0][1]["scale"],
name=layers[0][1]["name"],
)
boundaries_layer = napari.layers.Image(
layers[1][0],
scale=layers[1][1]["scale"],
name=layers[1][1]["name"],
add_registered_image_layers(
viewer, registration_directory=registration_directory
)
viewer.add_layer(atlas_layer)
viewer.add_layer(boundaries_layer)

def get_gui_logging_args():
args_dict = {}
Expand Down Expand Up @@ -314,19 +330,7 @@ def get_gui_logging_args():
)

@thread_worker
def run(
affine_n_steps,
affine_use_n_steps,
freeform_n_steps,
freeform_use_n_steps,
bending_energy_weight,
grid_spacing,
smoothing_sigma_reference,
smoothing_sigma_floating,
histogram_n_bins_floating,
histogram_n_bins_reference,
):

def run():
paths = Paths(pathlib.Path(registration_output_folder))

niftyreg_args = NiftyregArgs(
Expand Down Expand Up @@ -412,22 +416,15 @@ def run(
f"{paths.registration_output_folder}"
)

worker = run(
affine_n_steps,
affine_use_n_steps,
freeform_n_steps,
freeform_use_n_steps,
bending_energy_weight,
grid_spacing,
smoothing_sigma_reference,
smoothing_sigma_floating,
histogram_n_bins_floating,
histogram_n_bins_reference,
)
worker.returned.connect(add_image_layers)
worker = run()
if not block:
worker.returned.connect(load_registration_as_layers)

worker.start()

if block:
worker.await_workers()
load_registration_as_layers()

@widget.reset_button.changed.connect
def restore_defaults(event=None):
Expand Down
35 changes: 34 additions & 1 deletion brainreg_napari/tests/test_brainreg_napari.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import napari
import pytest

from brainreg_napari.register import brainreg_register
from brainreg_napari.register import (
add_registered_image_layers,
brainreg_register,
)


def test_add_detect_widget(make_napari_viewer):
Expand Down Expand Up @@ -50,5 +54,34 @@ def test_workflow(make_napari_viewer, tmp_path):
pixel_widget = getattr(widget, f"{dim}_pixel_um")
pixel_widget.value = brain_layer.metadata["voxel_size"][i]

assert len(viewer.layers) == 1

# Run registration
widget(block=True)

# Check that layers have been added
assert len(viewer.layers) == 3
# Check layers have expected type/name
labels = viewer.layers[1]
assert isinstance(labels, napari.layers.Labels)
assert labels.name == "example_mouse_100um"
for key in ["orientation", "atlas"]:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tuple marginally faster here

# There are lots of other keys in the metadata, but just check
# for a couple here.
assert (
key in labels.metadata
), f"Missing key '{key}' from labels metadata"

boundaries = viewer.layers[2]
assert isinstance(boundaries, napari.layers.Image)
assert boundaries.name == "Boundaries"


def test_add_layers_errors(tmp_path, make_napari_viewer):
"""
Check that an error is raised if registration metadata isn't present when
trying to add registered images to a napari viewer.
"""
viewer = make_napari_viewer()
with pytest.raises(FileNotFoundError):
add_registered_image_layers(viewer, registration_directory=tmp_path)