-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy path_new_plotter_widget.py
More file actions
426 lines (349 loc) · 13.1 KB
/
_new_plotter_widget.py
File metadata and controls
426 lines (349 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
from enum import Enum, auto
from pathlib import Path
import napari
import numpy as np
from biaplotter.plotter import ArtistType, CanvasWidget
from napari.utils.colormaps import ALL_COLORMAPS
from qtpy import uic
from qtpy.QtCore import Qt, Signal
from qtpy.QtWidgets import QComboBox, QVBoxLayout, QWidget
from ._algorithm_widget import BaseWidget
class PlottingType(Enum):
HISTOGRAM = auto()
SCATTER = auto()
class PlotterWidget(BaseWidget):
"""
Widget for plotting data from selected layers in napari.
Parameters
----------
napari_viewer : napari.Viewer
The napari viewer to connect to.
"""
input_layer_types = [
napari.layers.Labels,
napari.layers.Points,
napari.layers.Surface,
napari.layers.Vectors,
napari.layers.Shapes,
]
plot_needs_update = Signal()
def __init__(self, napari_viewer):
super().__init__(napari_viewer)
self._setup_ui(napari_viewer)
self._on_update_layer_selection(None)
self._setup_callbacks()
self.plot_needs_update.connect(self._replot)
def _setup_ui(self, napari_viewer):
"""
Helper function to set up the UI of the widget.
"""
self.control_widget = QWidget()
uic.loadUi(
Path(__file__).parent / "plotter_inputs.ui",
self.control_widget,
)
self._selectors = {
"x": self.control_widget.x_axis_box,
"y": self.control_widget.y_axis_box,
"hue": self.control_widget.hue_box,
}
self.layout = QVBoxLayout(self)
self.layout.setAlignment(Qt.AlignTop)
self.plotting_widget = CanvasWidget(napari_viewer, self)
self.plotting_widget.active_artist = self.plotting_widget.artists[
ArtistType.SCATTER
]
# Add plot and options as widgets
self.layout.addWidget(self.plotting_widget)
self.layout.addWidget(self.control_widget)
# Setting of Widget options
self.hue: QComboBox = self.control_widget.hue_box
self.control_widget.plot_type_box.addItems(
[PlottingType.SCATTER.name, PlottingType.HISTOGRAM.name]
)
self.control_widget.cmap_box.addItems(list(ALL_COLORMAPS.keys()))
self.control_widget.cmap_box.setCurrentIndex(
np.argwhere(np.array(list(ALL_COLORMAPS.keys())) == "magma")[0][0]
)
# Setting Visibility Defaults
self.control_widget.manual_bins_container.setVisible(False)
self.control_widget.bins_settings_container.setVisible(False)
self.control_widget.log_scale_container.setVisible(False)
def _setup_callbacks(self):
"""
Set up the callbacks for the widget.
"""
# Connect all necessary functions to the replot
connections_to_replot = [
(
self.control_widget.plot_type_box.currentIndexChanged,
self.plot_needs_update.emit,
),
(
self.control_widget.set_bins_button.clicked,
self.plot_needs_update.emit,
),
(
self.control_widget.auto_bins_checkbox.stateChanged,
self.plot_needs_update.emit,
),
(
self.control_widget.log_scale_checkbutton.stateChanged,
self.plot_needs_update.emit,
),
(
self.control_widget.non_selected_checkbutton.stateChanged,
self.plot_needs_update.emit,
),
(
self.control_widget.cmap_box.currentIndexChanged,
self.plot_needs_update.emit,
),
]
for signal, callback in connections_to_replot:
signal.connect(callback)
for dim in ["x", "y", "hue"]:
self._selectors[dim].currentTextChanged.connect(
self.plot_needs_update.emit
)
self.viewer.layers.selection.events.changed.connect(
self._on_update_layer_selection
)
# reset the coloring of the selected layer
self.control_widget.reset_button.clicked.connect(self._reset)
# connect data selection in plot to layer coloring update
active_artist = self.plotting_widget.active_artist
active_artist.color_indices_changed_signal.connect(
self._color_layer_by_cluster_id
)
def _replot(self):
"""
Replot the data with the current settings.
"""
# if no x or y axis is selected, return
if self.x_axis == "" or self.y_axis == "":
return
# retrieve the data from the selected layers
features = self._get_features()
x_data = features[self.x_axis].values
y_data = features[self.y_axis].values
# # if no hue is selected, set it to 0
# if self.hue_axis == "None":
# hue = np.zeros(len(features))
# elif self.hue_axis != "":
# hue = features[self.hue_axis].values
self.plotting_widget.active_artist.data = np.stack(
[x_data, y_data], axis=1
)
if "MANUAL_CLUSTER_ID" in features.columns:
self.plotting_widget.active_artist.color_indices = features[
"MANUAL_CLUSTER_ID"
].values
def _checkbox_status_changed(self):
self._replot()
def _plotting_type_changed(
self,
): # TODO NEED TO ADD WHICH VARIABLE STORES THE TYPE
if (
self.control_widget.plot_type_box.currentText()
== PlottingType.HISTOGRAM.name
):
self.control_widget.bins_settings_container.setVisible(True)
self.control_widget.log_scale_container.setVisible(True)
elif (
self.control_widget.plot_type_box.currentText()
== PlottingType.SCATTER.name
):
self.control_widget.bins_settings_container.setVisible(False)
self.control_widget.log_scale_container.setVisible(False)
self._replot()
def _bin_number_set(self):
self._replot()
def _bin_auto(self):
self.control_widget.manual_bins_container.setVisible(
not self.control_widget.auto_bins_checkbox.isChecked()
)
if self.control_widget.auto_bins_checkbox.isChecked():
self._replot()
# Connecting the widgets to actual object variables:
# using getters and setters for flexibility
@property
def log_scale(self):
return self.control_widget.log_scale_checkbutton.isChecked()
@log_scale.setter
def log_scale(self, val: bool):
self.control_widget.log_scale_checkbutton.setChecked(val)
@property
def automatic_bins(self):
return self.control_widget.auto_bins_checkbox.isChecked()
@automatic_bins.setter
def automatic_bins(self, val: bool):
self.control_widget.auto_bins_checkbox.setChecked(val)
@property
def bin_number(self):
return self.control_widget.n_bins_box.value()
@property
def hide_non_selected(self):
return self.control_widget.non_selected_checkbutton.isChecked()
@hide_non_selected.setter
def hide_non_selected(self, val: bool):
self.control_widget.non_selected_checkbutton.setChecked(val)
@property
def colormap_plot(self):
return self.control_widget.cmap_box.currentText()
@property
def plotting_type(self):
return self.control_widget.plot_type_box.currentText()
@plotting_type.setter
def plotting_type(self, plot_type):
if plot_type in PlottingType.__members__:
self.control_widget.plot_type_box.setCurrentText(plot_type)
@property
def x_axis(self):
return self.control_widget.x_axis_box.currentText()
@x_axis.setter
def x_axis(self, column: str):
self.control_widget.x_axis_box.setCurrentText(column)
self._replot()
@property
def y_axis(self):
return self.control_widget.y_axis_box.currentText()
@y_axis.setter
def y_axis(self, column: str):
self.control_widget.y_axis_box.setCurrentText(column)
self._replot()
@property
def hue_axis(self):
return self.control_widget.hue_box.currentText()
@hue_axis.setter
def hue_axis(self, column: str):
self.control_widget.hue_box.setCurrentText(
column
) # TODO insert checks and change values
@property
def n_selected_layers(self) -> int:
"""
Number of currently selected layers.
"""
return len(list(self.viewer.layers.selection))
def _on_update_layer_selection(
self, event: napari.utils.events.Event
) -> None:
"""
Called when the layer selection changes. Updates the layers attribute.
"""
# don't do anything if no layer is selected
if self.n_selected_layers == 0:
return
# check if the selected layers are of the correct type
selected_layer_types = [
type(layer) for layer in self.viewer.layers.selection
]
for layer_type in selected_layer_types:
if layer_type not in self.input_layer_types:
return
# check if all selected layers are of the same type
if len(set(selected_layer_types)) > 1:
return
self.layers = list(self.viewer.layers.selection)
self._update_feature_selection(None)
for layer in self.layers:
layer.events.features.connect(self._update_feature_selection)
def _update_feature_selection(
self, event: napari.utils.events.Event
) -> None:
"""
Update the features in the dropdowns.
"""
self.blockSignals(True)
current_x = self.x_axis
current_y = self.y_axis
current_hue = self.hue_axis
# block selector changed signals until all items added
for dim in ["x", "y", "hue"]:
self._selectors[dim].blockSignals(True)
for dim in ["x", "y", "hue"]:
self._selectors[dim].clear()
for dim in ["x", "y", "hue"]:
features_to_add = sorted(self.common_columns)
if "MANUAL_CLUSTER_ID" in features_to_add:
features_to_add.remove("MANUAL_CLUSTER_ID")
self._selectors[dim].addItems(features_to_add)
# it should always be possible to select no color
self._selectors["hue"].addItem("None")
# set the previous values if they are still available
for dim, value in zip(
["x", "y", "hue"], [current_x, current_y, current_hue]
):
if value in self.common_columns:
self._selectors[dim].setCurrentText(value)
for dim in ["x", "y", "hue"]:
self._selectors[dim].blockSignals(False)
self.blockSignals(False)
self.plot_needs_update.emit()
def _color_layer_by_cluster_id(self):
"""
Color the selected layer according to the color indices.
"""
features = self._get_features()
color_indices = self.plotting_widget.active_artist.color_indices
colors = self.plotting_widget.active_artist.categorical_colormap(
color_indices
)
for selected_layer in self.viewer.layers.selection:
layer_indices = features[
features["layer"] == selected_layer.name
].index
_apply_layer_color(selected_layer, colors[layer_indices])
# store cluster indeces in the features table
selected_layer.features["MANUAL_CLUSTER_ID"] = color_indices[
layer_indices
]
def _reset(self):
"""
Reset the selection in the current plotting widget.
"""
self.plotting_widget.active_artist.color_indices = np.zeros(
len(self._get_features())
)
self._color_layer_by_cluster_id()
def _apply_layer_color(layer, colors):
"""
Apply colors to the layer based on the layer type.
Parameters
----------
layer : napari.layers.Layer
The layer to color.
colors : np.ndarray
The color array (Nx4).
"""
from napari.utils import DirectLabelColormap
color_mapping = {
napari.layers.Points: lambda _layer, _color: setattr(
_layer, "face_color", _color
),
napari.layers.Vectors: lambda _layer, _color: setattr(
_layer, "edge_color", _color
),
napari.layers.Surface: lambda _layer, _color: setattr(
_layer, "vertex_colors", _color
),
napari.layers.Shapes: lambda _layer, _color: setattr(
_layer, "face_color", _color
),
napari.layers.Labels: lambda _layer, _color: setattr(
_layer,
"colormap",
DirectLabelColormap(
color_dict={
label: _color[label] for label in np.unique(_layer.data)
}
),
),
}
if type(layer) in color_mapping:
if type(layer) is napari.layers.Labels:
# add a color for the background at the first index
colors = np.insert(colors, 0, [0, 0, 0, 0], axis=0)
color_mapping[type(layer)](layer, colors)
layer.refresh()