Repository navigation
Closed
Labels
Description
Describe the new feature or enhancement
In mne/preprocessing/artifact_detection.py there is a function called _annotations_from_mask. As its name suggests it creates an annotation from a numpy array mask. A for loop has been used in its implementation, which could be very time-consuming when the number of components is large.
Describe your proposed implementation
This could be implemented without any for loop. I have the following code, working in my tests:
def _annotations_from_mask(times, mask, annot_name):
"""Construct annotations from boolean mask of the data."""
from scipy.ndimage.morphology import distance_transform_edt
from scipy.signal import find_peaks
mask_tf = distance_transform_edt(mask)
midpoint_index = find_peaks(mask_tf)[0]
onsets_index = midpoint_index - mask_tf[midpoint_index].astype(int) + 1
ends_index = midpoint_index + mask_tf[midpoint_index].astype(int) - 1
# Ensure onsets_index >= 0, otherwise the duration starts from the beginning
onsets_index[onsets_index < 0] = 0
# Ensure ends_index < len(times), otherwise the duration is to the end of times
ends_index[ends_index >= len(times)] = len(times) - 1
onsets = times[onsets_index]
ends = times[ends_index]
durations = ends - onsets
desc = [annot_name]*len(durations)
return Annotations(onsets, durations, desc)This implementation doesn't require any additional package.
With a mask of num_comps equal to 24389, %timeit gives for the original implementation and the mine respectively:
2min 1s ± 640 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)590 ms ± 16.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)Describe possible alternatives
I do not have any other implementation in mind.
Please tell me how you think of this enhancement. If everything seems fine, I will be glad to create a PR.
Activity
welcome commentedon Dec 3, 2021
Hello! 👋 Thanks for opening your first issue here! ❤️ We will try to get back to you soon. 🚴🏽♂️
agramfort commentedon Dec 4, 2021
implement fast annotation from mask mne-tools#10088
adhere to mne-python code style mne-tools#10088
add credits mne-tools#10088
snwnde commentedon Dec 4, 2021
I tweaked the code to address the following problems:
find_peakscannot find peaks at the start and the end of arrays,find_peaksreturns the first peak index, preventing the previous code to correctly give ends_index.address problem associated with find_peaks mne-tools#10088
agramfort commentedon Dec 4, 2021
snwnde commentedon Dec 4, 2021
@agramfort I created the PR #10089. Some checks fail though. It seems a precision problem.
maintain consistency with old code when len(times)>len(mask) mne-tool…
maintain consistency with old code when len(times)>len(mask) mne-tool…
Fast annotation from mask (#10089)