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

Support regions in image viewer #10

Merged
merged 6 commits into from
Nov 15, 2023
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
12 changes: 12 additions & 0 deletions glue_qt/utils/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,18 @@
self.addItem(label, userData=UserDataWrapper(cmap))
self._update_icons()

def refresh_options(self, colormaps=None):
if colormaps is None:
self.clear()
for label, cmap in config.colormaps:
self.addItem(label, userData=UserDataWrapper(cmap))
self._update_icons()
else:
self.clear()
for label, cmap in colormaps:
self.addItem(label, userData=UserDataWrapper(cmap))
self._update_icons()

Check warning on line 208 in glue_qt/utils/colors.py

View check run for this annotation

Codecov / codecov/patch

glue_qt/utils/colors.py#L205-L208

Added lines #L205 - L208 were not covered by tests

def _update_icons(self):
self.setIconSize(QtCore.QSize(self.width(), 15))
for index in range(self.count()):
Expand Down
7 changes: 4 additions & 3 deletions glue_qt/viewers/image/data_viewer.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from glue_qt.viewers.matplotlib.data_viewer import MatplotlibDataViewer
from glue_qt.viewers.scatter.layer_style_editor import ScatterLayerStyleEditor
from glue.viewers.scatter.layer_artist import ScatterLayerArtist
from glue_qt.viewers.scatter.layer_style_editor import ScatterLayerStyleEditor, ScatterRegionLayerStyleEditor
from glue.viewers.scatter.layer_artist import ScatterLayerArtist, ScatterRegionLayerArtist
from glue_qt.viewers.image.layer_style_editor import ImageLayerStyleEditor
from glue_qt.viewers.image.layer_style_editor_subset import ImageLayerSubsetStyleEditor
from glue.viewers.image.layer_artist import ImageLayerArtist, ImageSubsetLayerArtist
Expand All @@ -26,7 +26,8 @@ class ImageViewer(MatplotlibImageMixin, MatplotlibDataViewer):
_default_mouse_mode_cls = RoiClickAndDragMode
_layer_style_widget_cls = {ImageLayerArtist: ImageLayerStyleEditor,
ImageSubsetLayerArtist: ImageLayerSubsetStyleEditor,
ScatterLayerArtist: ScatterLayerStyleEditor}
ScatterLayerArtist: ScatterLayerStyleEditor,
ScatterRegionLayerArtist: ScatterRegionLayerStyleEditor}
_state_cls = ImageViewerState
_options_cls = ImageOptionsWidget

Expand Down
219 changes: 219 additions & 0 deletions glue_qt/viewers/image/tests/test_display_region_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
# pylint: disable=I0011,W0613,W0201,W0212,E1101,E1103

import os

import numpy as np
import shapely
from shapely.geometry import MultiPolygon, Polygon, Point

from glue.core.data_region import RegionData
from glue.core.data import Data
from glue.core.component import Component
from glue_qt.utils import combo_as_string, process_events
from glue_qt.app import GlueApplication
from glue.core.fixed_resolution_buffer import ARRAY_CACHE, PIXEL_CACHE
from glue.core.link_helpers import LinkSame

from astropy.wcs import WCS


from ..data_viewer import ImageViewer

DATA = os.path.join(os.path.dirname(__file__), 'data')


class TestRegionScatterViewer(object):

def setup_method(self, method):

poly_1 = Polygon([(20, 20), (60, 20), (60, 40), (20, 40)])
poly_2 = Polygon([(60, 50), (60, 70), (80, 70), (80, 50)])
poly_3 = Polygon([(10, 10), (15, 10), (15, 15), (10, 15)])
poly_4 = Polygon([(10, 20), (15, 20), (15, 30), (10, 30), (12, 25)])

polygons = MultiPolygon([poly_3, poly_4])

my_geoms = np.array([poly_1, poly_2, polygons])

representative_points = [s.representative_point() for s in my_geoms]

cell_number = Component(np.array([1, 2, 3]))

self.region_data = RegionData(regions=my_geoms,
cell_number=cell_number)

random_2d_array = np.random.randint(1, 20, size=(100, 100))
self.data_2d = Data(label='image_data', z=random_2d_array)
self.catalog = Data(label='catalog', c=[1, 3, 2], d=[4, 3, 3])

self.application = GlueApplication()

self.session = self.application.session

self.hub = self.session.hub

self.data_collection = self.session.data_collection
self.data_collection.append(self.region_data)
self.data_collection.append(self.data_2d)
self.data_collection.append(self.catalog)

self.viewer = self.application.new_data_viewer(ImageViewer)

self.data_collection.register_to_hub(self.hub)
self.viewer.register_to_hub(self.hub)

self.options_widget = self.viewer.options_widget()

def teardown_method(self, method):

# Properly close viewer and application
self.viewer.close()
self.viewer = None
self.application.close()
self.application = None

# Make sure cache is empty
if len(PIXEL_CACHE) > 0:
raise Exception("Pixel cache contains {0} elements".format(len(PIXEL_CACHE)))

Check warning on line 77 in glue_qt/viewers/image/tests/test_display_region_data.py

View check run for this annotation

Codecov / codecov/patch

glue_qt/viewers/image/tests/test_display_region_data.py#L77

Added line #L77 was not covered by tests
if len(ARRAY_CACHE) > 0:
raise Exception("Array cache contains {0} elements".format(len(ARRAY_CACHE)))

Check warning on line 79 in glue_qt/viewers/image/tests/test_display_region_data.py

View check run for this annotation

Codecov / codecov/patch

glue_qt/viewers/image/tests/test_display_region_data.py#L79

Added line #L79 was not covered by tests

def test_link_first_then_add(self):

# Check defaults when we add data

self.viewer.add_data(self.data_2d)
link1 = LinkSame(self.region_data.center_x_id, self.data_2d.pixel_component_ids[0])
link2 = LinkSame(self.region_data.center_y_id, self.data_2d.pixel_component_ids[1])

self.data_collection.add_link(link1)
self.data_collection.add_link(link2)
process_events()

assert len(self.viewer.state.layers) == 1

self.viewer.add_data(self.region_data)

assert len(self.viewer.state.layers) == 2
assert self.viewer.layers[0].enabled # image
assert self.viewer.layers[1].enabled # regions

def test_add_first_then_link(self):

# Check defaults when we add data

self.viewer.add_data(self.data_2d)

assert combo_as_string(self.options_widget.ui.combosel_x_att_world) == 'Coordinate components:Pixel Axis 0 [y]:Pixel Axis 1 [x]'
assert combo_as_string(self.options_widget.ui.combosel_y_att_world) == 'Coordinate components:Pixel Axis 0 [y]:Pixel Axis 1 [x]'

assert self.viewer.axes.get_xlabel() == 'Pixel Axis 1 [x]'
assert self.viewer.state.x_att_world is self.data_2d.id['Pixel Axis 1 [x]']
assert self.viewer.state.x_att is self.data_2d.pixel_component_ids[1]

assert self.viewer.axes.get_ylabel() == 'Pixel Axis 0 [y]'
assert self.viewer.state.y_att_world is self.data_2d.id['Pixel Axis 0 [y]']
assert self.viewer.state.y_att is self.data_2d.pixel_component_ids[0]

assert not self.viewer.state.x_log
assert not self.viewer.state.y_log

assert len(self.viewer.state.layers) == 1

self.viewer.add_data(self.region_data)

assert len(self.viewer.state.layers) == 2
assert self.viewer.layers[0].enabled # image
assert not self.viewer.layers[1].enabled # regions

process_events()

link1 = LinkSame(self.region_data.center_x_id, self.data_2d.pixel_component_ids[0])
link2 = LinkSame(self.region_data.center_y_id, self.data_2d.pixel_component_ids[1])

self.data_collection.add_link(link1)
self.data_collection.add_link(link2)
process_events()

assert len(self.viewer.state.layers) == 2
assert self.viewer.layers[0].enabled # image
assert self.viewer.layers[1].enabled # regions

def test_subset(self):
self.viewer.add_data(self.data_2d)

self.viewer.add_data(self.region_data)
link1 = LinkSame(self.region_data.center_x_id, self.data_2d.pixel_component_ids[0])
link2 = LinkSame(self.region_data.center_y_id, self.data_2d.pixel_component_ids[1])

self.data_collection.add_link(link1)
self.data_collection.add_link(link2)

self.data_collection.new_subset_group(subset_state=self.region_data.center_x_id > 20)

process_events()

assert self.viewer.layers[0].enabled # image
assert self.viewer.layers[1].enabled # scatter
assert self.viewer.layers[2].enabled # image subset
assert self.viewer.layers[3].enabled # scatter subset


class TestWCSRegionDisplay(object):
def setup_method(self, method):

wcs1 = WCS(naxis=2)
wcs1.wcs.ctype = 'DEC--TAN', 'RA---TAN'
wcs1.wcs.set()

self.image1 = Data(label='image1', a=[[3, 3], [2, 2]], b=[[4, 4], [3, 2]],
coords=wcs1)
SHAPELY_CIRCLE_ARRAY = np.array([Point(2.5, 2.5).buffer(1), Point(1, 1).buffer(1)])
self.region_data = RegionData(label='My Regions',
color=np.array(['red', 'blue']),
area=shapely.area(SHAPELY_CIRCLE_ARRAY),
boundary=SHAPELY_CIRCLE_ARRAY)
self.application = GlueApplication()

self.session = self.application.session

self.hub = self.session.hub

self.data_collection = self.session.data_collection
self.data_collection.append(self.image1)
self.data_collection.append(self.region_data)

self.viewer = self.application.new_data_viewer(ImageViewer)

self.data_collection.register_to_hub(self.hub)
self.viewer.register_to_hub(self.hub)

def teardown_method(self, method):

# Properly close viewer and application
self.viewer.close()
self.viewer = None
self.application.close()
self.application = None

# Make sure cache is empty
if len(PIXEL_CACHE) > 0:
raise Exception("Pixel cache contains {0} elements".format(len(PIXEL_CACHE)))

Check warning on line 201 in glue_qt/viewers/image/tests/test_display_region_data.py

View check run for this annotation

Codecov / codecov/patch

glue_qt/viewers/image/tests/test_display_region_data.py#L201

Added line #L201 was not covered by tests
if len(ARRAY_CACHE) > 0:
raise Exception("Array cache contains {0} elements".format(len(ARRAY_CACHE)))

Check warning on line 203 in glue_qt/viewers/image/tests/test_display_region_data.py

View check run for this annotation

Codecov / codecov/patch

glue_qt/viewers/image/tests/test_display_region_data.py#L203

Added line #L203 was not covered by tests

def test_basics(self):
self.viewer.add_data(self.image1)

link1 = LinkSame(self.region_data.center_x_id, self.image1.world_component_ids[0])
link2 = LinkSame(self.region_data.center_y_id, self.image1.world_component_ids[1])

self.data_collection.add_link(link1)
self.data_collection.add_link(link2)

self.viewer.add_data(self.region_data)

self.viewer.state._display_world
assert len(self.viewer.state.layers) == 2
assert self.viewer.layers[0].enabled
assert self.viewer.layers[1].enabled
4 changes: 3 additions & 1 deletion glue_qt/viewers/scatter/data_viewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
class ScatterViewer(MatplotlibScatterMixin, MatplotlibDataViewer):

LABEL = '2D Scatter'
_layer_style_widget_cls = ScatterLayerStyleEditor
# We don't yet allow ScatterRegionLayerArtists directly on a ScatterViewer.
# If we wanted to do so, we would need to expand these options.
_layer_style_widget_cls = {ScatterLayerArtist: ScatterLayerStyleEditor}
_state_cls = ScatterViewerState
_options_cls = ScatterOptionsWidget
_data_artist_cls = ScatterLayerArtist
Expand Down
80 changes: 80 additions & 0 deletions glue_qt/viewers/scatter/layer_style_editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from qtpy import QtWidgets, QtGui
from qtpy.QtCore import Qt
from echo import delay_callback

from glue.core import BaseData
from echo.qt import autoconnect_callbacks_to_qt, connect_value
Expand Down Expand Up @@ -49,6 +50,8 @@

self.layer_state.viewer_state.add_callback('x_att', self._update_checkboxes)
self.layer_state.viewer_state.add_callback('y_att', self._update_checkboxes)
self.layer_state.add_callback('cmap_att', self._update_cmaps, priority=10000)

if hasattr(self.layer_state.viewer_state, 'plot_mode'):
self.layer_state.viewer_state.add_callback('plot_mode', self._update_vectors_visible)

Expand Down Expand Up @@ -226,3 +229,80 @@
self.ui.combodata_cmap.show()
self.ui.label_colormap.show()
self.ui.color_color.hide()

def _update_cmaps(self, *args):

with delay_callback(self.layer_state, 'cmap'):
if isinstance(self.layer_state.layer, BaseData):
layer = self.layer_state.layer
else:
layer = self.layer_state.layer.data

Check warning on line 239 in glue_qt/viewers/scatter/layer_style_editor.py

View check run for this annotation

Codecov / codecov/patch

glue_qt/viewers/scatter/layer_style_editor.py#L239

Added line #L239 was not covered by tests

actual_component = layer.get_component(self.layer_state.cmap_att)
if getattr(actual_component, 'preferred_cmap', False):
cmap = actual_component.preferred_cmap
name = actual_component.cmap_name
self.ui.combodata_cmap.refresh_options(colormaps=[(name, cmap)])

Check warning on line 245 in glue_qt/viewers/scatter/layer_style_editor.py

View check run for this annotation

Codecov / codecov/patch

glue_qt/viewers/scatter/layer_style_editor.py#L243-L245

Added lines #L243 - L245 were not covered by tests
else:
self.ui.combodata_cmap.refresh_options()


class ScatterRegionLayerStyleEditor(QtWidgets.QWidget):

def __init__(self, layer, parent=None):

super().__init__(parent=parent)

self.ui = load_ui('region_layer_style_editor.ui', self,
directory=os.path.dirname(__file__))

connect_kwargs = {'alpha': dict(value_range=(0, 1))}
self._connections = autoconnect_callbacks_to_qt(layer.state, self.ui, connect_kwargs)

self.layer_state = layer.state

self.layer_state.add_callback('cmap_mode', self._update_cmap_mode)

self._update_cmap_mode()
self.layer_state.add_callback('cmap_att', self._update_cmaps, priority=10000)

def _update_cmap_mode(self, cmap_mode=None):

if self.layer_state.cmap_mode == 'Fixed':
self.ui.label_cmap_attribute.hide()
self.ui.combosel_cmap_att.hide()
self.ui.label_cmap_limits.hide()
self.ui.valuetext_cmap_vmin.hide()
self.ui.valuetext_cmap_vmax.hide()
self.ui.button_flip_cmap.hide()
self.ui.combodata_cmap.hide()
self.ui.label_colormap.hide()
self.ui.color_color.show()
self.ui.combosel_percentile.hide()
else:
self.ui.label_cmap_attribute.show()
self.ui.combosel_cmap_att.show()
self.ui.label_cmap_limits.show()
self.ui.valuetext_cmap_vmin.show()
self.ui.valuetext_cmap_vmax.show()
self.ui.button_flip_cmap.show()
self.ui.combodata_cmap.show()
self.ui.label_colormap.show()
self.ui.color_color.hide()
self.ui.combosel_percentile.show()

Check warning on line 292 in glue_qt/viewers/scatter/layer_style_editor.py

View check run for this annotation

Codecov / codecov/patch

glue_qt/viewers/scatter/layer_style_editor.py#L283-L292

Added lines #L283 - L292 were not covered by tests

def _update_cmaps(self, *args):

with delay_callback(self.layer_state, 'cmap'):
if isinstance(self.layer_state.layer, BaseData):
layer = self.layer_state.layer

Check warning on line 298 in glue_qt/viewers/scatter/layer_style_editor.py

View check run for this annotation

Codecov / codecov/patch

glue_qt/viewers/scatter/layer_style_editor.py#L296-L298

Added lines #L296 - L298 were not covered by tests
else:
layer = self.layer_state.layer.data

Check warning on line 300 in glue_qt/viewers/scatter/layer_style_editor.py

View check run for this annotation

Codecov / codecov/patch

glue_qt/viewers/scatter/layer_style_editor.py#L300

Added line #L300 was not covered by tests

actual_component = layer.get_component(self.layer_state.cmap_att)
if getattr(actual_component, 'preferred_cmap', False):
cmap = actual_component.preferred_cmap
name = actual_component.cmap_name
self.ui.combodata_cmap.refresh_options(colormaps=[(name, cmap)])

Check warning on line 306 in glue_qt/viewers/scatter/layer_style_editor.py

View check run for this annotation

Codecov / codecov/patch

glue_qt/viewers/scatter/layer_style_editor.py#L302-L306

Added lines #L302 - L306 were not covered by tests
else:
self.ui.combodata_cmap.refresh_options()

Check warning on line 308 in glue_qt/viewers/scatter/layer_style_editor.py

View check run for this annotation

Codecov / codecov/patch

glue_qt/viewers/scatter/layer_style_editor.py#L308

Added line #L308 was not covered by tests
2 changes: 1 addition & 1 deletion glue_qt/viewers/scatter/layer_style_editor.ui
Original file line number Diff line number Diff line change
Expand Up @@ -1051,4 +1051,4 @@
</customwidgets>
<resources/>
<connections/>
</ui>
</ui>
Loading
Loading