From 6a6ff07c4fd9537c52336726afe99d68e2388f54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Paul=20M=C3=BCller?= Date: Thu, 19 Nov 2026 17:59:46 +0100 Subject: [PATCH] enh: show Young's modulus warnings in the plots (#144) When the Young's modulus is plotted (axis or marker hue), the plots show the warnings that dclab issues when computing the Young's modulus (dclab caches the Young's modulus, so the warnings are deduced from the data): - "N% of events outside LUT" if more than 10% of the events are not covered by the look-up table - "Temperature out of range" if the temperature is outside of the valid range of the viscosity model The labels are shown like "Please reduce KDE spacing" and have the detailed description as tooltip. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG | 3 + dcscope/gui/pipeline_plot_compute.py | 81 +++++++++++++++++++++++++ dcscope/gui/pipeline_plot_item.py | 43 +++++++++++++ tests/test_gui_pipeline_plot_compute.py | 75 +++++++++++++++++++++++ tests/test_gui_plotting.py | 39 ++++++++++++ 5 files changed, 241 insertions(+) create mode 100644 tests/test_gui_pipeline_plot_compute.py diff --git a/CHANGELOG b/CHANGELOG index c79bbe5..288d7dd 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -29,6 +29,9 @@ to all datasets in the Dataset tab of the Analysis View (#198) - enh: allow to hide the traces of individual fluorescence channels in the Quick View (#200) + - enh: show warnings about an inaccurate Young's modulus (events + outside of the look-up table, temperature outside of the range of + the viscosity model) in the plots (#144) - docs: add quick guide for fluorescence crosstalk correction (#120) - docs: screenshot scripts download missing datasets from figshare and use the icon theme of DCscope diff --git a/dcscope/gui/pipeline_plot_compute.py b/dcscope/gui/pipeline_plot_compute.py index 3713b56..e577234 100644 --- a/dcscope/gui/pipeline_plot_compute.py +++ b/dcscope/gui/pipeline_plot_compute.py @@ -4,6 +4,9 @@ but you can prepare the plotted data (e.g. KDE computation) in the background, keeping the UI responsive. """ +import warnings + +from dclab.features.emodulus import viscosity from dclab.kde import KernelDensityEstimator from dclab.kde.smooth_contour import compute_contour_opening_angles import numpy as np @@ -175,3 +178,81 @@ def compute_scatter_data_from_state( brush = pg.mkBrush(colork) return x, y, kde, idx, brush + + +def get_emodulus_warnings(rtdc_ds, plot_state): + """Return warnings about inaccurate Young's modulus data in a plot (#144) + + The warnings correspond to those that dclab issues when computing + the Young's modulus. Since dclab caches the Young's modulus, its + warnings are only issued once, so they are deduced here: + + - more than 10% of the events are not covered by the look-up table + (:class:`dclab.features.emodulus.YoungsModulusLookupTableExceededWarning`) + - the temperature is outside the valid range of the viscosity model + (:class:`dclab.features.emodulus.viscosity.TemperatureOutOfRangeWarning`) + + Parameters + ---------- + rtdc_ds: dclab.rtdc_dataset.RTDCBase + Dataset with filters applied + plot_state: dict + Plot state; warnings are only returned if the Young's modulus + is plotted (axes or scatter plot hue) + + Returns + ------- + messages: list of tuple + Short messages for display in the plot and detailed + descriptions (e.g. for tooltips) + """ + gen = plot_state["general"] + sca = plot_state["scatter"] + features = [gen["axis x"], gen["axis y"]] + if sca["enabled"] and sca["marker hue"] == "feature": + features.append(sca["hue feature"]) + if "emodulus" not in features or "emodulus" not in rtdc_ds: + return [] + + messages = [] + filt = rtdc_ds.filter.all + emod = np.asarray(rtdc_ds["emodulus"][filt]) + if emod.size: + nan_fraction = np.mean(np.isnan(emod)) + if nan_fraction > 0.1: + lut = rtdc_ds.config["calculation"].get("emodulus lut", "") + messages.append(( + f"{nan_fraction:.0%} of events outside LUT", + f"The Young's modulus could not be computed for " + f"{nan_fraction:.0%} of the events, because they are not " + f"covered by the look-up table '{lut}'.")) + + # temperature range of the viscosity model (known media only) + calc = rtdc_ds.config["calculation"] + medium = calc.get("emodulus medium", "other") + if medium in viscosity.KNOWN_MEDIA: + if "emodulus temperature" in calc: + temperature = calc["emodulus temperature"] + elif "temp" in rtdc_ds: + temperature = np.asarray(rtdc_ds["temp"][filt]) + else: + temperature = None + if temperature is not None and np.size(temperature): + with warnings.catch_warnings(record=True) as ws: + warnings.simplefilter("always") + viscosity.get_viscosity( + medium=medium, + channel_width=rtdc_ds.config["setup"]["channel width"], + flow_rate=rtdc_ds.config["setup"]["flow rate"], + temperature=temperature, + model=calc.get("emodulus viscosity model", + "herold-2017"), + ) + for w in ws: + if issubclass(w.category, + viscosity.TemperatureOutOfRangeWarning): + messages.append(( + "Temperature out of range", + f"Young's modulus: {w.message}")) + break + return messages diff --git a/dcscope/gui/pipeline_plot_item.py b/dcscope/gui/pipeline_plot_item.py index aaac32d..425b412 100644 --- a/dcscope/gui/pipeline_plot_item.py +++ b/dcscope/gui/pipeline_plot_item.py @@ -15,6 +15,7 @@ compute_contours_from_state, compute_contour_reliable, compute_scatter_data_from_state, + get_emodulus_warnings, ) @@ -42,6 +43,8 @@ def __init__(self, task_manager: TaskManager, pipeline, *args, **kwargs): self._task_data_contour = [] self._task_data_scatter = [] self._list_contours = [] + #: warnings displayed in this plot (see `add_warning_labels`) + self._warnings_shown = [] self.legend = None # circumvent problems with removed plots self.setAcceptHoverEvents(False) @@ -106,6 +109,7 @@ def request_draw(self, dslist, slot_states, plot_state, hash_flag=None): for el in self._plot_elements: self.removeItem(el) self._plot_elements.clear() + self._warnings_shown.clear() self._list_contours.clear() if not dslist: @@ -304,6 +308,9 @@ def request_contour_handler(self, task: dict, result: tuple): dy=-12, ) + self.add_warning_labels( + get_emodulus_warnings(task["kwargs"]["rtdc_ds"], plot_state)) + with self._update_lock: self._list_contours += contours self._task_data_contour.remove(task) @@ -358,6 +365,9 @@ def request_scatter_handler(self, task: dict, result: tuple): if gen["scale y"] == "log": y = np.log10(y) + self.add_warning_labels( + get_emodulus_warnings(task["kwargs"]["rtdc_ds"], plot_state)) + # add dcnum hash label if hash_flag: add_label( @@ -388,6 +398,33 @@ def request_scatter_handler(self, task: dict, result: tuple): self._task_data_scatter.remove(task) self._plot_elements.append(scatter) + def add_warning_labels(self, messages): + """Display warnings in the plot (e.g. inaccurate Young's modulus) + + The warnings are shown in red in the bottom left corner, above + the "Please reduce KDE spacing" label, with a detailed + description as tooltip. Each warning is only shown once per + plot (e.g. when multiple datasets are plotted). + + Parameters + ---------- + messages: list of tuple + Short message and detailed description for each warning + """ + for msg, description in messages: + if msg in self._warnings_shown: + continue + label = add_label(msg, + anchor_parent=self.axes["bottom"]["item"], + font_size_diff=-1, + color="red", + text_halign="left", + text_valign="bottom", + dy=-26 - 14 * len(self._warnings_shown), + ) + label.setToolTip(description) + self._warnings_shown.append(msg) + def zoomin_contours(self, margin_per=5): """Zoom-in to contour data with margin""" if not self._list_contours: @@ -479,6 +516,11 @@ def add_label(text, anchor_parent, text_halign="center", text_valign="center", Manual horizontal positioning dy: float Manual vertical positioning + + Returns + ------- + label: QtWidgets.QGraphicsTextItem + The label item """ assert text_halign in ["left", "center", "right"] assert text_valign in ["top", "center", "bottom"] @@ -511,6 +553,7 @@ def add_label(text, anchor_parent, text_halign="center", text_valign="center", else: # "bottom" y = -height/2 label.setPos(x + dx, y + dy) + return label def get_axes_labels(plot_state, slot_states): diff --git a/tests/test_gui_pipeline_plot_compute.py b/tests/test_gui_pipeline_plot_compute.py new file mode 100644 index 0000000..dbdd1e0 --- /dev/null +++ b/tests/test_gui_pipeline_plot_compute.py @@ -0,0 +1,75 @@ +"""Tests for the background computations of the pipeline plots""" +import copy + +import dclab +import numpy as np +import pytest + +from dcscope.gui.pipeline_plot_compute import get_emodulus_warnings +from dcscope.pipeline.plot import DEFAULT_STATE + + +def make_dataset(num_outside_lut=0, temperature=25.0): + """Dataset with Young's modulus (some events outside of the LUT)""" + rng = np.random.default_rng(42) + area = np.concatenate([rng.uniform(50, 80, 100), + np.full(num_outside_lut, 10.0)]) + deform = np.concatenate([rng.uniform(0.02, 0.05, 100), + np.full(num_outside_lut, 0.2)]) + ds = dclab.new_dataset({"area_um": area, "deform": deform}) + ds.config["setup"]["channel width"] = 20 + ds.config["setup"]["flow rate"] = 0.04 + ds.config["imaging"]["pixel size"] = 0.34 + ds.config["calculation"] = { + "emodulus lut": "LE-2D-FEM-19", + "emodulus medium": "CellCarrier", + "emodulus temperature": temperature, + "emodulus viscosity model": "buyukurganci-2022", + } + return ds + + +def plot_state(axis_y="emodulus"): + state = copy.deepcopy(DEFAULT_STATE) + state["general"]["axis y"] = axis_y + return state + + +@pytest.mark.filterwarnings( + "ignore::dclab.features.emodulus.YoungsModulusLookupTableExceededWarning") +def test_emodulus_warnings_lut_exceeded_issue_144(): + ds = make_dataset(num_outside_lut=50) + warnings = get_emodulus_warnings(ds, plot_state()) + assert len(warnings) == 1 + assert warnings[0][0] == "33% of events outside LUT" + assert warnings[0][1].count("LE-2D-FEM-19") + # no warnings if the Young's modulus is not plotted + assert get_emodulus_warnings(ds, plot_state("deform")) == [] + # unless it is used for the marker hue + state = plot_state("deform") + state["scatter"]["marker hue"] = "feature" + state["scatter"]["hue feature"] = "emodulus" + assert len(get_emodulus_warnings(ds, state)) == 1 + + +@pytest.mark.filterwarnings( + "ignore::dclab.features.emodulus.viscosity.TemperatureOutOfRangeWarning") +def test_emodulus_warnings_temperature_out_of_range_issue_144(): + # valid range of "buyukurganci-2022" is 22 to 37 degC + ds = make_dataset(temperature=40) + warnings = get_emodulus_warnings(ds, plot_state()) + assert len(warnings) == 1 + assert warnings[0][0] == "Temperature out of range" + # the description contains the valid range + assert warnings[0][1].count("[22, 37]") + + +def test_emodulus_warnings_none(): + ds = make_dataset() + assert get_emodulus_warnings(ds, plot_state()) == [] + # filtered events only + ds2 = make_dataset(num_outside_lut=50) + ds2.config["filtering"]["deform min"] = 0 + ds2.config["filtering"]["deform max"] = 0.1 + ds2.apply_filter() + assert get_emodulus_warnings(ds2, plot_state()) == [] diff --git a/tests/test_gui_plotting.py b/tests/test_gui_plotting.py index 21ce41b..67f88da 100644 --- a/tests/test_gui_plotting.py +++ b/tests/test_gui_plotting.py @@ -745,3 +745,42 @@ def test_plot_range_on_first_show_issue_229(qtbot, mw): QtCore.QEventLoop.ProcessEventsFlag.AllEvents, 300) # two scatter plots and a contour plot check_plot_range_matches_data(mw, plot_id, num_plot_items=3) + + +@pytest.mark.filterwarnings( + "ignore::dclab.features.emodulus.YoungsModulusLookupTableExceededWarning") +@pytest.mark.filterwarnings( + 'ignore::dclab.kde.binning.KernelDensityEstimationForEmptyArrayWarning') +@pytest.mark.filterwarnings('ignore::dclab.kde.base.ContourSpacingTooLarge') +@pytest.mark.filterwarnings( + 'ignore::dcscope.pipeline.core.ContourSpacingWarning') +def test_emodulus_warning_in_plot_issue_144(qtbot, mw): + """Inaccurate Young's modulus data are indicated in the plots""" + qtbot.addWidget(mw) + # most of the events are outside of the look-up table + slot_ids = mw.add_dataslot(paths=[datapath / "extreme_shear.rtdc"]) + plot_id = mw.add_plot() + plot = mw.pipeline.get_plot(plot_id, run_checks=False) + state = plot.__getstate__() + state["general"]["axis y"] = "emodulus" + plot.__setstate__(state) + + pe = mw.ui.block_matrix.get_widget( + filt_plot_id=plot_id, slot_id=slot_ids[0]) + qtbot.mouseClick(pe, QtCore.Qt.MouseButton.LeftButton) + mw.wait_for_tasks() + QtWidgets.QApplication.processEvents( + QtCore.QEventLoop.ProcessEventsFlag.AllEvents, 300) + + plot_widget = mw.subwindows_plots[plot_id].widget() + + def warnings_shown(): + warnings = [pp._warnings_shown for pp in plot_widget.plot_items] + # scatter plot and contour plot + assert len(warnings) == 2 + for ws in warnings: + assert len(ws) == 1 + assert ws[0].count("of events outside LUT") + + # the warnings are added when the plot data are received + qtbot.waitUntil(warnings_shown, timeout=5000)