-
Notifications
You must be signed in to change notification settings - Fork 241
Implement select_sorting_periods in metrics
#4302
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
samuelgarcia
merged 51 commits into
SpikeInterface:main
from
alejoe91:select_sorting_periods
Jan 22, 2026
+1,052
−590
Merged
Changes from all commits
Commits
Show all changes
51 commits
Select commit
Hold shift + click to select a range
3dc5729
Test IBL extractors tests failing for PI update
alejoe91 d1a0532
Merge branch 'main' of github.com:SpikeInterface/spikeinterface
alejoe91 7279b67
wip
alejoe91 1962f21
Fix test for base sorting and propagate to basevector extension
alejoe91 528c82b
Fix tests in quailty metrics
alejoe91 775dda7
Fix retrieval of spikevector features
alejoe91 bb46f27
Update src/spikeinterface/core/sorting_tools.py
alejoe91 121a0b1
Apply suggestion from @chrishalcrow
alejoe91 cbf3213
refactor presence ratio and drift metrics to use periods properly
alejoe91 4409aa5
Fix rp_violations
alejoe91 71f8668
implement firing range and fix drift
alejoe91 1ea0d68
fix naming issue
alejoe91 a86c2d3
remove solved todos
alejoe91 d8e1f90
Merge branch 'main' of github.com:SpikeInterface/spikeinterface into …
alejoe91 3f93f97
Implement select_segment_periods in core
alejoe91 cd85456
remove utils
alejoe91 7a42fe3
rebase on #4316
alejoe91 4f754cb
Merge with main
alejoe91 cbc0986
Fix import
alejoe91 56b672e
Merge branch 'select_sorting_periods_core' into select_sorting_periods
alejoe91 046430e
fix import
alejoe91 bb86253
Add misc_metric changes
alejoe91 50f33f0
fix tests
alejoe91 80bc50f
Change base_period_dtype order and fix select_sorting_periods array i…
alejoe91 4c8fa23
fix conflicts
alejoe91 e1f5bab
Merge metrics implementations
alejoe91 96e6a53
fix tests
alejoe91 3198911
Fix generation of bins
alejoe91 87fbe9a
Merge branch 'main' of github.com:SpikeInterface/spikeinterface into …
alejoe91 7446a43
Use cached get_spike_vector_to_indices
alejoe91 873a687
Solve conflicts
alejoe91 51e906a
Fix error in merging
alejoe91 ab5a771
fix conflicts
alejoe91 2209514
Add supports_periods in BaseMetric/Extension
alejoe91 b23c431
wip: test metrics with periods
alejoe91 6fb26a4
almost there?
alejoe91 0fe7f3e
Fix periods arg in MetricExtensions
alejoe91 f087e08
Make bin edges unique
alejoe91 173e747
Add support_periods to spike train metrics and tests
alejoe91 066c378
Force NaN/-1 values for float/int metrics if num_spikes is 0
alejoe91 65e1848
Fix test_empty_units: -1 is a valid value for ints
alejoe91 f1c4682
Fix firing range if unit samples < bin samples
alejoe91 3291638
fix noise_cutoff if empty units
alejoe91 b5bf3c3
Move warnings at the end of the loop for firing range and drift
alejoe91 8aeedcc
clean up tests and add get_available_metric_names
alejoe91 d4db43c
simplify total samples
alejoe91 d0a1e66
Go back to Pierre's implementation for drifts
alejoe91 630c662
rename compute_periods to compute_regular_periods
alejoe91 1fd1fd4
Remove print
alejoe91 c541ba0
Merge branch 'select_sorting_periods' of github.com:alejoe91/spikeint…
alejoe91 f0d0ba7
Speed up function which was already fast but Sam didn't like it
alejoe91 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -13,6 +13,7 @@ | |
| import numpy as np | ||
| from collections import namedtuple | ||
|
|
||
| from .numpyextractors import NumpySorting | ||
| from .sortinganalyzer import SortingAnalyzer, AnalyzerExtension, register_result_extension | ||
| from .waveform_tools import extract_waveforms_to_single_buffer, estimate_templates_with_accumulator | ||
| from .recording_tools import get_noise_levels | ||
|
|
@@ -823,10 +824,9 @@ class BaseMetric: | |
| metric_columns = {} # column names and their dtypes of the dataframe | ||
| metric_descriptions = {} # descriptions of each metric column | ||
| needs_recording = False # whether the metric needs recording | ||
| needs_tmp_data = ( | ||
| False # whether the metric needs temporary data comoputed with _prepare_data at the MetricExtension level | ||
| ) | ||
| needs_job_kwargs = False | ||
| needs_tmp_data = False # whether the metric needs temporary data computed with MetricExtension._prepare_data | ||
| needs_job_kwargs = False # whether the metric needs job_kwargs | ||
| supports_periods = False # whether the metric function supports periods | ||
| depend_on = [] # extensions the metric depends on | ||
|
|
||
| # the metric function must have the signature: | ||
|
|
@@ -839,7 +839,7 @@ class BaseMetric: | |
| metric_function = None # to be defined in subclass | ||
|
|
||
| @classmethod | ||
| def compute(cls, sorting_analyzer, unit_ids, metric_params, tmp_data, job_kwargs): | ||
| def compute(cls, sorting_analyzer, unit_ids, metric_params, tmp_data, job_kwargs, periods=None): | ||
| """Compute the metric. | ||
|
|
||
| Parameters | ||
|
|
@@ -854,6 +854,8 @@ def compute(cls, sorting_analyzer, unit_ids, metric_params, tmp_data, job_kwargs | |
| Temporary data to pass to the metric function | ||
| job_kwargs : dict | ||
| Job keyword arguments to control parallelization | ||
| periods : np.ndarray | None | ||
| Numpy array of unit periods of unit_period_dtype if supports_periods is True | ||
|
|
||
| Returns | ||
| ------- | ||
|
|
@@ -865,6 +867,8 @@ def compute(cls, sorting_analyzer, unit_ids, metric_params, tmp_data, job_kwargs | |
| args += (tmp_data,) | ||
| if cls.needs_job_kwargs: | ||
| args += (job_kwargs,) | ||
| if cls.supports_periods: | ||
| args += (periods,) | ||
|
|
||
| results = cls.metric_function(*args, **metric_params) | ||
|
|
||
|
|
@@ -897,6 +901,17 @@ class BaseMetricExtension(AnalyzerExtension): | |
| need_backward_compatibility_on_load = False | ||
| metric_list: list[BaseMetric] = None # list of BaseMetric | ||
|
|
||
| @classmethod | ||
| def get_available_metric_names(cls): | ||
| """Get the available metric names. | ||
|
|
||
| Returns | ||
| ------- | ||
| available_metric_names : list[str] | ||
| List of available metric names. | ||
| """ | ||
| return [m.metric_name for m in cls.metric_list] | ||
|
|
||
| @classmethod | ||
| def get_default_metric_params(cls): | ||
| """Get the default metric parameters. | ||
|
|
@@ -988,6 +1003,7 @@ def _set_params( | |
| metric_params: dict | None = None, | ||
| delete_existing_metrics: bool = False, | ||
| metrics_to_compute: list[str] | None = None, | ||
| periods: np.ndarray | None = None, | ||
| **other_params, | ||
| ): | ||
| """ | ||
|
|
@@ -1004,6 +1020,8 @@ def _set_params( | |
| If True, existing metrics in the extension will be deleted before computing new ones. | ||
| metrics_to_compute : list[str] | None | ||
| List of metric names to compute. If None, all metrics in `metric_names` are computed. | ||
| periods : np.ndarray | None | ||
| Numpy array of unit_period_dtype defining periods to compute metrics over. | ||
| other_params : dict | ||
| Additional parameters for metric computation. | ||
|
|
||
|
|
@@ -1079,6 +1097,7 @@ def _set_params( | |
| metrics_to_compute=metrics_to_compute, | ||
| delete_existing_metrics=delete_existing_metrics, | ||
| metric_params=metric_params, | ||
| periods=periods, | ||
| **other_params, | ||
| ) | ||
| return params | ||
|
|
@@ -1129,6 +1148,8 @@ def _compute_metrics( | |
| if metric_names is None: | ||
| metric_names = self.params["metric_names"] | ||
|
|
||
| periods = self.params.get("periods", None) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I guess this is to be backward compatible. |
||
|
|
||
| column_names_dtypes = {} | ||
| for metric_name in metric_names: | ||
| metric = [m for m in self.metric_list if m.metric_name == metric_name][0] | ||
|
|
@@ -1153,6 +1174,7 @@ def _compute_metrics( | |
| metric_params=metric_params, | ||
| tmp_data=tmp_data, | ||
| job_kwargs=job_kwargs, | ||
| periods=periods, | ||
| ) | ||
| except Exception as e: | ||
| warnings.warn(f"Error computing metric {metric_name}: {e}") | ||
|
|
@@ -1179,6 +1201,7 @@ def _run(self, **job_kwargs): | |
|
|
||
| metrics_to_compute = self.params["metrics_to_compute"] | ||
| delete_existing_metrics = self.params["delete_existing_metrics"] | ||
| periods = self.params.get("periods", None) | ||
|
|
||
| _, job_kwargs = split_job_kwargs(job_kwargs) | ||
| job_kwargs = fix_job_kwargs(job_kwargs) | ||
|
|
@@ -1452,6 +1475,16 @@ def _get_data(self, outputs="numpy", concatenated=False, return_data_name=None, | |
| periods, | ||
| ) | ||
| all_data = all_data[keep_mask] | ||
| # since we have the mask already, we can use it directly to avoid double computation | ||
| spike_vector = self.sorting_analyzer.sorting.to_spike_vector(concatenated=True) | ||
| sliced_spike_vector = spike_vector[keep_mask] | ||
| sorting = NumpySorting( | ||
| sliced_spike_vector, | ||
| sampling_frequency=self.sorting_analyzer.sampling_frequency, | ||
| unit_ids=self.sorting_analyzer.unit_ids, | ||
| ) | ||
| else: | ||
| sorting = self.sorting_analyzer.sorting | ||
|
|
||
| if outputs == "numpy": | ||
| if copy: | ||
|
|
@@ -1460,10 +1493,10 @@ def _get_data(self, outputs="numpy", concatenated=False, return_data_name=None, | |
| return all_data | ||
| elif outputs == "by_unit": | ||
| unit_ids = self.sorting_analyzer.unit_ids | ||
| spike_vector = self.sorting_analyzer.sorting.to_spike_vector(concatenated=False) | ||
|
|
||
| if keep_mask is not None: | ||
| # since we are filtering spikes, we need to recompute the spike indices | ||
| spike_vector = spike_vector[keep_mask] | ||
| spike_vector = sorting.to_spike_vector(concatenated=False) | ||
| spike_indices = spike_vector_to_indices(spike_vector, unit_ids, absolute_index=True) | ||
| else: | ||
| # use the cache of indices | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,85 @@ | ||
| import pytest | ||
|
|
||
| from spikeinterface.postprocessing.tests.conftest import _small_sorting_analyzer | ||
| from spikeinterface.core import ( | ||
| generate_ground_truth_recording, | ||
| create_sorting_analyzer, | ||
| ) | ||
|
|
||
| job_kwargs = dict(n_jobs=2, progress_bar=True, chunk_duration="1s") | ||
|
|
||
|
|
||
| def make_small_analyzer(): | ||
| recording, sorting = generate_ground_truth_recording( | ||
| durations=[10.0], | ||
| num_units=10, | ||
| seed=1205, | ||
| ) | ||
|
|
||
| channel_ids_as_integers = [id for id in range(recording.get_num_channels())] | ||
| unit_ids_as_integers = [id for id in range(sorting.get_num_units())] | ||
| recording = recording.rename_channels(new_channel_ids=channel_ids_as_integers) | ||
| sorting = sorting.rename_units(new_unit_ids=unit_ids_as_integers) | ||
|
|
||
| sorting = sorting.select_units([2, 7, 0], ["#3", "#9", "#4"]) | ||
|
|
||
| sorting_analyzer = create_sorting_analyzer(recording=recording, sorting=sorting, format="memory") | ||
|
|
||
| extensions_to_compute = { | ||
| "random_spikes": {"seed": 1205}, | ||
| "noise_levels": {"seed": 1205}, | ||
| "waveforms": {}, | ||
| "templates": {"operators": ["average", "median"]}, | ||
| "spike_amplitudes": {}, | ||
| "spike_locations": {}, | ||
| "principal_components": {}, | ||
| } | ||
|
|
||
| sorting_analyzer.compute(extensions_to_compute) | ||
|
|
||
| return sorting_analyzer | ||
|
|
||
|
|
||
| @pytest.fixture(scope="module") | ||
| def small_sorting_analyzer(): | ||
| return _small_sorting_analyzer() | ||
| return make_small_analyzer() | ||
|
|
||
|
|
||
| @pytest.fixture(scope="module") | ||
| def sorting_analyzer_simple(): | ||
| # we need high firing rate for amplitude_cutoff | ||
| recording, sorting = generate_ground_truth_recording( | ||
| durations=[ | ||
| 120.0, | ||
| ], | ||
| sampling_frequency=30_000.0, | ||
| num_channels=6, | ||
| num_units=10, | ||
| generate_sorting_kwargs=dict(firing_rates=10.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=(200.0, 500.0), | ||
| ) | ||
| ), | ||
| noise_kwargs=dict(noise_levels=5.0, strategy="tile_pregenerated"), | ||
| seed=1205, | ||
| ) | ||
|
|
||
| channel_ids_as_integers = [id for id in range(recording.get_num_channels())] | ||
| unit_ids_as_integers = [id for id in range(sorting.get_num_units())] | ||
| recording = recording.rename_channels(new_channel_ids=channel_ids_as_integers) | ||
| sorting = sorting.rename_units(new_unit_ids=unit_ids_as_integers) | ||
|
|
||
| sorting_analyzer = create_sorting_analyzer(sorting, recording, format="memory", sparse=True) | ||
|
|
||
| sorting_analyzer.compute("random_spikes", max_spikes_per_unit=300, seed=1205) | ||
| sorting_analyzer.compute("noise_levels") | ||
| sorting_analyzer.compute("waveforms", **job_kwargs) | ||
| sorting_analyzer.compute("templates") | ||
| sorting_analyzer.compute(["spike_amplitudes", "spike_locations"], **job_kwargs) | ||
|
|
||
| return sorting_analyzer |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.