diff --git a/.gitignore b/.gitignore index c35a7442..dfa6c999 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ spikeinterface_gui/tests/*/* my_dataset/* +comparison_scripts/ diff --git a/docs/source/images/views/desktop/agreementmatrix.png b/docs/source/images/views/desktop/agreementmatrix.png new file mode 100644 index 00000000..f02549e0 Binary files /dev/null and b/docs/source/images/views/desktop/agreementmatrix.png differ diff --git a/docs/source/images/views/desktop/comparelabels.png b/docs/source/images/views/desktop/comparelabels.png new file mode 100644 index 00000000..5ce05d7e Binary files /dev/null and b/docs/source/images/views/desktop/comparelabels.png differ diff --git a/docs/source/images/views/desktop/comparemetrics.png b/docs/source/images/views/desktop/comparemetrics.png new file mode 100644 index 00000000..a08f43ce Binary files /dev/null and b/docs/source/images/views/desktop/comparemetrics.png differ diff --git a/docs/source/images/views/desktop/comparespikes.png b/docs/source/images/views/desktop/comparespikes.png new file mode 100644 index 00000000..5cbb0a21 Binary files /dev/null and b/docs/source/images/views/desktop/comparespikes.png differ diff --git a/docs/source/images/views/desktop/compareunitlist.png b/docs/source/images/views/desktop/compareunitlist.png new file mode 100644 index 00000000..428437c0 Binary files /dev/null and b/docs/source/images/views/desktop/compareunitlist.png differ diff --git a/docs/source/images/views/desktop/unitvenn.png b/docs/source/images/views/desktop/unitvenn.png new file mode 100644 index 00000000..fcedb988 Binary files /dev/null and b/docs/source/images/views/desktop/unitvenn.png differ diff --git a/docs/source/images/views/web/agreementmatrix.png b/docs/source/images/views/web/agreementmatrix.png new file mode 100644 index 00000000..6b14a173 Binary files /dev/null and b/docs/source/images/views/web/agreementmatrix.png differ diff --git a/docs/source/images/views/web/comparelabels.png b/docs/source/images/views/web/comparelabels.png new file mode 100644 index 00000000..a9c01420 Binary files /dev/null and b/docs/source/images/views/web/comparelabels.png differ diff --git a/docs/source/images/views/web/comparemetrics.png b/docs/source/images/views/web/comparemetrics.png new file mode 100644 index 00000000..a040c611 Binary files /dev/null and b/docs/source/images/views/web/comparemetrics.png differ diff --git a/docs/source/images/views/web/comparespikes.png b/docs/source/images/views/web/comparespikes.png new file mode 100644 index 00000000..27e21c0a Binary files /dev/null and b/docs/source/images/views/web/comparespikes.png differ diff --git a/docs/source/images/views/web/compareunitlist.png b/docs/source/images/views/web/compareunitlist.png new file mode 100644 index 00000000..5ab8d8b1 Binary files /dev/null and b/docs/source/images/views/web/compareunitlist.png differ diff --git a/docs/source/images/views/web/unitvenn.png b/docs/source/images/views/web/unitvenn.png new file mode 100644 index 00000000..cab2ad7e Binary files /dev/null and b/docs/source/images/views/web/unitvenn.png differ diff --git a/docs/source/launch.rst b/docs/source/launch.rst index 81c913fd..7558aa9b 100644 --- a/docs/source/launch.rst +++ b/docs/source/launch.rst @@ -106,6 +106,70 @@ The `curation_dict` can be saved inside the folder of the analyzer (for "binary_ Then it is auto-reloaded when the gui is re-opened. +Comparing two sorting outputs +----------------------------- + +To compare the output of two sorters on the same recording, use ``run_mainwindow_comparison`` +with two ``SortingAnalyzer`` computed on that recording. + +.. code-block:: python + + from spikeinterface_gui import run_mainwindow_comparison + + run_mainwindow_comparison( + analyzer1, + analyzer2, + analyzer1_name="kilosort4", + analyzer2_name="tridesclous2", + ) + +The two analyzers are virtually concatenated into a single unit list, so that all the usual +views (probe, waveforms, traces, amplitudes, ...) can display units of both sorters side by +side. Unit ids are made unique across the two: integer ids are offset, and other ids get the +analyzer name as a suffix (``5_kilosort4``). + +On top of that, ``spikeinterface.comparison.compare_two_sorters`` is run and dedicated +views are available: + +* the **compare unit list**, with one row per pair of matched units and one row per unit + found by only one of the two sorters. The GUI starts with its first row (the best match) + visible. The usual **unit list** is still available next to it, to see units of both + sorters individually, +* the **agreement matrix** shows the agreement score of every pair of units. Clicking a + cell makes that pair visible: a matched pair is highlighted in the compare unit list, + any other pair in the unit list, +* the **unit venn** view summarizes how many units are matched and how many are specific to each + sorter, with a slider for the agreement threshold, +* the **compare spikes** view splits the spikes of the visible pair in matched spikes and + spikes found by only one of the two units, which helps spotting over-merges and + over-splits. When the ``waveforms`` extension is available, sample waveforms of the 3 + groups are plotted, +* the **compare labels** view shows the proportions of a categorical unit property (e.g. a + quality label) for each sorter, as donut charts, +* the **compare metrics** view plots a unit metric of sorter 1 against the same metric of + sorter 2, for all the matched pairs. + +That agreement threshold is shared: moving the slider of the unit venn view also re-orders the +agreement matrix, re-categorizes the rows of the compare unit list and updates the pairs of +the compare metrics view. + +Both modes are supported, so the comparison can also be served as a web app: + +.. code-block:: python + + run_mainwindow_comparison(analyzer1, analyzer2, mode="web") + +Some things are not available in comparison mode: + +* curation, and therefore merging and splitting, +* the views that rely on extensions that cannot be shared between two sortings: + ``template_similarity``, ``isi_histograms`` and ``principal_components``. + For ``correlograms``, only the auto-correlograms of each sorter are shown. + +Only the recording of the first analyzer is used to display traces, and the two analyzers must +have matching recording attributes for the trace views to be shown at all. + + Open the GUI launcher --------------------- diff --git a/docs/source/views.rst b/docs/source/views.rst index 6a9c26c1..0445fba7 100644 --- a/docs/source/views.rst +++ b/docs/source/views.rst @@ -63,6 +63,7 @@ Controls * **ctrl + arrow up/down** : select next/previous unit and make it visible alone * **press 'ctrl+d'** : delete selected units (if curation=True) * **press 'ctrl+m'** : merge selected units (if curation=True) +* **press 'c'** : clear label of selected units (if curation=True) * **press 'g'** : label selected units as good (if curation=True) * **press 'm'** : label selected units as mua (if curation=True) * **press 'n'** : label selected units as noise (if curation=True) @@ -273,6 +274,14 @@ Correlograms View This view shows the auto-correlograms and cross-correlograms of the selected units. +Settings +~~~~~~~~ +- **window_ms** / **bin_ms** : the correlogram window and bin size (needs a re-compute). +- **display_axis** : show the axes of each plot. +- **show_cross_correlograms** : show the cross-correlograms (upper triangle), or only the +auto-correlograms side by side. In comparison mode only the auto-correlograms of both +sorters are available, so this is off by default. + Screenshots ~~~~~~~~~~~ @@ -393,11 +402,12 @@ revert, and export the curation data. Controls ~~~~~~~~ -- **save in analyzer**: Save the current curation state in the analyzer. +- **save in analyzer**/**save data**: Save the current curation state in the analyzer. +If a custom save callback is provided, it will be used instead. - **export/download JSON**: Export the current curation state to a JSON file. - **restore**: Restore the selected unit from the deleted units table. - **unmerge**: Unmerge the selected merges from the merged units table. -- **submit to parent**: Submit the current curation state to the parent window (for use in web applications). +- **unsplit**: Unsplit the selected split groups from the split units table. - **press 'ctrl+r'**: Restore the selected units from the deleted units table. - **press 'ctrl+u'**: Unmerge the selected merges from the merged units table. - **press 'ctrl+x'**: Unsplit the selected split groups from the split units table. @@ -485,6 +495,10 @@ positions and widths. - troughs are negative extrema and are displayed with a downward triangle symbol - peaks are positive extrema and are displayed with an upward triangle symbol +x-axis represents time and is in units of milliseconds. +y-axis represents the electrical signal. The units depend on your preprocessing +steps, but is usually in uV. + Screenshots ~~~~~~~~~~~ @@ -499,3 +513,234 @@ Screenshots - .. image:: images/views/web/maintemplate.png :width: 100% +No help text available. + +*Screenshots not available for this view.* + +Compare Unit List View +---------------------- + +The unit list in comparison mode. One row per pair of matched units, plus one row per unit +that only one of the two sorters found. + +The rows are sorted by decreasing agreement score, so the best matches come first and the +units that only one sorter found (score 0) come last. + +The matching is done at the agreement threshold shared with the other comparison views +(set it with the slider of the unit Venn view). The table is read only: there is no curation in +comparison mode. + +Settings +~~~~~~~~ +- **matching_mode** : "hungarian" gives a one to one matching, "best_match" simply takes +the best candidate for each unit of the first sorter, so a unit of the second sorter can +appear on several rows. + +Controls +~~~~~~~~ +- **left click on a row** : make the units of this row visible in the other views. +- **columns** : add unit properties that both sorters have (e.g. firing rate or a quality +label), as one column per sorter. + +Screenshots +~~~~~~~~~~~ + +.. list-table:: + :widths: 50 50 + :header-rows: 1 + + * - Desktop (Qt) + - Web (Panel) + * - .. image:: images/views/desktop/compareunitlist.png + :width: 100% + - .. image:: images/views/web/compareunitlist.png + :width: 100% + +Agreement Matrix View +--------------------- + +Agreement scores between the units of the two compared sorting outputs. + +Rows (horizontal axis) are the units of the first analyzer, columns (vertical axis) the +units of the second one. The score is the number of matched spikes divided by the total +number of spikes of both units, so it is 1 for two identical spike trains and 0 when no +spike matches. + +Settings +~~~~~~~~ +- **ordered** : reorder rows and columns so that the best matches are on the diagonal. +- **show_all** : when off, only the currently visible units are displayed. +- **max_labels** : hide the unit id labels when the matrix is bigger than this. + +Controls +~~~~~~~~ +- **left click** : select the pair of units of this cell, and make only those visible. +- **ctrl + left click** : add the pair of units to the visible ones. + +Screenshots +~~~~~~~~~~~ + +.. list-table:: + :widths: 50 50 + :header-rows: 1 + + * - Desktop (Qt) + - Web (Panel) + * - .. image:: images/views/desktop/agreementmatrix.png + :width: 100% + - .. image:: images/views/web/agreementmatrix.png + :width: 100% + +Unit Venn View +-------------- + +Venn diagram of the two compared sorting outputs. The area of each disc is proportional to +the number of units of that sorter, and the area of the intersection is proportional to the +number of units matched between the two, so the picture is quantitatively honest. + +The matching is one to one (hungarian) at the agreement threshold set with the slider. +That threshold is shared with the other comparison views: moving it also re-orders the +agreement matrix and re-categorizes the rows of the comparison unit table. + +Controls +~~~~~~~~ +- **slider** : the agreement threshold above which two units are considered matched. +- **filter** : only count the units whose categorical property (e.g. a quality label, shared +by both sorters) is one of the checked values. +- **left click on a region** : make one random unit of that region visible. Clicking again +picks another one, which is a quick way to walk through a region. Clicking the +intersection selects the two units of one matched pair, so that they can be compared. + +Only one unit (or one matched pair) is selected per click, so that the selection always +matches a single row of the comparison unit table. + +Settings +~~~~~~~~ +- **inclusion** : how a matched pair is counted when only one of its units passes the filter. +"both": the pair is matched only when both units pass, otherwise the passing unit counts as +found by its own sorter only. "any": the pair stays matched when at least one unit passes. + +Screenshots +~~~~~~~~~~~ + +.. list-table:: + :widths: 50 50 + :header-rows: 1 + + * - Desktop (Qt) + - Web (Panel) + * - .. image:: images/views/desktop/unitvenn.png + :width: 100% + - .. image:: images/views/web/unitvenn.png + :width: 100% + +Compare Spikes View +------------------- + +Spike level comparison of one pair of units, one unit of each sorter. Select a row of the +comparison unit table with two units: the comparison is computed automatically. + +The Venn diagram shows the spikes found by both units (matched, within the comparison +`delta_time`), and the spikes found by only one of them. The areas are proportional to the +spike counts. + +When the waveforms extension is loaded, sample waveforms of the 3 regions are plotted below, +on the extremum channel of the unit of sorter 1: sorter 1 only (left), both (middle) and +sorter 2 only (right), with the colors of the Venn diagram. +Waveforms only exist for the `random_spikes` subset, so only those spikes are plotted. The +titles tell how many of the region's spikes have waveforms. + +Controls +~~~~~~~~ +- **left click on a region** : select the spikes of that region (they show up in the spike +list and trace views). +- **Select {sorter 1} / Select match / Select {sorter 2}** : the same as clicking a region, +for when a region is too thin to click on. + +Settings +~~~~~~~~ +- **max_waveforms** : the maximum number of waveforms plotted per unit and region. + +Screenshots +~~~~~~~~~~~ + +.. list-table:: + :widths: 50 50 + :header-rows: 1 + + * - Desktop (Qt) + - Web (Panel) + * - .. image:: images/views/desktop/comparespikes.png + :width: 100% + - .. image:: images/views/web/comparespikes.png + :width: 100% + +Compare Labels View +------------------- + +Proportions of a categorical unit property (e.g. a quality label: SUA / MUA / noise) for the +two compared sorting outputs, as one donut chart per sorter. The total number of units is in +the middle of each donut. + +Only the non numeric properties that are set for both analyzers are listed. Units with no +value are counted as "n/a". + +Controls +~~~~~~~~ +- **property** : the categorical property to display. + +Settings +~~~~~~~~ +- **max_categories** : properties with more distinct values than this are not listed. + +Screenshots +~~~~~~~~~~~ + +.. list-table:: + :widths: 50 50 + :header-rows: 1 + + * - Desktop (Qt) + - Web (Panel) + * - .. image:: images/views/desktop/comparelabels.png + :width: 100% + - .. image:: images/views/web/comparelabels.png + :width: 100% + +Compare Metrics View +-------------------- + +Scatter plots of unit metrics for the matched pairs: the value of the unit of sorter 1 on the +horizontal axis, the value of the unit of sorter 2 on the vertical axis. The dashed line marks +equality. + +The pairs are the ones matched at the agreement threshold shared with the unit Venn view (set it +with the slider of the unit Venn view). The visible pair is drawn bigger, with a white outline. + +Controls +~~~~~~~~ +- **metrics** : the metrics to plot, one scatter plot per metric. +- **color by** : color the points by a categorical property (e.g. a quality label) of the +unit of sorter 1 or of sorter 2. +- **left click on a point** : make that pair of units visible. + +Settings +~~~~~~~~ +- **log_scale** : plot log10(value + .001), useful for firing rates and ISI violations. +- **num_columns** : the number of plots per row. +- **max_categories** : properties with more distinct values than this are not listed in "color by". + +Screenshots +~~~~~~~~~~~ + +.. list-table:: + :widths: 50 50 + :header-rows: 1 + + * - Desktop (Qt) + - Web (Panel) + * - .. image:: images/views/desktop/comparemetrics.png + :width: 100% + - .. image:: images/views/web/comparemetrics.png + :width: 100% + diff --git a/spikeinterface_gui/__init__.py b/spikeinterface_gui/__init__.py index 367d75ca..260c4e1f 100644 --- a/spikeinterface_gui/__init__.py +++ b/spikeinterface_gui/__init__.py @@ -12,5 +12,5 @@ from .version import version as __version__ -from .main import run_mainwindow, run_launcher +from .main import run_mainwindow, run_launcher, run_mainwindow_comparison diff --git a/spikeinterface_gui/agreementmatrixview.py b/spikeinterface_gui/agreementmatrixview.py new file mode 100644 index 00000000..138c6fea --- /dev/null +++ b/spikeinterface_gui/agreementmatrixview.py @@ -0,0 +1,269 @@ +import numpy as np +import matplotlib.cm +import matplotlib.colors + +from .view_base import ViewBase + + +class AgreementMatrixView(ViewBase): + """ + Agreement matrix between the units of the two compared analyzers. + + Rows (x axis) are the units of analyzer1, columns (y axis) the units of analyzer2. + Clicking a cell makes the corresponding pair of units visible. + """ + id = "agreementmatrix" + _supported_backend = ['qt', 'panel'] + _depend_on = ['comparison'] + _settings = [ + {'name': 'colormap', 'type': 'list', 'limits': ['viridis', 'jet', 'gray', 'hot']}, + {'name': 'ordered', 'type': 'bool', 'value': True}, + {'name': 'show_all', 'type': 'bool', 'value': True}, + {'name': 'max_labels', 'type': 'int', 'value': 30}, + ] + + def get_agreement_data(self): + """ + Sub-matrix to display. + + Returns (values, row_unit_ids, col_unit_ids) where the unit ids are the *combined* + ids in the row/column order of the displayed matrix, or (None, None, None) when + there is nothing to show. + """ + controller = self.controller + scores = controller.get_agreement_scores(ordered=self.settings['ordered']) + + row_unit_ids = np.array([controller.get_combined_unit_id(1, u) for u in scores.index]) + col_unit_ids = np.array([controller.get_combined_unit_id(2, u) for u in scores.columns]) + # pandas hands out a read-only view, but both pyqtgraph and bokeh may write into + # the array they are given, so pass them a writable copy + values = np.array(scores.values, dtype='float64') + + if not self.settings['show_all']: + visible_unit_ids = set(controller.get_visible_unit_ids()) + row_mask = np.array([u in visible_unit_ids for u in row_unit_ids], dtype='bool') + col_mask = np.array([u in visible_unit_ids for u in col_unit_ids], dtype='bool') + if not np.any(row_mask) or not np.any(col_mask): + return None, None, None + values = values[row_mask, :][:, col_mask] + row_unit_ids = row_unit_ids[row_mask] + col_unit_ids = col_unit_ids[col_mask] + + if values.size == 0: + return None, None, None + + return values, row_unit_ids, col_unit_ids + + def select_unit_pair_on_click(self, x, y, reset=True): + values, row_unit_ids, col_unit_ids = self.get_agreement_data() + if values is None: + return + + num_rows, num_cols = values.shape + if not ((0 <= x <= num_rows) and (0 <= y <= num_cols)): + return + # clip so that a click exactly on the far edge still selects the last unit + row = min(int(np.floor(x)), num_rows - 1) + col = min(int(np.floor(y)), num_cols - 1) + + if reset: + self.controller.set_all_unit_visibility_off() + self.controller.set_unit_visibility(row_unit_ids[row], True) + self.controller.set_unit_visibility(col_unit_ids[col], True) + self.notify_unit_and_channel_visibility_changed() + self.refresh() + + def get_colormap(self, num_colors=512): + return matplotlib.colormaps[self.settings['colormap']].resampled(num_colors) + + def get_axis_ticks(self, row_unit_ids, col_unit_ids): + """ + Tick positions and labels for both axes, or (None, None) when the matrix is too + big for the labels to be readable. + + The ticks are the unit ids in each analyzer's own namespace: the combined ids + would be far too long here, the axis label says which analyzer it is. + """ + max_labels = self.settings['max_labels'] + if max_labels <= 0 or max(len(row_unit_ids), len(col_unit_ids)) > max_labels: + return None, None + + bottom_ticks = [ + (i + 0.5, f'{self.controller.get_original_unit_id(unit_id)}') + for i, unit_id in enumerate(row_unit_ids) + ] + left_ticks = [ + (i + 0.5, f'{self.controller.get_original_unit_id(unit_id)}') + for i, unit_id in enumerate(col_unit_ids) + ] + return bottom_ticks, left_ticks + + def _qt_on_settings_changed(self): + N = 512 + cmap = self.get_colormap(N) + lut = [] + for i in range(N): + r, g, b, _ = matplotlib.colors.ColorConverter().to_rgba(cmap(i)) + lut.append([r * 255, g * 255, b * 255]) + self.lut = np.array(lut, dtype='uint8') + + self.refresh() + + def _panel_on_settings_changed(self): + N = 512 + cmap = self.get_colormap(N) + self.color_mapper.palette = [matplotlib.colors.rgb2hex(cmap(i)[:3]) for i in range(N)] + + self.refresh() + + ## Qt ## + def _qt_make_layout(self): + from .myqt import QT + import pyqtgraph as pg + from .utils_qt import ViewBoxHandlingClickToPositionWithCtrl + + self.layout = QT.QVBoxLayout() + self.graphicsview = pg.GraphicsView() + self.layout.addWidget(self.graphicsview) + + self.viewBox = ViewBoxHandlingClickToPositionWithCtrl() + self.viewBox.clicked.connect(self._qt_select_pair) + self.viewBox.disableAutoRange() + + self.plot = pg.PlotItem(viewBox=self.viewBox) + self.graphicsview.setCentralItem(self.plot) + self.plot.hideButtons() + + self.image = pg.ImageItem() + self.plot.addItem(self.image) + + # real axes: the tick labels are the unit ids of that analyzer, and the axis + # label says which analyzer it is. The combined ids would be far too long here. + self.plot.showAxis('bottom') + self.plot.showAxis('left') + self.plot.setLabel('bottom', f'{self.controller.analyzer1_name} units') + self.plot.setLabel('left', f'{self.controller.analyzer2_name} units') + + # this builds the lut and refreshes + self.on_settings_changed() + + def _qt_refresh(self): + values, row_unit_ids, col_unit_ids = self.get_agreement_data() + if values is None: + self.image.hide() + return + + # agreement scores are already normalized in [0, 1], no rescaling + self.image.setImage(values, lut=self.lut, levels=[0., 1.]) + self.image.show() + num_rows, num_cols = values.shape + self.plot.setXRange(0, num_rows) + self.plot.setYRange(0, num_cols) + + # one tick per unit, at the middle of its row/column. pyqtgraph drops the ones + # that would overlap, so no manual placement is needed. None gives back the + # automatic numeric ticks. + bottom_ticks, left_ticks = self.get_axis_ticks(row_unit_ids, col_unit_ids) + self.plot.getAxis('bottom').setTicks(None if bottom_ticks is None else [bottom_ticks]) + self.plot.getAxis('left').setTicks(None if left_ticks is None else [left_ticks]) + + def _qt_select_pair(self, x, y, reset): + self.select_unit_pair_on_click(x, y, reset=reset) + + ## panel ## + def _panel_make_layout(self): + import panel as pn + import bokeh.plotting as bpl + from bokeh.models import ColumnDataSource, LinearColorMapper, FixedTicker + from bokeh.events import Tap + from .utils_panel import _bg_color + + self.figure = bpl.figure( + sizing_mode="stretch_both", + tools="reset,wheel_zoom,tap", + background_fill_color=_bg_color, + border_fill_color=_bg_color, + outline_line_color="white", + styles={"flex": "1"}, + ) + self.figure.toolbar.logo = None + self.figure.grid.visible = False + self.figure.xaxis.axis_label = f'{self.controller.analyzer1_name} units' + self.figure.yaxis.axis_label = f'{self.controller.analyzer2_name} units' + + N = 512 + cmap = self.get_colormap(N) + # agreement scores are already normalized, the range is fixed + self.color_mapper = LinearColorMapper( + palette=[matplotlib.colors.rgb2hex(cmap(i)[:3]) for i in range(N)], low=0., high=1. + ) + + self.image_source = ColumnDataSource({"image": [np.zeros((1, 1))], "dw": [1], "dh": [1]}) + self.figure.image( + image="image", x=0, y=0, dw="dw", dh="dh", + color_mapper=self.color_mapper, source=self.image_source, + ) + + self.figure.on_event(Tap, self._panel_on_tap) + + self.layout = pn.Column( + self.figure, + styles={"display": "flex", "flex-direction": "column"}, + sizing_mode="stretch_both", + ) + + def _panel_refresh(self): + from bokeh.models import FixedTicker + + values, row_unit_ids, col_unit_ids = self.get_agreement_data() + if values is None: + self.image_source.data.update({"image": [np.zeros((1, 1))], "dw": [0], "dh": [0]}) + return + + num_rows, num_cols = values.shape + # bokeh reads image[y][x] while pyqtgraph reads image[x][y], so transpose to keep + # analyzer1 on the x axis in both backends + self.image_source.data.update({"image": [values.T], "dw": [num_rows], "dh": [num_cols]}) + + bottom_ticks, left_ticks = self.get_axis_ticks(row_unit_ids, col_unit_ids) + if bottom_ticks is None: + self.figure.xaxis.ticker = FixedTicker(ticks=[]) + self.figure.yaxis.ticker = FixedTicker(ticks=[]) + self.figure.xaxis.major_label_overrides = {} + self.figure.yaxis.major_label_overrides = {} + else: + self.figure.xaxis.ticker = FixedTicker(ticks=[pos for pos, _ in bottom_ticks]) + self.figure.xaxis.major_label_overrides = {pos: label for pos, label in bottom_ticks} + self.figure.yaxis.ticker = FixedTicker(ticks=[pos for pos, _ in left_ticks]) + self.figure.yaxis.major_label_overrides = {pos: label for pos, label in left_ticks} + + self.figure.x_range.start = 0 + self.figure.x_range.end = num_rows + self.figure.y_range.start = 0 + self.figure.y_range.end = num_cols + + def _panel_on_tap(self, event): + if event.x is None or event.y is None: + return + self.select_unit_pair_on_click(event.x, event.y, reset=True) + + +AgreementMatrixView._gui_help_txt = """ +## Agreement Matrix View + +Agreement scores between the units of the two compared sorting outputs. + +Rows (horizontal axis) are the units of the first analyzer, columns (vertical axis) the +units of the second one. The score is the number of matched spikes divided by the total +number of spikes of both units, so it is 1 for two identical spike trains and 0 when no +spike matches. + +### Settings +- **ordered** : reorder rows and columns so that the best matches are on the diagonal. +- **show_all** : when off, only the currently visible units are displayed. +- **max_labels** : hide the unit id labels when the matrix is bigger than this. + +### Controls +- **left click** : select the pair of units of this cell, and make only those visible. +- **ctrl + left click** : add the pair of units to the visible ones. +""" diff --git a/spikeinterface_gui/backend_panel.py b/spikeinterface_gui/backend_panel.py index 913fe1fd..6172da9a 100644 --- a/spikeinterface_gui/backend_panel.py +++ b/spikeinterface_gui/backend_panel.py @@ -17,6 +17,7 @@ class SignalNotifier(param.Parameterized): use_times_updated = param.Event() active_view_updated = param.Event() unit_color_changed = param.Event() + agreement_threshold_changed = param.Event() def __init__(self, view=None): param.Parameterized.__init__(self) @@ -51,6 +52,9 @@ def notify_active_view_updated(self): def notify_unit_color_changed(self): self.param.trigger("unit_color_changed") + def notify_agreement_threshold_changed(self): + self.param.trigger("agreement_threshold_changed") + class SignalHandler(param.Parameterized): def __init__(self, controller, parent=None): @@ -73,6 +77,7 @@ def connect_view(self, view): view.notifier.param.watch(self.on_use_times_updated, "use_times_updated") view.notifier.param.watch(self.on_active_view_updated, "active_view_updated") view.notifier.param.watch(self.on_unit_color_changed, "unit_color_changed") + view.notifier.param.watch(self.on_agreement_threshold_changed, "agreement_threshold_changed") def on_spike_selection_changed(self, param): if not self._active: @@ -141,6 +146,15 @@ def on_unit_color_changed(self, param): continue view.on_unit_color_changed() + def on_agreement_threshold_changed(self, param): + if not self._active: + return + for view in self.controller.views: + if param.obj.view == view: + continue + view.on_agreement_threshold_changed() + + param_type_map = { "float": param.Number, "int": param.Integer, @@ -259,8 +273,8 @@ def make_views(self, user_settings): tabs = [("📊", view.layout)] if view_class._settings is not None: - settings_param = pn.Param(view.settings._parameterized, sizing_mode="stretch_height", - name=f"{view_name.capitalize()} settings") + # natural height (no stretch_height): the scrolling column below scrolls it + settings_param = pn.Param(view.settings._parameterized, name=f"{view_name.capitalize()} settings") view._panel_settings_widget = settings_param if view_class._need_compute: compute_button = pn.widgets.Button(name="Compute", button_type="primary") @@ -268,6 +282,9 @@ def make_views(self, user_settings): settings = pn.Row(settings_param, compute_button) else: settings = settings_param + # scroll inside the tab: long settings would otherwise overflow the zone, over + # the tabs of the zone + settings = pn.Column(settings, scroll=True, sizing_mode="stretch_both") tabs.append(("âš™ī¸", settings)) tabs.append(("â„šī¸", info)) diff --git a/spikeinterface_gui/backend_qt.py b/spikeinterface_gui/backend_qt.py index 074b0543..85fae5c5 100644 --- a/spikeinterface_gui/backend_qt.py +++ b/spikeinterface_gui/backend_qt.py @@ -23,6 +23,7 @@ class SignalNotifier(QT.QObject): time_info_updated = QT.pyqtSignal() use_times_updated = QT.pyqtSignal() unit_color_changed = QT.pyqtSignal() + agreement_threshold_changed = QT.pyqtSignal() def __init__(self, parent=None, view=None): QT.QObject.__init__(self, parent=parent) @@ -49,6 +50,9 @@ def notify_use_times_updated(self): def notify_unit_color_changed(self): self.unit_color_changed.emit() + def notify_agreement_threshold_changed(self): + self.agreement_threshold_changed.emit() + # Used by controller to handle/callback signals class SignalHandler(QT.QObject): @@ -71,6 +75,7 @@ def connect_view(self, view): view.notifier.time_info_updated.connect(self.on_time_info_updated) view.notifier.use_times_updated.connect(self.on_use_times_updated) view.notifier.unit_color_changed.connect(self.on_unit_color_changed) + view.notifier.agreement_threshold_changed.connect(self.on_agreement_threshold_changed) def on_spike_selection_changed(self): if not self._active: @@ -136,6 +141,15 @@ def on_unit_color_changed(self): continue view.on_unit_color_changed() + def on_agreement_threshold_changed(self): + if not self._active: + return + for view in self.controller.views: + if view.qt_widget == self.sender().parent(): + # do not refresh it self + continue + view.on_agreement_threshold_changed() + def create_settings(view, parent): view.settings = pg.parametertree.Parameter.create(name="settings", type='group', children=view._settings) diff --git a/spikeinterface_gui/comparelabelsview.py b/spikeinterface_gui/comparelabelsview.py new file mode 100644 index 00000000..5a0d7723 --- /dev/null +++ b/spikeinterface_gui/comparelabelsview.py @@ -0,0 +1,273 @@ +import numpy as np +import matplotlib.colors +import matplotlib.pyplot as plt + +from .view_base import ViewBase + + +def get_categorical_properties(controller, max_categories): + """The non numeric columns of the units table that are set for both analyzers""" + table = controller.units_table + properties = [] + for name in controller.get_shared_unit_properties(): + if name == "sorter": + continue + column = table[name] + if column.dtype.kind in 'if': + continue + # too many values (e.g. main_channel_id) do not make a readable chart + if column.nunique() > max_categories: + continue + properties.append(name) + return properties + + +def get_category_colors(categories, cmap="tab10"): + """One hex color per category, in the order given""" + cmap = plt.get_cmap(cmap) + return [matplotlib.colors.rgb2hex(cmap(i % cmap.N)) for i in range(len(categories))] + + +class CompareLabelsView(ViewBase): + """ + Donut charts of a categorical unit property (e.g. a quality label), one per compared + analyzer, so that the label proportions of the two sorters can be compared. + """ + id = "comparelabels" + _supported_backend = ['qt', 'panel'] + _depend_on = ['comparison'] + _settings = [ + {'name': 'max_categories', 'type': 'int', 'value': 20}, + ] + # donut geometry, in data units + _outer_radius = 1. + _inner_radius = 0.7 + _spacing = 2.7 + # one donut per analyzer, stacked vertically + _centers = ((0., 0.), (0., -_spacing)) + + def get_categorical_properties(self): + return get_categorical_properties(self.controller, self.settings['max_categories']) + + def get_donut_data(self, property_name): + """ + Returns (categories, colors, counts) where counts has one row per analyzer. + Units with no value are counted as "n/a". + """ + column = self.controller.units_table[property_name].astype(object).where( + self.controller.units_table[property_name].notna(), "n/a" + ).astype(str) + categories = sorted(column.unique()) + colors = get_category_colors(categories, cmap=self.controller.main_settings['label_colormap']) + counts = np.array([ + [np.sum(column.loc[unit_ids] == category) for category in categories] + for unit_ids in (self.controller.unit_ids1, self.controller.unit_ids2) + ]) + return categories, colors, counts + + def get_wedge_polygons(self, counts, center, num_points=100): + """One annular sector per category as (xs, ys), clockwise from 12 o'clock""" + polygons = [] + fractions = np.cumsum(np.concatenate([[0.], counts / max(counts.sum(), 1)])) + for start, stop in zip(fractions[:-1], fractions[1:]): + if stop == start: + polygons.append(None) + continue + theta = np.pi / 2 - 2 * np.pi * np.linspace(start, stop, num_points) + xs = np.concatenate([self._outer_radius * np.cos(theta), self._inner_radius * np.cos(theta[::-1])]) + ys = np.concatenate([self._outer_radius * np.sin(theta), self._inner_radius * np.sin(theta[::-1])]) + polygons.append((center[0] + xs, center[1] + ys)) + return polygons + + def get_donut_patches(self, colors, counts): + """All the wedges as (xs, ys, color), the 2 donuts stacked vertically""" + patches = [] + for analyzer_row, center in zip(counts, self._centers): + for polygon, color in zip(self.get_wedge_polygons(analyzer_row, center), colors): + if polygon is not None: + patches.append((polygon[0], polygon[1], color)) + return patches + + def get_donut_labels(self, categories, colors, counts): + """The texts to draw, as a list of (x, y, text, color, size)""" + labels = [] + mid_radius = (self._outer_radius + self._inner_radius) / 2 + for analyzer_index, (analyzer_row, (center_x, center_y)) in enumerate(zip(counts, self._centers)): + total = analyzer_row.sum() + name = self.controller.get_analyzer_name(analyzer_index + 1) + labels.append((center_x, center_y + self._outer_radius * 1.15, name, '#FFFFFF', 12)) + labels.append((center_x, center_y, f'{total:,}\nunits', '#FFFFFF', 14)) + fractions = np.cumsum(np.concatenate([[0.], analyzer_row / max(total, 1)])) + for start, stop in zip(fractions[:-1], fractions[1:]): + if stop == start: + continue + theta = np.pi / 2 - np.pi * (start + stop) + labels.append(( + center_x + mid_radius * np.cos(theta), center_y + mid_radius * np.sin(theta), + f'{100 * (stop - start):.1f}%', '#FFFFFF', 9, + )) + # legend, one line per category on the left of the top donut + for i, (category, color) in enumerate(zip(categories, colors)): + labels.append((-1.7, self._outer_radius - 0.2 * i, f'■ {category}', color, 10)) + return labels + + def get_view_ranges(self): + return (-2.3, 1.2), (-self._spacing - 1.2, 1.4) + + def get_draw_data(self, property_name): + if property_name is None: + return [], [] + categories, colors, counts = self.get_donut_data(property_name) + return self.get_donut_patches(colors, counts), self.get_donut_labels(categories, colors, counts) + + ## Qt ## + def _qt_make_layout(self): + from .myqt import QT + import pyqtgraph as pg + + self.layout = QT.QVBoxLayout() + + header = QT.QHBoxLayout() + header.addWidget(QT.QLabel('property')) + self.property_combo = QT.QComboBox() + self.property_combo.addItems(self.get_categorical_properties()) + self.property_combo.currentTextChanged.connect(self.refresh) + header.addWidget(self.property_combo) + header.addStretch() + self.layout.addLayout(header) + + self.graphicsview = pg.GraphicsView() + self.layout.addWidget(self.graphicsview) + self.viewBox = pg.ViewBox() + self.viewBox.disableAutoRange() + self.viewBox.setAspectLocked(True) + self.plot = pg.PlotItem(viewBox=self.viewBox) + self.graphicsview.setCentralItem(self.plot) + self.plot.hideButtons() + self.plot.hideAxis('bottom') + self.plot.hideAxis('left') + self._items = [] + + def _qt_on_settings_changed(self): + current = self.property_combo.currentText() + self.property_combo.blockSignals(True) + self.property_combo.clear() + self.property_combo.addItems(self.get_categorical_properties()) + self.property_combo.setCurrentText(current) + self.property_combo.blockSignals(False) + self.refresh() + + def _qt_refresh(self): + from .myqt import QT + import pyqtgraph as pg + + for item in self._items: + self.plot.removeItem(item) + self._items = [] + + patches, labels = self.get_draw_data(self.property_combo.currentText() or None) + for xs, ys, color in patches: + polygon = QT.QPolygonF([QT.QPointF(x, y) for x, y in zip(xs, ys)]) + item = QT.QGraphicsPolygonItem(polygon) + item.setPen(pg.mkPen(None)) + item.setBrush(pg.mkBrush(color)) + self.plot.addItem(item) + self._items.append(item) + for x, y, text, color, size in labels: + item = pg.TextItem(text=text, color=color, anchor=(0.5, 0.5)) + item.setFont(QT.QFont('', size)) + item.setPos(x, y) + self.plot.addItem(item) + self._items.append(item) + + x_range, y_range = self.get_view_ranges() + # one call: with the aspect locked, separate x/y calls override each other and crop + self.viewBox.setRange(xRange=x_range, yRange=y_range, padding=0) + + ## panel ## + def _panel_make_layout(self): + import panel as pn + import bokeh.plotting as bpl + from bokeh.models import ColumnDataSource + from .utils_panel import _bg_color + + properties = self.get_categorical_properties() + self.property_select = pn.widgets.Select( + name='property', options=properties, value=properties[0] if properties else None, + sizing_mode="stretch_width", + ) + self.property_select.param.watch(lambda event: self.refresh(), 'value') + + self.figure = bpl.figure( + sizing_mode="stretch_both", + tools="reset,wheel_zoom", + background_fill_color=_bg_color, + border_fill_color=_bg_color, + match_aspect=True, + outline_line_color="white", + styles={"flex": "1"}, + ) + self.figure.toolbar.logo = None + self.figure.axis.visible = False + self.figure.grid.visible = False + # match_aspect only works with auto ranges: an invisible glyph on the view corners + # makes the auto range include the labels, setting range start/end would distort + self.bounds_source = ColumnDataSource({"x": [], "y": []}) + self.figure.scatter(x="x", y="y", source=self.bounds_source, alpha=0) + + self.patch_source = ColumnDataSource({"xs": [], "ys": [], "color": []}) + self.figure.patches(xs="xs", ys="ys", source=self.patch_source, fill_color="color", line_color=None) + self.text_source = ColumnDataSource({"x": [], "y": [], "text": [], "color": [], "size": []}) + self.figure.text( + x="x", y="y", text="text", text_color="color", text_font_size="size", source=self.text_source, + text_align="center", text_baseline="middle", + ) + + self.layout = pn.Column( + self.property_select, + self.figure, + styles={"display": "flex", "flex-direction": "column"}, + sizing_mode="stretch_both", + ) + + def _panel_on_settings_changed(self): + properties = self.get_categorical_properties() + self.property_select.options = properties + if self.property_select.value not in properties: + self.property_select.value = properties[0] if properties else None + self.refresh() + + def _panel_refresh(self): + patches, labels = self.get_draw_data(self.property_select.value) + self.patch_source.data.update({ + "xs": [p[0].tolist() for p in patches], + "ys": [p[1].tolist() for p in patches], + "color": [p[2] for p in patches], + }) + self.text_source.data.update({ + "x": [label[0] for label in labels], + "y": [label[1] for label in labels], + "text": [label[2] for label in labels], + "color": [label[3] for label in labels], + "size": [f'{label[4]}pt' for label in labels], + }) + x_range, y_range = self.get_view_ranges() + self.bounds_source.data.update({"x": list(x_range), "y": list(y_range)}) + + +CompareLabelsView._gui_help_txt = """ +## Compare Labels View + +Proportions of a categorical unit property (e.g. a quality label: SUA / MUA / noise) for the +two compared sorting outputs, as one donut chart per sorter. The total number of units is in +the middle of each donut. + +Only the non numeric properties that are set for both analyzers are listed. Units with no +value are counted as "n/a". + +### Controls +- **property** : the categorical property to display. + +### Settings +- **max_categories** : properties with more distinct values than this are not listed. +""" diff --git a/spikeinterface_gui/comparemainsettingsview.py b/spikeinterface_gui/comparemainsettingsview.py new file mode 100644 index 00000000..389ede1d --- /dev/null +++ b/spikeinterface_gui/comparemainsettingsview.py @@ -0,0 +1,201 @@ +from .view_base import ViewBase +from .utils_global import get_config_folder +import json +import spikeinterface_gui + + +qualitative_names = [ + 'Pastel1', 'Pastel2', 'Paired', 'Accent', + 'Dark2', 'Set1', 'Set2', 'Set3', + 'tab10', 'tab20', 'tab20b', 'tab20c' +] + + +# this control controller.main_settings +main_settings = [ + {'name': 'max_visible_units', 'type': 'int', 'value' : 10 }, + {'name': 'label_colormap', 'type': 'list', 'value': 'Set1', 'limits': qualitative_names}, + {'name': 'use_times', 'type': 'bool', 'value': False}, + {'name': 'num_colors', 'type': 'int', 'value' : 20}, +] + + +class CompareMainSettingsView(ViewBase): + id = "comparemainsettings" + _supported_backend = ['qt', 'panel'] + _settings = None + _depend_on = [] + _need_compute = False + + def __init__(self, controller=None, parent=None, backend="qt"): + # retrieve main settings from controller + self.main_settings_sync = main_settings.copy() + for setting in self.main_settings_sync: + setting_name = setting['name'] + setting_value = controller.main_settings.get(setting_name, setting['value']) + setting['value'] = setting_value + ViewBase.__init__(self, controller=controller, parent=parent, backend=backend) + + + def on_max_visible_units_changed(self): + max_visible = self.main_settings['max_visible_units'] + self.controller.main_settings['max_visible_units'] = max_visible + + visible_ids = self.controller.get_visible_unit_ids() + if len(visible_ids) > max_visible: + visible_ids = visible_ids[:max_visible] + self.controller.set_visible_unit_ids(visible_ids) + self.notify_unit_visibility_changed() + + def on_change_label_colormap(self): + self.controller.main_settings['label_colormap'] = self.main_settings['label_colormap'] + self.controller.refresh_colors() + self.notify_unit_color_changed() + + def on_num_colors_changed(self): + self.controller.main_settings['num_colors'] = self.main_settings['num_colors'] + self.controller.refresh_colors() + self.notify_unit_color_changed() + + def on_use_times(self): + self.controller.main_settings['use_times'] = self.main_settings['use_times'] + self.controller.update_time_info() + self.notify_use_times_updated() + + def save_current_settings(self, event=None): + + backend = self.controller.backend + + settings_dict = {} + for view in self.controller.views: + + # If view does not have any settings (e.g. MergeView) then skip + if view._settings is None: + continue + + view_class_name = view.__class__.__name__ + view_name = view_class_name.replace("View", "").lower() + + if view_name == "unitlist": + continue + + settings_dict[view_name] = {} + + if backend == "panel": + settings_dict[view_name] = self.panel_make_settings_dict(view) + elif backend == "qt": + settings_dict[view_name] = self.qt_make_settings_dict(view) + + sigui_version = spikeinterface_gui.__version__ + + config_folder = get_config_folder() + config_version_folder = config_folder / sigui_version + config_version_folder.mkdir(parents=True, exist_ok=True) + + with open(config_version_folder / 'settings.json', 'w') as f: + json.dump(settings_dict, f, indent=4) + + ## QT zone + def _qt_make_layout(self): + from .myqt import QT + import pyqtgraph as pg + + self.layout = QT.QVBoxLayout() + + txt = self.controller.get_information_txt() + self.info_label = QT.QLabel(txt) + self.layout.addWidget(self.info_label) + + if not self.controller.disable_save_settings_button: + but = QT.QPushButton('Save as default settings') + but.clicked.connect(self.save_current_settings) + self.layout.addWidget(but) + + self.main_settings = pg.parametertree.Parameter.create( + name="main settings", + type='group', + children=self.main_settings_sync + ) + + # not that the parent is not the view (not Qt anymore) itself but the widget + self.tree_main_settings = pg.parametertree.ParameterTree(parent=self.qt_widget) + self.tree_main_settings.header().hide() + self.tree_main_settings.setParameters(self.main_settings, showTop=True) + # self.tree_main_settings.setWindowTitle(u'Main settings') + self.layout.addWidget(self.tree_main_settings) + + self.main_settings.param('max_visible_units').sigValueChanged.connect(self.on_max_visible_units_changed) + self.main_settings.param('label_colormap').sigValueChanged.connect(self.on_change_label_colormap) + self.main_settings.param('num_colors').sigValueChanged.connect(self.on_num_colors_changed) + self.main_settings.param('use_times').sigValueChanged.connect(self.on_use_times) + + def qt_make_settings_dict(self, view): + """For a given view, return the current settings in a dict""" + + current_settings_dict_from_view = view.settings.getValues() + + current_settings_dict = {} + for setting_name, (setting_value, _) in current_settings_dict_from_view.items(): + current_settings_dict[setting_name] = setting_value + + return current_settings_dict + + + def _qt_refresh(self): + pass + + + ## panel zone + def _panel_make_layout(self): + import panel as pn + from .backend_panel import create_dynamic_parameterized, SettingsProxy + + if self.controller.disable_save_settings_button: + self.save_setting_button = None + else: + self.save_setting_button = pn.widgets.Button(name="Save as default settings", button_type="primary", sizing_mode="stretch_width") + self.save_setting_button.on_click(self.save_current_settings) + + # Create method and arguments layout + self.main_settings = SettingsProxy(create_dynamic_parameterized(self.main_settings_sync)) + self.main_settings_layout = pn.Param(self.main_settings._parameterized, sizing_mode="stretch_both", + name=f"Main settings") + self.main_settings._parameterized.param.watch(self._panel_on_max_visible_units_changed, 'max_visible_units') + self.main_settings._parameterized.param.watch(self._panel_on_change_label_colormap, 'label_colormap') + self.main_settings._parameterized.param.watch(self._panel_on_num_colors_changed, 'num_colors') + self.main_settings._parameterized.param.watch(self._panel_on_use_times, 'use_times') + self.layout = pn.Column(self.save_setting_button, self.main_settings_layout, sizing_mode="stretch_both") + + def panel_make_settings_dict(self, view): + """For a given view, return the current settings in a dict""" + + current_settings_dict_from_param = view.settings._parameterized.param.values() + current_settings_dict = {} + for setting_name, setting_value in current_settings_dict_from_param.items(): + # The param also saves the name of the view - we don't want to propagate this + if setting_name != "name": + current_settings_dict[setting_name] = setting_value + return current_settings_dict + + def _panel_on_max_visible_units_changed(self, event): + self.on_max_visible_units_changed() + + def _panel_on_change_label_colormap(self, event): + self.on_change_label_colormap() + + def _panel_on_num_colors_changed(self, event): + self.on_num_colors_changed() + + def _panel_on_use_times(self, event): + self.on_use_times() + + def _panel_refresh(self): + pass + + +CompareMainSettingsView._gui_help_txt = """ +## Main settings + +Overview and main controls. +Can save current settings for entire GUI as the default user settings using the "Save as default settings" button. +""" \ No newline at end of file diff --git a/spikeinterface_gui/comparemetricsview.py b/spikeinterface_gui/comparemetricsview.py new file mode 100644 index 00000000..744b756b --- /dev/null +++ b/spikeinterface_gui/comparemetricsview.py @@ -0,0 +1,290 @@ +import numpy as np + +from .view_base import ViewBase +from .comparelabelsview import get_categorical_properties, get_category_colors + + +_default_visible_metrics = ("firing_rate", "isi_violations_ratio", "amplitude_median", "presence_ratio") +_default_color = '#BBBBBB' + + +class CompareMetricsView(ViewBase): + """ + Scatter plots of unit metrics, sorter 1 against sorter 2, for the matched pairs at the + agreement threshold shared with the unit Venn view. Clicking a point makes its pair visible. + """ + id = "comparemetrics" + _supported_backend = ['qt', 'panel'] + _depend_on = ['comparison'] + _settings = [ + {'name': 'log_scale', 'type': 'bool', 'value': False}, + {'name': 'num_columns', 'type': 'int', 'value': 2}, + {'name': 'max_categories', 'type': 'int', 'value': 20}, + ] + + def __init__(self, controller=None, parent=None, backend="qt"): + table = controller.units_table + metrics = [col for col in controller.get_shared_unit_properties() if table[col].dtype.kind in 'if'] + default_metrics = [m for m in metrics if m in _default_visible_metrics] or metrics[:4] + self.visible_metrics_dict = {m: m in default_metrics for m in metrics} + ViewBase.__init__(self, controller=controller, parent=parent, backend=backend) + + def get_visible_metrics(self): + return [m for m, visible in self.visible_metrics_dict.items() if visible] + + def get_color_options(self): + """'none' then each categorical property seen from either sorter, as {label: (property, analyzer_index)}""" + options = {'none': None} + for name in get_categorical_properties(self.controller, self.settings['max_categories']): + for analyzer_index in (1, 2): + options[f'{name} ({self.controller.get_analyzer_name(analyzer_index)})'] = (name, analyzer_index) + return options + + def get_pairs(self): + return self.controller.get_venn_unit_ids()['matched'] + + def get_pair_colors(self, pairs, color_option): + """One color per pair, and the legend as a list of (category, color)""" + if color_option is None or len(pairs) == 0: + return [_default_color] * len(pairs), [] + name, analyzer_index = color_option + column = self.controller.units_table[name] + unit_ids = [pair[analyzer_index - 1] for pair in pairs] + values = column.loc[unit_ids].astype(object).where(column.loc[unit_ids].notna(), "n/a").astype(str) + categories = sorted(column.astype(object).where(column.notna(), "n/a").astype(str).unique()) + color_by_category = dict( + zip( + categories, + get_category_colors( + categories, + cmap=self.controller.main_settings['label_colormap'] + ) + ) + ) + return [color_by_category[v] for v in values], list(color_by_category.items()) + + def get_metric_values(self, metric, pairs): + """(x, y) for sorter 1 and sorter 2, log10(value + .001) when log_scale is on""" + table = self.controller.units_table + x = table.loc[[pair[0] for pair in pairs], metric].to_numpy(dtype='float64') + y = table.loc[[pair[1] for pair in pairs], metric].to_numpy(dtype='float64') + if self.settings['log_scale']: + with np.errstate(invalid='ignore', divide='ignore'): + x, y = np.log10(x + 1e-3), np.log10(y + 1e-3) + return x, y + + def get_axis_label(self, analyzer_index): + name = self.controller.get_analyzer_name(analyzer_index) + return f'{name} log10(value + .001)' if self.settings['log_scale'] else name + + @staticmethod + def get_equality_line(x, y): + """The diagonal over the range of the finite values, or None""" + values = np.concatenate([x, y]) + values = values[np.isfinite(values)] + if values.size == 0: + return None + return [values.min(), values.max()] + + def get_visible_mask(self, pairs): + visible_unit_ids = set(self.controller.get_visible_unit_ids()) + return np.array([pair[0] in visible_unit_ids and pair[1] in visible_unit_ids for pair in pairs], dtype=bool) + + def select_pair(self, pair_index): + pair = self.get_pairs()[pair_index] + self.controller.set_visible_unit_ids(list(pair)) + self.notify_unit_and_channel_visibility_changed() + self.refresh() + + def get_legend_html(self, legend): + return " ".join(f'■ {category}' for category, color in legend) + + ## Qt ## + def _qt_make_layout(self): + from .myqt import QT + import pyqtgraph as pg + + self.layout = QT.QVBoxLayout() + + tree = [{'name': str(m), 'type': 'bool', 'value': v} for m, v in self.visible_metrics_dict.items()] + self.qt_visible_metrics = pg.parametertree.Parameter.create(name='visible metrics', type='group', children=tree) + self.tree_visible_metrics = pg.parametertree.ParameterTree(parent=self.qt_widget) + self.tree_visible_metrics.header().hide() + self.tree_visible_metrics.setParameters(self.qt_visible_metrics, showTop=True) + self.qt_visible_metrics.sigTreeStateChanged.connect(self._qt_on_visible_metrics_changed) + self.layout.addWidget(self.tree_visible_metrics) + self.tree_visible_metrics.hide() + + but = QT.QPushButton('metrics') + but.clicked.connect(lambda: self.tree_visible_metrics.setVisible(not self.tree_visible_metrics.isVisible())) + self.qt_widget.view_toolbar.addWidget(but) + + header = QT.QHBoxLayout() + header.addWidget(QT.QLabel('color by')) + self.color_combo = QT.QComboBox() + self._color_options = self.get_color_options() + self.color_combo.addItems(list(self._color_options.keys())) + self.color_combo.currentTextChanged.connect(self.refresh) + header.addWidget(self.color_combo) + self.legend_label = QT.QLabel('') + header.addWidget(self.legend_label) + header.addStretch() + self.layout.addLayout(header) + + self.grid = pg.GraphicsLayoutWidget() + self.layout.addWidget(self.grid) + + def _qt_on_visible_metrics_changed(self): + for m in self.visible_metrics_dict.keys(): + self.visible_metrics_dict[m] = self.qt_visible_metrics[m] + self.refresh() + + def _qt_on_settings_changed(self): + self.refresh() + + def _qt_on_unit_visibility_changed(self): + self.refresh() + + def _qt_refresh(self): + import pyqtgraph as pg + + self.grid.clear() + pairs = self.get_pairs() + colors, legend = self.get_pair_colors(pairs, self._color_options.get(self.color_combo.currentText())) + self.legend_label.setText(self.get_legend_html(legend)) + visible_mask = self.get_visible_mask(pairs) + brushes = [pg.mkBrush(color) for color in colors] + pens = [pg.mkPen('#FFFFFF', width=2) if v else pg.mkPen(None) for v in visible_mask] + sizes = np.where(visible_mask, 12, 7) + + num_columns = max(self.settings['num_columns'], 1) + for i, metric in enumerate(self.get_visible_metrics()): + plot = self.grid.addPlot(row=i // num_columns, col=i % num_columns, title=metric) + plot.setLabel('bottom', self.get_axis_label(1)) + plot.setLabel('left', self.get_axis_label(2)) + x, y = self.get_metric_values(metric, pairs) + line = self.get_equality_line(x, y) + if line is not None: + plot.plot(line, line, pen=pg.mkPen('#888888', style=pg.QtCore.Qt.DashLine)) + finite = np.flatnonzero(np.isfinite(x) & np.isfinite(y)) + scatter = pg.ScatterPlotItem( + x=x[finite], y=y[finite], data=finite, pxMode=True, + brush=[brushes[k] for k in finite], pen=[pens[k] for k in finite], size=sizes[finite], + ) + scatter.sigClicked.connect(self._qt_on_points_clicked) + plot.addItem(scatter) + + def _qt_on_points_clicked(self, scatter, points, *args): + if len(points) > 0: + self.select_pair(int(points[0].data())) + + ## panel ## + def _panel_make_layout(self): + import panel as pn + + from .utils_panel import make_toggled_checkboxes + + self.metrics_toggle, self.metrics_select, metrics_box = make_toggled_checkboxes( + "metrics", + options=list(self.visible_metrics_dict.keys()), + value=self.get_visible_metrics(), + on_change=self._panel_on_metrics_changed, + ) + + self._color_options = self.get_color_options() + self.color_select = pn.widgets.Select(name="color by", options=list(self._color_options.keys()), value='none') + self.color_select.param.watch(lambda event: self.refresh(), 'value') + self.legend_pane = pn.pane.HTML("") + + self.layout = pn.Column( + pn.Row(self.metrics_toggle, self.color_select, self.legend_pane, sizing_mode="stretch_width"), + metrics_box, + pn.Column(sizing_mode="stretch_both"), + sizing_mode="stretch_both", + ) + + def _panel_on_metrics_changed(self, event): + for m in self.visible_metrics_dict.keys(): + self.visible_metrics_dict[m] = m in event.new + self.refresh() + + def _panel_on_settings_changed(self): + self.refresh() + + def _panel_on_unit_visibility_changed(self): + self.refresh() + + def _panel_refresh(self): + import panel as pn + import bokeh.plotting as bpl + from bokeh.layouts import gridplot + from bokeh.models import ColumnDataSource + from .utils_panel import _bg_color + + pairs = self.get_pairs() + colors, legend = self.get_pair_colors(pairs, self._color_options.get(self.color_select.value)) + self.legend_pane.object = self.get_legend_html(legend) + visible_mask = self.get_visible_mask(pairs) + + figures = [] + for metric in self.get_visible_metrics(): + fig = bpl.figure( + title=metric, + tools="pan,wheel_zoom,reset,tap", + background_fill_color=_bg_color, + border_fill_color=_bg_color, + outline_line_color="white", + x_axis_label=self.get_axis_label(1), + y_axis_label=self.get_axis_label(2), + ) + fig.toolbar.logo = None + fig.grid.visible = False + x, y = self.get_metric_values(metric, pairs) + line = self.get_equality_line(x, y) + if line is not None: + fig.line(line, line, line_dash="dashed", color="#888888") + finite = np.flatnonzero(np.isfinite(x) & np.isfinite(y)) + source = ColumnDataSource({ + "x": x[finite], "y": y[finite], "pair_index": finite, + "color": [colors[k] for k in finite], + "line_color": ["#FFFFFF" if visible_mask[k] else None for k in finite], + "size": np.where(visible_mask[finite], 12, 7), + }) + fig.scatter("x", "y", source=source, color="color", line_color="line_color", line_width=2, size="size") + source.selected.on_change('indices', self._panel_make_tap_callback(source)) + figures.append(fig) + + if len(figures) == 0: + self.layout[2] = pn.Column(sizing_mode="stretch_both") + return + grid = gridplot(figures, ncols=max(self.settings['num_columns'], 1), sizing_mode="stretch_both", toolbar_location="right") + self.layout[2] = pn.Column(grid, sizing_mode="stretch_both", styles={'background-color': f'{_bg_color}'}) + + def _panel_make_tap_callback(self, source): + def callback(attr, old, new): + if len(new) > 0: + self.select_pair(int(source.data["pair_index"][new[0]])) + return callback + + +CompareMetricsView._gui_help_txt = """ +## Compare Metrics View + +Scatter plots of unit metrics for the matched pairs: the value of the unit of sorter 1 on the +horizontal axis, the value of the unit of sorter 2 on the vertical axis. The dashed line marks +equality. + +The pairs are the ones matched at the agreement threshold shared with the unit Venn view (set it +with the slider of the unit Venn view). The visible pair is drawn bigger, with a white outline. + +### Controls +- **metrics** : the metrics to plot, one scatter plot per metric. +- **color by** : color the points by a categorical property (e.g. a quality label) of the + unit of sorter 1 or of sorter 2. +- **left click on a point** : make that pair of units visible. + +### Settings +- **log_scale** : plot log10(value + .001), useful for firing rates and ISI violations. +- **num_columns** : the number of plots per row. +- **max_categories** : properties with more distinct values than this are not listed in "color by". +""" diff --git a/spikeinterface_gui/comparespikesview.py b/spikeinterface_gui/comparespikesview.py new file mode 100644 index 00000000..0a1a544c --- /dev/null +++ b/spikeinterface_gui/comparespikesview.py @@ -0,0 +1,312 @@ +import numpy as np + +from .compareunitvennview import CompareUnitVennView, solve_venn_geometry + + +class CompareSpikesView(CompareUnitVennView): + """ + Venn diagram of the spikes of one pair of units (one per sorter): spikes found by both, + and spikes found by only one of the two. Clicking a region selects its spikes. + When the waveforms extension is loaded, sample waveforms of the 3 regions are plotted below. + """ + id = "comparespikes" + _supported_backend = ['qt', 'panel'] + _depend_on = ['comparison'] + _settings = [ + {'name': 'max_waveforms', 'type': 'int', 'value': 100}, + ] + # the waveform panels, left to right like the venn regions + _regions = ('only1', 'matched', 'only2') + + def __init__(self, controller=None, parent=None, backend="qt"): + # the spike venn of the visible pair, recomputed when the pair changes (it is cheap) + self._compared_pair = None + self._spike_venn = None + CompareUnitVennView.__init__(self, controller=controller, parent=parent, backend=backend) + + def has_waveforms(self): + return self.controller.waveforms_ext is not None + + def get_visible_pair(self): + """The (unit_id1, unit_id2) pair when the visible units are one unit of each sorter, else None""" + visible_unit_ids = list(self.controller.get_visible_unit_ids()) + if len(visible_unit_ids) != 2: + return None + visible_unit_ids.sort(key=self.controller.get_analyzer_index) + if [self.controller.get_analyzer_index(u) for u in visible_unit_ids] != [1, 2]: + return None + return tuple(visible_unit_ids) + + def update_spike_venn(self): + pair = self.get_visible_pair() + if pair == self._compared_pair: + return + self._compared_pair = pair + self._spike_venn = None if pair is None else self.controller.get_spike_venn(*pair) + + def get_venn_data(self): + if self._spike_venn is None: + venn = dict(matched=[], only1=[], only2=[]) + else: + venn = dict( + matched=self._spike_venn['matched1'], + only1=self._spike_venn['only1'], + only2=self._spike_venn['only2'], + ) + geometry = solve_venn_geometry(len(venn['only1']), len(venn['matched']), len(venn['only2'])) + return venn, geometry + + def get_region_spikes(self, region): + """The spikes of a region, as {unit_id: spike_inds}""" + unit_id1, unit_id2 = self._compared_pair + if region == 'matched': + return { + unit_id1: self._spike_venn['matched1'], + unit_id2: self._spike_venn['matched2'], + } + elif region == 'only1': + return {unit_id1: self._spike_venn['only1']} + else: + return {unit_id2: self._spike_venn['only2']} + + def select_units_on_click(self, x, y, reset=True): + # here a click selects the spikes of a region, not units + _, geometry = self.get_venn_data() + self.select_region(self.get_clicked_region(x, y, geometry)) + + def get_region_button_labels(self): + """{region: label} of the buttons that select a region, which can be too thin to click""" + return { + 'only1': f'Select {self.controller.analyzer1_name}', + 'matched': 'Select match', + 'only2': f'Select {self.controller.analyzer2_name}', + } + + def select_region(self, region): + """Select the spikes of a region: 'only1', 'matched' or 'only2'""" + venn, _ = self.get_venn_data() + if region is None or len(venn[region]) == 0: + return + spike_inds_by_unit = self.get_region_spikes(region) + self.controller.set_indices_spike_selected(np.sort(np.concatenate(list(spike_inds_by_unit.values())))) + self.notify_spike_selection_changed() + + def get_waveforms_data(self, spike_inds_by_unit): + """ + The waveforms to plot, on the extremum channel of the unit of sorter 1, so that the + 3 panels are comparable. + + Returns (times_ms, lines, title) where lines is a list of (color, wfs, is_mean), + or None when there are no waveforms. + """ + controller = self.controller + unit_id1, unit_id2 = self._compared_pair + channel_index = controller.get_main_channel(unit_id1) + colors = {unit_id1: self._color1, unit_id2: self._color2} + rng = np.random.default_rng() + + lines = [] + num_plotted = [] + for unit_id, spike_inds in spike_inds_by_unit.items(): + result = controller.get_waveforms_for_spikes(unit_id, spike_inds) + if result is None: + return None + wfs, chan_inds, kept = result + num_plotted.append(len(kept)) + chan_pos = np.flatnonzero(chan_inds == channel_index) + if len(chan_pos) == 0 or len(kept) == 0: + # the extremum channel is not in the sparsity of this unit + continue + wfs = wfs[:, :, chan_pos[0]] + if wfs.shape[0] > self.settings['max_waveforms']: + wfs = wfs[rng.choice(wfs.shape[0], self.settings['max_waveforms'], replace=False)] + lines.append((colors[unit_id], wfs, False)) + lines.append((colors[unit_id], wfs.mean(axis=0, keepdims=True), True)) + + num_samples = controller.nbefore + controller.nafter + times_ms = (np.arange(num_samples) - controller.nbefore) / controller.sampling_frequency * 1000. + # the counts of the regions are in the Venn diagram, the title only tells how many + # spikes have waveforms: short, a title wider than the plot crops it in Qt + if len(num_plotted) == 1: + title = f"n={num_plotted[0]}" + else: + title = " ".join(f"n{i + 1}={n}" for i, n in enumerate(num_plotted)) + return times_ms, lines, title + + def iter_waveforms_data(self): + """(panel index, waveforms data or None) for the 3 regions""" + for i, region in enumerate(self._regions): + data = None if self._spike_venn is None else self.get_waveforms_data(self.get_region_spikes(region)) + yield i, data + + ## Qt ## + def _qt_make_layout(self): + from .myqt import QT + import pyqtgraph as pg + + self.layout = QT.QVBoxLayout() + + self.pair_label = QT.QLabel('') + self.layout.addWidget(self.pair_label) + + self._qt_make_venn_plot() + + buttons = QT.QHBoxLayout() + self.region_buttons = {} + for region, label in self.get_region_button_labels().items(): + button = QT.QPushButton(label) + button.clicked.connect(lambda checked=False, region=region: self.select_region(region)) + buttons.addWidget(button) + self.region_buttons[region] = button + self.layout.addLayout(buttons) + + self.waveform_plots = [] + if self.has_waveforms(): + waveform_layout = QT.QHBoxLayout() + for i in range(len(self._regions)): + plot = pg.PlotWidget() + plot.setLabel('bottom', 'time (ms)') + if i > 0: + plot.setYLink(self.waveform_plots[0]) + waveform_layout.addWidget(plot) + self.waveform_plots.append(plot) + self.layout.addLayout(waveform_layout) + + def _qt_refresh(self): + self.update_spike_venn() + pair = self._compared_pair + if pair is None: + self.pair_label.setText('select a pair of units, one of each sorter') + else: + self.pair_label.setText(f'{pair[0]} vs {pair[1]}') + venn, geometry = self.get_venn_data() + self._qt_draw_venn(venn, geometry) + for region, button in self.region_buttons.items(): + button.setEnabled(len(venn[region]) > 0) + self._qt_draw_waveforms() + + def _qt_draw_waveforms(self): + import pyqtgraph as pg + + for i, data in self.iter_waveforms_data() if self.has_waveforms() else []: + plot = self.waveform_plots[i] + plot.clear() + plot.setTitle('') + if data is None: + continue + times_ms, lines, title = data + for color, wfs, is_mean in lines: + qcolor = pg.mkColor(color) + qcolor.setAlphaF(1.0 if is_mean else 0.3) + # all the waveforms of a unit in one curve, separated by nan + xs = np.tile(np.append(times_ms, np.nan), wfs.shape[0]) + ys = np.hstack([wfs, np.full((wfs.shape[0], 1), np.nan)]).ravel() + curve = pg.PlotCurveItem(xs, ys, connect='finite', pen=pg.mkPen(qcolor, width=3 if is_mean else 1)) + plot.addItem(curve) + plot.setTitle(title, size='9pt') + # a zoom on a previous pair would otherwise stick to the next ones + plot.enableAutoRange() + + ## panel ## + def _panel_make_layout(self): + import panel as pn + import bokeh.plotting as bpl + from bokeh.models import ColumnDataSource + from .utils_panel import _bg_color + + self.pair_label = pn.pane.Markdown("") + + self._panel_make_venn_figure() + + self.waveform_figures = [] + self.waveform_sources = [] + if self.has_waveforms(): + for i in range(len(self._regions)): + # the 3 panels share the y range of the first one + y_range = dict(y_range=self.waveform_figures[0].y_range) if i > 0 else {} + fig = bpl.figure( + sizing_mode="stretch_both", + tools="pan,wheel_zoom,reset", + background_fill_color=_bg_color, + border_fill_color=_bg_color, + outline_line_color="white", + x_axis_label="time (ms)", + **y_range, + ) + fig.toolbar.logo = None + source = ColumnDataSource({"xs": [], "ys": [], "color": [], "alpha": [], "width": []}) + fig.multi_line( + xs="xs", ys="ys", source=source, + line_color="color", line_alpha="alpha", line_width="width", + ) + self.waveform_figures.append(fig) + self.waveform_sources.append(source) + + self.region_buttons = {} + for region, label in self.get_region_button_labels().items(): + button = pn.widgets.Button(name=label, sizing_mode="stretch_width") + button.on_click(lambda event, region=region: self.select_region(region)) + self.region_buttons[region] = button + + items = [self.pair_label, self.figure, pn.Row(*self.region_buttons.values(), sizing_mode="stretch_width")] + if self.has_waveforms(): + items.append(pn.Row(*self.waveform_figures, sizing_mode="stretch_both", styles={"flex": "1"})) + self.layout = pn.Column( + *items, + styles={"display": "flex", "flex-direction": "column"}, + sizing_mode="stretch_both", + ) + + def _panel_refresh(self): + self.update_spike_venn() + pair = self._compared_pair + self.pair_label.object = "select a pair of units, one of each sorter" if pair is None else f"{pair[0]} vs {pair[1]}" + venn, geometry = self.get_venn_data() + self._panel_draw_venn(venn, geometry) + for region, button in self.region_buttons.items(): + button.disabled = len(venn[region]) == 0 + self._panel_draw_waveforms() + + def _panel_draw_waveforms(self): + for i, wf_data in self.iter_waveforms_data() if self.has_waveforms() else []: + data = {"xs": [], "ys": [], "color": [], "alpha": [], "width": []} + title = "" + if wf_data is not None: + times_ms, lines, title = wf_data + for color, wfs, is_mean in lines: + for wf in wfs: + data["xs"].append(times_ms.tolist()) + data["ys"].append(wf.tolist()) + data["color"].append(color) + data["alpha"].append(1.0 if is_mean else 0.3) + data["width"].append(3 if is_mean else 1) + self.waveform_sources[i].data.update(data) + self.waveform_figures[i].title.text = title + + +CompareSpikesView._gui_help_txt = """ +## Compare Spikes View + +Spike level comparison of one pair of units, one unit of each sorter. Select a row of the +comparison unit table with two units: the comparison is computed automatically. + +The Venn diagram shows the spikes found by both units (matched, within the comparison +`delta_time`), and the spikes found by only one of them. The areas are proportional to the +spike counts. + +When the waveforms extension is loaded, sample waveforms of the 3 regions are plotted below, +on the extremum channel of the unit of sorter 1: sorter 1 only (left), both (middle) and +sorter 2 only (right), with the colors of the Venn diagram. +Waveforms only exist for the `random_spikes` subset, so only those spikes are plotted. The +titles tell how many of the region's spikes have waveforms (`n1` and `n2` for the units of +sorter 1 and 2 in the middle panel). + +### Controls +- **left click on a region** : select the spikes of that region (they show up in the spike + list and trace views). +- **Select {sorter 1} / Select match / Select {sorter 2}** : the same as clicking a region, + for when a region is too thin to click on. + +### Settings +- **max_waveforms** : the maximum number of waveforms plotted per unit and region. +""" diff --git a/spikeinterface_gui/compareunitlistview.py b/spikeinterface_gui/compareunitlistview.py new file mode 100644 index 00000000..78d4ff2a --- /dev/null +++ b/spikeinterface_gui/compareunitlistview.py @@ -0,0 +1,400 @@ +import numpy as np + +from .view_base import ViewBase + + +class CompareUnitListView(ViewBase): + """ + View for displaying unit comparison between two analyzers. + Shows matched units, their agreement scores, and spike counts. + """ + id = "compareunitlist" + _supported_backend = ['qt', 'panel'] + _depend_on = ['comparison'] + _settings = [ + {"name": "matching_mode", "type": "list", "limits": ["hungarian", "best_match"]}, + ] + + def __init__(self, controller=None, parent=None, backend="qt"): + # optional columns: unit properties that both sorters have, shown once per sorter + self.shared_columns_dict = {col: False for col in controller.get_shared_unit_properties()} + ViewBase.__init__(self, controller=controller, parent=parent, backend=backend) + + def get_shared_columns(self): + return [col for col, visible in self.shared_columns_dict.items() if visible] + + def get_column_names(self): + """The header of the table: the 2 units, the score, then each shared column per sorter""" + names = [ + f'Unit ({self.controller.analyzer1_name})', + f'Unit ({self.controller.analyzer2_name})', + 'Agreement Score', + ] + for col in self.get_shared_columns(): + names += [f'{col} ({self.controller.analyzer1_name})', f'{col} ({self.controller.analyzer2_name})'] + return names + + def get_shared_values(self, row): + """The values of the shared columns of a row, in the order of get_column_names""" + table = self.controller.units_table + values = [] + for col in self.get_shared_columns(): + for unit_id in (row['unit_id1'], row['unit_id2']): + value = None if unit_id is None else table.at[unit_id, col] + values.append(None if value is None or (isinstance(value, float) and np.isnan(value)) else value) + return values + + def get_rows(self): + """ + One row per match pair, plus one row per unmatched unit of either analyzer, + sorted by decreasing agreement score. + + Each row is a dict with the *combined* unit ids (or None when there is no unit on + that side) and the numeric agreement score. + """ + controller = self.controller + + if self.settings['matching_mode'] == 'best_match': + matching_12, _ = controller.get_best_matching() + else: + matching_12, _ = controller.get_matching() + agreement_scores = controller.get_agreement_scores() + + rows = [] + matched_original2 = set() + for original_unit_id1 in matching_12.index: + original_unit_id2 = matching_12[original_unit_id1] + unit_id1 = controller.get_combined_unit_id(1, original_unit_id1) + if controller.is_unmatched(original_unit_id2): + # unmatched unit of analyzer1 + rows.append(dict(unit_id1=unit_id1, unit_id2=None, agreement_score=0.)) + else: + rows.append(dict( + unit_id1=unit_id1, + unit_id2=controller.get_combined_unit_id(2, original_unit_id2), + agreement_score=float(agreement_scores.at[original_unit_id1, original_unit_id2]), + )) + matched_original2.add(original_unit_id2) + + # unmatched units of analyzer2 + for original_unit_id2 in controller.analyzer2.unit_ids: + if original_unit_id2 in matched_original2: + continue + rows.append(dict( + unit_id1=None, + unit_id2=controller.get_combined_unit_id(2, original_unit_id2), + agreement_score=0., + )) + + # best matches first, so both backends show the same order. The sort is stable, + # so the unmatched units keep their own order at the bottom. + rows.sort(key=lambda row: row['agreement_score'], reverse=True) + + return rows + + def on_agreement_threshold_changed(self): + # the matching, and therefore the rows, depend on the threshold + self.refresh() + + ## Qt ## + def _qt_make_layout(self): + from .myqt import QT + + import pyqtgraph as pg + + self.layout = QT.QVBoxLayout() + + # shared columns, shown with the "columns" button of the toolbar + tree = [{'name': str(col), 'type': 'bool', 'value': v} for col, v in self.shared_columns_dict.items()] + self.qt_shared_columns = pg.parametertree.Parameter.create(name='shared columns', type='group', children=tree) + self.tree_shared_columns = pg.parametertree.ParameterTree(parent=self.qt_widget) + self.tree_shared_columns.header().hide() + self.tree_shared_columns.setParameters(self.qt_shared_columns, showTop=True) + self.qt_shared_columns.sigTreeStateChanged.connect(self._qt_on_shared_columns_changed) + self.layout.addWidget(self.tree_shared_columns) + self.tree_shared_columns.hide() + but = QT.QPushButton('columns') + but.clicked.connect(lambda: self.tree_shared_columns.setVisible(not self.tree_shared_columns.isVisible())) + self.qt_widget.view_toolbar.addWidget(but) + + # Create table widget + self.table = QT.QTableWidget() + self.layout.addWidget(self.table) + + # Setup table + self.table.setSelectionBehavior(QT.QAbstractItemView.SelectRows) + self.table.setSelectionMode(QT.QAbstractItemView.SingleSelection) + self.table.itemSelectionChanged.connect(self._qt_on_selection_changed) + + self.table.setSortingEnabled(True) + # Sort by Agreement Score column (index 2) by default + self.table.sortItems(2, QT.Qt.DescendingOrder) + + def _qt_on_shared_columns_changed(self): + for col in self.shared_columns_dict.keys(): + self.shared_columns_dict[col] = self.qt_shared_columns[col] + self.refresh() + + def _qt_make_unit_item(self, unit_id): + """A table item showing the unit id, its spike count and its color""" + from .myqt import QT + + if unit_id is None: + item = QT.QTableWidgetItem('') + item.setFlags(QT.Qt.ItemIsEnabled | QT.Qt.ItemIsSelectable) + item.unit_id = None + return item + + num_spikes = self.controller.num_spikes[unit_id] + item = QT.QTableWidgetItem(f'{unit_id} n={num_spikes}') + item.setData(QT.Qt.ItemDataRole.UserRole, unit_id) + item.setFlags(QT.Qt.ItemIsEnabled | QT.Qt.ItemIsSelectable) + item.setIcon(self.get_unit_icon(unit_id)) + item.unit_id = unit_id + return item + + def _qt_refresh(self): + from .myqt import QT + + rows = self.get_rows() + + # Disable sorting while populating, otherwise rows move under us + self.table.setSortingEnabled(False) + self.table.clearContents() + column_names = self.get_column_names() + self.table.setColumnCount(len(column_names)) + self.table.setHorizontalHeaderLabels(column_names) + self.table.setRowCount(len(rows)) + + for i, row in enumerate(rows): + self.table.setItem(i, 0, self._qt_make_unit_item(row['unit_id1'])) + self.table.setItem(i, 1, self._qt_make_unit_item(row['unit_id2'])) + # scores are in [0, 1] and always formatted with 3 decimals, so every string + # has the same width and the lexicographic sort of the column is the numeric one + score_item = QT.QTableWidgetItem(f"{row['agreement_score']:.3f}") + score_item.setFlags(QT.Qt.ItemIsEnabled | QT.Qt.ItemIsSelectable) + self.table.setItem(i, 2, score_item) + for j, value in enumerate(self.get_shared_values(row)): + item = QT.QTableWidgetItem() + if isinstance(value, (int, float, np.integer, np.floating)) and not isinstance(value, bool): + # numbers as data, so that the column sorts numerically + item.setData(QT.Qt.DisplayRole, round(float(value), 4)) + elif value is not None: + item.setText(str(value)) + item.setFlags(QT.Qt.ItemIsEnabled | QT.Qt.ItemIsSelectable) + self.table.setItem(i, 3 + j, item) + + self.table.setSortingEnabled(True) + self.table.resizeColumnsToContents() + self._qt_select_visible_row() + + def _qt_on_selection_changed(self): + """Handle row selection and update unit visibility""" + selected_rows = {item.row() for item in self.table.selectedItems()} + if len(selected_rows) == 0: + return + row_idx = min(selected_rows) + + visible_unit_ids = [] + for col in (0, 1): + item = self.table.item(row_idx, col) + if item is not None and item.unit_id is not None: + visible_unit_ids.append(item.unit_id) + + if len(visible_unit_ids) == 0: + return + + current_visible_units = self.controller.get_visible_unit_ids() + self.controller.set_visible_unit_ids(visible_unit_ids) + if set(current_visible_units) != set(self.controller.get_visible_unit_ids()): + self.notify_unit_and_channel_visibility_changed() + + def _qt_select_visible_row(self): + """Highlight the row holding the currently visible units, without notifying back""" + visible_unit_ids = set(self.controller.get_visible_unit_ids()) + if len(visible_unit_ids) == 0: + return + + for row_idx in range(self.table.rowCount()): + row_unit_ids = set() + for col in (0, 1): + item = self.table.item(row_idx, col) + if item is not None and item.unit_id is not None: + row_unit_ids.add(item.unit_id) + if visible_unit_ids.issubset(row_unit_ids): + self.table.blockSignals(True) + self.table.selectRow(row_idx) + self.table.blockSignals(False) + self.table.scrollToItem(self.table.item(row_idx, 0)) + if set(visible_unit_ids) != row_unit_ids: + self._qt_on_selection_changed() + return + # the visible units are not one row (e.g. a non matched pair): highlight nothing + self.table.blockSignals(True) + self.table.clearSelection() + self.table.blockSignals(False) + + def _qt_on_unit_visibility_changed(self): + self._qt_select_visible_row() + + ## panel ## + def _panel_make_layout(self): + import panel as pn + + pn.extension("tabulator") + + from .utils_panel import make_toggled_checkboxes + + self.shared_columns_toggle, self.shared_columns_select, shared_columns_box = make_toggled_checkboxes( + "columns", + options=list(self.shared_columns_dict.keys()), + value=self.get_shared_columns(), + on_change=self._panel_on_shared_columns_changed, + ) + + self._panel_create_table() + + self.layout = pn.Column( + self.shared_columns_toggle, + shared_columns_box, + self.table, + sizing_mode="stretch_both", + ) + + def _panel_create_table(self): + import pandas as pd + import matplotlib.colors as mcolors + from .utils_panel import unit_formatter, SelectableTabulator + + rows = self.get_rows() + + def cell(unit_id): + if unit_id is None: + return None + return { + "id": str(unit_id), + "color": mcolors.to_hex(self.controller.get_unit_color(unit_id)), + "shape": self.controller.get_unit_shape(unit_id), + "n": self.controller.num_spikes[unit_id], + } + + column_names = self.get_column_names() + unit1_col, unit2_col = column_names[:2] + data = { + unit1_col: [cell(row['unit_id1']) for row in rows], + unit2_col: [cell(row['unit_id2']) for row in rows], + 'Agreement Score': [row['agreement_score'] for row in rows], + } + shared_values = [self.get_shared_values(row) for row in rows] + for j, name in enumerate(column_names[3:]): + data[name] = pd.Series([values[j] for values in shared_values]) + df = pd.DataFrame(data=data, index=list(range(len(rows)))) + # keep the combined unit ids out of the view, the selection callback needs them. + # dtype=object is required: a column mixing unit ids and None would be coerced to + # float, turning the unit ids into floats and the None into NaN + df['_unit_id1'] = pd.Series([row['unit_id1'] for row in rows], dtype=object) + df['_unit_id2'] = pd.Series([row['unit_id2'] for row in rows], dtype=object) + + # the comparison table is read only: nothing here can be curated, and an edit + # from the browser would try to patch a read-only array + editors = {col: {'type': 'editable', 'value': False} for col in df.columns} + + self.table = SelectableTabulator( + df, + formatters={unit1_col: unit_formatter, unit2_col: unit_formatter}, + editors=editors, + hidden_columns=['_unit_id1', '_unit_id2'], + sizing_mode="stretch_both", + layout="fit_data", + show_index=False, + selectable=True, + pagination=None, + # SelectableTabulator functions + skip_sort_columns=[unit1_col, unit2_col], + parent_view=self, + conditional_shortcut=self.is_view_active, + on_selection_changed=self._panel_on_selection_changed, + on_only_function=self._panel_on_selection_changed, + ) + + def _panel_on_shared_columns_changed(self, event): + for col in self.shared_columns_dict.keys(): + self.shared_columns_dict[col] = col in event.new + self.refresh() + + def _panel_on_selection_changed(self): + selected_rows = self.table.selection + if len(selected_rows) == 0: + return + df = self.table.value + row = df.iloc[selected_rows[0]] + + visible_unit_ids = [ + unit_id for unit_id in (row['_unit_id1'], row['_unit_id2']) if unit_id is not None + ] + if len(visible_unit_ids) == 0: + return + + current_visible_units = self.controller.get_visible_unit_ids() + self.controller.set_visible_unit_ids(visible_unit_ids) + # this runs twice when the row is selected from code (directly, then from the selection + # watcher): notifying twice refreshes the correlograms twice and they render blank + if set(current_visible_units) != set(self.controller.get_visible_unit_ids()): + self.notify_unit_and_channel_visibility_changed() + + def _panel_refresh(self): + # the rows depend on the matching, so the whole table is rebuilt + old_panel = self.table.__panel__() + table_index = next(i for i, obj in enumerate(self.layout.objects) if obj is old_panel) + self._panel_create_table() + self.layout[table_index] = self.table + # visibility changes are skipped while the tab is hidden, so re-select on refresh (as in qt) + self._panel_on_unit_visibility_changed() + + def _panel_on_unit_visibility_changed(self): + # the rows themselves do not change, only which one is highlighted + visible_unit_ids = set(self.controller.get_visible_unit_ids()) + if len(visible_unit_ids) == 0: + return + df = self.table.value + for row_index in range(len(df)): + row = df.iloc[row_index] + row_unit_ids = { + unit_id for unit_id in (row['_unit_id1'], row['_unit_id2']) if unit_id is not None + } + # subset, like in qt: picking one unit (e.g. from the probe view) selects its row + if visible_unit_ids.issubset(row_unit_ids): + if self.table.selection != [row_index]: + # the selection watcher then makes the whole pair visible + self.table.selection = [row_index] + if visible_unit_ids != row_unit_ids: + self._panel_on_selection_changed() + return + # the visible units are not one row (e.g. a non matched pair): highlight nothing + if self.table.selection != []: + self.table.selection = [] + + +CompareUnitListView._gui_help_txt = """ +## Compare Unit List View + +The unit list in comparison mode. One row per pair of matched units, plus one row per unit +that only one of the two sorters found. + +The rows are sorted by decreasing agreement score, so the best matches come first and the +units that only one sorter found (score 0) come last. + +The matching is done at the agreement threshold shared with the other comparison views +(set it with the slider of the unit Venn view). The table is read only: there is no curation in +comparison mode. + +### Settings +- **matching_mode** : "hungarian" gives a one to one matching, "best_match" simply takes + the best candidate for each unit of the first sorter, so a unit of the second sorter can + appear on several rows. + +### Controls +- **left click on a row** : make the units of this row visible in the other views. +- **columns** : add unit properties that both sorters have (e.g. firing rate or a quality + label), as one column per sorter. +""" diff --git a/spikeinterface_gui/compareunitvennview.py b/spikeinterface_gui/compareunitvennview.py new file mode 100644 index 00000000..a520b0b6 --- /dev/null +++ b/spikeinterface_gui/compareunitvennview.py @@ -0,0 +1,546 @@ +import numpy as np + +from .view_base import ViewBase +from .comparelabelsview import get_categorical_properties + + +def solve_venn_geometry(num_only1, num_matched, num_only2): + """ + Two circle Venn geometry with areas proportional to the unit counts. + + Returns (radius1, radius2, center_x1, center_x2). The disc areas are `num1` and `num2` + and the area of the lens is `num_matched`, so the picture is quantitatively honest. + The two circles are centered on y=0 and symmetric around x=0. + """ + num1 = num_only1 + num_matched + num2 = num_matched + num_only2 + + if num1 == 0 and num2 == 0: + return 0., 0., 0., 0. + + # disc area == unit count + radius1 = np.sqrt(num1 / np.pi) + radius2 = np.sqrt(num2 / np.pi) + + if num1 == 0 or num2 == 0: + # one of the two is empty, put the other one in the middle + distance = radius1 + radius2 + elif num_matched == 0: + # disjoint, just touching + distance = radius1 + radius2 + elif num_matched >= min(num1, num2): + # fully nested + distance = abs(radius1 - radius2) + else: + distance = _solve_center_distance(radius1, radius2, num_matched) + + return radius1, radius2, -distance / 2., distance / 2. + + +def _lens_area(distance, radius1, radius2): + """Area of the intersection of two discs whose centers are `distance` apart""" + if distance >= radius1 + radius2: + return 0. + if distance <= abs(radius1 - radius2): + return np.pi * min(radius1, radius2) ** 2 + d, r1, r2 = distance, radius1, radius2 + part1 = r1 ** 2 * np.arccos((d ** 2 + r1 ** 2 - r2 ** 2) / (2 * d * r1)) + part2 = r2 ** 2 * np.arccos((d ** 2 + r2 ** 2 - r1 ** 2) / (2 * d * r2)) + part3 = 0.5 * np.sqrt(max((-d + r1 + r2) * (d + r1 - r2) * (d - r1 + r2) * (d + r1 + r2), 0.)) + return part1 + part2 - part3 + + +def _solve_center_distance(radius1, radius2, target_area): + """Center distance giving an intersection of `target_area`. The lens area decreases with d.""" + from scipy.optimize import brentq + + low = abs(radius1 - radius2) + high = radius1 + radius2 + return brentq(lambda d: _lens_area(d, radius1, radius2) - target_area, low, high) + + +class CompareUnitVennView(ViewBase): + """ + Venn diagram of the two compared sortings: units matched by both, and units found + by only one of the two. The agreement threshold is set with a slider and is shared + with the other comparison views. + """ + id = "unitvenn" + _supported_backend = ['qt', 'panel'] + _depend_on = ['comparison'] + _settings = [ + {'name': 'inclusion', 'type': 'list', 'limits': ['both', 'any']}, + ] + + _color1 = "#1f77b4" + _color2 = "#ff7f0e" + _max_filter_categories = 20 + + # the unit filter: a categorical property and the values to keep, None for no filter + _filter_property = None + _filter_values = () + + def get_filter_properties(self): + return get_categorical_properties(self.controller, self._max_filter_categories) + + def get_property_values(self, property_name): + """The values of a property as strings, indexed by unit id. Missing values are "n/a".""" + column = self.controller.units_table[property_name] + return column.astype(object).where(column.notna(), "n/a").astype(str) + + def set_filter(self, property_name, values): + self._filter_property = property_name + self._filter_values = tuple(values) + self.refresh() + + def filter_venn(self, venn): + """ + Keep only the units whose filter property is one of the filter values. + + With inclusion "both" a matched pair stays matched when both units pass, and a passing + unit whose match does not pass counts as found by its own sorter only. With "any" a + pair stays matched when at least one of its units passes. + """ + if self._filter_property is None: + return venn + values = self.get_property_values(self._filter_property) + passing = set(values.index[values.isin(self._filter_values)]) + matched = [] + only1 = [u for u in venn['only1'] if u in passing] + only2 = [u for u in venn['only2'] if u in passing] + for unit_id1, unit_id2 in venn['matched']: + pass1, pass2 = unit_id1 in passing, unit_id2 in passing + if (pass1 and pass2) or (self.settings['inclusion'] == 'any' and (pass1 or pass2)): + matched.append((unit_id1, unit_id2)) + else: + if pass1: + only1.append(unit_id1) + if pass2: + only2.append(unit_id2) + return dict(matched=matched, only1=only1, only2=only2) + + def get_venn_data(self): + """Returns (venn_dict, geometry) where geometry is (r1, r2, cx1, cx2)""" + venn = self.filter_venn(self.controller.get_venn_unit_ids()) + geometry = solve_venn_geometry(len(venn['only1']), len(venn['matched']), len(venn['only2'])) + return venn, geometry + + def get_clicked_region(self, x, y, geometry): + """The region under (x, y): 'matched', 'only1', 'only2' or None""" + radius1, radius2, center_x1, center_x2 = geometry + inside1 = (x - center_x1) ** 2 + y ** 2 <= radius1 ** 2 + inside2 = (x - center_x2) ** 2 + y ** 2 <= radius2 ** 2 + if inside1 and inside2: + return 'matched' + elif inside1: + return 'only1' + elif inside2: + return 'only2' + return None + + def select_units_on_click(self, x, y, reset=True): + """ + Make visible one random entry of the clicked region. + + A region can hold hundreds of units, so a click picks one of them at random and + clicking the same region again picks another: that is how one walks a region. + + Exactly one entry is selected, never more, so that the selection always matches a + single row of the comparison unit table, which is single selection. In the + intersection an entry is a matched *pair*, so both of its units become visible, + which is still that one row. + """ + venn, geometry = self.get_venn_data() + region = self.get_clicked_region(x, y, geometry) + if region is None: + return + candidates = venn[region] + if len(candidates) == 0: + return + + rng = np.random.default_rng() + candidate = candidates[rng.integers(len(candidates))] + if isinstance(candidate, tuple): + # a matched pair, both units so that they can be compared + unit_ids = list(candidate) + else: + unit_ids = [candidate] + + # note that `reset` is ignored on purpose: accumulating entries would put several + # rows of the comparison unit table in the visible set, which it cannot show + self.controller.set_visible_unit_ids(unit_ids) + self.notify_unit_and_channel_visibility_changed() + self.refresh() + + def set_agreement_threshold(self, threshold): + self.controller.set_agreement_threshold(threshold) + self.notify_agreement_threshold_changed() + self.refresh() + + def get_venn_labels(self, venn, geometry): + """ + The texts to draw, as a list of (x, y, text, color). + + Each count sits in the middle of its own region along y=0, and each analyzer name + on the outer side of its own circle, in its own color so that the two never + overlap when the circles are close together. + """ + radius1, radius2, center_x1, center_x2 = geometry + num_only1 = len(venn['only1']) + num_matched = len(venn['matched']) + num_only2 = len(venn['only2']) + + left1, right1 = center_x1 - radius1, center_x1 + radius1 + left2, right2 = center_x2 - radius2, center_x2 + radius2 + labels = [] + + if num_only1 > 0: + # the only1 region runs from the left of circle1 to the left of circle2, + # or spans the whole of circle1 when the two are disjoint + only1_right = min(right1, max(left2, left1)) + labels.append(((left1 + only1_right) / 2., 0., f'{num_only1}', '#FFFFFF')) + if num_only2 > 0: + only2_left = max(left2, min(right1, right2)) + labels.append(((only2_left + right2) / 2., 0., f'{num_only2}', '#FFFFFF')) + if num_matched > 0 and radius1 + radius2 > abs(center_x2 - center_x1): + # middle of the lens along x + labels.append(((right1 + left2) / 2., 0., f'{num_matched}', '#FFFFFF')) + + top = max(radius1, radius2) + labels.append((left1 + radius1 * 0.45, top * 1.15, f'{self.controller.analyzer1_name}', self._color1)) + labels.append((right2 - radius2 * 0.45, top * 1.15, f'{self.controller.analyzer2_name}', self._color2)) + + return labels + + def get_circle_polygon(self, radius, center_x, num_points=100): + """A closed circle as (xs, ys), for the backends that draw polygons""" + theta = np.linspace(0, 2 * np.pi, num_points) + return center_x + radius * np.cos(theta), radius * np.sin(theta) + + def get_view_ranges(self, geometry): + radius1, radius2, center_x1, center_x2 = geometry + top = max(radius1, radius2) + margin = 0.2 * top + x_range = (center_x1 - radius1 - margin, center_x2 + radius2 + margin) + y_range = (-top - margin, top * 1.3 + margin) + return x_range, y_range + + ## Qt ## + def _qt_make_layout(self): + from .myqt import QT + + self.layout = QT.QVBoxLayout() + + # threshold slider, the controller holds the value + header = QT.QHBoxLayout() + header.addWidget(QT.QLabel('agreement threshold')) + self.slider = QT.QSlider(QT.Qt.Horizontal) + self.slider.setMinimum(0) + self.slider.setMaximum(100) + self.slider.setValue(int(round(self.controller.agreement_threshold * 100))) + self.slider.valueChanged.connect(self._qt_on_slider_changed) + header.addWidget(self.slider) + self.threshold_label = QT.QLabel(f'{self.controller.agreement_threshold:.2f}') + header.addWidget(self.threshold_label) + self.layout.addLayout(header) + self._qt_make_filter() + + # dragging the slider emits one signal per step: debounce the re-matching so that + # a drag does not re-run the matching and rebuild the unit table on every step + self._commit_timer = QT.QTimer(self.qt_widget) + self._commit_timer.setSingleShot(True) + self._commit_timer.setInterval(150) + self._commit_timer.timeout.connect(self._qt_commit_threshold) + + self._qt_make_venn_plot() + + def _qt_make_filter(self): + from .myqt import QT + + row = QT.QHBoxLayout() + row.addWidget(QT.QLabel('filter')) + self.filter_combo = QT.QComboBox() + self.filter_combo.addItems(['none'] + self.get_filter_properties()) + self.filter_combo.currentTextChanged.connect(self._qt_on_filter_property_changed) + row.addWidget(self.filter_combo) + # the values of the property, as checkable items laid out in a row + self.filter_values_list = QT.QListWidget() + self.filter_values_list.setFlow(QT.QListView.LeftToRight) + self.filter_values_list.setWrapping(True) + self.filter_values_list.setMaximumHeight(50) + self.filter_values_list.itemChanged.connect(self._qt_on_filter_values_changed) + self.filter_values_list.hide() + row.addWidget(self.filter_values_list, stretch=1) + self.layout.addLayout(row) + + def _qt_on_filter_property_changed(self, text): + from .myqt import QT + + property_name = None if text == 'none' else text + values = [] if property_name is None else sorted(self.get_property_values(property_name).unique()) + self.filter_values_list.blockSignals(True) + self.filter_values_list.clear() + for value in values: + item = QT.QListWidgetItem(value) + item.setFlags(item.flags() | QT.Qt.ItemIsUserCheckable) + item.setCheckState(QT.Qt.Checked) + self.filter_values_list.addItem(item) + self.filter_values_list.blockSignals(False) + self.filter_values_list.setVisible(property_name is not None) + self.set_filter(property_name, values) + + def _qt_on_filter_values_changed(self, item=None): + from .myqt import QT + + values = [ + self.filter_values_list.item(i).text() for i in range(self.filter_values_list.count()) + if self.filter_values_list.item(i).checkState() == QT.Qt.Checked + ] + self.set_filter(self._filter_property, values) + + def _qt_make_venn_plot(self): + import pyqtgraph as pg + from .utils_qt import ViewBoxHandlingClickToPositionWithCtrl + + self.graphicsview = pg.GraphicsView() + self.layout.addWidget(self.graphicsview) + + self.viewBox = ViewBoxHandlingClickToPositionWithCtrl() + self.viewBox.clicked.connect(self._qt_select_units) + self.viewBox.disableAutoRange() + self.viewBox.setAspectLocked(True) + + self.plot = pg.PlotItem(viewBox=self.viewBox) + self.graphicsview.setCentralItem(self.plot) + self.plot.hideButtons() + self.plot.hideAxis('bottom') + self.plot.hideAxis('left') + + self._items = [] + + def _qt_on_slider_changed(self, value): + # the label follows the slider immediately, the rest is debounced + self.threshold_label.setText(f'{value / 100.:.2f}') + self._commit_timer.start() + + def _qt_commit_threshold(self): + self.set_agreement_threshold(self.slider.value() / 100.) + + def _qt_select_units(self, x, y, reset): + self.select_units_on_click(x, y, reset=reset) + + def _qt_refresh(self): + # keep the slider in sync when the threshold is changed elsewhere, but never + # while an edit of our own is still pending, otherwise a refresh triggered by + # another view would snap the handle back under the user's cursor + slider_value = int(round(self.controller.agreement_threshold * 100)) + if self.slider.value() != slider_value and not self._commit_timer.isActive(): + self.slider.blockSignals(True) + self.slider.setValue(slider_value) + self.slider.blockSignals(False) + # the label always shows what the handle shows + self.threshold_label.setText(f'{self.slider.value() / 100.:.2f}') + + self._qt_draw_venn(*self.get_venn_data()) + + def _qt_draw_venn(self, venn, geometry): + from .myqt import QT + import pyqtgraph as pg + + for item in self._items: + self.plot.removeItem(item) + self._items = [] + + radius1, radius2, center_x1, center_x2 = geometry + + if radius1 == 0. and radius2 == 0.: + return + + for radius, center_x, color in ( + (radius1, center_x1, self._color1), + (radius2, center_x2, self._color2), + ): + if radius == 0.: + continue + circle = QT.QGraphicsEllipseItem(center_x - radius, -radius, 2 * radius, 2 * radius) + circle.setPen(pg.mkPen(color, width=2)) + # semi transparent so that the intersection reads as a third region + brush_color = QT.QColor(color) + brush_color.setAlpha(110) + circle.setBrush(pg.mkBrush(brush_color)) + self.plot.addItem(circle) + self._items.append(circle) + + for x, y, text, color in self.get_venn_labels(venn, geometry): + item = pg.TextItem(text=text, color=color, anchor=(0.5, 0.5), border=None) + item.setPos(x, y) + self.plot.addItem(item) + self._items.append(item) + + x_range, y_range = self.get_view_ranges(geometry) + self.plot.setXRange(*x_range) + self.plot.setYRange(*y_range) + + ## panel ## + def _panel_make_layout(self): + import panel as pn + + # value_throttled only fires at the end of a drag, which is the debounce that + # the Qt side has to do with a timer + self.threshold_slider = pn.widgets.FloatSlider( + name='agreement threshold', + start=0., end=1., step=0.01, + value=float(self.controller.agreement_threshold), + sizing_mode="stretch_width", + ) + self.threshold_slider.param.watch(self._panel_on_slider_changed, 'value_throttled') + + self.filter_select = pn.widgets.Select( + name='filter', options=['none'] + self.get_filter_properties(), value='none', + sizing_mode="stretch_width", + ) + self.filter_values_select = pn.widgets.MultiChoice( + name='values', options=[], value=[], visible=False, sizing_mode="stretch_width", + ) + self.filter_select.param.watch(self._panel_on_filter_property_changed, 'value') + self.filter_values_select.param.watch( + lambda event: self.set_filter(self._filter_property, event.new), 'value' + ) + + self._panel_make_venn_figure() + + self.layout = pn.Column( + self.threshold_slider, + self.filter_select, + self.filter_values_select, + self.figure, + styles={"display": "flex", "flex-direction": "column"}, + sizing_mode="stretch_both", + ) + + def _panel_make_venn_figure(self): + import bokeh.plotting as bpl + from bokeh.models import ColumnDataSource + from bokeh.events import Tap + from .utils_panel import _bg_color + + self.figure = bpl.figure( + sizing_mode="stretch_both", + tools="reset,wheel_zoom,tap", + background_fill_color=_bg_color, + border_fill_color=_bg_color, + match_aspect=True, + outline_line_color="white", + styles={"flex": "1"}, + ) + self.figure.toolbar.logo = None + self.figure.axis.visible = False + self.figure.grid.visible = False + # match_aspect only works with auto ranges: an invisible glyph on the view corners + # makes the auto range include the labels, setting range start/end would distort + self.bounds_source = ColumnDataSource({"x": [], "y": []}) + self.figure.scatter(x="x", y="y", source=self.bounds_source, alpha=0) + + # one entry per circle, updated in place on refresh + self.circle_source = ColumnDataSource({"xs": [], "ys": [], "color": []}) + self.figure.patches( + xs="xs", ys="ys", source=self.circle_source, + fill_color="color", line_color="color", fill_alpha=0.43, line_width=2, + ) + + self.text_source = ColumnDataSource({"x": [], "y": [], "text": [], "color": []}) + self.figure.text( + x="x", y="y", text="text", text_color="color", source=self.text_source, + text_align="center", text_baseline="middle", + ) + + self.figure.on_event(Tap, self._panel_on_tap) + + def _panel_on_filter_property_changed(self, event): + property_name = None if event.new == 'none' else event.new + values = [] if property_name is None else sorted(self.get_property_values(property_name).unique()) + # set the filter before the values, so that the values watcher filters the new property + self._filter_property = property_name + self.filter_values_select.options = values + self.filter_values_select.visible = property_name is not None + if self.filter_values_select.value == values: + self.set_filter(property_name, values) + else: + self.filter_values_select.value = values + + def _panel_on_slider_changed(self, event): + self.set_agreement_threshold(event.new) + + def _panel_on_tap(self, event): + if event.x is None or event.y is None: + return + self.select_units_on_click(event.x, event.y, reset=True) + + def _panel_refresh(self): + # keep the slider in sync when the threshold is changed elsewhere + threshold = float(self.controller.agreement_threshold) + if self.threshold_slider.value != threshold: + self.threshold_slider.value = threshold + + self._panel_draw_venn(*self.get_venn_data()) + + def _panel_draw_venn(self, venn, geometry): + radius1, radius2, center_x1, center_x2 = geometry + + if radius1 == 0. and radius2 == 0.: + self.circle_source.data.update({"xs": [], "ys": [], "color": []}) + self.text_source.data.update({"x": [], "y": [], "text": [], "color": []}) + return + + all_xs, all_ys, colors = [], [], [] + for radius, center_x, color in ( + (radius1, center_x1, self._color1), + (radius2, center_x2, self._color2), + ): + if radius == 0.: + continue + xs, ys = self.get_circle_polygon(radius, center_x) + all_xs.append(xs.tolist()) + all_ys.append(ys.tolist()) + colors.append(color) + self.circle_source.data.update({"xs": all_xs, "ys": all_ys, "color": colors}) + + labels = self.get_venn_labels(venn, geometry) + self.text_source.data.update({ + "x": [label[0] for label in labels], + "y": [label[1] for label in labels], + "text": [label[2] for label in labels], + "color": [label[3] for label in labels], + }) + + x_range, y_range = self.get_view_ranges(geometry) + self.bounds_source.data.update({"x": list(x_range), "y": list(y_range)}) + + +CompareUnitVennView._gui_help_txt = """ +## Unit Venn View + +Venn diagram of the two compared sorting outputs. The area of each disc is proportional to +the number of units of that sorter, and the area of the intersection is proportional to the +number of units matched between the two, so the picture is quantitatively honest. + +The matching is one to one (hungarian) at the agreement threshold set with the slider. +That threshold is shared with the other comparison views: moving it also re-orders the +agreement matrix and re-categorizes the rows of the comparison unit table. + +### Controls +- **slider** : the agreement threshold above which two units are considered matched. +- **filter** : only count the units whose categorical property (e.g. a quality label, shared + by both sorters) is one of the checked values. +- **left click on a region** : make one random unit of that region visible. Clicking again + picks another one, which is a quick way to walk through a region. Clicking the + intersection selects the two units of one matched pair, so that they can be compared. + +Only one unit (or one matched pair) is selected per click, so that the selection always +matches a single row of the comparison unit table. + +### Settings +- **inclusion** : how a matched pair is counted when only one of its units passes the filter. + "both": the pair is matched only when both units pass, otherwise the passing unit counts as + found by its own sorter only. "any": the pair stays matched when at least one unit passes. +""" diff --git a/spikeinterface_gui/controller.py b/spikeinterface_gui/controller.py index 59b06f76..365a7ec0 100644 --- a/spikeinterface_gui/controller.py +++ b/spikeinterface_gui/controller.py @@ -9,10 +9,11 @@ from spikeinterface import compute_sparsity from spikeinterface.core.base import minimum_spike_dtype +from spikeinterface.core.sorting_tools import spike_vector_to_indices from spikeinterface.curation import validate_curation_dict, apply_curation from spikeinterface.curation.curation_model import Curation from spikeinterface.widgets.utils import make_units_table_from_analyzer -from spikeinterface.widgets.utils import make_units_table_from_analyzer +from spikeinterface.widgets.sorting_summary import _default_displayed_unit_properties from .utils_global import add_new_unit_ids_to_curation_dict @@ -29,8 +30,7 @@ split_new_id_strategy = 'append', num_colors=20, ) - -from spikeinterface.widgets.sorting_summary import _default_displayed_unit_properties + class Controller(): @@ -343,38 +343,8 @@ def set_analyzer_info(self, analyzer): self._ext_channel_inds = np.array([self._main_channels[unit_id] for unit_id in self.unit_ids]) - cached = self.analyzer.sorting._cached_spike_vector_segment_slices - if cached is not None: - # shape (num_seg, 2): columns are [start, stop] - self.segment_slices = {seg: slice(int(cached[seg, 0]), int(cached[seg, 1])) for seg in range(num_seg)} - else: - bounds = np.searchsorted(np.asarray(self.spikes["segment_index"]), np.arange(num_seg + 1)) - self.segment_slices = {seg: slice(int(bounds[seg]), int(bounds[seg + 1])) for seg in range(num_seg)} - - # Load unit_index once to build per-unit lookup structures, avoiding a - # second to_spike_vector() call that would materialise full structured - # arrays from zarr for every segment. - unit_index_all = np.asarray(self.spikes["unit_index"]) - - # last sample per segment: one cheap element read instead of full materialisation - sample_index_arr = self.spikes["sample_index"] - self.final_spike_samples = [int(sample_index_arr[self.segment_slices[seg].stop - 1]) for seg in range(num_seg)] - - # dict[segment_index][unit_id] -> absolute spike indices for that unit in that segment - num_units = len(unit_ids) - self._spike_index_by_segment_and_units = {} - for seg_ind in range(num_seg): - sl = self.segment_slices[seg_ind] - seg_unit_idx = unit_index_all[sl] - abs_offset = sl.start - order = np.argsort(seg_unit_idx, stable=True) - sorted_unit = seg_unit_idx[order] - sorted_abs = (order + abs_offset).astype(np.int64) - boundaries = np.searchsorted(sorted_unit, np.arange(num_units + 1, dtype=np.int64)) - self._spike_index_by_segment_and_units[seg_ind] = { - uid: sorted_abs[boundaries[u]:boundaries[u + 1]].copy() - for u, uid in enumerate(unit_ids) - } + # self.num_spikes = self.analyzer.sorting.count_num_spikes_per_unit(outputs="dict") + self._build_spike_indices(num_seg) t1 = time.perf_counter() if self.verbose: @@ -468,6 +438,40 @@ def set_curation_info(self, curation, iterative_curation, curation_data, label_d print('Curation quality labels are the default ones') self.has_default_quality_labels = True + curation_data = Curation(**curation_data).model_dump() + self.curation_data = curation_data + + def _build_spike_indices(self, num_seg): + """ + Build the per-segment and per-unit spike index bookkeeping from `self.spikes`. + + `self.spikes` must already be filled and sorted by sample_index within each segment. + Sets `segment_slices`, `final_spike_samples`, `_spike_index_by_units` and + `_spike_index_by_segment_and_units`. Shared with ControllerComparison. + """ + seg_limits = np.searchsorted(self.spikes["segment_index"], np.arange(num_seg + 1)) + self.segment_slices = {segment_index: slice(seg_limits[segment_index], seg_limits[segment_index + 1]) for segment_index in range(num_seg)} + + spike_vector2 = [] + for segment_index in range(num_seg): + seg_slice = self.segment_slices[segment_index] + spike_vector2.append(self.spikes[seg_slice]) + self.final_spike_samples = [segment_spike_vector[-1][0] for segment_spike_vector in spike_vector2] + # this is dict of list because per segment spike_indices[segment_index][unit_id] + spike_indices_abs = spike_vector_to_indices(spike_vector2, self.unit_ids, absolute_index=True) + spike_indices = spike_vector_to_indices(spike_vector2, self.unit_ids) + # this is flatten + spike_per_seg = [s.size for s in spike_vector2] + # dict[unit_id] -> all indices for this unit across segments + self._spike_index_by_units = {} + # dict[segment_index][unit_id] -> all indices for this unit for one segment + self._spike_index_by_segment_and_units = spike_indices_abs + for unit_id in self.unit_ids: + inds = [] + for seg_ind in range(num_seg): + inds.append(spike_indices[seg_ind][unit_id] + int(np.sum(spike_per_seg[:seg_ind]))) + self._spike_index_by_units[unit_id] = np.concatenate(inds) + def check_is_view_possible(self, view_name): from .viewlist import get_all_possible_views possible_class_views = get_all_possible_views() @@ -493,6 +497,13 @@ def channel_ids(self): def unit_ids(self): return self.analyzer.unit_ids + @property + def unit_shapes(self): + return ["circle"] * len(self.unit_ids) + + def get_unit_shape(self, unit_id): + return "circle" + def get_time(self): """ Returns selected time and segment index @@ -612,7 +623,9 @@ def get_divergent_unit_colors(self, num_entries=20): import glasbey import matplotlib.colors as mcolors - unit_locations = self.analyzer.get_extension("unit_locations").get_data() + # self.unit_positions is the 2D unit locations, already stacked for both + # analyzers in comparison mode + unit_locations = self.unit_positions # lexsort by x and y sorted_inds = np.lexsort((unit_locations[:, 0], unit_locations[:, 1])) @@ -825,9 +838,9 @@ def get_waveform_sweep(self): def get_waveforms_range(self): return np.nanmin(self.templates_average), np.nanmax(self.templates_average) - def get_waveforms(self, unit_id): - wfs = self.waveforms_ext.get_waveforms_one_unit(unit_id, force_dense=False) - if self.analyzer.sparsity is None: + def get_waveforms(self, unit_id, force_dense=False): + wfs = self.waveforms_ext.get_waveforms_one_unit(unit_id, force_dense=force_dense) + if self.analyzer.sparsity is None or force_dense: # dense waveforms chan_inds = np.arange(self.analyzer.get_num_channels(), dtype='int64') else: @@ -1316,3 +1329,5 @@ def remove_category_from_unit(self, unit_id, category): elif lbl.get('labels') is not None and category in lbl.get('labels'): lbl['labels'].pop(category) self.curation_data["manual_labels"][ix] = lbl + + diff --git a/spikeinterface_gui/controllercomparison.py b/spikeinterface_gui/controllercomparison.py new file mode 100644 index 00000000..3e5a47d1 --- /dev/null +++ b/spikeinterface_gui/controllercomparison.py @@ -0,0 +1,737 @@ +import time + +import numpy as np +import pandas as pd + + +from spikeinterface import compute_sparsity +from spikeinterface.core.recording_tools import get_rec_attributes, do_recording_attributes_match +from spikeinterface.comparison import compare_two_sorters +from spikeinterface.widgets.utils import make_units_table_from_analyzer +from spikeinterface.widgets.sorting_summary import _default_displayed_unit_properties + +from spikeinterface.core.base import minimum_spike_dtype + +from .controller import Controller + + +_default_main_settings = dict( + max_visible_units=10, + label_colormap='Set1', + use_times=False, + num_colors=20, + # unused + color_mode='color_by_unit' +) + +# extensions that cannot be shared/concatenated between the two analyzers +# correlograms are not concatenated either, only their diagonal (the ACGs) is used +_comparison_skip_extensions = ["principal_components", "isi_histograms", "template_similarity"] + + +class ControllerComparison(Controller): + """ + Controller for comparison mode. + + Two SortingAnalyzer are virtually concatenated into a single unit_id namespace so that + all the standard views can be reused. On top of that a `compare_two_sorters` comparison + is computed and exposed through `get_agreement_scores()` / `get_matching()` / + `get_venn_unit_ids()`. + + `Controller.__init__` is deliberately not called: this `__init__` establishes the same + attribute contract (`spikes`, `unit_ids`, `templates_average`, `unit_positions`, ...) from + the two analyzers, and `self.analyzer` is set to `analyzer1` so that every recording/probe + facing method of the base class keeps working (only analyzer1's recording is used, the + channels are shared). + """ + + def __init__( + self, analyzer1=None, analyzer2=None, + analyzer1_name="1", analyzer2_name="2", comparison=None, match_score=0.5, + backend="qt", parent=None, verbose=False, with_traces=True, + displayed_unit_properties=None, + extra_unit_properties=None, skip_extensions=None, disable_save_settings_button=False, + user_main_settings=None, + ): + self.views = [] + skip_extensions = list(skip_extensions) if skip_extensions is not None else [] + skip_extensions.extend(_comparison_skip_extensions) + self.skip_extensions = sorted(set(skip_extensions)) + + self.backend = backend + self.disable_save_settings_button = disable_save_settings_button + # curation is not possible in comparison mode + self.curation = False + # this is not to have a popup when closing + self.current_curation_saved = True + self.external_data = None + self.events = None + self.save_on_compute = False + + if self.backend == "qt": + from .backend_qt import SignalHandler + self.signal_handler = SignalHandler(self, parent=parent) + + elif self.backend == "panel": + from .backend_panel import SignalHandler + self.signal_handler = SignalHandler(self, parent=parent) + + self.with_traces = with_traces + + self.analyzer1 = analyzer1 + self.analyzer2 = analyzer2 + self.analyzer1_name = analyzer1_name + self.analyzer2_name = analyzer2_name + # the base class methods that touch the recording/probe/format use self.analyzer + self.analyzer = analyzer1 + assert self.analyzer1.get_extension("random_spikes") is not None + assert self.analyzer2.get_extension("random_spikes") is not None + + assert self.analyzer1.return_in_uV == self.analyzer2.return_in_uV + self.return_in_uV = self.analyzer1.return_in_uV + + # check recording attributes match + recording1 = None + recording2 = None + self.use_recordings = False + + try: + recording1 = self.analyzer1.recording + except: + pass + try: + recording2 = self.analyzer2.recording + except: + pass + if recording1 is not None and recording2 is not None: + match, diff = do_recording_attributes_match( + recording1, get_rec_attributes(recording2) + ) + if match: + self.use_recordings = True + + self.verbose = verbose + t0 = time.perf_counter() + + self.main_settings = _default_main_settings.copy() + if user_main_settings is not None: + self.main_settings.update(user_main_settings) + + # some direct attribute + self.num_channels = self.analyzer1.get_num_channels() + self.num_segments = self.analyzer1.get_num_segments() + self.sampling_frequency = self.analyzer1.sampling_frequency + + # the combined unit_id namespace and the mappings back to the original ids. + # computed once: unit_ids is read inside loops all over the views. + self._make_unit_id_mappings() + + # sparsity1 + if self.analyzer1.sparsity is None: + self.external_sparsity1 = compute_sparsity(self.analyzer1, method="radius", radius_um=90.) + self.analyzer_sparsity1 = None + else: + self.external_sparsity1 = None + self.analyzer_sparsity1 = self.analyzer1.sparsity + # sparsity2 + if self.analyzer2.sparsity is None: + self.external_sparsity2 = compute_sparsity(self.analyzer2, method="radius", radius_um=90.) + self.analyzer_sparsity2 = None + else: + self.external_sparsity2 = None + self.analyzer_sparsity2 = self.analyzer2.sparsity + + if comparison is not None: + # check that the comparison object matches the analyzers in terms of unit_ids + if set(comparison.sorting1.unit_ids) != set(self.analyzer1.sorting.unit_ids): + raise ValueError("Comparison object does not match analyzer1 unit_ids") + if set(comparison.sorting2.unit_ids) != set(self.analyzer2.sorting.unit_ids): + raise ValueError("Comparison object does not match analyzer2 unit_ids") + self.comp = comparison + else: + if verbose: + print("Comparing spike sorting outputs") + t0 = time.perf_counter() + self.comp = compare_two_sorters( + self.analyzer1.sorting, + self.analyzer2.sorting, + sorting1_name=self.analyzer1_name, + sorting2_name=self.analyzer2_name, + match_score=match_score + ) + if verbose: + print("Comparing took", time.perf_counter() - t0) + # agreement threshold shared by all the comparison views + self._agreement_threshold = self.comp.match_score + self._matching_cache = {} + self._ordered_agreement_scores = None + + # this now private and should be access using function + self._visible_unit_ids = self._get_best_matched_pair() + + # spikes + t0 = time.perf_counter() + if verbose: + print('Gathering all spikes') + main_channels1 = self.analyzer1.get_main_channels(outputs="index", with_dict=True) + main_channels2 = self.analyzer2.get_main_channels(outputs="index", with_dict=True) + self._main_channels = {} + for unit_id in self.unit_ids: + main_channels = main_channels1 if self.get_analyzer_index(unit_id) == 1 else main_channels2 + self._main_channels[unit_id] = main_channels[self.get_original_unit_id(unit_id)] + self._ext_channel_inds = np.array([self._main_channels[unit_id] for unit_id in self.unit_ids]) + + spike_vector1 = self.analyzer1.sorting.to_spike_vector(concatenated=True) + spike_vector2 = self.analyzer2.sorting.to_spike_vector(concatenated=True) + + random_spikes_indices1 = np.asarray(self.analyzer1.get_extension("random_spikes").get_data()) + random_spikes_indices2 = np.asarray(self.analyzer2.get_extension("random_spikes").get_data()) + + # align=True is required for np.searchsorted (and therefore trace views) to be fast. + self.spikes = np.zeros(spike_vector1.size + spike_vector2.size, dtype=np.dtype(minimum_spike_dtype, align=True)) + self.spikes['sample_index'] = np.concatenate([spike_vector1['sample_index'], spike_vector2['sample_index']]) + self.spikes['unit_index'] = np.concatenate([spike_vector1['unit_index'], spike_vector2['unit_index'] + self._num_units1]) + self.spikes['segment_index'] = np.concatenate([spike_vector1['segment_index'], spike_vector2['segment_index']]) + + # sort spikes by segment then sample, so that the base class bookkeeping applies + num_seg = self.analyzer1.get_num_segments() + self.spike_order = np.lexsort((self.spikes['sample_index'], self.spikes['segment_index'])) + self.spikes = self.spikes[self.spike_order] + + # random spikes as indices into the sorted self.spikes. Sorted, so that within a unit + # they keep the time order of the rows of its waveforms + new_index_by_old = np.empty_like(self.spike_order) + new_index_by_old[self.spike_order] = np.arange(self.spike_order.size) + self.random_spikes_indices = np.sort(new_index_by_old[ + np.concatenate([random_spikes_indices1, random_spikes_indices2 + spike_vector1.size]) + ]) + self._random_spikes_set = set(int(i) for i in self.random_spikes_indices) + + self._build_spike_indices(num_seg) + + t1 = time.perf_counter() + if verbose: + print('Gathering all spikes took', t1 - t0) + + if verbose: + print('Loading extensions') + # Mandatory extensions: computation forced + if verbose: + print('\tLoading templates') + temp_ext1 = self.analyzer1.get_extension("templates") + temp_ext2 = self.analyzer2.get_extension("templates") + assert temp_ext1 is not None and temp_ext2 is not None, "Both analyzers should have 'templates' extension" + self.nbefore, self.nafter = temp_ext1.nbefore, temp_ext1.nafter + + self.templates_average = np.vstack([temp_ext1.get_templates(operator='average'), temp_ext2.get_templates(operator='average')]) + + if 'std' in temp_ext1.params['operators'] and 'std' in temp_ext2.params['operators']: + self.templates_std = np.vstack([temp_ext1.get_templates(operator='std'), temp_ext2.get_templates(operator='std')]) + else: + self.templates_std = None + + if verbose: + print('\tLoading unit_locations') + ext1 = self.analyzer1.get_extension('unit_locations') + ext2 = self.analyzer2.get_extension('unit_locations') + assert ext1 is not None and ext2 is not None, "Both analyzers should have 'unit_locations' extension" + self.unit_positions = np.vstack([ext1.get_data()[:, :2], ext2.get_data()[:, :2]]) + + # Optional extensions : can be None or skipped + if verbose: + print('\tLoading noise_levels') + ext1 = self.analyzer1.get_extension('noise_levels') + if ext1 is None and self.has_extension('recording'): + print('Force compute "noise_levels" is needed') + ext1 = self.analyzer1.compute_one_extension('noise_levels') + self.noise_levels = ext1.get_data() if ext1 is not None else None + + if "quality_metrics" in self.skip_extensions: + if self.verbose: + print('\tSkipping quality_metrics') + self.metrics = None + else: + if verbose: + print('\tLoading quality_metrics') + qm_ext1 = self.analyzer1.get_extension('quality_metrics') + qm_ext2 = self.analyzer2.get_extension('quality_metrics') + if qm_ext1 is not None and qm_ext2 is not None: + self.metrics = pd.concat([qm_ext1.get_data(), qm_ext2.get_data()]) + self.metrics.index = self.unit_ids + else: + self.metrics = None + + if "spike_amplitudes" in self.skip_extensions: + if self.verbose: + print('\tSkipping spike_amplitudes') + self.spike_amplitudes = None + else: + if verbose: + print('\tLoading spike_amplitudes') + sa_ext1 = self.analyzer1.get_extension('spike_amplitudes') + sa_ext2 = self.analyzer2.get_extension('spike_amplitudes') + if sa_ext1 is not None and sa_ext2 is not None: + self.spike_amplitudes = np.concatenate([sa_ext1.get_data(), sa_ext2.get_data()])[self.spike_order] + else: + self.spike_amplitudes = None + + if "amplitude_scalings" in self.skip_extensions: + self.amplitude_scalings = None + else: + as_ext1 = self.analyzer1.get_extension('amplitude_scalings') + as_ext2 = self.analyzer2.get_extension('amplitude_scalings') + if as_ext1 is not None and as_ext2 is not None: + self.amplitude_scalings = np.concatenate([as_ext1.get_data(), as_ext2.get_data()])[self.spike_order] + else: + self.amplitude_scalings = None + + if "spike_locations" in self.skip_extensions: + if self.verbose: + print('\tSkipping spike_locations') + self.spike_depths = None + else: + if verbose: + print('\tLoading spike_locations') + sl_ext1 = self.analyzer1.get_extension('spike_locations') + sl_ext2 = self.analyzer2.get_extension('spike_locations') + if sl_ext1 is not None and sl_ext2 is not None: + self.spike_depths = np.concatenate([sl_ext1.get_data()["y"], sl_ext2.get_data()["y"]])[self.spike_order] + else: + self.spike_depths = None + + # Correlograms: only the ACGs of both analyzers, the cross-sorter CCGs are not relevant + self.correlograms, self.correlograms_bins = None, None + if "correlograms" in self.skip_extensions: + if self.verbose: + print('\tSkipping correlograms') + else: + if verbose: + print('\tLoading correlograms') + ccg_ext1 = self.analyzer1.get_extension('correlograms') + ccg_ext2 = self.analyzer2.get_extension('correlograms') + if ccg_ext1 is not None and ccg_ext2 is not None: + ccg1, bins1 = ccg_ext1.get_data() + ccg2, bins2 = ccg_ext2.get_data() + if np.array_equal(bins1, bins2): + self._set_correlograms_from_acgs(ccg1, ccg2, bins1) + + # ISIs and template_similarity cannot be concatenated: always skipped + self.isi_histograms, self.isi_bins = None, None + self._similarity_by_method = {} + + if "waveforms" in self.skip_extensions: + if self.verbose: + print('\tSkipping waveforms') + self.waveforms_ext1, self.waveforms_ext2 = None, None + else: + if verbose: + print('\tLoading waveforms') + wf_ext1 = self.analyzer1.get_extension('waveforms') + wf_ext2 = self.analyzer2.get_extension('waveforms') + if wf_ext1 is not None and wf_ext2 is not None: + self.waveforms_ext1 = wf_ext1 + self.waveforms_ext2 = wf_ext2 + else: + self.waveforms_ext1, self.waveforms_ext2 = None, None + self.waveforms_ext = self.waveforms_ext1 + + # valid_unit_periods, keyed by the combined unit ids. Only used when both + # analyzers have it, like the other optional per-unit extensions above. + if self.analyzer1.has_extension("valid_unit_periods") and self.analyzer2.has_extension("valid_unit_periods"): + valid_periods1 = self.analyzer1.get_extension("valid_unit_periods").get_data(outputs="by_unit") + valid_periods2 = self.analyzer2.get_extension("valid_unit_periods").get_data(outputs="by_unit") + self.valid_periods = [] + for seg_index in range(self.num_segments): + valid_periods_dict = {} + for unit_id in self.unit_ids: + valid_periods = valid_periods1 if self.get_analyzer_index(unit_id) == 1 else valid_periods2 + valid_periods_dict[unit_id] = valid_periods[seg_index][self.get_original_unit_id(unit_id)] + self.valid_periods.append(valid_periods_dict) + else: + self.valid_periods = None + + # principal_components is always skipped: the two analyzers have unrelated PC spaces + self._pc_projections = None + self._pc_indices = None + self.pc_ext = None + + self._potential_merges = None + + t1 = time.perf_counter() + if verbose: + print('Loading extensions took', t1 - t0) + + t0 = time.perf_counter() + + num_spikes1 = self.analyzer1.sorting.count_num_spikes_per_unit(outputs="dict") + num_spikes2 = self.analyzer2.sorting.count_num_spikes_per_unit(outputs="dict") + self.num_spikes = {} + for unit_id in self.unit_ids: + num_spikes = num_spikes1 if self.get_analyzer_index(unit_id) == 1 else num_spikes2 + self.num_spikes[unit_id] = num_spikes[self.get_original_unit_id(unit_id)] + + # spikeinterface handle colors in matplotlib style tuple values in range (0,1) + self.refresh_colors() + + # at init, we set the visible channels as the sparsity of the first unit + self.visible_channel_inds = np.flatnonzero(self.get_sparsity_mask()[0]) + + self._spike_visible_indices = np.array([], dtype='int64') + self._spike_selected_indices = np.array([], dtype='int64') + self.update_visible_spikes() + + self._traces_cached = {} + + unit_tables = [] + for analyzer, sorter in zip([self.analyzer1, self.analyzer2], [self.analyzer1_name, self.analyzer2_name]): + unit_table = make_units_table_from_analyzer(analyzer) + unit_table.loc[:, "sorter"] = sorter + unit_tables.append(unit_table) + self.units_table = pd.concat(unit_tables, ignore_index=True) + self.units_table.index = self.unit_ids + if displayed_unit_properties is None: + displayed_unit_properties = list(_default_displayed_unit_properties) + if extra_unit_properties is not None: + displayed_unit_properties += list(extra_unit_properties.keys()) + displayed_unit_properties = [v for v in displayed_unit_properties if v in self.units_table.columns] + self.displayed_unit_properties = displayed_unit_properties + + # set default time info + self.update_time_info() + + ## combined unit_id namespace ## + + def _make_unit_id_mappings(self): + """ + Build the combined unit_ids and the mappings between combined and original ids. + + Integer unit ids are offset, other ids are suffixed with the analyzer name. + """ + unit_ids1 = np.asarray(self.analyzer1.unit_ids) + unit_ids2 = np.asarray(self.analyzer2.unit_ids) + self._num_units1 = unit_ids1.size + + # if unit_ids1.dtype.kind == "i" and unit_ids2.dtype.kind == "i": + # self._unit_ids = np.concatenate((unit_ids1, unit_ids2 + max(unit_ids1) + 1)) + # else: + self._unit_ids = np.array( + [f"{unit_id}_{self.analyzer1_name}" for unit_id in unit_ids1] + + [f"{unit_id}_{self.analyzer2_name}" for unit_id in unit_ids2] + ) + + original_unit_ids = list(unit_ids1) + list(unit_ids2) + analyzer_indices = [1] * unit_ids1.size + [2] * unit_ids2.size + self._original_unit_id_by_id = dict(zip(self._unit_ids, original_unit_ids)) + self._analyzer_index_by_id = dict(zip(self._unit_ids, analyzer_indices)) + # (analyzer_index, original_unit_id) -> combined unit_id + self._combined_unit_id_by_original = { + (analyzer_index, original_unit_id): unit_id + for analyzer_index, original_unit_id, unit_id in zip(analyzer_indices, original_unit_ids, self._unit_ids) + } + + @property + def unit_ids(self): + return self._unit_ids + + @property + def unit_shapes(self): + return ["circle"] * len(self.unit_ids1) + ["square"] * len(self.unit_ids2) + + def get_unit_shape(self, unit_id): + return "circle" if self._analyzer_index_by_id[unit_id] == 1 else "square" + + @property + def unit_ids1(self): + return self._unit_ids[:self._num_units1] + + @property + def unit_ids2(self): + return self._unit_ids[self._num_units1:] + + def get_original_unit_id(self, unit_id): + """Get the unit id in its own analyzer, given a combined unit_id""" + return self._original_unit_id_by_id[unit_id] + + def get_analyzer_index(self, unit_id): + """Get 1 or 2, telling which analyzer a combined unit_id belongs to""" + return self._analyzer_index_by_id[unit_id] + + def get_combined_unit_id(self, analyzer_index, original_unit_id): + """Inverse of get_original_unit_id: (1 or 2, original unit id) -> combined unit_id""" + return self._combined_unit_id_by_original[(analyzer_index, original_unit_id)] + + def get_analyzer_name(self, analyzer_index): + return self.analyzer1_name if analyzer_index == 1 else self.analyzer2_name + + def get_shared_unit_properties(self): + """The columns of the units table that have values for units of both analyzers""" + table = self.units_table + return [ + col for col in table.columns + if table.loc[self.unit_ids1, col].notna().any() and table.loc[self.unit_ids2, col].notna().any() + ] + + ## comparison zone ## + + @property + def agreement_threshold(self): + return self._agreement_threshold + + def set_agreement_threshold(self, threshold): + """Set the agreement threshold shared by all the comparison views""" + self._agreement_threshold = float(threshold) + + def get_agreement_scores(self, ordered=False): + """ + Agreement scores as a DataFrame indexed by the *original* unit ids of + analyzer1 (rows) and analyzer2 (columns). + + When `ordered` is True the diagonalized ordering of the comparison is returned. + """ + if not ordered: + return self.comp.agreement_scores + if self._ordered_agreement_scores is None: + self._ordered_agreement_scores = self.comp.get_ordered_agreement_scores() + return self._ordered_agreement_scores + + def get_matching(self, threshold=None): + """ + One-to-one (hungarian) matching at the given agreement threshold. + + Returns (match_12, match_21), two pandas Series indexed by the original unit ids. + Unmatched units hold a sentinel that depends on the unit id dtype, use + `is_unmatched()` to test it. + """ + from spikeinterface.comparison.comparisontools import make_hungarian_match + + if threshold is None: + threshold = self._agreement_threshold + threshold = float(threshold) + if threshold not in self._matching_cache: + self._matching_cache[threshold] = make_hungarian_match(self.comp.agreement_scores, threshold) + return self._matching_cache[threshold] + + def _get_best_matched_pair(self): + """The best matched pair (the first row of the comparison unit list), else the first unit""" + matching_12, _ = self.get_matching() + scores = self.get_agreement_scores() + best_pair, best_score = [self.unit_ids[0]], -1. + for original_unit_id1, original_unit_id2 in matching_12.items(): + if self.is_unmatched(original_unit_id2): + continue + score = scores.at[original_unit_id1, original_unit_id2] + if score > best_score: + best_score = score + best_pair = [ + self.get_combined_unit_id(1, original_unit_id1), + self.get_combined_unit_id(2, original_unit_id2), + ] + return best_pair + + def get_best_matching(self, threshold=None): + """ + Best (not necessarily one-to-one) matching at the given agreement threshold. + + Returns (best_match_12, best_match_21), same convention as `get_matching`. + """ + from spikeinterface.comparison.comparisontools import make_best_match + + if threshold is None: + threshold = self._agreement_threshold + return make_best_match(self.comp.agreement_scores, float(threshold)) + + @staticmethod + def is_unmatched(original_unit_id): + """ + Test the unmatched sentinel of a match Series. + + spikeinterface uses -1 for integer unit ids and "" for string/object unit ids. + """ + if isinstance(original_unit_id, str): + return original_unit_id == "" + return original_unit_id == -1 + + def get_venn_unit_ids(self, threshold=None): + """ + Split the units in the 3 regions of the comparison Venn diagram. + + Returns a dict with combined unit_ids: + * "matched" : list of (unit_id1, unit_id2) pairs agreeing above the threshold + * "only1" : units of analyzer1 with no match + * "only2" : units of analyzer2 with no match + """ + match_12, _ = self.get_matching(threshold=threshold) + + matched = [] + only1 = [] + matched_original2 = set() + for original_unit_id1 in match_12.index: + original_unit_id2 = match_12[original_unit_id1] + unit_id1 = self.get_combined_unit_id(1, original_unit_id1) + if self.is_unmatched(original_unit_id2): + only1.append(unit_id1) + else: + matched.append((unit_id1, self.get_combined_unit_id(2, original_unit_id2))) + matched_original2.add(original_unit_id2) + + only2 = [ + self.get_combined_unit_id(2, original_unit_id2) + for original_unit_id2 in self.analyzer2.unit_ids + if original_unit_id2 not in matched_original2 + ] + + return dict(matched=matched, only1=only1, only2=only2) + + def get_spike_venn(self, unit_id1, unit_id2): + """ + Split the spikes of a pair of units (one per analyzer) in the 3 regions of a Venn diagram. + + Two spikes match when they are within the `delta_frames` of the comparison. + Returns a dict of absolute indices into `self.spikes`: + * "matched1" / "matched2" : the matched spikes, seen from unit_id1 / unit_id2 + * "only1" / "only2" : the spikes found only by unit_id1 / unit_id2 + """ + from spikeinterface.comparison.comparisontools import make_matching_events + + matched1, matched2, only1, only2 = [], [], [], [] + for segment_index in range(self.num_segments): + inds1 = self.get_spike_indices(unit_id1, segment_index=segment_index) + inds2 = self.get_spike_indices(unit_id2, segment_index=segment_index) + events = make_matching_events( + self.spikes['sample_index'][inds1], self.spikes['sample_index'][inds2], self.comp.delta_frames + ) + # a spike can be in several matching events, keep each spike once (like the agreement count) + _, first = np.unique(events['index1'], return_index=True) + events = events[first] + _, first = np.unique(events['index2'], return_index=True) + events = events[first] + mask1 = np.zeros(inds1.size, dtype=bool) + mask1[events['index1']] = True + mask2 = np.zeros(inds2.size, dtype=bool) + mask2[events['index2']] = True + matched1.append(inds1[events['index1']]) + matched2.append(inds2[events['index2']]) + only1.append(inds1[~mask1]) + only2.append(inds2[~mask2]) + + return { + key: np.sort(np.concatenate(value)).astype('int64') + for key, value in dict(matched1=matched1, matched2=matched2, only1=only1, only2=only2).items() + } + + def get_waveforms_for_spikes(self, unit_id, spike_inds): + """ + Waveforms of some spikes of one unit, given as absolute indices into `self.spikes`. + + Waveforms only exist for the random_spikes subset, so the other spikes are dropped. + Returns (wfs, chan_inds, kept_spike_inds), or None without the waveforms extension. + """ + if self.waveforms_ext1 is None: + return None + unit_inds = self.get_spike_indices(unit_id) + # the random spikes of the unit, in the same order as the rows of its waveforms + random_inds = unit_inds[np.isin(unit_inds, self.random_spikes_indices)] + kept = np.asarray(spike_inds)[np.isin(spike_inds, random_inds)] + wfs, chan_inds = self.get_waveforms(unit_id) + return wfs[np.searchsorted(random_inds, kept)], chan_inds, kept + + ## overrides of the single analyzer behavior ## + + def has_extension(self, extension_name): + if extension_name == 'recording': + return self.use_recordings + elif extension_name == 'comparison': + return True + elif extension_name == 'correlograms': + # the ACGs can always be computed from both analyzers + return "correlograms" not in self.skip_extensions + else: + return Controller.has_extension(self, extension_name) + + def get_information_txt(self): + nseg = self.analyzer1.get_num_segments() + nchan = self.analyzer1.get_num_channels() + txt = f"{nchan} channels - {nseg} segments\n" + txt += f"{self.analyzer1_name}: {len(self.unit_ids1)} units - " + txt += f"{self.analyzer2_name}: {len(self.unit_ids2)} units\n" + venn = self.get_venn_unit_ids() + txt += f"{len(venn['matched'])} matched pairs at agreement >= {self.agreement_threshold:.2f}" + return txt + + def get_waveforms(self, unit_id, force_dense=False): + if self.get_analyzer_index(unit_id) == 1: + analyzer, waveforms_ext = self.analyzer1, self.waveforms_ext1 + else: + analyzer, waveforms_ext = self.analyzer2, self.waveforms_ext2 + original_unit_id = self.get_original_unit_id(unit_id) + wfs = waveforms_ext.get_waveforms_one_unit(original_unit_id, force_dense=force_dense) + if analyzer.sparsity is None or force_dense: + # dense waveforms + chan_inds = np.arange(analyzer.get_num_channels(), dtype='int64') + else: + # sparse waveforms + chan_inds = analyzer.sparsity.unit_id_to_channel_indices[original_unit_id] + return wfs, chan_inds + + def get_sparsity_mask(self): + masks = [] + for external_sparsity, analyzer_sparsity in ( + (self.external_sparsity1, self.analyzer_sparsity1), + (self.external_sparsity2, self.analyzer_sparsity2), + ): + masks.append(external_sparsity.mask if external_sparsity is not None else analyzer_sparsity.mask) + return np.vstack(masks) + + def get_all_pcs(self): + # the two analyzers have unrelated PC spaces, they cannot be concatenated + return None, None + + def get_template_upsampling_factor(self): + # template_metrics of the two analyzers are not merged: no upsampling in comparison mode + return 1 + + def get_upsampled_templates(self, unit_id): + # same 3-tuple contract as the base class, without the upsampled part + unit_index = list(self.unit_ids).index(unit_id) + chan_ind = self.get_main_channel(unit_id) + template = self.templates_average[unit_index, :, chan_ind] + return template, None, None + + def compute_unit_positions(self, method, method_kwargs): + unit_positions = [] + for analyzer in (self.analyzer1, self.analyzer2): + ext = analyzer.compute_one_extension( + 'unit_locations', save=self.save_on_compute, method=method, **method_kwargs + ) + unit_positions.append(ext.get_data()[:, :2]) + self.unit_positions = np.vstack(unit_positions) + + def compute_similarity(self, method='l1'): + raise NotImplementedError("template_similarity cannot be computed in comparison mode") + + def _set_correlograms_from_acgs(self, ccg1, ccg2, bins): + """Combined correlograms with only the ACGs filled in, the off-diagonal is left to zeros""" + num_units1 = self._num_units1 + num_units = self.unit_ids.size + ccg1, ccg2 = np.asarray(ccg1), np.asarray(ccg2) + self.correlograms = np.zeros((num_units, num_units, ccg1.shape[2]), dtype=ccg1.dtype) + inds1 = np.arange(num_units1) + inds2 = np.arange(num_units - num_units1) + self.correlograms[inds1, inds1] = ccg1[inds1, inds1] + self.correlograms[inds2 + num_units1, inds2 + num_units1] = ccg2[inds2, inds2] + self.correlograms_bins = np.asarray(bins) + + def compute_correlograms(self, window_ms, bin_ms): + ccgs = [] + for analyzer in (self.analyzer1, self.analyzer2): + ext = analyzer.compute("correlograms", save=self.save_on_compute, window_ms=window_ms, bin_ms=bin_ms) + ccgs.append(ext.get_data()) + (ccg1, bins), (ccg2, _) = ccgs + self._set_correlograms_from_acgs(ccg1, ccg2, bins) + return self.correlograms, self.correlograms_bins + + def compute_isi_histograms(self, window_ms, bin_ms): + raise NotImplementedError("isi_histograms cannot be computed in comparison mode") + + def compute_auto_merge(self, **params): + raise NotImplementedError("auto merge is not available in comparison mode") diff --git a/spikeinterface_gui/correlogramview.py b/spikeinterface_gui/correlogramview.py index 386f03b0..7f178b0b 100644 --- a/spikeinterface_gui/correlogramview.py +++ b/spikeinterface_gui/correlogramview.py @@ -12,21 +12,52 @@ class CorrelogramView(ViewBase): {'name': 'window_ms', 'type': 'float', 'value' : 50. }, {'name': 'bin_ms', 'type': 'float', 'value' : 1.0 }, {'name': 'display_axis', 'type': 'bool', 'value' : True }, + {'name': 'show_cross_correlograms', 'type': 'bool', 'value' : True }, ] _need_compute = True def __init__(self, controller=None, parent=None, backend="qt"): ViewBase.__init__(self, controller=controller, parent=parent, backend=backend) - self.ccg, self.bins = self.controller.get_correlograms() self.figure_cache = {} self.max_cache_size = 20 - + # the settings are changed before self.ccg is set, so that _on_settings_changed + # does not discard the loaded correlograms + self.ccg, self.bins = None, None + ccg, bins = self.controller.get_correlograms() + if bins is not None: + # match the loaded correlograms, otherwise any setting change would discard them + self.settings['window_ms'] = float(bins[-1] - bins[0]) + self.settings['bin_ms'] = float(bins[1] - bins[0]) + if self.controller.has_extension('comparison'): + # in comparison mode only the ACGs are available, the off-diagonal is zeros + self.settings['show_cross_correlograms'] = False + self.ccg, self.bins = ccg, bins + def _on_settings_changed(self): - self.ccg = None + # only a new window/bin needs a re-compute, the display settings just need new figures + if self.bins is not None: + window_ms = self.bins[-1] - self.bins[0] + bin_ms = self.bins[1] - self.bins[0] + if not (np.isclose(window_ms, self.settings['window_ms']) and np.isclose(bin_ms, self.settings['bin_ms'])): + self.ccg = None + self.figure_cache = {} self.refresh() + def _get_columns(self, r, n): + """The columns of row r: the upper triangle, or only the diagonal (the ACG)""" + if self.settings['show_cross_correlograms']: + return range(r, n) + return range(r, r + 1) + + def get_acg_ymax(self, visible_unit_ids): + """The y max shared by the auto-correlograms of the visible units, so that they compare""" + unit_ids = list(self.controller.unit_ids) + inds = [unit_ids.index(unit_id) for unit_id in visible_unit_ids] + ymax = max((self.ccg[i, i, :].max() for i in inds), default=0) + return float(ymax) * 1.05 if ymax > 0 else 1. + def _compute(self): self.ccg, self.bins = self.controller.compute_correlograms( self.settings['window_ms'], self.settings['bin_ms'] @@ -75,9 +106,10 @@ def _qt_refresh(self): } ccg = self.ccg bins = self.bins + acg_plots = [] for r in range(n): - for c in range(r, n): + for c in self._get_columns(r, n): unit_id1 = visible_unit_ids[r] unit_id2 = visible_unit_ids[c] if (unit_id1, unit_id2) in self.figure_cache: @@ -114,7 +146,21 @@ def _qt_refresh(self): if len(self.figure_cache) >= self.max_cache_size: self.figure_cache.pop(next(iter(self.figure_cache))) self.figure_cache[(unit_id1, unit_id2)] = plot - self.grid.addItem(plot, row=r, col=c) + if r == c: + acg_plots.append(plot) + if self.settings['show_cross_correlograms']: + self.grid.addItem(plot, row=r, col=c) + else: + # only ACGs: side by side on one row + self.grid.addItem(plot, row=0, col=r) + + if not self.settings['show_cross_correlograms']: + # the ACGs share the y axis (also when zooming), the plots can come from the cache + # with a link to a plot that is not shown anymore + ymax = self.get_acg_ymax(visible_unit_ids) if len(acg_plots) > 0 else None + for i, plot in enumerate(acg_plots): + plot.setYLink(None if i == 0 else acg_plots[0]) + plot.setYRange(0, ymax, padding=0) ## panel ## def _panel_make_layout(self): @@ -129,6 +175,8 @@ def _panel_make_layout(self): outline_line_color="white", ) self.empty_plot_pane = pn.pane.Bokeh(empty_fig, sizing_mode="stretch_both") + # ids of the figures in the grid currently shown + self._panel_shown_figure_ids = set() self.layout = pn.Column( self.empty_plot_pane, @@ -139,6 +187,7 @@ def _panel_refresh(self): import panel as pn import bokeh.plotting as bpl from bokeh.layouts import gridplot + from bokeh.models import Range1d from .utils_panel import _bg_color if self.ccg is None: @@ -154,15 +203,19 @@ def _panel_refresh(self): ccg = self.ccg bins = self.bins figures = [] + acg_figs = [] first_fig = None for r in range(n): row_plots = [] - for c in range(r, n): + for c in self._get_columns(r, n): unit1 = visible_unit_ids[r] unit2 = visible_unit_ids[c] - if (unit1, unit2) in self.figure_cache: - fig = self.figure_cache[(unit1, unit2)] + # a cached figure still in the shown grid cannot be moved to the new grid + # (bokeh renders it blank), so it is re-created + cached_fig = self.figure_cache.get((unit1, unit2)) + if cached_fig is not None and id(cached_fig) not in self._panel_shown_figure_ids: + fig = cached_fig # for the color_by_visibility if self.controller.main_settings["color_mode"] == 'color_by_visibility': # Update color in cached figure @@ -221,13 +274,28 @@ def _panel_refresh(self): if len(self.figure_cache) >= self.max_cache_size: self.figure_cache.pop(next(iter(self.figure_cache))) self.figure_cache[(unit1, unit2)] = fig + if r == c: + acg_figs.append(fig) row_plots.append(fig) - # Fill row with None for proper spacing - full_row = [None] * r + row_plots + [None] * (n - len(row_plots)) - figures.append(full_row) + if self.settings['show_cross_correlograms']: + # Fill row with None for proper spacing + full_row = [None] * r + row_plots + [None] * (n - r - len(row_plots)) + figures.append(full_row) + else: + # only ACGs: side by side on one row + if len(figures) == 0: + figures.append([]) + figures[0].extend(row_plots) + + if not self.settings['show_cross_correlograms']: + # the ACGs share the y axis (also when zooming), the figures can come from the cache + acg_y_range = Range1d(0, self.get_acg_ymax(visible_unit_ids)) + for fig in acg_figs: + fig.y_range = acg_y_range grid = gridplot(figures, toolbar_location="right", sizing_mode="stretch_both") grid.toolbar.logo = None + self._panel_shown_figure_ids = {id(fig) for row in figures for fig in row if fig is not None} self.layout[0] = pn.Column( grid, styles={'background-color': f'{_bg_color}'} @@ -239,4 +307,13 @@ def _panel_refresh(self): ## Correlograms View This view shows the auto-correlograms and cross-correlograms of the selected units. + +### Settings +- **window_ms** / **bin_ms** : the correlogram window and bin size (needs a re-compute). +- **display_axis** : show the axes of each plot. + +The auto-correlograms share the y axis, so that the firing of the units can be compared. +- **show_cross_correlograms** : show the cross-correlograms (upper triangle), or only the + auto-correlograms side by side. In comparison mode only the auto-correlograms of both + sorters are available, so this is off by default. """ diff --git a/spikeinterface_gui/layout_presets.py b/spikeinterface_gui/layout_presets.py index 86192571..cf1a8e42 100644 --- a/spikeinterface_gui/layout_presets.py +++ b/spikeinterface_gui/layout_presets.py @@ -1,4 +1,5 @@ import json +from copy import deepcopy from spikeinterface_gui.viewlist import get_all_possible_views import numpy as np @@ -51,7 +52,8 @@ def get_layout_description(preset_name, layout=None): else: if preset_name is None: preset_name = 'default' - return _presets[preset_name] + # deepcopy so that a caller mutating the returned dict does not corrupt the preset + return deepcopy(_presets[preset_name]) default_layout = dict( zone1=['curation', 'spikelist'], @@ -104,3 +106,19 @@ def get_layout_description(preset_name, layout=None): _presets['merge_focus'] = merge_focus_layout + +# comparison mode: the unit list is replaced by the comparison table and the +# comparison specific views take the place of similarity/ndscatter. +# merge, curation and isi are not available when comparing two analyzers, and the +# correlogram view only shows the auto-correlograms. +comparison_layout = dict( + zone1=['comparespikes'], + zone2=['compareunitlist', 'unitlist'], + zone3=['trace', 'tracemap', 'spikeamplitude', 'amplitudescalings', 'spikedepth', 'spikerate', 'event'], + zone4=[], + zone5=['probe'], + zone6=['unitvenn', 'comparelabels', 'agreementmatrix'], + zone7=['waveform', 'waveformheatmap'], + zone8=['correlogram', 'comparemetrics', 'maintemplate', 'comparemainsettings'], +) +_presets['comparison'] = comparison_layout diff --git a/spikeinterface_gui/main.py b/spikeinterface_gui/main.py index efa11eab..209caac2 100644 --- a/spikeinterface_gui/main.py +++ b/spikeinterface_gui/main.py @@ -113,7 +113,6 @@ def run_mainwindow( disable_save_settings_button: bool, default: False If True, disables the "save default settings" button, so that user cannot do this. """ - if mode == "desktop": backend = "qt" elif mode == "web": @@ -264,6 +263,199 @@ def run_launcher(mode="desktop", analyzer_folders=None, root_folder=None, addres else: raise ValueError(f"spikeinterface-gui wrong mode {mode}") + +# curation is off in comparison mode, and these views need extensions that cannot be +# shared between two different sortings (the correlogram view only shows the ACGs) +_comparison_incompatible_views = ("merge", "curation", "similarity", "isi") + + +def run_mainwindow_comparison( + analyzer1, + analyzer2, + analyzer1_name="1", + analyzer2_name="2", + match_score=0.5, + mode="desktop", + with_traces=True, + displayed_unit_properties=None, + extra_unit_properties=None, + skip_extensions=None, + recording=None, + start_app=True, + layout_preset=None, + layout=None, + address="localhost", + port=0, + panel_start_server_kwargs=None, + panel_window_servable=True, + verbose=False, + user_settings=None, + disable_save_settings_button=False, +): + """ + Create the main window and start the QT app loop. + + Parameters + ---------- + analyzer1: SortingAnalyzer + The first sorting analyzer object + analyzer2: SortingAnalyzer + The second sorting analyzer object + analyzer1_name: str, default: "1" + The name to display for the first analyzer + analyzer2_name: str, default: "2" + The name to display for the second analyzer + mode: 'desktop' | 'web' + The GUI mode to use. + 'desktop' will run a Qt app. + 'web' will run a Panel app. + with_traces: bool, default: True + If True, traces are displayed + displayed_unit_properties: list | None, default: None + The displayed unit properties in the unit table + extra_unit_properties: list | None, default: None + The extra unit properties in the unit table + skip_extensions: list | None, default: None + The list of extensions to skip when loading the sorting analyzer + recording: RecordingExtractor | None, default: None + The recording object to display traces. This can be used when the + SortingAnalyzer is recordingless. + start_app: bool, default: True + If True, the app loop is started + layout_preset : str | None + The name of the layout preset. None uses the 'comparison' preset. + layout : dict | None + The layout dictionary to use instead of the preset. + address: str, default : "localhost" + For "web" mode only. By default it is "localhost". + Use "auto-ip" to use the real IP address of the machine. + port: int, default: 0 + For "web" mode only. If 0 then the port is automatic. + panel_start_server_kwargs: dict, default: None + For "web" mode only. Additional arguments to pass to the Panel server + - `{'show': True}` to automatically open the browser (default is True). + - `{'dev': True}` to enable development mode (default is False). + - `{'autoreload': True}` to enable autoreload of the server when files change + (default is False). + panel_window_servable: bool, default: True + For "web" mode only. If True, the Panel app is made servable. + This is useful when embedding the GUI in another Panel app. In that case, + the `panel_window_servable` should be set to False. + verbose: bool, default: False + If True, print some information in the console + user_settings: dict, default: None + A dictionary of user settings for each view, which overwrite the default settings. + disable_save_settings_button: bool, default: False + If True, disables the "save default settings" button, so that user cannot do this. + """ + from .controllercomparison import ControllerComparison + + if mode == "desktop": + backend = "qt" + elif mode == "web": + backend = "panel" + else: + raise ValueError(f"spikeinterface-gui wrong mode {mode}") + + # Order of preference for settings is set here: + # 1) User specified settings + # 2) Settings in the config folder + # 3) Default settings of each view + user_main_settings = None + if user_settings is not None: + user_main_settings = user_settings.get('mainsettings') + + if user_settings is None: + sigui_version = spikeinterface_gui.__version__ + config_version_folder = get_config_folder() / sigui_version + settings_file = config_version_folder / "settings.json" + if settings_file.is_file(): + try: + with open(settings_file) as f: + user_settings = json.load(f) + except json.JSONDecodeError as e: + print(f"Config file at {settings_file} is not decodable. Error: {e}") + print("Using default settings.") + + if recording is not None: + analyzer1.set_temporary_recording(recording) + analyzer2.set_temporary_recording(recording) + + if verbose: + import time + t0 = time.perf_counter() + + if layout_preset is None and layout is None: + # the 'comparison' preset already swaps in the comparison views and drops the + # ones that make no sense when comparing two analyzers + layout_preset = "comparison" + + layout_dict = get_layout_description(layout_preset, layout) + if skip_extensions is None: + skip_extensions = find_skippable_extensions(layout_dict) + + # a user given preset/layout can still hold views that cannot work in comparison mode, + # so filter them out whatever the layout. get_layout_description returns a copy, so + # this does not touch the shared presets. + # a layout made for a single analyzer gets the comparison unit list in place of the unit list + has_compareunitlist = any('compareunitlist' in views_in_zone for views_in_zone in layout_dict.values()) + for zone, views_in_zone in layout_dict.items(): + views_in_zone = [ + 'compareunitlist' if view_name == 'unitlist' and not has_compareunitlist else view_name + for view_name in views_in_zone + if view_name not in _comparison_incompatible_views + ] + layout_dict[zone] = views_in_zone + + controller = ControllerComparison( + analyzer1, analyzer2, analyzer1_name=analyzer1_name, analyzer2_name=analyzer2_name, match_score=match_score, + backend=backend, verbose=verbose, + with_traces=with_traces, + displayed_unit_properties=displayed_unit_properties, + extra_unit_properties=extra_unit_properties, + skip_extensions=skip_extensions, + disable_save_settings_button=disable_save_settings_button, + user_main_settings=user_main_settings, + ) + if verbose: + t1 = time.perf_counter() + print('controller init time', t1 - t0) + + if backend == "qt": + from spikeinterface_gui.myqt import QT, mkQApp + from spikeinterface_gui.backend_qt import QtMainWindow + + # Suppress a known pyqtgraph warning + warnings.filterwarnings("ignore", category=RuntimeWarning, module="pyqtgraph") + warnings.filterwarnings('ignore', category=UserWarning, message=".*QObject::connect.*") + + app = mkQApp() + + win = QtMainWindow(controller, layout_dict=layout_dict, user_settings=user_settings) + win.setWindowTitle('SpikeInterface GUI') + # Set window icon + icon_file = Path(__file__).absolute().parent / 'img' / 'si.png' + if icon_file.exists(): + app.setWindowIcon(QT.QIcon(str(icon_file))) + win.show() + if start_app: + app.exec() + + elif backend == "panel": + from .backend_panel import PanelMainWindow, start_server + win = PanelMainWindow(controller, layout_dict=layout_dict, user_settings=user_settings) + + if start_app or panel_window_servable: + win.main_layout.servable(title='SpikeInterface GUI') + + if start_app: + panel_start_server_kwargs = panel_start_server_kwargs or {} + _ = start_server(win, address=address, port=port, **panel_start_server_kwargs) + + return win + + + def check_folder_is_analyzer(folder): """ Check if the given folder is a valid SortingAnalyzer folder. diff --git a/spikeinterface_gui/mainsettingsview.py b/spikeinterface_gui/mainsettingsview.py index 3d60aa8e..e8bda901 100644 --- a/spikeinterface_gui/mainsettingsview.py +++ b/spikeinterface_gui/mainsettingsview.py @@ -33,7 +33,7 @@ def __init__(self, controller=None, parent=None, backend="qt"): def on_max_visible_units_changed(self): - max_visible = self.main_settings_sync['max_visible_units'] + max_visible = self.main_settings['max_visible_units'] self.controller.main_settings['max_visible_units'] = max_visible visible_ids = self.controller.get_visible_unit_ids() diff --git a/spikeinterface_gui/metricsview.py b/spikeinterface_gui/metricsview.py index 3c3b12bf..874c999b 100644 --- a/spikeinterface_gui/metricsview.py +++ b/spikeinterface_gui/metricsview.py @@ -153,15 +153,15 @@ def _panel_make_layout(self): import panel as pn import bokeh.plotting as bpl import pandas as pd - from .utils_panel import _bg_color + from .utils_panel import _bg_color, make_toggled_checkboxes # Create metrics selection widget - self.metrics_select = pn.widgets.MultiChoice( - name="Visible Metrics", - value=list([k for k, v in self.visible_metrics_dict.items() if v]), + self.metrics_toggle, self.metrics_select, metrics_box = make_toggled_checkboxes( + "metrics", options=list(self.visible_metrics_dict.keys()), + value=list([k for k, v in self.visible_metrics_dict.items() if v]), + on_change=self._panel_on_metrics_changed, ) - self.metrics_select.param.watch(self._panel_on_metrics_changed, 'value') empty_fig = bpl.figure( sizing_mode="stretch_both", @@ -172,7 +172,7 @@ def _panel_make_layout(self): self.empty_plot_pane = pn.pane.Bokeh(empty_fig, sizing_mode="stretch_both") self.layout = pn.Column( - pn.Row(self.metrics_select, sizing_mode="stretch_width", height=100), + pn.Column(self.metrics_toggle, metrics_box, sizing_mode="stretch_width"), self.empty_plot_pane, sizing_mode="stretch_both" ) diff --git a/spikeinterface_gui/probeview.py b/spikeinterface_gui/probeview.py index 315e27e4..4723ffab 100644 --- a/spikeinterface_gui/probeview.py +++ b/spikeinterface_gui/probeview.py @@ -10,6 +10,8 @@ class ProbeView(ViewBase): id = "probe" _supported_backend = ['qt', 'panel'] + alpha_selected = 0.8 + alpha_unselected = 0.5 _settings = [ {'name': 'show_channel_id', 'type': 'bool', 'value': False}, {'name': 'radius_channel', 'type': 'float', 'value': 50.}, @@ -136,8 +138,8 @@ def _qt_make_layout(self): # units unit_positions = self.controller.unit_positions - brush = [self.get_unit_color(u) for u in self.controller.unit_ids] - self.scatter = pg.ScatterPlotItem(pos=unit_positions, pxMode=False, size=10, brush=brush) + brush = self._qt_unit_brushes() + self.scatter = pg.ScatterPlotItem(pos=unit_positions, pxMode=False, size=10, brush=brush, symbol=self._qt_unit_symbols()) self.plot.addItem(self.scatter) # range @@ -155,20 +157,31 @@ def _qt_reinitialize(self): self.plot.removeItem(self.scatter) unit_positions = self.controller.unit_positions - brush = [self.get_unit_color(u) for u in self.controller.unit_ids] - self.scatter = pg.ScatterPlotItem(pos=unit_positions, pxMode=False, size=10, brush=brush) + brush = self._qt_unit_brushes() + self.scatter = pg.ScatterPlotItem(pos=unit_positions, pxMode=False, size=10, brush=brush, symbol=self._qt_unit_symbols()) self.plot.addItem(self.scatter) self._qt_refresh() + def _qt_unit_brushes(self): + return [ + self.get_unit_color(u, alpha=self.alpha_selected if self.controller.get_unit_visibility(u) else self.alpha_unselected) + for u in self.controller.unit_ids + ] + + def _qt_unit_symbols(self): + symbol_lookup = {"circle": "o", "square": "s"} + return [symbol_lookup[shape] for shape in self.controller.unit_shapes] + def _qt_refresh(self): current_unit_positions = self.controller.unit_positions # if not np.array_equal(current_unit_positions, self._unit_positions): if True: self._unit_positions = current_unit_positions - brush = [self.get_unit_color(u) for u in self.controller.unit_ids] - self.scatter.setData(pos=current_unit_positions, pxMode=False, size=10, brush=brush) + brush = self._qt_unit_brushes() + # setData resets all point attributes, so symbols must be passed again + self.scatter.setData(pos=current_unit_positions, pxMode=False, size=10, brush=brush, symbol=self._qt_unit_symbols()) r, x, y = circle_from_roi(self.roi_channel) radius = self.settings['radius_channel'] @@ -279,7 +292,7 @@ def _qt_highlight_visible_units(self, auto_zoom=None): if self.controller.get_unit_visibility(u) else pg.mkPen('black', width=4) for u in self.controller.unit_ids] self.scatter.setPen(pen) - brush = [self.get_unit_color(u) for u in self.controller.unit_ids] + brush = self._qt_unit_brushes() self.scatter.setBrush(brush) # auto zoom @@ -335,7 +348,7 @@ def _compute(self): def _panel_make_layout(self): import panel as pn import bokeh.plotting as bpl - from bokeh.models import ColumnDataSource, HoverTool, Label, PanTool, Range1d + from bokeh.models import ColumnDataSource, CustomJS, HoverTool, Label, PanTool, Range1d from bokeh.events import Tap, PanStart, PanEnd from .utils_panel import CustomCircle, _bg_color @@ -390,10 +403,8 @@ def _panel_make_layout(self): if contour is not None: self.figure.line(contour[:, 0], contour[:, 1], line_color="#7FFF00") - self.alpha_selected = 1 - self.alpha_unselected = 0.3 - self.unit_marker_size_unselected = 15 - self.unit_marker_size_selected = 20 + self.unit_marker_size_unselected = 25 + self.unit_marker_size_selected = 40 # Initialize unit glyphs unit_positions = self.controller.unit_positions @@ -426,11 +437,12 @@ def _panel_make_layout(self): "alpha": alphas, "size": sizes, "unit_id": [str(u) for u in self.controller.unit_ids], + "marker": list(self.controller.unit_shapes), } ) self.unit_glyphs = self.figure.scatter( "x", "y", source=self.glyphs_data_source, size="size", fill_color="color", - line_color="line_color", alpha="alpha" + line_color="line_color", alpha="alpha", marker="marker" ) # Add hover tool to new glyph @@ -478,7 +490,22 @@ def _panel_make_layout(self): # Add pan tool for dragging pan_tool = PanTool() self.figure.add_tools(pan_tool) - self.figure.toolbar.active_drag = None + self.figure.toolbar.active_drag = pan_tool + # shift + drag moves/resizes the circles: the pan tool is switched off in the browser for + # that drag, since the python PanStart callback arrives too late to stop the panning + toolbar = self.figure.toolbar + self.figure.js_on_event(PanStart, CustomJS(args=dict(toolbar=toolbar), code=""" + if (cb_obj.modifiers.shift && toolbar.active_drag != null) { + toolbar._paused_drag = toolbar.active_drag; + toolbar.active_drag = null; + } + """)) + self.figure.js_on_event(PanEnd, CustomJS(args=dict(toolbar=toolbar), code=""" + if (toolbar._paused_drag != null) { + toolbar.active_drag = toolbar._paused_drag; + toolbar._paused_drag = null; + } + """)) # Connect pan events for circle dragging self.figure.on_event(PanStart, self._panel_on_pan_start) @@ -635,20 +662,15 @@ def _panel_update_unit_glyphs(self): pn.state.execute(lambda: self.glyphs_data_source.patch(patch_dict), schedule=True) def _panel_on_pan_start(self, event): - import panel as pn - + # a plain drag pans the plot, shift + drag acts on the circles + if not event.modifiers["shift"]: + return x, y = event.x, event.y - def _do_update(): - self.figure.toolbar.active_drag = None - - pn.state.execute(_do_update, schedule=True) - if self.unit_circle.is_close_to_diamond(x, y): self.should_resize_unit_circle = [x, y] self.unit_circle.select() elif self.unit_circle.is_position_inside(x, y, skip_other_positions=self._unit_positions): - self.figure.toolbar.active_drag = None # Update unit circle self.should_move_unit_circle = [x, y] self.unit_circle.select() @@ -656,7 +678,6 @@ def _do_update(): self.should_resize_channel_circle = [x, y] self.channel_circle.select() elif self.channel_circle.is_position_inside(x, y, skip_other_positions=self._unit_positions): - self.figure.toolbar.active_drag = None # Update channel circle self.should_move_channel_circle = [x, y] self.channel_circle.select() @@ -791,4 +812,5 @@ def circle_from_roi(roi): - **ctrl + left click** : add unit to selection - **mouse drag from within circle** : change channel visibility and unit visibility on other views - **mouse drag from "diamond"** : change channel / unit radii size +- **panel only** : a plain drag pans the plot, use **shift + drag** on the circles / diamonds """ diff --git a/spikeinterface_gui/similarityview.py b/spikeinterface_gui/similarityview.py index 00a90c68..a4a81aad 100644 --- a/spikeinterface_gui/similarityview.py +++ b/spikeinterface_gui/similarityview.py @@ -44,19 +44,23 @@ def select_unit_pair_on_click(self, x, y, reset=True): unit_ids = self.controller.unit_ids if self.settings['show_all']: - visible_ids = unit_ids + displayed_ids = unit_ids else: - visible_ids = self.get_visible_unit_ids() - - n = len(visible_ids) - + # same mask, and therefore the same order, as the sub-matrix drawn by + # get_similarity_data(). get_visible_unit_ids() is in selection order, + # which would map the click to the wrong units. + displayed_ids = unit_ids[self.controller.get_units_visibility_mask()] + + n = len(displayed_ids) + inside = (0 <= x <= n) and (0 <= y <= n) if not inside: return - - unit_id0 = unit_ids[int(np.floor(x))] - unit_id1 = unit_ids[int(np.floor(y))] + + # clip so that a click exactly on the far edge still selects the last unit + unit_id0 = displayed_ids[min(int(np.floor(x)), n - 1)] + unit_id1 = displayed_ids[min(int(np.floor(y)), n - 1)] if reset: self.controller.set_all_unit_visibility_off() diff --git a/spikeinterface_gui/tests/debug_views.py b/spikeinterface_gui/tests/debug_views.py index 10483e44..fa65b78a 100644 --- a/spikeinterface_gui/tests/debug_views.py +++ b/spikeinterface_gui/tests/debug_views.py @@ -1,7 +1,10 @@ import spikeinterface_gui as sigui -from spikeinterface_gui.tests.testingtools import clean_all, make_analyzer_folder, make_curation_dict +from spikeinterface_gui.tests.testingtools import ( + clean_all, make_analyzer_folder, make_comparison_analyzer_folders, make_curation_dict +) from spikeinterface_gui.controller import Controller +from spikeinterface_gui.controllercomparison import ControllerComparison from spikeinterface_gui.myqt import mkQApp from spikeinterface_gui.viewlist import get_all_possible_views from spikeinterface_gui.backend_qt import ViewWidget @@ -17,29 +20,51 @@ # test_folder = Path(__file__).parents[2] / 'my_dataset_big' # test_folder = Path(__file__).parents[2] / 'my_dataset_multiprobe' +# for the comparison views, see make_comparison_analyzer_folders() +comparison_test_folder = Path(__file__).parents[2] / 'my_dataset_comparison_small' -def debug_one_view(): - app = mkQApp() +def make_controller(): analyzer = si.load_sorting_analyzer(test_folder / "sorting_analyzer", load_extensions=False) - + curation_dict = make_curation_dict(analyzer) # curation_dict = None curation = curation_dict is not None - + controller = Controller(analyzer, verbose=True, curation=curation, curation_data=curation_dict, skip_extensions=['principal_components'], ) - + controller.set_visible_unit_ids(analyzer.unit_ids[:2]) - - # view_class = possible_class_views['unitlist'] - # view_class = possible_class_views['mainsettings'] - # view_class = possible_class_views['spikeamplitude'] + return controller + + +def make_comparison_controller(): + """A ControllerComparison, to debug the comparison views (compareunitlist, agreementmatrix, venn)""" + if not comparison_test_folder.is_dir(): + make_comparison_analyzer_folders(comparison_test_folder, case="small", unit_dtype="int") + + analyzer1 = si.load_sorting_analyzer(comparison_test_folder / "sorting_analyzer_1") + analyzer2 = si.load_sorting_analyzer(comparison_test_folder / "sorting_analyzer_2") + + controller = ControllerComparison(analyzer1, analyzer2, analyzer1_name="sorter1", analyzer2_name="sorter2", + verbose=True) + controller.set_visible_unit_ids(controller.unit_ids[:2]) + return controller + + +def debug_one_view(view_name, comparison=False): + + app = mkQApp() + + if comparison: + controller = make_comparison_controller() + else: + controller = make_controller() + possible_class_views = get_all_possible_views() - # view_class = possible_class_views['metrics'] - view_class = possible_class_views[''] + view_class = possible_class_views[view_name] widget = ViewWidget(view_class) view = view_class(controller=controller, parent=widget, backend='qt') widget.set_view(view) @@ -50,4 +75,12 @@ def debug_one_view(): if __name__ == '__main__': - debug_one_view() + # debug_one_view('unitlist') + # debug_one_view('mainsettings') + # debug_one_view('spikeamplitude') + # debug_one_view('metrics') + + # the comparison only views + debug_one_view('unitvenn', comparison=True) + # debug_one_view('agreementmatrix', comparison=True) + # debug_one_view('compareunitlist', comparison=True) diff --git a/spikeinterface_gui/tests/test_mainwindow_comparison_panel.py b/spikeinterface_gui/tests/test_mainwindow_comparison_panel.py new file mode 100644 index 00000000..47e837b2 --- /dev/null +++ b/spikeinterface_gui/tests/test_mainwindow_comparison_panel.py @@ -0,0 +1,67 @@ +from argparse import ArgumentParser +from pathlib import Path + +from spikeinterface import load_sorting_analyzer + +from spikeinterface_gui import run_mainwindow_comparison + +from spikeinterface_gui.tests.testingtools import clean_all, make_comparison_analyzer_folders + + +test_folder = Path(__file__).parents[2] / "my_dataset_comparison_small" + + +def setup_module(): + case = test_folder.stem.split('_')[-1] + make_comparison_analyzer_folders(test_folder, case=case, unit_dtype="int") + + +def teardown_module(): + clean_all(test_folder) + + +def test_mainwindow_comparison(start_app=False, verbose=True, port=0): + + analyzer1 = load_sorting_analyzer(test_folder / "sorting_analyzer_1") + analyzer2 = load_sorting_analyzer(test_folder / "sorting_analyzer_2") + + labels_analyzer1 = ["good"] * (len(analyzer1.unit_ids) - 10) + ["noise"] * 10 + analyzer1.set_sorting_property("label", labels_analyzer1, save=False) + labels_analyzer2 = ["noise"] * (len(analyzer2.unit_ids) - 10) + ["good"] * 10 + analyzer2.set_sorting_property("label", labels_analyzer2, save=False) + + print(analyzer1) + print(analyzer2) + + win = run_mainwindow_comparison( + analyzer1, + analyzer2, + analyzer1_name="sorter1", + analyzer2_name="sorter2", + mode="web", + start_app=start_app, + verbose=verbose, + port=port, + ) + + return win + + +parser = ArgumentParser() +parser.add_argument('--dataset', default="small", help='Path to the dataset folder') +parser.add_argument('--port', default=0, type=int, help='Port for the web server') +parser.add_argument('--no-start', action="store_true", help='Do not start the app') + +if __name__ == '__main__': + args = parser.parse_args() + if args.dataset is not None: + test_folder = Path(__file__).parents[2] / f"my_dataset_comparison_{args.dataset}" + + if not test_folder.is_dir(): + setup_module() + + win = test_mainwindow_comparison(start_app=not args.no_start, verbose=True, port=args.port) + +# TO RUN with panel serve: +# win = test_mainwindow_comparison(start_app=False, verbose=True) +# >>> panel serve test_mainwindow_comparison_panel.py --autoreload diff --git a/spikeinterface_gui/tests/test_mainwindow_comparison_qt.py b/spikeinterface_gui/tests/test_mainwindow_comparison_qt.py new file mode 100644 index 00000000..1edbb027 --- /dev/null +++ b/spikeinterface_gui/tests/test_mainwindow_comparison_qt.py @@ -0,0 +1,60 @@ +from argparse import ArgumentParser +from pathlib import Path + +from spikeinterface import load_sorting_analyzer + +from spikeinterface_gui import run_mainwindow_comparison + +from spikeinterface_gui.tests.testingtools import clean_all, make_comparison_analyzer_folders + + +test_folder = Path(__file__).parents[2] / "my_dataset_comparison_small" + + +def setup_module(): + case = test_folder.stem.split('_')[-1] + make_comparison_analyzer_folders(test_folder, case=case, unit_dtype="int") + + +def teardown_module(): + clean_all(test_folder) + + +def test_mainwindow_comparison(start_app=False, verbose=True): + + analyzer1 = load_sorting_analyzer(test_folder / "sorting_analyzer_1") + analyzer2 = load_sorting_analyzer(test_folder / "sorting_analyzer_2") + + print(analyzer1) + print(analyzer2) + + labels_analyzer1 = ["good"] * (len(analyzer1.unit_ids) - 10) + ["noise"] * 10 + analyzer1.set_sorting_property("label", labels_analyzer1, save=False) + labels_analyzer2 = ["noise"] * (len(analyzer2.unit_ids) - 10) + ["good"] * 10 + analyzer2.set_sorting_property("label", labels_analyzer2, save=False) + + win = run_mainwindow_comparison( + analyzer1, + analyzer2, + analyzer1_name="sorter1", + analyzer2_name="sorter2", + mode="desktop", + start_app=start_app, + verbose=verbose, + ) + + return win + + +parser = ArgumentParser() +parser.add_argument('--dataset', default="small", help='Path to the dataset folder') + +if __name__ == '__main__': + args = parser.parse_args() + if args.dataset is not None: + test_folder = Path(__file__).parents[2] / f"my_dataset_comparison_{args.dataset}" + + if not test_folder.is_dir(): + setup_module() + + win = test_mainwindow_comparison(start_app=True, verbose=True) diff --git a/spikeinterface_gui/tests/test_mainwindow_panel.py b/spikeinterface_gui/tests/test_mainwindow_panel.py index a304f7f0..d34f08df 100644 --- a/spikeinterface_gui/tests/test_mainwindow_panel.py +++ b/spikeinterface_gui/tests/test_mainwindow_panel.py @@ -115,6 +115,8 @@ def test_launcher(verbose=True): parser.add_argument('--iterative', action="store_true", help='Run iterative curation') parser.add_argument('--layout', default="default", help='Layout of the GUI, default is "default"') parser.add_argument('--lazy', action="store_true", help='Lazy load') +parser.add_argument('--port', default=0, type=int, help='Port for the web server') +parser.add_argument('--no-start', action="store_true", help='Do not start the app') if __name__ == '__main__': args = parser.parse_args() @@ -127,11 +129,11 @@ def test_launcher(verbose=True): setup_module() win = test_mainwindow( - start_app=True, + start_app=not args.no_start, verbose=True, curation=True, events=args.events, - port=0, + port=args.port, layout=args.layout, iterative_curation=args.iterative, lazy_load=args.lazy diff --git a/spikeinterface_gui/tests/testingtools.py b/spikeinterface_gui/tests/testingtools.py index 7ec9180f..03ebd0ef 100644 --- a/spikeinterface_gui/tests/testingtools.py +++ b/spikeinterface_gui/tests/testingtools.py @@ -145,6 +145,101 @@ def make_analyzer_folder(test_folder, case="small", unit_dtype="str"): sorting_analyzer.compute("template_metrics") +def make_comparison_analyzer_folders(test_folder, case="small", unit_dtype="str", + fraction_shared=0.7, fraction_dropped_spikes=0.1): + """ + Two analyzer folders to compare, in test_folder / "sorting_analyzer_1" and "_2". + + One ground truth sorting is split in three: `fraction_shared` of the units go to both + sortings, and half of the rest goes to each one only. So the comparison has units in + the three regions of the Venn diagram. + + To add some variability, `fraction_dropped_spikes` of the spikes of the second sorting + are then dropped at random. The shared units therefore agree strongly but not + perfectly, which is closer to a real comparison than an agreement of exactly 1. + """ + clean_all(test_folder) + + if case == 'small': + durations = [300.0, 100.0] + num_channels = 32 + num_units = 30 + elif case == 'medium': + durations = [600.0,] + num_channels = 128 + num_units = 100 + else: + raise ValueError(f"Wrong dataset type {case}") + + job_kwargs = dict(n_jobs=-1, progress_bar=True, chunk_duration="1s") + + recording, sorting = si.generate_ground_truth_recording( + durations=durations, + num_channels=num_channels, + num_units=num_units, + + sampling_frequency=30000.0, + + generate_sorting_kwargs=dict(firing_rates=3.0, refractory_period_ms=4.0), + generate_unit_locations_kwargs=dict( + margin_um=5.0, + minimum_z=5.0, + maximum_z=20.0, + ), + generate_templates_kwargs=dict( + unit_params=dict( + alpha=(100.0, 500.0), + ) + ), + noise_kwargs=dict(noise_levels=10.0, strategy="tile_pregenerated"), + seed=2205, + ) + + rng = np.random.default_rng(seed=2205) + + # split the units: shared / only in sorting1 / only in sorting2 + shuffled_unit_ids = sorting.unit_ids.copy() + rng.shuffle(shuffled_unit_ids) + num_shared = int(fraction_shared * num_units) + num_only = (num_units - num_shared) // 2 + shared_unit_ids = set(shuffled_unit_ids[:num_shared]) + only1_unit_ids = set(shuffled_unit_ids[num_shared:num_shared + num_only]) + only2_unit_ids = set(shuffled_unit_ids[num_shared + num_only:num_shared + 2 * num_only]) + + # keep the original unit order, so that the unit ids of both analyzers stay sorted + sorting1 = sorting.select_units([u for u in sorting.unit_ids if u in shared_unit_ids | only1_unit_ids]) + sorting2 = sorting.select_units([u for u in sorting.unit_ids if u in shared_unit_ids | only2_unit_ids]) + + # drop some spikes of sorting2, so that the shared units do not agree perfectly + spikes2 = sorting2.to_spike_vector() + keep = rng.random(spikes2.size) >= fraction_dropped_spikes + sorting2 = si.NumpySorting(spikes2[keep], sorting2.sampling_frequency, sorting2.unit_ids) + + folders = [] + for i, sorting_i in enumerate([sorting1, sorting2]): + sorting_i = sorting_i.rename_units(sorting_i.unit_ids.astype(unit_dtype)) + sorting_i.set_property(key='my_own_property', + values=np.array([f"yep{i}" for i in range(sorting_i.unit_ids.size)])) + + folder = test_folder / f"sorting_analyzer_{i + 1}" + sorting_analyzer = si.create_sorting_analyzer(sorting_i, recording, + format="binary_folder", + folder=folder, + **job_kwargs) + sorting_analyzer.compute("random_spikes", method="uniform", max_spikes_per_unit=500) + sorting_analyzer.compute("waveforms", **job_kwargs) + sorting_analyzer.compute("templates", **job_kwargs) + sorting_analyzer.compute("noise_levels", **job_kwargs) + sorting_analyzer.compute("unit_locations") + sorting_analyzer.compute("quality_metrics", metric_names=["snr", "firing_rate"]) + sorting_analyzer.compute("template_metrics") + sorting_analyzer.compute(["spike_amplitudes", "spike_locations", "amplitude_scalings"], **job_kwargs) + sorting_analyzer.compute("correlograms") + folders.append(folder) + + return folders + + def make_curation_dict(analyzer): unit_ids = analyzer.unit_ids.tolist() curation_dict = { diff --git a/spikeinterface_gui/tracemapview.py b/spikeinterface_gui/tracemapview.py index 995c529f..a32b7af3 100644 --- a/spikeinterface_gui/tracemapview.py +++ b/spikeinterface_gui/tracemapview.py @@ -213,6 +213,11 @@ def _panel_make_layout(self): self.figure.on_event(MouseWheel, self._panel_gain_zoom) self.figure.on_event(DoubleTap, self._panel_on_double_tap) + # Placeholder for events, set by the bottom bar when the analyzer has some. + # MixinViewTrace._panel_add_event_lines() reads it on every refresh. + self.event_line = None + self.event_source = None + # Add selection line self.selection_line = self.figure.line( x=[], y=[], line_color="purple", line_width=2, line_dash="dashed", visible=False diff --git a/spikeinterface_gui/unitlistview.py b/spikeinterface_gui/unitlistview.py index 329104fd..e780c3cd 100644 --- a/spikeinterface_gui/unitlistview.py +++ b/spikeinterface_gui/unitlistview.py @@ -29,13 +29,6 @@ def update_manual_labels(self): elif self.backend == 'panel': self._panel_update_labels() - def notify_unit_and_channel_visibility_changed(self): - selected_units = self.controller.get_visible_unit_ids() - visible_channel_inds = self.controller.get_common_sparse_channels(selected_units) - self.controller.set_channel_visibility(visible_channel_inds) - self.notify_channel_visibility_changed() - self.notify_unit_visibility_changed() - ## Qt ## def _qt_make_layout(self): @@ -181,7 +174,6 @@ def _qt_refresh_visibility_items(self): target_item = self.items_visibility[view_target_unit_id] self.table.scrollToItem(target_item, QT.QAbstractItemView.PositionAtCenter) - unit_ids_list = list(self.controller.unit_ids) for unit_id in self.controller.unit_ids: item = self.items_visibility[unit_id] item.setCheckState(QT.Qt.Unchecked) @@ -191,8 +183,12 @@ def _qt_refresh_visibility_items(self): self.table.clearSelection() for unit_id in visible_unit_ids: - row = unit_ids_list.index(unit_id) - self.table.selectRow(row) + # This accounts for row ordering when table sorted by e.g. a metric value + row = self.items_visibility[unit_id].row() + # selectRow would replace the selection in ExtendedSelection mode, keeping only the last unit + self.table.selectionModel().select( + self.table.model().index(row, 0), QT.QItemSelectionModel.Select | QT.QItemSelectionModel.Rows + ) self._qt_refresh_color_icons() @@ -200,23 +196,15 @@ def _qt_refresh_color_icons(self): from .myqt import QT # refresh colors for i, unit_id in enumerate(self.controller.unit_ids): - color = self.get_unit_color(unit_id) - pix = QT.QPixmap(16,16) - pix.fill(color) - icon = QT.QIcon(pix) - self.items_icon[unit_id].setIcon(icon) + self.items_icon[unit_id].setIcon(self.get_unit_icon(unit_id)) self.table.itemChanged.connect(self._qt_on_item_changed) def _qt_refresh(self): - # # TODO sam change this bad hack after speedup the combox - # if hasattr(self, 'items_visibility'): - # self._qt_refresh_visibility_items() - # else: - # # the time at startup - # self._qt_full_table_refresh() - - self._qt_full_table_refresh() + if hasattr(self, 'items_visibility'): + self._qt_refresh_visibility_items() + else: + self._qt_full_table_refresh() def _qt_set_default_label(self, label): @@ -283,10 +271,7 @@ def _qt_full_table_refresh(self): self.items_visibility = {} self.items_icon = {} for i, unit_id in enumerate(unit_ids): - color = self.get_unit_color(unit_id) - pix = QT.QPixmap(16,16) - pix.fill(color) - icon = QT.QIcon(pix) + icon = self.get_unit_icon(unit_id) # item = QT.QTableWidgetItem( f'{unit_id}') item = CustomItemUnitID(unit_ids, f'{unit_id}') @@ -334,6 +319,20 @@ def _qt_full_table_refresh(self): for i in range(5): self.table.resizeColumnToContents(i) self.table.setSortingEnabled(True) + + # re-select the appropriate unit on a full refresh + self.table.clearSelection() + for unit_id in visible_unit_ids: + item = self.items_visibility[unit_id] + # this logic is needed when table is sorted by e.g. a metric + self.table.selectionModel().select( + self.table.model().index(item.row(), 0), + QT.QItemSelectionModel.Select | QT.QItemSelectionModel.Rows + ) + if len(visible_unit_ids) > 0: + target_item = self.items_visibility[visible_unit_ids[0]] + self.table.scrollToItem(target_item, QT.QAbstractItemView.PositionAtCenter) + self.table.itemChanged.connect(self._qt_on_item_changed) # Restore column order if it exists @@ -514,7 +513,8 @@ def _panel_create_table(self): self.main_cols = list(data.keys()) for unit_index, unit_id in enumerate(unit_ids): data["unit_id"].append( - {"id": str(unit_id), "color": mcolors.to_hex(self.controller.get_unit_color(unit_id))} + {"id": str(unit_id), "color": mcolors.to_hex(self.controller.get_unit_color(unit_id)), + "shape": self.controller.get_unit_shape(unit_id)} ) data["channel_id"].append( self.controller.channel_ids[self.controller.get_main_channel(unit_id)] @@ -781,7 +781,8 @@ def _panel_refresh_colors(self): unit_ids_data.append( { "id": str(unit_id), - "color": mcolors.to_hex(self.controller.get_unit_color(unit_id)) + "color": mcolors.to_hex(self.controller.get_unit_color(unit_id)), + "shape": self.controller.get_unit_shape(unit_id), } ) self.table.value.loc[:, "unit_id"] = unit_ids_data diff --git a/spikeinterface_gui/utils_panel.py b/spikeinterface_gui/utils_panel.py index 61445c38..604dd0ca 100644 --- a/spikeinterface_gui/utils_panel.py +++ b/spikeinterface_gui/utils_panel.py @@ -92,7 +92,7 @@ def _apply(): unit_formatter = HTMLTemplateFormatter( template="""
- ● <%= value ? value.id : '' %><%= value && value.n !== undefined ? ' n=' + value.n : '' %> + <%= value && value.shape === 'square' ? '■' : '●' %> <%= value ? value.id : '' %><%= value && value.n !== undefined ? ' n=' + value.n : '' %>
""" ) @@ -126,6 +126,24 @@ def _apply(): """ +def make_toggled_checkboxes(name, options, value, on_change, max_height=200): + """ + A toggle button that shows a list of checkboxes, hidden again when the toggle is off: + the panel twin of the Qt parameter tree shown by a toolbar button, and more compact than + a MultiChoice once several options are selected. + + on_change is called with the event of the checkboxes value (event.new is the list of + checked options). Returns (toggle, checkboxes, box): the toggle and the box are placed in + the view layout, the box scrolls the checkboxes (one per row) past max_height. + """ + toggle = pn.widgets.Toggle(name=name, value=False, width=100, align="end") + checkboxes = pn.widgets.CheckBoxGroup(options=options, value=value, sizing_mode="stretch_width") + box = pn.Column(checkboxes, scroll=True, max_height=max_height, visible=False, sizing_mode="stretch_width") + toggle.param.watch(lambda event: setattr(box, "visible", event.new), "value") + checkboxes.param.watch(on_change, "value") + return toggle, checkboxes, box + + def insert_warning(view, warning_msg): clear_warning(view) alert_html = f""" diff --git a/spikeinterface_gui/view_base.py b/spikeinterface_gui/view_base.py index b9f45479..a401e571 100644 --- a/spikeinterface_gui/view_base.py +++ b/spikeinterface_gui/view_base.py @@ -62,6 +62,14 @@ def notify_unit_visibility_changed(self): def notify_channel_visibility_changed(self): self.notifier.notify_channel_visibility_changed() + def notify_unit_and_channel_visibility_changed(self): + """Set the visible channels to the sparse channels of the visible units, then notify both""" + selected_units = self.controller.get_visible_unit_ids() + visible_channel_inds = self.controller.get_common_sparse_channels(selected_units) + self.controller.set_channel_visibility(visible_channel_inds) + self.notify_channel_visibility_changed() + self.notify_unit_visibility_changed() + def notify_manual_curation_updated(self): self.controller.current_curation_saved = False self.notifier.notify_manual_curation_updated() @@ -80,6 +88,10 @@ def notify_active_view_updated(self): def notify_unit_color_changed(self): self.notifier.notify_unit_color_changed() + def notify_agreement_threshold_changed(self): + # comparison mode only: the agreement threshold is shared by the comparison views + self.notifier.notify_agreement_threshold_changed() + def on_settings_changed(self, *params): # what to do when one settings is changed # optionally views can implement custom method @@ -185,6 +197,23 @@ def continue_from_user(self, warning_msg, action, *args): # Panel: asynchronous approach with callback self._panel_insert_warning_with_choice(warning_msg, action, *args) + def get_unit_icon(self, unit_id): + """Qt icon with the unit color and shape""" + from .myqt import QT + + pix = QT.QPixmap(16, 16) + pix.fill(QT.Qt.transparent) + painter = QT.QPainter(pix) + painter.setRenderHint(QT.QPainter.Antialiasing) + painter.setPen(QT.Qt.NoPen) + painter.setBrush(self.get_unit_color(unit_id)) + if self.controller.get_unit_shape(unit_id) == "square": + painter.drawRect(1, 1, 14, 14) + else: + painter.drawEllipse(1, 1, 14, 14) + painter.end() + return QT.QIcon(pix) + def get_unit_color(self, unit_id, alpha=1.0): if self.backend == "qt": from .myqt import QT @@ -262,6 +291,12 @@ def on_unit_color_changed(self): elif self.backend == "panel": self._panel_on_unit_color_changed() + def on_agreement_threshold_changed(self): + if self.backend == "qt": + self._qt_on_agreement_threshold_changed() + elif self.backend == "panel": + self._panel_on_agreement_threshold_changed() + def busy_cursor(self): if self.backend == "qt": return self._qt_busy_cursor() @@ -314,6 +349,9 @@ def _qt_on_use_times_updated(self): def _qt_on_unit_color_changed(self): self.refresh() + def _qt_on_agreement_threshold_changed(self): + self.refresh() + def _qt_insert_warning(self, warning_msg): from .myqt import QT @@ -377,6 +415,9 @@ def _panel_on_use_times_updated(self): def _panel_on_unit_color_changed(self): self.refresh() + def _panel_on_agreement_threshold_changed(self): + self.refresh() + def _panel_insert_warning(self, warning_msg): import panel as pn diff --git a/spikeinterface_gui/viewlist.py b/spikeinterface_gui/viewlist.py index 39cc70d8..680f87df 100644 --- a/spikeinterface_gui/viewlist.py +++ b/spikeinterface_gui/viewlist.py @@ -22,13 +22,23 @@ from .maintemplateview import MainTemplateView from .eventview import EventView +from .compareunitlistview import CompareUnitListView +from .agreementmatrixview import AgreementMatrixView +from .comparemainsettingsview import CompareMainSettingsView +from .compareunitvennview import CompareUnitVennView +from .comparespikesview import CompareSpikesView +from .comparelabelsview import CompareLabelsView +from .comparemetricsview import CompareMetricsView + # probe and mainsettings view are first, since they affect other views (e.g., time info) builtin_views = [ ProbeView, MainSettingsView, UnitListView, SpikeRateView, MergeView, TraceView, TraceMapView, WaveformView, WaveformHeatMapView, ISIView, CorrelogramView, NDScatterView, SimilarityView, SpikeAmplitudeView, SpikeDepthView, SpikeRateView, CurationView, MetricsView, SpikeListView, - AmplitudeScalingsView, MainTemplateView, EventView + AmplitudeScalingsView, MainTemplateView, EventView, + CompareMainSettingsView, CompareUnitListView, AgreementMatrixView, CompareUnitVennView, CompareSpikesView, + CompareLabelsView, CompareMetricsView, ] def get_all_possible_views(): diff --git a/spikeinterface_gui/waveformview.py b/spikeinterface_gui/waveformview.py index dfc06f7c..562a6d1e 100644 --- a/spikeinterface_gui/waveformview.py +++ b/spikeinterface_gui/waveformview.py @@ -555,7 +555,6 @@ def _qt_refresh_with_spikes(self): if num_waveforms <= 0: self.curve_waveforms.setData([], []) return - wf_ext = self.controller.analyzer.get_extension("waveforms") visible_unit_ids = self.controller.get_visible_unit_ids() # Process waveforms per unit to maintain color association @@ -563,7 +562,7 @@ def _qt_refresh_with_spikes(self): width = None for unit_id in visible_unit_ids: - waveforms = wf_ext.get_waveforms_one_unit(unit_id, force_dense=True) + waveforms, _ = self.controller.get_waveforms(unit_id, force_dense=True) if waveforms is None or len(waveforms) == 0: continue @@ -1283,7 +1282,6 @@ def _panel_refresh_waveforms_samples(self): self.lines_data_source_wfs_geom.data = dict(xs=[], ys=[], colors=[]) return - wf_ext = self.controller.analyzer.get_extension("waveforms") visible_unit_ids = self.controller.get_visible_unit_ids() # Process waveforms per unit to maintain color association @@ -1291,7 +1289,7 @@ def _panel_refresh_waveforms_samples(self): width = None for unit_id in visible_unit_ids: - waveforms = wf_ext.get_waveforms_one_unit(unit_id, force_dense=True) + waveforms, _ = self.controller.get_waveforms(unit_id, force_dense=True) if waveforms is None or len(waveforms) == 0: continue