-
Notifications
You must be signed in to change notification settings - Fork 240
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
base: main
Are you sure you want to change the base?
Changes from 7 commits
3dc5729
d1a0532
7279b67
1962f21
528c82b
775dda7
bb46f27
121a0b1
cbf3213
4409aa5
71f8668
1ea0d68
a86c2d3
d8e1f90
3f93f97
cd85456
7a42fe3
4f754cb
cbc0986
56b672e
046430e
bb86253
50f33f0
80bc50f
4c8fa23
e1f5bab
96e6a53
3198911
87fbe9a
7446a43
873a687
51e906a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -22,11 +22,20 @@ | |
| ("segment_index", "int64"), | ||
| ] | ||
|
|
||
|
|
||
| spike_peak_dtype = base_peak_dtype + [ | ||
| ("unit_index", "int64"), | ||
| ] | ||
|
|
||
| base_period_dtype = [ | ||
|
||
| ("start_sample_index", "int64"), | ||
| ("end_sample_index", "int64"), | ||
| ("segment_index", "int64"), | ||
| ] | ||
|
|
||
| unit_period_dtype = base_period_dtype + [ | ||
| ("unit_index", "int64"), | ||
| ] | ||
|
|
||
|
|
||
| class PipelineNode: | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -228,6 +228,83 @@ def random_spikes_selection( | |
| return random_spikes_indices | ||
|
|
||
|
|
||
| def select_sorting_periods_mask(sorting: BaseSorting, periods): | ||
| """ | ||
| Returns a boolean mask for the spikes in the sorting object, restricted to the given periods of dtype unit_period_dtype. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| sorting : BaseSorting | ||
| The sorting object. | ||
| periods : numpy.array of unit_period_dtype | ||
| Periods (segment_index, start_sample_index, end_sample_index, unit_index) | ||
| on which to restrict the sorting. | ||
|
|
||
| Returns | ||
| ------- | ||
| numpy.array | ||
| A boolean mask of the spikes in the sorting object, with True for spikes within the specified periods. | ||
| """ | ||
| spike_vector = sorting.to_spike_vector() | ||
| spike_vector_list = sorting.to_spike_vector(concatenated=False) | ||
| keep_mask = np.zeros(len(spike_vector), dtype=bool) | ||
| all_global_indices = spike_vector_to_indices(spike_vector_list, unit_ids=sorting.unit_ids, absolute_index=True) | ||
|
||
| for segment_index in range(sorting.get_num_segments()): | ||
| global_indices_segment = all_global_indices[segment_index] | ||
| # filter periods by segment | ||
| periods_in_segment = periods[periods["segment_index"] == segment_index] | ||
|
Collaborator
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. assuming not too many periods, these masks would be fine. Otherwise, we'll need to optimize |
||
| for unit_index, unit_id in enumerate(sorting.unit_ids): | ||
| # filter by unit index | ||
| periods_for_unit = periods_in_segment[periods_in_segment["unit_index"] == unit_index] | ||
| global_indices = global_indices_segment[unit_id] | ||
| spiketrains = spike_vector[global_indices]["sample_index"] | ||
| if len(periods_for_unit) > 0: | ||
| for period in periods_for_unit: | ||
| mask = (spiketrains >= period["start_sample_index"]) & (spiketrains < period["end_sample_index"]) | ||
| keep_mask[global_indices[mask]] = True | ||
| return keep_mask | ||
|
|
||
|
|
||
| def select_sorting_periods(sorting: BaseSorting, periods) -> BaseSorting: | ||
| """ | ||
| Returns a new sorting object, restricted to the given periods of dtype unit_period_dtype. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| S | ||
alejoe91 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| periods : numpy.array of unit_period_dtype | ||
| Periods (segment_index, start_sample_index, end_sample_index, unit_index) | ||
| on which to restrict the sorting. | ||
|
|
||
| Returns | ||
| ------- | ||
| BaseSorting | ||
| A new sorting object with only samples between start_sample_index and end_sample_index | ||
| for the given segment_index. | ||
| """ | ||
| from spikeinterface.core.numpyextractors import NumpySorting | ||
| from spikeinterface.core.node_pipeline import unit_period_dtype | ||
|
|
||
| if periods is not None: | ||
| if not isinstance(periods, np.ndarray): | ||
| periods = np.array([periods], dtype=unit_period_dtype) | ||
| required = set(np.dtype(unit_period_dtype).names) | ||
| if not required.issubset(periods.dtype.names): | ||
| raise ValueError(f"Period must have the following fields: {required}") | ||
|
|
||
| spike_vector = sorting.to_spike_vector() | ||
| keep_mask = select_sorting_periods_mask(sorting, periods) | ||
| sliced_spike_vector = spike_vector[keep_mask] | ||
|
|
||
| sorting = NumpySorting( | ||
| sliced_spike_vector, sampling_frequency=sorting.sampling_frequency, unit_ids=sorting.unit_ids | ||
| ) | ||
| sorting.copy_metadata(sorting) | ||
| return sorting | ||
| else: | ||
| return sorting | ||
|
|
||
|
|
||
| ### MERGING ZONE ### | ||
| def apply_merges_to_sorting( | ||
| sorting: BaseSorting, | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,9 +3,7 @@ | |
| but check only for BaseRecording general methods. | ||
| """ | ||
|
|
||
| import shutil | ||
| from pathlib import Path | ||
|
|
||
| import time | ||
| import numpy as np | ||
| import pytest | ||
| from numpy.testing import assert_raises | ||
|
|
@@ -17,15 +15,15 @@ | |
| SharedMemorySorting, | ||
| NpzFolderSorting, | ||
| NumpyFolderSorting, | ||
| generate_ground_truth_recording, | ||
| generate_sorting, | ||
| create_sorting_npz, | ||
| generate_sorting, | ||
| load, | ||
| ) | ||
| from spikeinterface.core.base import BaseExtractor | ||
| from spikeinterface.core.testing import check_sorted_arrays_equal, check_sortings_equal | ||
| from spikeinterface.core.generate import generate_sorting | ||
|
|
||
| from spikeinterface.core import generate_recording, generate_ground_truth_recording | ||
| from spikeinterface.core.node_pipeline import unit_period_dtype | ||
|
|
||
|
|
||
| def test_BaseSorting(create_cache_folder): | ||
|
|
@@ -226,7 +224,66 @@ def test_time_slice(): | |
| ) | ||
|
|
||
|
|
||
| def test_select_periods(): | ||
| sampling_frequency = 10_000.0 | ||
| duration = 1_000 | ||
| num_samples = int(sampling_frequency * duration) | ||
| num_units = 1000 | ||
| sorting = generate_sorting( | ||
| durations=[duration, duration], sampling_frequency=sampling_frequency, num_units=num_units | ||
| ) | ||
|
|
||
| rng = np.random.default_rng() | ||
|
|
||
| # number of random periods | ||
| n_periods = 10_000 | ||
|
||
| # generate random periods | ||
| segment_indices = rng.integers(0, sorting.get_num_segments(), n_periods) | ||
| start_samples = rng.integers(0, num_samples, n_periods) | ||
| durations = rng.integers(100, 100_000, n_periods) | ||
| end_samples = start_samples + durations | ||
| valid_periods = end_samples < num_samples | ||
| segment_indices = segment_indices[valid_periods] | ||
| start_samples = start_samples[valid_periods] | ||
| end_samples = end_samples[valid_periods] | ||
| unit_index = rng.integers(0, num_units - 1, len(segment_indices)) | ||
|
|
||
| periods = np.zeros(len(segment_indices), dtype=unit_period_dtype) | ||
| periods["segment_index"] = segment_indices | ||
| periods["start_sample_index"] = start_samples | ||
| periods["end_sample_index"] = end_samples | ||
| periods["unit_index"] = unit_index | ||
| periods = np.sort(periods, order=["segment_index", "start_sample_index"]) | ||
|
|
||
| t_start = time.perf_counter() | ||
| sliced_sorting = sorting.select_periods(periods=periods) | ||
| t_stop = time.perf_counter() | ||
| elapsed = t_stop - t_start | ||
| print(f"select_periods took {elapsed:.2f} seconds for {len(periods)} periods") | ||
|
|
||
| # Check that all spikes in the sliced sorting are within the periods | ||
| for segment_index in range(sorting.get_num_segments()): | ||
| periods_in_segment = periods[periods["segment_index"] == segment_index] | ||
|
Collaborator
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. do we assume not too many periods, just to be sure that all these masks won't take too long? |
||
| for unit_index, unit_id in enumerate(sorting.unit_ids): | ||
| spiketrain = sorting.get_unit_spike_train(segment_index=segment_index, unit_id=unit_id) | ||
|
|
||
| periods_for_unit = periods_in_segment[periods_in_segment["unit_index"] == unit_index] | ||
| spiketrain_in_periods = [] | ||
| for period in periods_for_unit: | ||
| start_sample = period["start_sample_index"] | ||
| end_sample = period["end_sample_index"] | ||
| spiketrain_in_periods.append(spiketrain[(spiketrain >= start_sample) & (spiketrain < end_sample)]) | ||
| if len(spiketrain_in_periods) == 0: | ||
| spiketrain_in_periods = np.array([], dtype=spiketrain.dtype) | ||
| else: | ||
| spiketrain_in_periods = np.unique(np.concatenate(spiketrain_in_periods)) | ||
|
|
||
| spiketrain_sliced = sliced_sorting.get_unit_spike_train(segment_index=segment_index, unit_id=unit_id) | ||
| assert len(spiketrain_in_periods) == len(spiketrain_sliced) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| test_BaseSorting() | ||
| test_npy_sorting() | ||
| test_empty_sorting() | ||
| test_select_periods() | ||
Uh oh!
There was an error while loading. Please reload this page.