Skip to content

how to correctly preprocess data in spikeinterface before running kilosort #3483

Open

Description

@chongtianyifa

Hi,

I am confused about the preprocessing chain before running kilosort. In nearly all provided examples, 'highpass_filter', 'phase_shift' and 'common_reference' were run and sorters were called like:
sorting = si.run_sorter('kilosort2_5', rec, output_folder=base_folder / 'kilosort2.5_output', docker_image=True, verbose=True, **params_kilosort2_5)
Here 'car' and 'skip_kilosort_preprocessing' should be True and False by default, which means the filtering and common_reference were calculated again in kilosort. What is the meaning of the preprocessing in spikeinterface?

I am trying to do all preprocessing and drift correction using 'dreg' in spikeinterface before calling kilosort by:
sorting = si.run_sorter(sorter_name='kilosort2_5', recording=raw_rec, folder=r'F:\B12M2S10_g0\B12M2S10_g0_imec0\kilo25-3\sort', skip_kilosort_preprocessing=True, scaleproc=200, do_correction=False, docker_image=False, verbose=True)
The running failed, most likely due to the data not being whitened by setting skip_kilosort_preprocessing as True. Any suggestion about my pipeline?

Activity

  1. zm711 commented on Oct 17, 2024

    @zm711
    Member

    Sorry I'm trying to understand this part of your statement:

    Here 'car' and 'skip_kilosort_preprocessing' should be True and False by default, which means the filtering and common_reference were calculated again in kilosort. What is the meaning of the preprocessing in spikeinterface?

    The default is to do the Kilosort preprocessing. This is true for all sorters. We want the default to just be what the sorter wants do to. Ie you just put in a raw_recording in order to let the sorter handle everything. We also give you the option to do your own preprocessing so you can fine-tune in which case you do the preprocessing yourself and then set the values to car=False, skip_kilosort_preprocessing=True.

    As far as your second issue. You raise a great point that whitening is super important for many spike sorters these days. We have a whitening function you can read the params here and you could add that to kilosort workflow. Since I don't know the dredge workflow super well I'll tag @cwindolf to see if he has advice on plugging in his code into a kilosort workflow or whether we should tag someone else on the team.

  2. added
    question
    on Oct 17, 2024
  3. cwindolf commented on Oct 17, 2024

    @cwindolf
    Collaborator

    Thanks @zm711 -- whitening is definitely important for KS, so adding a si.whiten() to your preprocessing chain would be important if you have skip_kilosort_preprocessing=True. I actually haven't used it before, so I'm not sure whether you need to do that with int_scale=200 -- maybe someone else can comment? Can't find an example of a workflow like this in the docs.

  4. JoeZiminski commented on Oct 17, 2024

    @JoeZiminski
    Contributor

    Hey @chongtianyifa could you link some of the examples that were followed? I agree with @zm711 this is the expected behaviour. It might be useful to update these examples so kilosort is called with car=False and freq_min=<some value lower than the low bound on the spikeinterface bandpass> (unfortunately you can't turn it off entirely in KS) so it is clear what is going on. Doing these two preprocessing steps again should have little effect (both filters are zero phase) but might as well skip it if you can.

    I think @cwindolf is correct you should run si.whiten with int_scale=200 to replicate the kilosort behaviour. As this workflow is relatively new (all preprocessing in spikeinterface, sorting only with KS) I would suggest comparing the outputs of kilosort using the two workflows. Unfortunately it is not simple to get access to the KS preprocessed data (#2650 , though this may have changed in KS4) but you can get a rough idea by looking at the template shapes (in general, their order will unlikely correspond 1:1 across runs) and plotting spikes directly from the kilosort output with kilosort drift map. I'm currently porting this to python / spikeinterface, should be able to finalise the PR by today / tomorrow so will keep you updated if useful.

    That being said, it depends what you want to do. If you want to leverage the spikeinterface postprocessing toolkit, you will want a recording object to pass to the sorting analyzer that matches as closely as possible the preprocessed recording. As an extreme example, it would be a mistake to load raw data into spikeinterface, run the sorting with all kilosort preprocessing steps, then load the sorting output and the raw (unpreprocessed) spikeinterface recording into a sorting analyzer.

    However, if you don't want to use spikeinterface postprocessing, you can just pass the raw data to kilosort (using it's own preprocessing) and work with the kilosort output directly.

  5. chongtianyifa commented on Oct 17, 2024

    @chongtianyifa
    Author

    @JoeZiminski These two examples preprocessed recording and called kilosort allowing it to preprocess again:
    https://github.com/SpikeInterface/spikeinterface/blob/main/examples/get_started/quickstart.py
    https://github.com/SpikeInterface/spikeinterface/blob/main/examples/how_to/analyze_neuropixels.py.
    According to your explanation, can I say that repeating preprocessing should be ok as CAR and highpass filtering should not affect preprocessed data too much?

    By summary, there are three options about preprocessing. Please correct me @cwindolf @JoeZiminski @zm711 if my understanding is not right.

    1. Do not preprocess, just feed the raw recording into kilosort. Then you cannot use postprocessing toolkits.
    2. Do all preprocessing in spikeinterface, including 'highpass_filter', 'phase_shift', 'common_reference' and 'whiten'. Feed this rec_preprocess into kilosort by calling si.run_sorter(sorter_name='kilosort2_5', recording=rec_preprocess, folder=r'F:\B12M2S10_g0\B12M2S10_g0_imec0\kilo25-3\sort', car=False, skip_kilosort_preprocessing=True, scaleproc=200). Then you can perfectly combine rec_preprocess and kilosort output using sorting analyzer.
    3. Partially preprocess data in spikeinterface, including 'highpass_filter', 'phase_shift', 'common_reference' without 'whiten'. Feed this rec_preprocess_part into kilosort by calling si.run_sorter(sorter_name='kilosort2_5', recording=rec_preprocess_part , folder=r'F:\B12M2S10_g0\B12M2S10_g0_imec0\kilo25-3\sort', car=False, freq_min=<some value lower than the low bound on the spikeinterface bandpass>, scaleproc=200). This is in fact what most examples do. My question is how to combine rec_preprocess_part and kilosort output using sorting analyzer as data is further whitened by kilosort.
  6. self-assigned this
    on Oct 22, 2024
  7. JoeZiminski commented on Oct 22, 2024

    @JoeZiminski
    Contributor

    Hi @chongtianyifa that looks correct to me. For 2. you may also want to run a drift-correction step prior to whitening.

    For 3. this step will also be run by kilosort before whitening. The whitening step changes the waveforms significantly so it is usual to un-whiten the data before waveform extraction, so that's not a problem. However, the drift correction could be, depending on how much drift is in your data.

    In this case, 3. spikeinterface will be performing postprocessing using the information from the sorting output, and on a recording that has not been drift corrected (while the sorting estimation is on corrected data). I'm not 100% sure of the practical implications of this, you may have noise propagated through the data. My understanding is, as the waveforms (across all channels) will be extracted based on the spike times from the sorting. Then these will be averaged for template generation and maximum loading channels estimated. If there is uncorrected drift, then the templates and position estimates will be noisier. @zm711 @alejoe91 @samuelgarcia will be able to confirm if this is correct.

  8. chiyu1203 commented on Apr 7, 2025

    @chiyu1203
  9. anhknguyen96 commented on May 6, 2025

    @anhknguyen96

    Hey @chongtianyifa could you link some of the examples that were followed? I agree with @zm711 this is the expected behaviour. It might be useful to update these examples so kilosort is called with car=False and freq_min=<some value lower than the low bound on the spikeinterface bandpass> (unfortunately you can't turn it off entirely in KS) so it is clear what is going on. Doing these two preprocessing steps again should have little effect (both filters are zero phase) but might as well skip it if you can.

    I think @cwindolf is correct you should run si.whiten with int_scale=200 to replicate the kilosort behaviour. As this workflow is relatively new (all preprocessing in spikeinterface, sorting only with KS) I would suggest comparing the outputs of kilosort using the two workflows. Unfortunately it is not simple to get access to the KS preprocessed data (#2650 , though this may have changed in KS4) but you can get a rough idea by looking at the template shapes (in general, their order will unlikely correspond 1:1 across runs) and plotting spikes directly from the kilosort output with kilosort drift map. I'm currently porting this to python / spikeinterface, should be able to finalise the PR by today / tomorrow so will keep you updated if useful.

    That being said, it depends what you want to do. If you want to leverage the spikeinterface postprocessing toolkit, you will want a recording object to pass to the sorting analyzer that matches as closely as possible the preprocessed recording. As an extreme example, it would be a mistake to load raw data into spikeinterface, run the sorting with all kilosort preprocessing steps, then load the sorting output and the raw (unpreprocessed) spikeinterface recording into a sorting analyzer.

    However, if you don't want to use spikeinterface postprocessing, you can just pass the raw data to kilosort (using it's own preprocessing) and work with the kilosort output directly.

    Hi, now that with kilosort4 we can save a preprocessed copy of the recording data, can we in principle load that as a recording object to the sorting analyzer?

  10. zm711 commented on May 6, 2025

    @zm711
    Member

    @anhknguyen96, in principle yes though we wouldn't recommend it. We thought about doing an extractor for this see here, but it was a little too involved to generate something that would easily work. So we don't provide any tools to do this ourselves currently. Feel free to read some of our concerns in that PR.

    We also recommend against this (in a more general sense) because the whitening of the data distorts the waveforms so the sorting analyzer that you would make is misformed. We recommend instead to do some preprocessing on your recording (for example you could mimic the filter + CAR of KS) and load that into your sorting analyzer instead.

  11. anhknguyen96 commented on May 6, 2025

    @anhknguyen96

    I see. That ended up way more complicated than I thought.

    I attempted doing preprocessing entirely with spikeinterface, but the one done with kilosort gives the best sorting result. My recording data has a lot of motion artefacts (induced by licking, acute NP2 recording), and so replicating kilosort's preprocessing pipeline has been a bit of a challenge.

    `## highpass filter the recording (for NPx recording)
    recording_f_dict = si.highpass_filter(chan_group_rec, freq_min=400.)

    ## dead channel detection and removal
    bad_channel_ids, channel_labels = si.detect_bad_channels(recording_f_dict, method='coherence+psd')
    # only remove channels that are dead
    recording_f_dict = recording_f_dict.remove_channels(bad_channel_ids)
    print(bad_channel_ids)
    print(channel_labels)
    
    ## phase shift
    rec_shift = si.phase_shift(recording=recording_f_dict)
    
    ## common reference
    recording_good_channels = si.common_reference(rec_shift, reference='global', operator='median')
    
    ## drift correction
    # ref https://github.com/SpikeInterface/spikeinterface/issues/3790
    motion_folder = os.path.join(spike_itf_folder, 'motion_analyzed_shank'+str(grouper))
    rec_corrected, motion_info = si.correct_motion(recording=recording_good_channels, preset="kilosort_like",
                                                   estimate_motion_kwargs={'win_step_um': 75,
                                                                           'win_scale_um': 150},
                                                   folder=motion_folder, output_motion_info=True)
    
    ## whitening
    rec_w = si.whiten(recording=rec_corrected)
    preprocessed_recording_dict[grouper] = rec_w
    del recording_f_dict, rec_shift, recording_good_channels,rec_corrected, rec_w`
    

    This is currently what I have for spikeinterface's preprocessing pipeline. Do you have an intuition on which step/parameter I should improve/tweak to mimic kilosort's preprocessing pipeline, especially regarding motion correction?

  12. zm711 commented on May 6, 2025

    @zm711
    Member

    You can totally use KS and it's preprocessing for your sorting. For the analyzer we would recommend not doing that and using a recording that has had some processing. If KS gives you the best sorting you can take the sorting results and apply it to the original recording, but with some SI preprocessing.

    It might help to know exactly what you're hoping to do so we know which data you actually need. What is the problem with doing

    KS4 -> sorting + (original recording before KS4 + filter+CAR)-> analyzer stuff.

    If we know what the specific issue with that workflow is then maybe we can help more.

  13. anhknguyen96 commented on May 6, 2025

    @anhknguyen96

    I'd like to use the whole spikeinterface pipeline, especially the postprocessing and automatic curation part.

    KS4 -> sorting + (original recording before KS4 + filter+CAR)-> analyzer stuff.

    would this be an issue for the sorting analyzer to compute quality metrics given that the preprocessed data is not motion corrected, which I expect to be drastically different from the corrected data, and hence give unreliable results?

  14. zm711 commented on May 7, 2025

    @zm711
    Member

    I see. @chrishalcrow is currently working on our motion correction high level api (it is still relatively low-level for use). Maybe he can comment on how to get it working currently?

  15. chrishalcrow commented on May 7, 2025

    @chrishalcrow
    Member

    Motion correction is a bit annoying, but there are some workflows that work! This is my understanding: it's best to think about having a recording for sorting and a recording for postprocessing. Ideally they're the same. But sometimes they're different: e.g. some sorting algorithms apply whitening to the recording; but whitening ruins the physical units associated with the raw traces. So I prefer to do my post-processing on a non-whitened recording.

    For the case discussed in this thread: there are two options I've tried. This is just my advice from trying out different bits and pieces.

    1. Do your preprocessing and motion correction in spikeinterface, then turn these things off when you use kilosort. Then use the corrected recording in your postprocessing. This workflow looks something like (I've compressed it into a few lines - probably don't do this!!):
    import spikeinterface.full as si
    recording = si.load("path/to/recording")
    pp_rec = si.correct_motion(si.whiten(si.bandpass_filter(recording)))
    sorting = si.run_sorter(recording=pp_rec, sorter_name="kilosort4", do_correction=False, skip_kilosort_preprocessing=True)
    # kilosort sometimes has spikes past the final recording time, so remove these
    sorting = si.remove_excess_spikes(sorting=sorting, recording=recording)
    analyzer = si.create_sorting_analyzer(recording=pp_rec, sorting=sorting)
    1. Let kilosort do the preprocessing and motion correction, then try and imitate these using spikeinterface. This is a bit of a hack, but works pretty well in my experience!
    recording = si.load("path/to/recording")
    sorting = si.run_sorter(recording=recording, sorter_name="kilosort4", use_binary_file=False)
    # kilo sort sometimes has spikes past the final recording time, so remove these
    sorting = si.remove_excess_spikes(sorting=sorting, recording=recording)
    
    # now try to remake the preprocessed recording
    pp_rec = si.correct_motion(si.whiten(si.bandpass_filter(recording)), preset="kilosort_like")
    analyzer = si.create_sorting_analyzer(recording=pp_rec, sorting=sorting)

    or, if you're like me and don't like the whitened recording for your postprocessing, you can compute your motion correction and apply it to a non-whitened recording. Note: you need spikeinterface 102.3 for this code (released today!)

    motion = si.compute_motion(si.whiten(si.bandpass_filter(recording)), preset="kilosort_like")
    # you probably need to common_reference if you're not whitening.
    motion_corrected_recording = si.interpolate_motion(si.common_reference(si.bandpass_filter(recording)), motion=motion)
    analyzer = si.create_sorting_analyzer(recording=motion_corrected_recording, sorting=sorting)

    All of these options should work fine for the analyzer extensions like quality metrics. I've not actually tried running this code, you might need to neaten it up a little!

    (I've just noticed that kilosort has a save_preprocessed_copy parameter which might make life easier - I've never tired it, sorry!)

  16. zm711 commented on May 7, 2025

    @zm711
    Member

    (I've just noticed that kilosort has a save_preprocessed_copy parameter which might make life easier - I've never tired it, sorry!)

    Just related to this--this is the whitened data and we don't have tools for that so again this is probably not the right option :) I would reccomend trying Chris' option 3 to try. That may you mimic the KS motion, but you don't make the sorter with the whitened data!
    Thanks @chrishalcrow !

  17. anhknguyen96 commented on May 8, 2025

    @anhknguyen96

    Thank you so much @chrishalcrow and @zm711 !!!

    Just it off curiosity, can you give me a quick pointer to why whitened recording is not ideal for postprocessing?

  18. zm711 commented on May 8, 2025

    @zm711
    Member

    I think the simplest intuition is that

    filtering -> removes artifacts (under the assumption these are actual junk, ie line noise coming from your computer being plugged into the wall) you don't want to analyze this so we throw it away

    referencing -> provides you the baseline noise present everywhere (natural electric activity present in all living things and in salty solutions), you don't want to over-interpret this information as real signal when it is background stuff so try to clean this up

    motion -> tissue moves, tissue swells, temp changes (etc) so if you want to make sure a neuron is kept track of you want to account for motion, but this is closer to the cutting edge where many people are still working on this hard (similar to people trying to make better and better sorters)

    whitening -> decorrelate data (but also tends to squish data to make comparisons easier so this is good for sorting because we don't care about the shape of the data per se--a mathematical action potential doesn't have to look like what you're taught in school) but when we want to do post-hoc analysis we probably don't want distorted APs we want the actual AP shape (with the noise and artifacts taken out). Maybe the whitening minimally distorts the AP and so it is not a big deal, but even KS relies on unwhitening the temp_wh.dat when it is loaded into phy so that you don't see the whitened templates. We don't have the option to appropriately unwhiten the data (because not all sorters whiten internally), so why spend the time whitening when you need to unwhiten to analyze the final data.

    Again I hope this explanation is more intuitive and less mathematically rigorous so if @chrishalcrow or @alejoe91 want to pick apart the vibes and give a more rigorous answer then you could have it both ways.

  19. pas-calc commented on Dec 1, 2026

    @pas-calc
    Contributor

    or, if you're like me and don't like the whitened recording for your postprocessing, you can compute your motion correction and apply it to a non-whitened recording.

    It looks like some function names were changed and since I was interested in also using this idea (it is very useful), this solution adapted code works well with newest spikeinterface (Version: 0.105.4)

    import spikeinterface.full as si
    import spikeinterface.preprocessing as spr
    from spikeinterface.sortingcomponents.motion import interpolate_motion
    
    recording_filtered = si.bandpass_filter(recording, freq_min=300.0, freq_max=6000.0)
    recording_referenced = si.common_reference(recording_filtered, reference="global", operator="median")
    
    motion = si.compute_motion(
        recording=si.whiten(si.bandpass_filter(recording, freq_min=300.0, freq_max=6000.0), dtype="float32"),
        preset="kilosort_like"
    )
    
    recording_for_analyzer = interpolate_motion(
        recording=recording_referenced,
        motion=motion,
        dtype="float32"
    )
    
    si.create_sorting_analyzer(
        sorting=sorting,
        recording=recording_for_analyzer,
    )
    
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

question

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions