Compilation of electrophysiology sorters and preprocessing tools supported in the U19 Ephys Pipeline
uv sync # full environment (large: pulls torch with CUDA wheels)
uv tool install prek # or: pip install pre-commit
prek install # run the hooks on every commit
prek run --all-files
uv run pytest
CI runs the tests with only the dev dependency group (uv sync --only-group dev),
since the smoke tests need no GPU or sorting libraries.
Example of a slurm command to preprocess and process an ephys session (Normally all parameters will be generated from the automation pipeline):
sbatch --export=recording_process_id=28,raw_data_directory='ms81/ms81_M004/20210507/towersTask_g0/towersTask_g0_imec0',processed_data_directory='ms81/ms81_M004/20210507/towersTask_g0/towersTask_g0_imec0/recording_process_id_28',repository_dir='/scratch/gpfs/BRAINCOGS/electrophysiology_processing/BrainCogsEphysSorters',process_script_path='main_script.py' slurm_real.slurm
To test code for a new ephys session:
- Go to directory
/scratch/gpfs/BRAINCOGS. - Check that the ephys session you want to process is located on
/Data/Raw/electrophysiology/(netID)/subject_fullname/date/..(ask main developer if session is not there). - Copy parameters files (preprocess_paramset_x.json & process_paramset_x.json)located in
/ParameterFiles(x is a number that reference the ephys session). - Rename copied parameter files with a new number (preprocess_paramset_y.json & process_paramset_y.json) (y could be any number)
- Run sbatch command (from the top of this section) with following modifications:
- recording_process_id =y (Change the number to match the parameter file name modification
- raw_data_directory = Relative directory to the ephys session probe
(netID)/subject_fullname/date/.../imec(z) - processed_data_directory = Same as raw_data_directory but include recording_process_id_y (where y is the number from the parameter file)
Logs will be written:
- for Kilosort:
/Output_log/kilosort_out.log - for CatGT:
/BrainCogsEphysSortets/CatGT.log(appended every time)
Preprocess parameter file is a json file to configure preprocessing steps and select the desired sorter, main parameters are:
- clustering_method: (str) Which sorter will be used (
kilosort2,kilosort3,kilosort4; see SpikeInterface path for the others). - cat_gt: (dict) All parameters corresponding to catGT preprocessing.
- use_cat_gt: (bool) 0 if cat_gt will not be used, 1 otherwise.
- "cat_gt_params": (dict) Cat_GT params that are included in command line when it is called
- process_cluster: (str) NA, Choose which available cluster will be used for processing (tiger, spock, etc)
Example: Next preprocess param file will run Kilosort2 and use catGT:
{
"process_cluster": "tiger",
"clustering_method": "Kilosort2",
"cat_gt": {
"use_cat_gt": 1,
"cat_gt_params": {
"dir": "",
"run": "towersTask",
"g": 0,
"t": 0,
"apfilter": ["biquad",2,300,0],
"gfix": [0.40,0.10,0.02],
"extras": ["prb_3A", "prb_fld", "t_miss_ok", "ap", "gblcar", "out_prb_fld"],
"dest": ""
}
}
}
The catGT command from these params is:
./runit.sh '-dir=raw_data_directory -run=towersTask -g=0 -t=0 -prb_fld -prb=0 -t_miss_ok -ap -apfilter=biquad,2,300,0 -gblcar -gfix=0.40,0.10,0.02 -dest=processed_data_directory -out_prb_fld
Add a dredge entry as a later preprocessing step (in the DB: a PreClusterParamSteps.Step with a higher
step_number than the CatGT step). run_dredge reads the *ap.bin/*ap.meta produced by the previous step,
estimates and applies motion with SpikeInterface's dredge preset on the GPU, and writes a corrected SpikeGLX-style
ap.bin into dredge_output/, which the sorter then consumes exactly like a CatGT output.
{
"dredge": {
"preset": "dredge",
"device": "cuda",
"motion_kwargs": {},
"job_kwargs": {"n_jobs": 8},
"disable_sorter_drift": true
}
}
- preset: SpikeInterface
correct_motionpreset (dredge,dredge_fast,kilosort_like, ...). - device:
cuda(falls back tocpuif no GPU) orcpu. - motion_kwargs / job_kwargs: forwarded to
correct_motion(estimation options / parallel chunk options). - disable_sorter_drift: (bool, default
true) when true the sorter stage setsnblocks=0(KS3/KS4) orreorder=0(KS2) so motion is corrected only once. A sort run through SpikeInterface (a containersorter_versionor a namespaced paramset, see below) getsdo_correction=falseinstead (KS2.5/KS3/KS4; SpikeInterface's KS2 has no drift option). Set tofalseto keep Kilosort's own drift correction on top of DREDge.
Process parameter file is a json file to configure sorter. To configure this file refer to each sorter documentation:
A process parameter file can pin the sorter build with a sorter_version key from
sorter_registry.json, the allow-list of versions a job can run:
{
"clustering_method": "kilosort3",
"sorter_version": "kilosort3@3.0.2",
"detect_threshold": 6
}
- No
sorter_version(ornull): unchanged behavior (KS4 from the job env, KS2/KS3 through MATLAB). nativeentries (e.g.kilosort4@4.1.7) run in the job env, and the job fails if the installedkilosortisn't that exact version, so a shared env can't be upgraded silently.containerentries run the sorter through SpikeInterface inside a cached Apptainer image, so KS2/2.5/3 don't need a MATLAB license. The remaining params are SpikeInterface sorter params (detect_threshold, ...), not Kilosortops, and the probe comes from the SpikeGLX.metarather than the chanmap file. The Kilosort/phy files end up directly in<clustering_method>_output/, as for a native run; SpikeInterface's own files are in itsspikeinterface/subfolder. Kilosort 2.5 has no native runner, so a legacykilosort2_5paramset needs a containersorter_version.- Unknown keys, a
clustering_methodthat doesn't match the key, or an image that isn't cached fail the job before sorting starts. What ran is recorded insorter_provenance.jsonnext to the sorter output.
python -m u19_sorting.apptainer_cache (below) cannot build the Kilosort images: they ship Python 3.9
and spikeinterface >= 0.104 needs Python >= 3.10, and on spock its %post step fails anyway (no
/etc/subuid entry, so Apptainer falls back to its bundled fakeroot: GLIBC_2.34' not found (required by /.singularity.d/libs/faked)). Use scripts/sorter_image.sh instead, from the checkout with .venv
synced:
scripts/sorter_image.sh fetch kilosort2@2.0.2 # login node: layers + wheels into the caches
sbatch scripts/sorter_image.sh build kilosort2@2.0.2 # compute node, offline, ~6 min
The image gets a uv Python 3.13 venv with the spikeinterface, neo, probeinterface and numpy
versions of .venv, first on PATH; the sorter keeps the image's own runtime. Unpacking and packing
are done on the node's local disk: on the login VM or on NFS they take hours. Jobs run each command
in the image with apptainer exec (u19_sorting/apptainer_exec.py) rather than in the Apptainer
instance SpikeInterface would start: on spock such instances were killed seconds into the sort on some
nodes.
Compute nodes have no internet, so they never pull images. Build them once on a login node into shared storage:
python -m u19_sorting.apptainer_cache --dry-run # what's missing
python -m u19_sorting.apptainer_cache # build all missing images (or pass keys)
python -m u19_sorting.apptainer_cache --check # exit 1 if any image is missing
Each image is the digest-pinned SpikeInterface docker image with the pinned spikeinterface[full] installed on top
(jobs run with installation_mode="no-install", so nothing is pip-installed at run time). The host's
spikeinterface must match the entry's spikeinterface version. Images are built next to their final
location and renamed into place read-only; existing images are never rebuilt. Add --fakeroot if the
cluster requires it for apptainer build.
| Setting | Default | Override |
|---|---|---|
| Registry | sorter_registry.json in this repo |
U19_SORTER_REGISTRY |
Images (.sif) |
apptainer/sif next to the checkout: /scratch/gpfs/BRAINCOGS/electrophysiology_processing/apptainer/sif on della, AutomaticPipelineProcessing/electrophysiology_processing/apptainer/sif on spock |
U19_APPTAINER_SIF_DIR |
| Apptainer layer cache | apptainer/cache next to the checkout |
U19_APPTAINER_CACHEDIR |
Each container entry pins the spikeinterface version that uv.lock installs on the host (a test checks
this): the host serializes the recording and the image's SpikeInterface loads it. After a lock update that
changes spikeinterface, add new entries (new .sif names) for the new version and build them.
To add a version: append a new key to sorter_registry.json (never edit or reuse an existing key, since past
jobs' provenance points at it), then run python -m u19_sorting.apptainer_cache <key> on a login node.
An image is only rebuilt when its .sif file is missing, so if the build recipe in apptainer_cache.py changes,
new entries need new .sif names.
Next to the CatGT + Kilosort path, a job can preprocess and sort through SpikeInterface. A job that uses neither of the two pieces below runs exactly as before.
A preprocessing step whose method is spikeinterface takes a list of SpikeInterface preprocessing functions,
applied in list order:
{
"spikeinterface": {
"steps": [
{"name": "phase_shift", "kwargs": {}},
{"name": "highpass_filter", "kwargs": {"freq_min": 300}},
{"name": "common_reference", "kwargs": {"operator": "median", "reference": "global"}},
{"name": "correct_motion", "kwargs": {"preset": "dredge"}}
],
"job_kwargs": {"n_jobs": 8},
"materialize": false,
"disable_sorter_drift": true
}
}
- steps: each
namemust be injob_spec.SI_STEP_NAMES, a list of functions that keep the channel count and the sampling rate (bandpass_filter,highpass_filter,common_reference,phase_shift,whiten, ...).kwargsgo to that function.correct_motionis the motion step: itspresetdefaults todredgeand its motion estimation runs oncudawhen available (setestimate_motion_kwargs.deviceto change that). - job_kwargs: (optional) SpikeInterface job kwargs for
correct_motionand for writing the result. Withoutn_jobs, the number of cores slurm gave the job (SLURM_CPUS_PER_TASK) is used, here and for the sorter's and the postprocessing's job kwargs, so a paramset does not have to know the job's resources. - materialize: (bool, default
false) see below. - disable_sorter_drift: (bool, default
true) as for DREDge: if the list has acorrect_motionstep, the sorter's own drift correction is turned off. When the job has more than one motion step, the first one decides.
spikeinterface, catgt and dredge steps chain in the order of the preprocess list: each reads the SpikeGLX
ap.bin/ap.meta the previous step wrote (or the raw run). A spikeinterface step is written to disk, as an
int16 SpikeGLX ap.bin with the sync channel appended back and a copy of the ap.meta, in
spikeinterface_output/ (spikeinterface_output_2/, ... for later ones). The exception is a step that is the
last preprocessing step of a job with a namespaced clustering paramset (below): unless it sets
"materialize": true, nothing is written and the steps are applied lazily to the recording handed to the sorter.
An empty step list is never written. Because a written copy is rounded to int16, steps that rescale the traces
(whiten, zscore, scale, ...) need a scale that survives that (for example int_scale for whiten and
zscore). Like the CatGT and DREDge outputs, spikeinterface_output* folders are deleted at the end of the job.
SpikeInterface documents how to reproduce both in its preprocessing guide (How to implement "IBL destriping" or "SpikeGLX CatGT" in SpikeInterface). As step lists:
CatGT (phase_shift is CatGT's tshift, the global median reference is -gblcar; the high-pass stands in for
-apfilter=biquad,2,300,0, which is not part of SpikeInterface's recipe):
{"steps": [
{"name": "phase_shift", "kwargs": {}},
{"name": "highpass_filter", "kwargs": {"freq_min": 300}},
{"name": "common_reference", "kwargs": {"operator": "median", "reference": "global"}}
]}
CatGT's -gfix (removal of fast, large transients seen on many channels at once) has no counterpart in this
list.
IBL destriping (the guide passes n_channel_pad=60 to highpass_filter, which spikeinterface 0.105 refuses;
that argument belongs to highpass_spatial_filter, where 60 is the default):
{"steps": [
{"name": "highpass_filter", "kwargs": {}},
{"name": "phase_shift", "kwargs": {}},
{"name": "detect_and_interpolate_bad_channels", "kwargs": {}},
{"name": "highpass_spatial_filter", "kwargs": {}}
]}
A namespaced clustering paramset (next section) can carry its own preprocessing step list. With the
Nothing preprocess method selected, that single paramset then describes the entire run, and all of it goes
through SpikeInterface: the raw SpikeGLX run is read, the steps are applied lazily, the sorter (Kilosort
included) is run with run_sorter, and the postprocessing follows. Nothing is written between the stages.
{
"clustering_method": "kilosort4",
"sorter_version": "kilosort4@4.1.7",
"preprocessing": {
"steps": [
{"name": "phase_shift", "kwargs": {}},
{"name": "highpass_filter", "kwargs": {"freq_min": 300}},
{"name": "common_reference", "kwargs": {"operator": "median", "reference": "global"}}
]
},
"sorter_params": {"Th_universal": 9},
"si_params": {"save_preprocessed_copy": true, "n_jobs": 8},
"postprocessing": {"extensions": {"quality_metrics": {}}}
}
preprocessing takes the same keys as the spikeinterface preprocessing step, except materialize (it is
always lazy). If the preprocess file also ends with a lazy spikeinterface step, that one runs first.
A process parameter file without a sorter_params key is a legacy paramset: every key except
clustering_method and sorter_version is passed to the sorter, exactly as before. clustering_method must be
kilosort4, kilosort3, kilosort2 or (with a container sorter_version) kilosort2_5.
{
"clustering_method": "kilosort4",
"n_chan_bin": 385,
"Th_universal": 9
}
A process parameter file with a sorter_params key is a namespaced paramset and is sorted through
SpikeInterface's run_sorter, in the job environment or, with a container sorter_version, in its Apptainer
image. The probe comes from the SpikeGLX .meta, not from the chanmap file.
{
"clustering_method": "kilosort4",
"sorter_version": "kilosort4@4.1.7",
"sorter_params": {"Th_universal": 9},
"si_params": {"save_preprocessed_copy": true, "n_jobs": 8},
"postprocessing": {
"extensions": {"quality_metrics": {}},
"export": null,
"job_kwargs": {"n_jobs": 8}
}
}
- Only
clustering_method,sorter_version,sorter_params,si_paramsandpostprocessingare allowed at the top level.clustering_methodis one of the keys ofconfig.si_sorters(kilosort2,kilosort2_5,kilosort3,kilosort4,mountainsort5,spykingcircus2,tridesclous2,lupin,simple). - sorter_params: the sorter's own settings. For Kilosort 4 only Kilosort settings are accepted;
n_chan_binandfscome from the recording. - preprocessing: (optional) a SpikeInterface step list applied lazily before the sort; see "The whole run through SpikeInterface, from one paramset" above.
- resources: (optional) what the cluster job should ask slurm for, e.g.
{"cpus": 16, "gpus": 1, "mem": "120G", "time": "12:00:00"}. U19-pipeline-python reads it when it writes the slurm file; this repo ignores it and takes its worker count from the cores slurm granted. Without it a SpikeInterface job asks for the largestn_jobsnamed in its paramsets, or the cluster default (4 cores and 1 GPU on spock)."gpus": 0is for sorters that do not use a GPU. Kilosort uses one GPU however many are requested. - si_params: SpikeInterface's options for the sorter wrapper (for Kilosort 4:
do_correction,skip_kilosort_preprocessing,save_preprocessed_copy,delete_recording_dat, ...) and job kwargs (n_jobs, ...). For the other sorters SpikeInterface does not separate the two, so either namespace takes any of the wrapper's params. - A key in the wrong namespace, an unknown key, a key in both, or a
run_sorterargument the job sets itself (folder,singularity_image, ...) fails the job before sorting starts. - For the Kilosort sorters
delete_recording_datdefaults totrue, so SpikeInterface's raw-sizedrecording.datcopy does not stay in the output. - After a motion-correction step, Kilosort 2.5/3/4 get
do_correction=false(seedisable_sorter_drift).
clustering_method: "SpikeInterface" is not a sorter: it used to skip sorting and leave an empty output folder,
and now fails the job with a message saying to name the sorter and use sorter_params.
- extensions:
{name: kwargs}of sorting analyzer extensions to compute (quality_metrics,template_metrics, ...). The extensions they depend on are added. - export:
"phy"ornull. A Kilosort sorter's own folder already is the phy folder, so nothing is exported over it; the other sorters are always exported to phy, whatever this says. - job_kwargs: SpikeInterface job kwargs for the analyzer and the export.
Postprocessing runs when postprocessing is not empty or the sorter is not Kilosort.
<clustering_method>_output/ is the Kilosort/phy folder U19-pipeline-python loads, whichever path made it:
- Kilosort through SpikeInterface: the sorter's phy files are moved up from SpikeInterface's
sorter_output/into<clustering_method>_output/, andparams.pyis repointed at their new place. - Other sorters: the sorting is exported to phy there and adjusted to what the DataJoint element's Kilosort
reader and the IBL step expect: dense
templates.npywithtemplates_ind.npy, identitywhitening_mat.npy/whitening_mat_inv.npy,cluster_group.tsvlabelsunsortedreplaced bymua, and positiveamplitudes.npy. - SpikeInterface's own files are in
<clustering_method>_output/spikeinterface/: therun_sorterlog and params (and, for the other sorters, their nativesorter_output/), the motion folder of a lazycorrect_motionstep, the sorting analyzer (analyzer/) andquality_metrics.csv/template_metrics.csv. Nometrics.csvis written next to the phy files, since the element reads that file as a sign that ecephys quality control ran.
As BRAINCOGS we have a common directory in the Tiger Cluster for processing data:
/scratch/gpfs/BRAINCOGS
These are the main directories that can be found on it:
-
/Data→ Replicate /braininit/Data directory path (raw sessions, processed sessions, etc) -
/electrophysiology_processing→ All repositories for processing ephys/BrainCogsEphysSortersCommon library to process ephys in all BrainCogs (this Repository)
-
/ParameterFiles→ Preprocess and process params files for processing sessions (all modalities) -
/Output_log→ Output data from processing sessions (all modalities)
These are the main directories of the repository
-
/preprocess_libs→ All libraries we are going to use for preprocessing (CatGt, etc) -
/sorters→ All repositories from sorter algorithm libraries (Kilosort, SpikeInterface, etc.) -
/u19_sorting→ Call to all preprocess and process (sorters) codes.- preprocess_wrappers.py Wrappers to call all preprocess libraries with corresponding params
- sorters_wrappers.py Wrappers to call all sorters libraries with corresponding params
-
main_script.py → Script that is executed on runtime
Since this is a repository with submodules it is needed to add --recurse-submodules when cloning it. So log into tiger and execute:
git clone --recurse-submodules git@github.com:BrainCOGS/BrainCogsEphysSorters.git
And for branches, add the flag
git clone -b tmp --single-branch --recurse-submodules https://github.com/BrainCOGS/BrainCogsEphysSorters
For preprocessing, we currently support CatGT:
cd ./CatGT-linux/
chmod +x ./install.sh
./install.sh
-
User config files (channel maps and sorting config files) should be deposited in
user_config_files. -
The two example channel maps
chanMap_npx1_staggered.matandchanMap_npx2_hStripe_bottom2.matwere written for staggered Neuropixel 1.0 probes, and the bottom horizontal strip of a 4-shank Neuropixel 2.0 probe. -
The example config file
config_manuel.mis adjusted and mildly optimized from the file\eMouse_drift\config_eMouse_drift_KS2.m, which is part of the kilosort repository. -
A test script that uses
kilosortbatch, a wrapper around kilosort, is in the folder/sandbox/. It plays well withnpy-matlabversionb7b0a4eandkilosortversion1a1fd3a. -
Once kilosort has run, waveforms should be inspected with phy, e.g.
phy template-gui D:\NPX_DATA\manuel\tmp\TowersTask_g0_imec2\params.py -
TODO: ks2_run is not needed anymore. Some general cleanup.