Skip to content

Potential bug in detect_peaks #1121

Closed
Closed

Description

@hornauerp

I tried to sort a MaxWell chip recording (10min, ~9gb) that I had previously sorted with an older spykingcircus version, using the spikeinterface-based sorters (spykingcircus 2 and tridesclous 2, v0.96.1) with default parameters - other than sorter_params['job_kwargs']['n_jobs'] = 8. However, while there are clear spikes in the recording, both sorters did not find any peaks and gave an error afterwards. I went line by line through the spykingcircus2 code, and right before the detect_peaks call, there are still clear spikes in the data (example of one channel):
grafik

Interestingly, when I used method=by_channel, a few peaks were found, but they all belonged to the same channel. When I lowered the detection threshold to sorter_params['detection']['detect_threshold'] = 4, the number of peaks increased quite a bit, but still all peaks belonged to the same channel and the amplitudes also were very odd:
grafik

When running tridesclous2, I additionally get the following warnings and also detect 0 peaks:

E:\envs\si\lib\site-packages\spikeinterface\preprocessing\normalize_scale.py:230: RuntimeWarning: divide by zero encountered in true_divide
  gain = 1 / mads
E:\envs\si\lib\site-packages\spikeinterface\preprocessing\normalize_scale.py:231: RuntimeWarning: invalid value encountered in true_divide
  offset = -medians / mads

Since the sorting worked with the old spykingcircus, and the preprocessing does not seem to distort the data (clear spikes visible), I am not sure where to go from here on. Might there be a bug in the detect_peaks function?

Activity

  1. yger commented on Nov 30, 2022

    @yger
    Contributor

    Thanks for the feedback. The bug is not necessarily in the detect_peak function. It could be in the way data are loaded/filtered, and or in the preprocessing steps. Could it be possible to share the data, or are they too big?

  2. samuelgarcia commented on Nov 30, 2022

    @samuelgarcia
    Member

    Hi,
    detect_peaks() have an important kwargs which is noise_level.
    By default it is computed internally.
    I would advice to compute outside with get_noise_levels(rec) , so you can check that this level is OK.

    What is your preprocessing ?

  3. yger commented on Nov 30, 2022

    @yger
    Contributor

    Indeed, look at the distribution of noise levels, and maybe share the plot here. Just also, as a sanity check, maybe plotting some traces with si.plot_timeseries of the recording. Are you giving a raw recording to spyking circus 2 (and thus let the pipeline do the preprocessing), or a preprocessed recording (and with apply_preprocessing set to False in sc2)?

  4. hornauerp commented on Nov 30, 2022

    @hornauerp
    Author

    Thanks for your quick replies!

    Initially, I did the preprocessing outside of the sorter (apply_preprocessing set to False), but to rule out any errors in my preprocessing pipeline, I now use the raw recording (so just rec = si.MaxwellRecordingExtractor(rec_path)) and set apply_preprocessing to True. However, both give the same result.
    I also checked si.remove_bad_channels(rec), but it does not detect any bad channels.

    The histogram of the noise levels looks like this:
    grafik

    And I uploaded the raw file here if you have time to take a closer look.

    Sorry for the confusion, I accidentally closed the issue.

  5. yger commented on Nov 30, 2022

    @yger
    Contributor

    i'll download the file and have to look to understand what is happening

  6. yger commented on Nov 30, 2022

    @yger
    Contributor

    I ran the following code

    `
    import spikeinterface.full as si

    rec = si.read_maxwell('recording.raw.h5')

    sub_rec = rec.frame_slice(0, 20000*60) ## To take only

    from spikeinterface.sortingcomponents.peak_detection import detect_peaks

    sub_rec = si.bandpass_filter(sub_rec, dtype='float32')

    sub_rec = si.common_reference(sub_rec)

    sub_rec = si.zscore(sub_rec)

    peaks = detect_peaks(sub_rec, noise_levels=np.ones(1020), method='by_channel', n_jobs=-1, verbose=True,

    progress_bar=True, chunk_memory="100M")

    import pylab as plt

    plt.hist(peaks['channel_ind'], 100)
    `
    téléchargement

  7. yger commented on Nov 30, 2022

    @yger
    Contributor

    Actually, same with locally_exclusive, so except if the bug is after the first 60s, evertyhing looks fine to me. Could you double test on your side with the latest git version, and see if you have similar results? The zscore function is a default in SC2, such that all channels have the same noise levels of 1
    Could also be that you are not forcing the data to be float32 after filtering. You should, because they are int16, and otherwise the median common reference is false. But again, this is a default behavior in SC2, so I don't know exactly where the bug comes from

  8. hornauerp commented on Dec 1, 2022

    @hornauerp
    Author

    I pulled the latest master branch from github and ran the exact same code (except for explicitly assigning n_jobs ( #867 )), but I still get the same result:
    grafik

  9. yger commented on Dec 1, 2022

    @yger
    Contributor

    Hum... So you ran the code I wrote in the cell, and we have a major discrepancy... Damned.
    Can you share the details of your env, such that I can see if I could reproduce it? This was performed with python 3.8

  10. hornauerp commented on Dec 1, 2022

    @hornauerp
    Author

    Interesting, the issue seems to be the parallelization. I created a new environment on our Linux server using the .yaml file in the installation_tips folder, ran the exact code that you provided and got a new error message:

    peaks = detect_peaks(sub_rec, noise_levels=np.ones(1020), method='by_channel', n_jobs=20, verbose=True, progress_bar=True, chunk_memory="100M")
    detect peaks with n_jobs = 20 and chunk_size = 24509
    detect peaks:   0%|                                                                                                                                                                                                               | 0/49 [00:00<?, ?it/s]Exception in initializer:
    Traceback (most recent call last):
      File "/home/phornauer/miniconda3/envs/si2/lib/python3.9/concurrent/futures/process.py", line 233, in _process_worker
        initializer(*initargs)
      File "/home/phornauer/Git/spikeinterface/spikeinterface/core/job_tools.py", line 353, in worker_initializer
        _worker_ctx = init_func(*init_args)
      File "/home/phornauer/Git/spikeinterface/spikeinterface/sortingcomponents/peak_detection.py", line 101, in _init_worker_detect_peaks
        recording = load_extractor(recording)
      File "/home/phornauer/Git/spikeinterface/spikeinterface/core/base.py", line 919, in load_extractor
        return BaseExtractor.from_dict(file_or_folder_or_dict, base_folder=base_folder)
      File "/home/phornauer/Git/spikeinterface/spikeinterface/core/base.py", line 373, in from_dict
        extractor = _load_extractor_from_dict(d)
      File "/home/phornauer/Git/spikeinterface/spikeinterface/core/base.py", line 864, in _load_extractor_from_dict
        extractor = cls(**kwargs)
      File "/home/phornauer/Git/spikeinterface/spikeinterface/preprocessing/normalize_scale.py", line 228, in __init__
        mads = np.median(np.abs(random_data - medians), axis=0) / 0.6745
    numpy.core._exceptions._ArrayMemoryError: Unable to allocate 1.52 GiB for an array with shape (200000, 1020) and data type float64
    Exception in initializer:
    Traceback (most recent call last):
      File "/home/phornauer/miniconda3/envs/si2/lib/python3.9/concurrent/futures/process.py", line 233, in _process_worker
        initializer(*initargs)
      File "/home/phornauer/Git/spikeinterface/spikeinterface/core/job_tools.py", line 353, in worker_initializer
        _worker_ctx = init_func(*init_args)
      File "/home/phornauer/Git/spikeinterface/spikeinterface/sortingcomponents/peak_detection.py", line 101, in _init_worker_detect_peaks
        recording = load_extractor(recording)
      File "/home/phornauer/Git/spikeinterface/spikeinterface/core/base.py", line 919, in load_extractor
        return BaseExtractor.from_dict(file_or_folder_or_dict, base_folder=base_folder)
      File "/home/phornauer/Git/spikeinterface/spikeinterface/core/base.py", line 373, in from_dict
        extractor = _load_extractor_from_dict(d)
      File "/home/phornauer/Git/spikeinterface/spikeinterface/core/base.py", line 864, in _load_extractor_from_dict
        extractor = cls(**kwargs)
      File "/home/phornauer/Git/spikeinterface/spikeinterface/preprocessing/normalize_scale.py", line 228, in __init__
        mads = np.median(np.abs(random_data - medians), axis=0) / 0.6745
    numpy.core._exceptions._ArrayMemoryError: Unable to allocate 1.52 GiB for an array with shape (200000, 1020) and data type float64
    detect peaks:   0%|                                                                                                                                                                                                               | 0/49 [00:57<?, ?it/s]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/home/phornauer/Git/spikeinterface/spikeinterface/sortingcomponents/peak_detection.py", line 83, in detect_peaks
        outputs = processor.run()
      File "/home/phornauer/Git/spikeinterface/spikeinterface/core/job_tools.py", line 330, in run
        for res in results:
      File "/home/phornauer/miniconda3/envs/si2/lib/python3.9/site-packages/tqdm/std.py", line 1195, in __iter__
        for obj in iterable:
      File "/home/phornauer/miniconda3/envs/si2/lib/python3.9/concurrent/futures/process.py", line 562, in _chain_from_iterable_of_lists
        for element in iterable:
      File "/home/phornauer/miniconda3/envs/si2/lib/python3.9/concurrent/futures/_base.py", line 609, in result_iterator
        yield fs.pop().result()
      File "/home/phornauer/miniconda3/envs/si2/lib/python3.9/concurrent/futures/_base.py", line 446, in result
        return self.__get_result()
      File "/home/phornauer/miniconda3/envs/si2/lib/python3.9/concurrent/futures/_base.py", line 391, in __get_result
        raise self._exception
    concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.
    
    

    I also tried locally exclusive, which gives the same error, but an additional division by zero RuntimeWarning:

    peaks = detect_peaks(sub_rec, noise_levels=np.ones(1020), method='locally_exclusive', n_jobs=20, verbose=True, progress_bar=True, chunk_memory="100M")
    detect peaks with n_jobs = 20 and chunk_size = 24509
    detect peaks:   0%|                                                                                                                                                                                                               | 0/49 [00:00<?, ?it/s]/home/phornauer/Git/spikeinterface/spikeinterface/preprocessing/normalize_scale.py:230: RuntimeWarning: divide by zero encountered in true_divide
      gain = 1 / mads
    /home/phornauer/Git/spikeinterface/spikeinterface/preprocessing/normalize_scale.py:231: RuntimeWarning: invalid value encountered in true_divide
      offset = -medians / mads
    Exception in initializer:
    Traceback (most recent call last):
      File "/home/phornauer/miniconda3/envs/si2/lib/python3.9/concurrent/futures/process.py", line 233, in _process_worker
        initializer(*initargs)
      File "/home/phornauer/Git/spikeinterface/spikeinterface/core/job_tools.py", line 353, in worker_initializer
        _worker_ctx = init_func(*init_args)
      File "/home/phornauer/Git/spikeinterface/spikeinterface/sortingcomponents/peak_detection.py", line 101, in _init_worker_detect_peaks
        recording = load_extractor(recording)
      File "/home/phornauer/Git/spikeinterface/spikeinterface/core/base.py", line 919, in load_extractor
        return BaseExtractor.from_dict(file_or_folder_or_dict, base_folder=base_folder)
      File "/home/phornauer/Git/spikeinterface/spikeinterface/core/base.py", line 373, in from_dict
        extractor = _load_extractor_from_dict(d)
      File "/home/phornauer/Git/spikeinterface/spikeinterface/core/base.py", line 864, in _load_extractor_from_dict
        extractor = cls(**kwargs)
      File "/home/phornauer/Git/spikeinterface/spikeinterface/preprocessing/normalize_scale.py", line 228, in __init__
        mads = np.median(np.abs(random_data - medians), axis=0) / 0.6745
      File "<__array_function__ internals>", line 5, in median
      File "/home/phornauer/miniconda3/envs/si2/lib/python3.9/site-packages/numpy/lib/function_base.py", line 3655, in median
        r, k = _ureduce(a, func=_median, axis=axis, out=out,
      File "/home/phornauer/miniconda3/envs/si2/lib/python3.9/site-packages/numpy/lib/function_base.py", line 3564, in _ureduce
        r = func(a, **kwargs)
      File "/home/phornauer/miniconda3/envs/si2/lib/python3.9/site-packages/numpy/lib/function_base.py", line 3690, in _median
        part = partition(a, kth, axis=axis)
      File "<__array_function__ internals>", line 5, in partition
      File "/home/phornauer/miniconda3/envs/si2/lib/python3.9/site-packages/numpy/core/fromnumeric.py", line 754, in partition
        a = asanyarray(a).copy(order="K")
    numpy.core._exceptions._ArrayMemoryError: Unable to allocate 1.52 GiB for an array with shape (200000, 1020) and data type float64
    detect peaks:   0%|                                                                                                                                                                                                               | 0/49 [00:46<?, ?it/s]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/home/phornauer/Git/spikeinterface/spikeinterface/sortingcomponents/peak_detection.py", line 83, in detect_peaks
        outputs = processor.run()
      File "/home/phornauer/Git/spikeinterface/spikeinterface/core/job_tools.py", line 330, in run
        for res in results:
      File "/home/phornauer/miniconda3/envs/si2/lib/python3.9/site-packages/tqdm/std.py", line 1195, in __iter__
        for obj in iterable:
      File "/home/phornauer/miniconda3/envs/si2/lib/python3.9/concurrent/futures/process.py", line 562, in _chain_from_iterable_of_lists
        for element in iterable:
      File "/home/phornauer/miniconda3/envs/si2/lib/python3.9/concurrent/futures/_base.py", line 609, in result_iterator
        yield fs.pop().result()
      File "/home/phornauer/miniconda3/envs/si2/lib/python3.9/concurrent/futures/_base.py", line 446, in result
        return self.__get_result()
      File "/home/phornauer/miniconda3/envs/si2/lib/python3.9/concurrent/futures/_base.py", line 391, in __get_result
        raise self._exception
    concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.
    
    

    I then set n_jobs=1 and did not specify a chunk_size, and suddenly it worked. I went ahead and tried it on my local Windows machine, and also there n_jobs=1 and not specifying chunk_size did the trick and I get the same result as you:
    grafik

  11. yger commented on Dec 1, 2022

    @yger
    Contributor

    The issue about the size in memory seems to be related to slice and preprocessors @samuelgarcia, any hints? chunk_memory is not properly taken into account there?

  12. yger commented on Dec 1, 2022

    @yger
    Contributor

    The default code was run on windows, or on linux?

  13. hornauerp commented on Dec 1, 2022

    @hornauerp
    Author

    I initially worked locally on windows.

  14. added
    bug
    bug in sorter
    on Dec 2, 2022
  15. alejoe91 commented on Jun 12, 2023

    @alejoe91
    Member

    @hornauerp any update on this?

  16. hornauerp commented on Jun 13, 2023

    @hornauerp
    Author

    I have resorted to work with KS again, so unfortunately no news from my side.

  17. alejoe91 commented on Nov 6, 2023

    @alejoe91
    Member

    @hornauerp ok to close this?

  18. hornauerp commented on Nov 6, 2023

    @hornauerp
    Author

    Yes, I will close it 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugbug in sorter

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions