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

Coloring by features as well as cluster #257

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
146 changes: 140 additions & 6 deletions napari_clusters_plotter/_plotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import pandas as pd
from matplotlib.figure import Figure
from napari.utils.colormaps import ALL_COLORMAPS
from napari_skimage_regionprops._parametric_images import map_measurements_on_labels
from napari_tools_menu import register_dock_widget
from qtpy import QtWidgets
from qtpy.QtCore import Qt
Expand All @@ -22,11 +23,13 @@
QVBoxLayout,
QWidget,
)
from vispy.color import Color

from ._plotter_utilities import (
apply_cluster_colors_to_bars,
clustered_plot_parameters,
estimate_number_bins,
feature_plot_parameters,
make_cluster_overlay_img,
unclustered_plot_parameters,
)
Expand Down Expand Up @@ -85,6 +88,7 @@ def __init__(self, napari_viewer):

self.analysed_layer = None
self.visualized_labels_layer = None
self.visualized_feature_layer = None

def manual_clustering_method(inside):
inside = np.array(inside) # leads to errors sometimes otherwise
Expand Down Expand Up @@ -221,11 +225,11 @@ def plotting_type_changed():
self.bin_number_container.setVisible(True)
self.log_scale_container.setVisible(True)
self.plot_hide_non_selected.setChecked(True)
self.colormap_container.setVisible(True)
# self.colormap_container.setVisible(True)
else:
self.bin_number_container.setVisible(False)
self.log_scale_container.setVisible(False)
self.colormap_container.setVisible(False)
# self.colormap_container.setVisible(False)
replot()

def bin_number_set():
Expand Down Expand Up @@ -310,7 +314,7 @@ def bin_auto():
options={"choices": list(ALL_COLORMAPS.keys())},
label="Colormap",
)
self.colormap_container.setVisible(False)
self.colormap_container.setVisible(True)
self.colormap_dropdown.native.currentIndexChanged.connect(replot)
self.advanced_options_container.layout().addWidget(self.colormap_container)

Expand Down Expand Up @@ -484,6 +488,16 @@ def update_axes_and_clustering_id_lists(self):
if "CLUSTER" in feature
]
)
self.plot_cluster_id.addItems(
[
feature
for feature in list(features.keys())
if "frame" not in feature.lower()
and "label" not in feature.lower()
and "CLUSTER" not in feature
]
)

self.plot_x_axis.setCurrentIndex(former_x_axis)
self.plot_y_axis.setCurrentIndex(former_y_axis)
self.plot_cluster_id.setCurrentIndex(former_cluster_id)
Expand All @@ -501,6 +515,10 @@ def run(
This function that runs after the run button is clicked.
"""

###############
# INITIALISATION
###############

if not self.isVisible() and force_redraw is False:
# don't redraw in case the plot is invisible anyway
return
Expand Down Expand Up @@ -534,11 +552,17 @@ def run(
tracking_data = len(self.analysed_layer.data.shape) == 4 and "frame" not in [
key.lower() for key in features.keys()
]

##########################
# CLUSTERING VISUALISATION
##########################

colors = get_nice_colormap()
if (
plot_cluster_name is not None
and plot_cluster_name != "label"
and plot_cluster_name in list(features.keys())
and "CLUSTER" in plot_cluster_name
):
if self.plot_hide_non_selected.isChecked():
features.loc[
Expand All @@ -550,6 +574,7 @@ def run(
self.label_ids = features["label"]
self.cluster_ids = features[plot_cluster_name].fillna(-1)

# Determine Current Frame
if len(self.analysed_layer.data.shape) == 4 and not tracking_data:
frame_id = features[POINTER].tolist()
current_frame = self.frame
Expand All @@ -559,6 +584,8 @@ def run(
else:
warnings.warn("Image dimensions too high for processing!")

############################
# Scatter Plot Visualisation
if self.plotting_type.currentText() == PlottingType.SCATTER.name:
a, sizes, colors_plot = clustered_plot_parameters(
cluster_id=self.cluster_ids,
Expand All @@ -574,6 +601,9 @@ def run(

self.graphics_widget.axes.set_xlabel(plot_x_axis_name)
self.graphics_widget.axes.set_ylabel(plot_y_axis_name)

#########################
# Histogram Visualisation
else:
if self.bin_auto.isChecked():
if plot_x_axis_name == plot_y_axis_name:
Expand Down Expand Up @@ -644,8 +674,8 @@ def run(

self.graphics_widget.match_napari_layout()

from vispy.color import Color

##############################
# Generating the cluster image
cmap = [Color(hex_name).RGBA.astype("float") / 255 for hex_name in colors]

# generate dictionary mapping each prediction to its respective color
Expand All @@ -663,11 +693,11 @@ def run(

keep_selection = list(self.viewer.layers.selection)

# Generating the cluster image
if redraw_cluster_image:
# depending on the dimensionality of the data
# generate the cluster image
if len(self.analysed_layer.data.shape) == 4:
# Check which kind of timelapse and modify labels accordingly
if not tracking_data:
max_timepoint = features[POINTER].max() + 1
label_id_list_per_timepoint = [
Expand All @@ -690,12 +720,14 @@ def run(
for i in range(self.analysed_layer.data.shape[0])
]

# Generate the dask image
cluster_image = dask_cluster_image_timelapse(
self.analysed_layer.data,
label_id_list_per_timepoint,
prediction_lists_per_timepoint,
)

# 3d case -> no dask needed
elif len(self.analysed_layer.data.shape) <= 3:
cluster_image = generate_cluster_image(
self.analysed_layer.data, self.label_ids, self.cluster_ids
Expand All @@ -704,6 +736,11 @@ def run(
warnings.warn("Image dimensions too high for processing!")
return

# hiding the feature layer:
if self.visualized_feature_layer is not None:
self.visualized_feature_layer.opacity = 0

# Adding the cluster image
# if the cluster image layer doesn't yet exist make it
# otherwise just update it
if (
Expand All @@ -726,6 +763,103 @@ def run(
for s in keep_selection:
self.viewer.layers.selection.add(s)

#######################
# FEATURE VISUALISATION
#######################
elif (
plot_cluster_name is not None
and plot_cluster_name != "label"
and plot_cluster_name in list(features.keys())
and "CLUSTER" not in plot_cluster_name
):
if self.plotting_type.currentText() != PlottingType.SCATTER.name:
warnings.warn("Feature Visualisation Only Availible in Scatter Plot!")
return
feature_values = features[plot_cluster_name].fillna(0)

# Determine Current Frame
if len(self.analysed_layer.data.shape) == 4 and not tracking_data:
frame_id = features[POINTER].tolist()
current_frame = self.frame
elif len(self.analysed_layer.data.shape) <= 3 or tracking_data:
frame_id = None
current_frame = None
else:
warnings.warn("Image dimensions too high for processing!")

############################
# Scatter Plot Visualisation

a, sizes, colors_plot = feature_plot_parameters(
feature_values=feature_values,
frame_id=frame_id,
current_frame=current_frame,
n_datapoints=number_of_points,
colormap=self.colormap_dropdown.value,
)

self.graphics_widget.make_scatter_plot(
self.data_x, self.data_y, colors_plot, sizes, a
)

self.graphics_widget.axes.set_xlabel(plot_x_axis_name)
self.graphics_widget.axes.set_ylabel(plot_y_axis_name)

keep_selection = list(self.viewer.layers.selection)

self.graphics_widget.match_napari_layout()

if redraw_cluster_image:
# depending on the dimensionality of the data
# generate the feature image
if len(self.analysed_layer.data.shape) > 4:
warnings.warn("Image dimensions too high for processing!")
return
else:
feature_image = map_measurements_on_labels(
self.analysed_layer, plot_cluster_name, self.viewer
)
# Adding the feature image
# if the feature image layer doesn't yet exist make it
# otherwise just update it
if (
self.visualized_feature_layer is None
or self.visualized_feature_layer not in self.viewer.layers
):
self.visualized_feature_layer = self.viewer.add_image(
feature_image,
name="feature visualisation",
scale=self.analysed_layer.scale,
)
else:
# Making sure that the feature visualisation layer is on top
if self.viewer.layers[-1] != self.visualized_feature_layer:
for i, layer in enumerate(self.viewer.layers):
if layer == self.visualized_feature_layer:
feature_layer_index = i
self.viewer.layers.move(
feature_layer_index, len(self.viewer.layers)
)
# updating data
self.visualized_feature_layer.data = feature_image

# Adjusting the Layer
self.visualized_feature_layer.contrast_limits = np.percentile(
features[plot_cluster_name].to_numpy(), (1, 99)
)
self.visualized_feature_layer.colormap = (
self.colormap_dropdown.value
)
self.visualized_feature_layer.opacity = 1

self.viewer.layers.selection.clear()
for s in keep_selection:
self.viewer.layers.selection.add(s)

###########################
# Unclustered Visualisation
###########################

else:
if len(self.analysed_layer.data.shape) == 4 and not tracking_data:
frame_id = features[POINTER].tolist()
Expand Down
Loading