Skip to content

Commit

Permalink
ruff fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
alessandratrapani committed Jan 24, 2025
1 parent 2724f32 commit 74c4ee7
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 46 deletions.
65 changes: 42 additions & 23 deletions src/pynwb/ndx_microscopy/ndx_microscopy.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,50 @@
from hdmf.utils import docval, popargs
from pynwb import get_class, register_class
from pynwb.core import MultiContainerInterface
from pynwb import get_class
import numpy as np

extension_name = "ndx-microscopy"

MicroscopyPlaneSegmentation = get_class("MicroscopyPlaneSegmentation", extension_name)

@docval({'name': 'pixel_mask', 'type': 'array_data', 'default': None,
'doc': 'pixel mask for 2D ROIs: [(x1, y1, weight1), (x2, y2, weight2), ...]',
'shape': (None, 3)},
{'name': 'voxel_mask', 'type': 'array_data', 'default': None,
'doc': 'voxel mask for 3D ROIs: [(x1, y1, z1, weight1), (x2, y2, z2, weight2), ...]',
'shape': (None, 4)},
{'name': 'image_mask', 'type': 'array_data', 'default': None,
'doc': 'image with the same size of image where positive values mark this ROI',
'shape': [[None]*2, [None]*3]},
{'name': 'id', 'type': int, 'doc': 'the ID for the ROI', 'default': None},
allow_extra=True)

@docval(
{
"name": "pixel_mask",
"type": "array_data",
"default": None,
"doc": "pixel mask for 2D ROIs: [(x1, y1, weight1), (x2, y2, weight2), ...]",
"shape": (None, 3),
},
{
"name": "voxel_mask",
"type": "array_data",
"default": None,
"doc": "voxel mask for 3D ROIs: [(x1, y1, z1, weight1), (x2, y2, z2, weight2), ...]",
"shape": (None, 4),
},
{
"name": "image_mask",
"type": "array_data",
"default": None,
"doc": "image with the same size of image where positive values mark this ROI",
"shape": [[None] * 2, [None] * 3],
},
{"name": "id", "type": int, "doc": "the ID for the ROI", "default": None},
allow_extra=True,
)
def add_roi(self, **kwargs):
"""Add a Region Of Interest (ROI) data to this"""
pixel_mask, voxel_mask, image_mask = popargs('pixel_mask', 'voxel_mask', 'image_mask', kwargs)
pixel_mask, voxel_mask, image_mask = popargs("pixel_mask", "voxel_mask", "image_mask", kwargs)
if image_mask is None and pixel_mask is None and voxel_mask is None:
raise ValueError("Must provide 'image_mask' and/or 'pixel_mask'")
rkwargs = dict(kwargs)
if image_mask is not None:
rkwargs['image_mask'] = image_mask
rkwargs["image_mask"] = image_mask
if pixel_mask is not None:
rkwargs['pixel_mask'] = pixel_mask
rkwargs["pixel_mask"] = pixel_mask
if voxel_mask is not None:
rkwargs['voxel_mask'] = voxel_mask
return super(MicroscopyPlaneSegmentation,self).add_row(**rkwargs)
rkwargs["voxel_mask"] = voxel_mask
return super(MicroscopyPlaneSegmentation, self).add_row(**rkwargs)


@staticmethod
Expand All @@ -45,11 +58,12 @@ def pixel_to_image(pixel_mask):
image_matrix[y_coords, x_coords] = weights
return image_matrix


@staticmethod
def image_to_pixel(image_mask):
"""Converts an image_mask of a ROI into a pixel_mask"""
pixel_mask = []
it = np.nditer(image_mask, flags=['multi_index'])
it = np.nditer(image_mask, flags=["multi_index"])
while not it.finished:
weight = it[0][()]
if weight > 0:
Expand All @@ -59,14 +73,19 @@ def image_to_pixel(image_mask):
it.iternext()
return pixel_mask


MicroscopyPlaneSegmentation.add_roi = add_roi
MicroscopyPlaneSegmentation.pixel_to_image = pixel_to_image
MicroscopyPlaneSegmentation.image_to_pixel = image_to_pixel

@docval({'name': 'description', 'type': str, 'doc': 'a brief description of what the region is'},
{'name': 'region', 'type': (slice, list, tuple), 'doc': 'the indices of the table', 'default': slice(None)},
{'name': 'name', 'type': str, 'doc': 'the name of the ROITableRegion', 'default': 'rois'})

@docval(
{"name": "description", "type": str, "doc": "a brief description of what the region is"},
{"name": "region", "type": (slice, list, tuple), "doc": "the indices of the table", "default": slice(None)},
{"name": "name", "type": str, "doc": "the name of the ROITableRegion", "default": "rois"},
)
def create_roi_table_region(self, **kwargs):
return super(MicroscopyPlaneSegmentation,self).create_region(**kwargs)
return super(MicroscopyPlaneSegmentation, self).create_region(**kwargs)


MicroscopyPlaneSegmentation.create_roi_table_region = create_roi_table_region
36 changes: 18 additions & 18 deletions src/pynwb/tests/test_api_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,28 @@

import numpy as np
import pytest
from pynwb import NWBFile
from datetime import datetime
from ndx_microscopy.testing import (
mock_PlanarImagingSpace,
mock_MicroscopyPlaneSegmentation,
mock_MicroscopySegmentations,
)
from ndx_microscopy import MicroscopyPlaneSegmentation


def test_add_roi_with_pixel_mask():
"""Test adding ROI with pixel mask."""

pixel_mask = [[1, 2, 1.0], [3, 4, 1.0], [5, 6, 1.0], [7, 8, 2.0], [9, 10, 2.0]]

imaging_space = mock_PlanarImagingSpace()
name="MicroscopyPlaneSegmentation"
description="A mock instance of a MicroscopyPlaneSegmentation type to be used for rapid testing."
name = "MicroscopyPlaneSegmentation"
description = "A mock instance of a MicroscopyPlaneSegmentation type to be used for rapid testing."

plane_seg = MicroscopyPlaneSegmentation(name=name, description=description, imaging_space=imaging_space)

plane_seg.add_roi(pixel_mask=pixel_mask)
assert plane_seg.pixel_mask[:] == pixel_mask



def test_add_roi_with_voxel_mask():
"""Test adding ROI with voxel mask."""
voxel_mask = [[1, 2, 3, 1.0], [3, 4, 5, 1.0], [5, 6, 7, 1.0], [7, 8, 9, 2.0], [9, 10, 11, 2.0]]
Expand All @@ -38,6 +37,7 @@ def test_add_roi_with_voxel_mask():
plane_seg.add_roi(voxel_mask=voxel_mask)
assert plane_seg.voxel_mask[:] == voxel_mask


def test_add_roi_with_image_mask():
"""Test adding ROI with image mask."""
w, h = 5, 5
Expand All @@ -52,14 +52,16 @@ def test_add_roi_with_image_mask():

assert plane_seg.image_mask[0] == image_mask


def test_add_roi_without_masks():
"""Test adding ROI without any masks raises ValueError."""
imaging_space = mock_PlanarImagingSpace()
plane_seg = mock_MicroscopyPlaneSegmentation(imaging_space=imaging_space)

with pytest.raises(ValueError, match="Must provide 'image_mask' and/or 'pixel_mask"):
plane_seg.add_roi(id=4)


def test_pixel_to_image():
"""Test conversion from pixel mask to image mask."""
imaging_space = mock_PlanarImagingSpace()
Expand All @@ -70,9 +72,8 @@ def test_pixel_to_image():
pixel_mask = [[0, 0, 1.0], [1, 0, 2.0], [2, 0, 2.0]]

img_mask = plane_seg.pixel_to_image(pixel_mask)
np.testing.assert_allclose(img_mask, np.asarray([[1, 2, 2.0],
[0, 0, 0.0],
[0, 0, 0.0]]))
np.testing.assert_allclose(img_mask, np.asarray([[1, 2, 2.0], [0, 0, 0.0], [0, 0, 0.0]]))


def test_image_to_pixel():
"""Test conversion from image mask to pixel mask."""
Expand All @@ -81,33 +82,32 @@ def test_image_to_pixel():
description = "A mock instance of a MicroscopyPlaneSegmentation type to be used for rapid testing."
plane_seg = MicroscopyPlaneSegmentation(name=name, description=description, imaging_space=imaging_space)

image_mask = np.asarray([[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0]])
image_mask = np.asarray([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])

pixel_mask = plane_seg.image_to_pixel(image_mask)
np.testing.assert_allclose(pixel_mask, np.asarray([[0, 0, 1.0], [1, 1, 1.0], [2, 2, 1.0]]))


def test_create_roi_table_region():
"""Test creating ROI table region."""
imaging_space = mock_PlanarImagingSpace()
name = "MicroscopyPlaneSegmentation"
description = "A mock instance of a MicroscopyPlaneSegmentation type to be used for rapid testing."
plane_seg = MicroscopyPlaneSegmentation(name=name, description=description, imaging_space=imaging_space)

# Add some ROIs first
pixel_mask = [[0, 0, 1.0], [1, 0, 2.0], [2, 0, 2.0]]

plane_seg.add_roi(pixel_mask=pixel_mask)
plane_seg.add_roi(pixel_mask=pixel_mask)

# Test with specific region indices
region = plane_seg.create_roi_table_region(
description="Test region",
name="test_region",
region=[0] # Only include first ROI
region=[0], # Only include first ROI
)

assert region.name == "test_region"
assert region.description == "Test region"
assert len(region.data) == 1
Expand Down
10 changes: 5 additions & 5 deletions src/pynwb/tests/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def test_constructor_volumetric_image_space():

def test_constructor_microscopy_segmentations():
microscopy_segmentations = mock_MicroscopySegmentations()
assert "MicroscopySegmentations" in microscopy_segmentations.name
assert "MicroscopySegmentations" in microscopy_segmentations.name


def test_constructor_microscopy_plane_segmentation():
Expand Down Expand Up @@ -90,13 +90,13 @@ def test_constructor_microscopy_image_segmentation_with_plane_segmentation():
def test_constructor_planar_microscopy_series():
microscope = mock_Microscope()
excitation_light_path = mock_ExcitationLightPath()
planar_imaging_space = mock_PlanarImagingSpace()
planar_imaging_space = mock_PlanarImagingSpace()
emission_light_path = mock_EmissionLightPath()

planar_microscopy_series = mock_PlanarMicroscopySeries(
microscope=microscope,
excitation_light_path=excitation_light_path,
planar_imaging_space=planar_imaging_space ,
planar_imaging_space=planar_imaging_space,
emission_light_path=emission_light_path,
)
assert (
Expand All @@ -108,13 +108,13 @@ def test_constructor_planar_microscopy_series():
def test_constructor_variable_depth_microscopy_series():
microscope = mock_Microscope()
excitation_light_path = mock_ExcitationLightPath()
planar_imaging_space = mock_PlanarImagingSpace()
planar_imaging_space = mock_PlanarImagingSpace()
emission_light_path = mock_EmissionLightPath()

variable_depth_microscopy_series = mock_VariableDepthMicroscopySeries(
microscope=microscope,
excitation_light_path=excitation_light_path,
planar_imaging_space =planar_imaging_space ,
planar_imaging_space=planar_imaging_space,
emission_light_path=emission_light_path,
)
assert (
Expand Down

0 comments on commit 74c4ee7

Please sign in to comment.