K-Dense-AI/scientific-agent-skills / skills/neuropixels-analysis
neuropixels-analysis
VerifiedAnalyzes Neuropixels extracellular recordings end-to-end with SpikeInterface. Covers loading SpikeGLX/Open Ephys/NWB data, preprocessing, drift/motion correction, Kilosort4 (and CPU) spike sorting, quality metrics, and unit curation (threshold-based, model-based UnitRefine, and AI-assisted visual review). Use when working with Neuropixels 1.0/2.0 recordings, spike sorting, or extracellular electrophysiology analysis.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 19.7 KB |
| assets/analysis_template.py | script | 9.3 KB |
| references/AI_CURATION.md | markdown | 6.4 KB |
| references/ANALYSIS.md | markdown | 11.1 KB |
| references/AUTOMATED_CURATION.md | markdown | 6.3 KB |
| references/MOTION_CORRECTION.md | markdown | 4.6 KB |
| references/PREPROCESSING.md | markdown | 4.8 KB |
| references/QUALITY_METRICS.md | markdown | 6.2 KB |
| references/SPIKE_SORTING.md | markdown | 5.8 KB |
| references/api_reference.md | markdown | 7.9 KB |
| references/plotting_guide.md | markdown | 11.7 KB |
| references/standard_workflow.md | markdown | 9.9 KB |
| scripts/_common.py | script | 2.7 KB |
| scripts/compute_metrics.py | script | 5.5 KB |
| scripts/explore_recording.py | script | 5.7 KB |
| scripts/export_to_phy.py | script | 2.6 KB |
| scripts/neuropixels_pipeline.py | script | 12.5 KB |
| scripts/preprocess_recording.py | script | 4.7 KB |
| scripts/run_sorting.py | script | 2.7 KB |
scripts/preprocess_recording.py
View on GitHub#!/usr/bin/env python
"""
Preprocess Neuropixels recording.
Usage:
python preprocess_recording.py /path/to/data --output preprocessed/ --format spikeglx
"""
import argparse
from pathlib import Path
import spikeinterface.full as si
from _common import validate_recording, apply_phase_correction, reference_by_shank
def preprocess_recording(
input_path: str,
output_dir: str,
format: str = 'auto',
stream_name: str = None,
freq_min: float = 300,
freq_max: float = 6000,
phase_shift: bool = True,
common_ref: bool = True,
detect_bad: bool = True,
n_jobs: int = -1,
):
"""Preprocess a Neuropixels recording."""
print(f"Loading recording from: {input_path}")
# Identify acquisition format explicitly; do not hide reader errors as fallback loads.
source = Path(input_path)
if format == 'auto':
if source.suffix.lower() == '.nwb':
format = 'nwb'
elif any(source.rglob('*.ap.meta')):
format = 'spikeglx'
elif any(source.rglob('*.oebin')):
format = 'openephys'
else:
format = 'saved'
if format == 'spikeglx':
recording = si.read_spikeglx(input_path, stream_name=stream_name or 'imec0.ap')
elif format == 'openephys':
recording = si.read_openephys(input_path, stream_name=stream_name)
elif format == 'nwb':
recording = si.read_nwb(input_path)
elif format == 'saved':
recording = si.load(input_path)
else:
raise ValueError(f"Unknown format: {format}")
validate_recording(recording)
if not 0 < freq_min < freq_max < recording.get_sampling_frequency() / 2:
raise ValueError("Require 0 < freq_min < freq_max < Nyquist frequency.")
print(f"Recording: {recording.get_num_channels()} channels, {recording.get_total_duration():.1f}s")
# Preprocessing chain
rec = recording
# Bandpass filter
print(f"Applying bandpass filter ({freq_min}-{freq_max} Hz)...")
rec = si.bandpass_filter(rec, freq_min=freq_min, freq_max=freq_max)
# Phase shift correction (for Neuropixels ADC)
if phase_shift:
print("Applying phase shift correction...")
rec = apply_phase_correction(rec)
# Bad channel detection
if detect_bad:
print("Detecting bad channels...")
bad_channel_ids, bad_labels = si.detect_bad_channels(rec)
if len(bad_channel_ids) > 0:
print(f" Removing {len(bad_channel_ids)} bad channels: {bad_channel_ids[:10]}...")
rec = rec.remove_channels(bad_channel_ids)
# Common median reference
if common_ref:
print("Applying common median reference...")
rec = reference_by_shank(rec)
# Save preprocessed
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
print(f"Saving preprocessed recording to: {output_path}")
rec = rec.save(folder=output_path / 'preprocessed', n_jobs=n_jobs)
# Save probe info
probe = rec.get_probe()
if probe is not None:
from probeinterface import write_probeinterface
write_probeinterface(output_path / 'probe.json', probe)
print("Done!")
print(f" Output channels: {rec.get_num_channels()}")
print(f" Output duration: {rec.get_total_duration():.1f}s")
return rec
def main():
parser = argparse.ArgumentParser(description='Preprocess Neuropixels recording')
parser.add_argument('input', help='Path to input recording')
parser.add_argument('--output', '-o', default='preprocessed/', help='Output directory')
parser.add_argument('--format', '-f', default='auto', choices=['auto', 'spikeglx', 'openephys', 'nwb'])
parser.add_argument('--stream-name', default=None, help='Stream name for multi-probe recordings (e.g. imec0.ap)')
parser.add_argument('--freq-min', type=float, default=300, help='Highpass cutoff (Hz)')
parser.add_argument('--freq-max', type=float, default=6000, help='Lowpass cutoff (Hz)')
parser.add_argument('--no-phase-shift', action='store_true', help='Skip phase shift correction')
parser.add_argument('--no-cmr', action='store_true', help='Skip common median reference')
parser.add_argument('--no-bad-channel', action='store_true', help='Skip bad channel detection')
parser.add_argument('--n-jobs', type=int, default=-1, help='Number of parallel jobs')
args = parser.parse_args()
preprocess_recording(
args.input,
args.output,
format=args.format,
stream_name=args.stream_name,
freq_min=args.freq_min,
freq_max=args.freq_max,
phase_shift=not args.no_phase_shift,
common_ref=not args.no_cmr,
detect_bad=not args.no_bad_channel,
n_jobs=args.n_jobs,
)
if __name__ == '__main__':
main()
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirements | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |