Skip to content

Kilosort output for sorting analyzer #4366

Open

Description

@Djoels

As mentioned in the KS (2.5/4) documentation, part of the sorting output prepared for curation is a number of npy files containing templates, similar templates, PC's, ... which are also calculated using a sorting analyzer for a number of metrics.

Could these features somehow be reused, or are they incompatible with sorting analyzer way of working?

Furthermore, what would be the advice when analyzing a recording processed by Kilosort: use the original recording or use the temp_wh.dat file produced by KS which contains already preprocessed (car, whitening, highpass filtered) data?

Activity

  1. Djoels commented on Feb 4, 2026

    @Djoels
    Author

    Hmm, I already stumbled upon an indication of whether the temp_wh.dat file should be used: I guess not then, because it needs to be "unwhitened" before applying sorting analyzer?

  2. chrishalcrow commented on Feb 4, 2026

    @chrishalcrow
    Member

    Hey @Djoels I'm actively working on this! There's already some functionality to import kilosort output as an analyzer (https://spikeinterface.readthedocs.io/en/latest/how_to/import_kilosort_data.html) You'll need use the main branch of spikeinterface (locally clone and install rather than just "pip install spikeinterface"). At the moment it just loads the "easy" stuff.

    But I have a branch here which adds the "hard" stuff: main...chrishalcrow:spikeinterface:add-amps-to-kilosort-convert but it's not quite ready for a proper PR yet. You've already figured out the hard stuff is: some output is whitened, some is in PC space, some is in physical space, and we can only approximately go between the spaces. But think I've figured it all out for KS4 output now.

    For an analyzer, I take a raw recording and lightly preprocess it (bandpass + CMR) then combine with the kilosort sorting output - this seems to work pretty well for my data (chronic NP2).

  3. Djoels commented on Feb 4, 2026

    @Djoels
    Author

    That is great news!
    At our labs we're mostly still using KS2.5 so I'm keen to find out whether this would also work.
    Our recordings are mostly on custom platform or Maxwell recordings (so in vitro HD-MEA's).
    Will give it a try shortly, thanks!

  4. added
    exporters
    question
    on Feb 4, 2026
  5. pas-calc commented on Feb 5, 2026

    @pas-calc
    Contributor

    What happens if templates were split or merged after kilosort as a manual curation? I think in this case it is crucial to only read the spike_templates.npy and not the spike_clusters.npy file. The BasePhyKilosortSortingExtractor tries to load spike_clusters.npy if present. But here it is important that metrics are only calculated for templates and are not updated after manual curation.
    https://phy.readthedocs.io/en/latest/terminology/#cluster-vs-templates
    https://kilosort.readthedocs.io/en/latest/export_files.html

    Alternatively we can load both files and then decompose a cluster into the template like this:

    # load
    st = np.load("spike_templates.npy")
    sc = np.load("spike_clusters.npy")
    clusterids = np.unique(sc)
    
    # decompose cluster into templates
    def decompose_cluster(c):
        """
        phy split/merge leads to cluster = sum of templates. Function to decompose a cluster in its templates
        Returns: templates with its weights (proportion of number of spikes)
        """
        if not c in clusterids:
            raise ValueError("invalid cluster: {} from {} clusters".format(c,len(clusterids)))
        s_ind = (sc==c) # get spikes associated to that cluster c (np.where)
    	s_templates = st[s_ind] # get templates associated to these spikes
    	# now you have: cluster -> spikes -> templates, and thus a mapping from the cluster c to the templates on which the corresponding spikes were detected
    	unique, counts = np.unique(s_templates, return_counts=True) # get the distribution of the templates from the cluster c
    	weights = counts / np.sum(counts) # normalize
    	return unique, weights
                
    # you could run this to decompose each cluster in its templates
    for c in clusterids:
        print("cluster:",c)
        unique, weights = decompose_cluster(c)
        print(dict(zip(unique, weights)))
        print("")
    

    We could apply these weights on the data (waveforms...) but it won't be accurate. For example if we split a template into two clusters, we don't know the waveform of each. It would assign the same

  6. chrishalcrow commented on Feb 5, 2026

    @chrishalcrow
    Member

    Hello, that's beyond the scope of what I'm trying to do. I just want to be able to load in plain, untouched kilosort output (for now!)

  7. pas-calc commented on Feb 6, 2026

    @pas-calc
    Contributor

    Hello, that's beyond the scope of what I'm trying to do. I just want to be able to load in plain, untouched kilosort output (for now!)

    Yes I can understand, and I think it is better to use the actual output, not the manual refinement.
    I just did not see it either here #4202 but just one should make sure to only use the spike_templates.npy file

    Just want to warn about sorting = read_phy(phy_path) in read_kilosort_as_analyzer because it guesses the npy file

    if (phy_folder / "spike_clusters.npy").is_file():
    spike_clusters = np.load(phy_folder / "spike_clusters.npy")
    else:
    spike_clusters = np.load(phy_folder / "spike_templates.npy")

  8. chiyu1203 commented on Apr 15, 2026

    @chiyu1203

    @chrishalcrow Hi, I have a quick question related to this topic. I installed spikeinterface via the main branch on Github and then followed this document to create sorting analyser.
    Everything was fine until I wanted to include raw traces with set_temporary_recording(preprocessed_recording)

    I bumped into this error

    Image

    My recording data is a ChannelsAggregationReocrding in float32 dtype, which has gone through

    raw_rec = se.read_openephys(oe_folder,block_index=0,stream_id='0')
    raw_rec = raw_rec.set_probe(probe,group_mode='by_shank')
    recording_f = spre.bandpass_filter(raw_rec, freq_min=600, freq_max=6000)
    recordings_dict = recording_f.split_by(property='group', outputs='dict')
    recording_cmr = spre.common_reference(recordings_dict, reference="global", operator="median")
    recording_for_analysis=si.aggregate_channels(recording_corrected_dict)
    

    The kilosort4 output came from another customised code using kilosort4's API. No manual curation was done.

    I used CambridgeNeurotech's probe and the probe information was made by ourselves with probe interface. Not sure if this is an issue. Is there any suggestion for me to troubleshoot this problem?

    Coding environment:
    spikeinterface 0.104.1
    Kilosort version 4.1.3
    python 3.12.X
    Windows 11

  9. chrishalcrow commented on Apr 15, 2026

    @chrishalcrow
    Member

    We need to make sure the channels all match up between the recording you gave to kilosort and the recording you're trying to attach to the analyzer. What recording does Kilosort receive? As in, is it just the raw openephys folder? Do you let kilosort do the sorting on the raw data, or do you do any si preprocessing first? It's a bit odd that the number of samples don't match.

  10. chiyu1203 commented on Apr 15, 2026

    @chiyu1203

    @chrishalcrow thanks for your quick response. I let kilosort do the sorting on the raw data (kilosort standalone) so feeding raw openephys folder to kilosort.run_kilosort. I have digged into the issue and probably know what caused this.

    For some reasons, in the function of read_kilosort_as_analyzer, generate_ground_truth_recording was called for a slightly longer duration, and resulted in more samples than the raw data
    Image

    , which is probably what this comment inside the function of read_kilosort_as_analyzer refers to

    # kilosort occasionally contains a few spikes just beyond the recording end point, which can lead
    # to errors later. To avoid this, we pad the recording with an extra second of blank time.
    

    In addition, the current way to load probe information inside read_kilosort_as_analyzer is based on either (1) probe.prb or (2) "channel_positions.npy" in the phy folder.
    In the (1) case, is there any reason to implement selecting the first probe only?

            warnings.warn("Found more than one probe. Selecting the first probe in ProbeGroup.")
    

    I am asking this because my probe is a 2-shank probe and its map is saved as a prb file. Whenever I load the prb file, it returns as a ProbeGroup with each shank represents a probe. If I follow how read_kilosort_as_analyzer load information from prb file, I basically need to hack my prb file and remove that shank information, so that information about every channel is all loaded in the first probe in ProbeGroup

    In the (2) case, I am not sure if probe.set_device_channel_indices(range(probe.get_contact_count())) is a good idea. A similar issue was discussed here. The argument is that when creating a customised probe map, it is not intuitive to make the gemetry or device_channel_indices ascending order. That is why once Kilosort v4.1.3 sorts 'geometry' keys in the prb file, it will mess up the coupling between 'chanMap' and channel location. The situation is bit different here but a different set of device_channel_indices (compared to my original prb file) was created due to probe.set_device_channel_indices(range(probe.get_contact_count()))

    Image

    But I actually dont know how to solve this issue so perhaps it is easier to force users always load their original probe.prb?!

    To summarise, I think the problem lies in kilosort itself (in the case of duration) and the current method to circuvment that causing different number of samples. And then I am worried about the channel mapping for non-Neuropixels users, who always need their own prb files to run kilosort standalone

  11. chrishalcrow commented on Apr 16, 2026

    @chrishalcrow
    Member

    Thanks for all the info!

    Loading the first probe is n oversight on my behalf. Could you send me your probe.prb file so that I can test out a multi-probe set-up?

    We'd be able to deal with the spikes beyond the recording end point if we knew the length of the original recording. So another solution is to let the user pass their own recording to read_kilosort_as_analyzer? Then we'd attach it to the analyzer during the function call. I think we should still load the probe from the output and check that it was consistent with the probe of the recording. Do you think that sounds reasonable?

  12. pas-calc commented on Apr 16, 2026

    @pas-calc
    Contributor

    In addition, the current way to load probe information inside read_kilosort_as_analyzer is based on either (1) probe.prb or (2) "channel_positions.npy" in the phy folder.
    [...]
    In the (2) case, I am not sure if probe.set_device_channel_indices(range(probe.get_contact_count())) is a good idea.

    For case (2) one could load "channel_map.npy" in addition and use the sorting order for probes device channels.

  13. chiyu1203 commented on Apr 16, 2026

    @chiyu1203

    Thanks for the quick response. Here I have attached my probe.prb file.
    probe.zip

    let the user pass their own recording

    we should still load the probe from the output

    I like these ideas. They both sound reasonable and convenient .

  14. chrishalcrow commented on Apr 17, 2026

    @chrishalcrow
    Member

    Hello, I started on the PR. @chiyu1203 - now you can pass your own recording! And we now use the channel_map.npy, thanks @pas-calc !
    I'm not 100% sure what to do with the ProbeGroups. I think it might be easier to never use the prb file and always construct the probe from channel_map and channel_locations. What do you both think? Could you send me the channel_map.npy and channel_locations.npy from the multi-probe @chiyu1203 - would be super useful!

  15. pas-calc commented on Apr 17, 2026

    @pas-calc
    Contributor

    [...] And we now use the channel_map.npy, thanks @pas-calc ! I'm not 100% sure what to do with the ProbeGroups. I think it might be easier to never use the prb file and always construct the probe from channel_map and channel_locations. What do you both think?

    I think this makes sense because in a kilosort output we can expect these two npy files for channel configuration, however assuming a prb file is questionable.

  16. chrishalcrow commented on Apr 17, 2026

    @chrishalcrow
    Member

    Ok, great, I was prioritizing the probe.prb because I think it contains some more information. But I think it's safest to instead use the minimal amount of simple data we can (channel_map and channel_locations). Thanks!

  17. chiyu1203 commented on Apr 17, 2026

    @chiyu1203

    Hello, I started on the PR. @chiyu1203 - now you can pass your own recording! And we now use the channel_map.npy, thanks @pas-calc ! I'm not 100% sure what to do with the ProbeGroups. I think it might be easier to never use the prb file and always construct the probe from channel_map and channel_locations. What do you both think? Could you send me the channel_map.npy and channel_locations.npy from the multi-probe @chiyu1203 - would be super useful!

    No problem! Here are example files. Thank you so much! There is even a npy file called 'channel_shanks.npy'

    channel_map.zip

  18. chiyu1203 commented on Apr 18, 2026

    @chiyu1203

    Ok, great, I was prioritizing the probe.prb because I think it contains some more information. But I think it's safest to instead use the minimal amount of simple data we can (channel_map and channel_locations). Thanks!

    note: .prb file contains all necessary information to create channel_map.npy, channel_locations.npy, and channel_shanks.npy. It is just that .prb file stores less information than .json file so perhaps .json file is the future

  19. chrishalcrow commented on Apr 20, 2026

    @chrishalcrow
    Member

    Ok, I've finished the main features on #4529
    Could you try it on your data @chiyu1203 ? Would be great to try attaching your recording, and also not attaching your recording. Thanks!

  20. chiyu1203 commented on Apr 24, 2026

    @chiyu1203

    @chrishalcrow thank you so much for your help! Did you know where I can find that commit? I checked the "main" but could not find it.

  21. chrishalcrow commented on Apr 24, 2026

    @chrishalcrow
    Member

    Hello, the PR hasn't been merged yet, but you can try it out by checking out the PR locally. There are some instructions here: https://spikeinterface.readthedocs.io/en/stable/get_started/installation.html#testing-a-pr
    So if you have the github cli, you need to run gh pr checkout 4529 from your terminal while you're in the spikeinterface folder.

  22. chiyu1203 commented on Apr 25, 2026

    @chiyu1203

    Thanks for the guidance!!! I did not know how to use PRs. That is really helpful.
    I have tested both attaching and not attaching the recording. When attaching the recording, I can do se.read_kilosort_as_analyzer(), sorting_analyzer.set_temporary_recording and etc. However, when not attaching the recording, I still bumped into the original error

    ValueError: Recording do not match in the following attributes: ['channel_ids', 'num_samples']

    In addition, as long as I attached the recording, it does not matter if I provide probe.prb in the phy folder or not. Both works.

    Noteably, I have only tested these functions with single shank probe. As for the dual-shank probe, I have my own issue with device_channel_indices being sorted when executing set_probe(), so the map between a Recording and prb file or kilosort output was never a match. Will create a seperate issue about that.

    Out of curiosity, channel_shanks.npy is not yet used in se.read_kilosort_as_analyzer(). Would it be possible to add that?

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

    exportersquestion

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions