Automated spike sorting pipeline using SpikeInterface with Kilosort2/Mountainsort5, quality metrics, and Phy export for extracellular neural recordings.
Installer avec Codex ou Claude Copiez ce prompt, collez-le dans Codex, Claude ou un autre assistant, puis laissez-le vérifier la page du skill et l'installer pour vous.
Une commande directe contourne le prompt de vérification. Examinez la source avant de l'exécuter.
La commande reste sur une seule ligne. Faites défiler horizontalement pour la vérifier avant de la copier.
Vous préférez une copie locale ? Téléchargez les fichiers actuellement disponibles dans SkillsMP.
Affichage de SKILL.md
SKILL.md
Instructions source · Aperçu en lecture seule
name
spike-sorting
description
Automated spike sorting pipeline using SpikeInterface with Kilosort2/Mountainsort5, quality metrics, and Phy export for extracellular neural recordings.
Automated pipeline for sorting spikes from extracellular multi-electrode recordings. Covers
multi-probe loading, signal preprocessing, running Kilosort2 or Mountainsort5, computing
unit quality metrics, and exporting curated results to Phy or CSV.
When to Use This Skill
You have raw binary, NWB, SpikeGLX (.bin/.meta), or Open Ephys recordings and need to
identify individual neuron spike trains.
You want a reproducible, multi-sorter comparison pipeline rather than running a single
GUI-based sorter.
You need automated quality control: ISI violations, SNR, presence ratio, amplitude cutoff.
You want to export results for manual curation in Phy or downstream population analyses.
You are processing multi-probe (Neuropixels) datasets with hundreds of channels.
Background & Key Concepts
Extracellular Electrophysiology
A multi-electrode array records local field potentials and action potentials (spikes) from
nearby neurons. Spike sorting is the computational step that assigns each detected spike
waveform to a putative single unit.
SpikeInterface
SpikeInterface is a Python framework that provides a unified API over dozens of file formats
and sorters. Key objects:
RecordingExtractor — wraps raw data, channel geometry, and probe info.
SortingExtractor — wraps a set of unit spike trains.
WaveformExtractor / SortingAnalyzer — computes templates and extensions (PCA, metrics).
Preprocessing Steps
Step
Purpose
Bandpass filter (300–6000 Hz)
Remove LFP and high-frequency noise
Common Median Reference (CMR)
Cancel common-mode noise across channels
Whitening
Decorrelate channels for some sorters
Bad-channel removal
Prevent noisy channels from contaminating sorting
Quality Metrics
Metric
Good threshold
ISI violation ratio
< 0.05
SNR (peak-to-peak / noise)
> 3
Presence ratio
> 0.8
Amplitude cutoff
< 0.1
Firing rate (Hz)
> 0.1
Sorters
Kilosort2 — GPU-accelerated template-matching sorter; best for Neuropixels data.
Mountainsort5 — CPU-based, reproducible; good for tetrodes and lower channel counts.
Tridesclous2 — Fast CPU sorter with built-in quality control.
# Install the MATLAB Kilosort2 code separately, then point SpikeInterface to it# Alternatively, use the Kilosort Python port:
pip install kilosort # PyKilosort (Kilosort4 Python port)
Mountainsort5 (pure Python, no MATLAB required)
pip install mountainsort5
Verify Installation
import spikeinterface as si
import spikeinterface.extractors as se
import spikeinterface.preprocessing as sp
import spikeinterface.sorters as ss
import spikeinterface.postprocessing as spost
import spikeinterface.qualitymetrics as sqm
print("SpikeInterface version:", si.__version__)
print("Available sorters:", ss.available_sorters())
from spikeinterface.comparison import compare_multiple_sorters
import spikeinterface.widgets as sw
# Run all three sorters on the same recording (see Step 3)
sorting_list = [sorting_kilosort, sorting_ms5, sorting_tdc]
sorter_names = ["kilosort4", "mountainsort5", "tridesclous2"]
comparison = compare_multiple_sorters(
sorting_list=sorting_list,
name_list=sorter_names,
delta_time=0.4, # ms window for matching spikes
match_score=0.5,
)
# Agreement matrix — shows how many spikes each sorter pair shareprint(comparison.agreement_scores)
# Units agreed upon by all three sorters (high confidence)
agreement_sorting = comparison.get_agreement_sorting(minimum_agreement_count=3)
print(f"Units agreed by all 3 sorters: {agreement_sorting.get_num_units()}")
Drift Correction
from spikeinterface.preprocessing import correct_motion
# Estimate and correct probe drift (important for long recordings)
recording_motion_corrected, motion_info = correct_motion(
recording_preprocessed,
preset="nonrigid_accurate", # or "rigid_fast"
output_motion_info=True,
n_jobs=8,
)
# Visualize estimated drift
fig, ax = plt.subplots(figsize=(12, 4))
motion = motion_info["motion"]
time_axis = motion_info["temporal_bins_s"]
ax.plot(time_axis, motion.displacement[0][:, 0], lw=1)
ax.set_xlabel("Time (s)")
ax.set_ylabel("Estimated drift (µm)")
ax.set_title("Probe drift over session")
plt.tight_layout()
plt.savefig("drift_estimate.png", dpi=150)
plt.show()
# Inspect channel coherence before removal
recording_check = sp.detect_bad_channels(
recording_raw,
method="coherence+psd",
dead_channel_threshold=0.4,
noisy_channel_threshold=1.0, # raise to keep noisier channels
)
Phy Export Fails
# Ensure phy is installed
pip install phy
# Check that templates and PCA extensions are computed
python -c "
from pathlib import Path
import spikeinterface as si
analyzer = si.load_sorting_analyzer('path/to/analyzer')
print(analyzer.get_loaded_extension_names())
"