neuropixels-analysis

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Neuropixels Data Analysis

Neuropixels神经数据分析

Overview

概述

Comprehensive toolkit for analyzing Neuropixels high-density neural recordings using current best practices from SpikeInterface, Allen Institute, and International Brain Laboratory (IBL). Supports the full workflow from raw data to publication-ready curated units.
这是一套基于SpikeInterface、Allen Institute和International Brain Laboratory (IBL)当前最佳实践打造的Neuropixels高密度神经记录综合分析工具包,支持从原始数据到可用于发表的筛选后单元的完整工作流。

When to Use This Skill

适用场景

This skill should be used when:
  • Working with Neuropixels recordings (.ap.bin, .lf.bin, .meta files)
  • Loading data from SpikeGLX, Open Ephys, or NWB formats
  • Preprocessing neural recordings (filtering, CAR, bad channel detection)
  • Detecting and correcting motion/drift in recordings
  • Running spike sorting (Kilosort4, SpykingCircus2, Mountainsort5)
  • Computing quality metrics (SNR, ISI violations, presence ratio)
  • Curating units using Allen/IBL criteria
  • Creating visualizations of neural data
  • Exporting results to Phy or NWB
本技能适用于以下场景:
  • 处理Neuropixels记录数据(.ap.bin、.lf.bin、.meta文件)
  • 从SpikeGLX、Open Ephys或NWB格式加载数据
  • 神经记录预处理(滤波、共参考、坏通道检测)
  • 检测并校正记录中的运动/漂移
  • 运行Spike分选(Kilosort4、SpykingCircus2、Mountainsort5)
  • 计算质量指标(SNR、ISI违规率、存在率)
  • 基于Allen/IBL标准筛选单元
  • 创建神经数据可视化图表
  • 将结果导出至Phy或NWB格式

Supported Hardware & Formats

支持的硬件与格式

ProbeElectrodesChannelsNotes
Neuropixels 1.0960384Requires phase_shift correction
Neuropixels 2.0 (single)1280384Denser geometry
Neuropixels 2.0 (4-shank)5120384Multi-region recording
FormatExtensionReader
SpikeGLX
.ap.bin
,
.lf.bin
,
.meta
si.read_spikeglx()
Open Ephys
.continuous
,
.oebin
si.read_openephys()
NWB
.nwb
si.read_nwb()
探针电极数通道数说明
Neuropixels 1.0960384需要phase_shift校正
Neuropixels 2.0 (单针)1280384更密集的几何结构
Neuropixels 2.0 (4针)5120384多区域记录
格式扩展名读取函数
SpikeGLX
.ap.bin
,
.lf.bin
,
.meta
si.read_spikeglx()
Open Ephys
.continuous
,
.oebin
si.read_openephys()
NWB
.nwb
si.read_nwb()

Quick Start

快速开始

Basic Import and Setup

基础导入与设置

python
import spikeinterface.full as si
import neuropixels_analysis as npa
python
import spikeinterface.full as si
import neuropixels_analysis as npa

Configure parallel processing

配置并行处理

job_kwargs = dict(n_jobs=-1, chunk_duration='1s', progress_bar=True)
undefined
job_kwargs = dict(n_jobs=-1, chunk_duration='1s', progress_bar=True)
undefined

Loading Data

加载数据

python
undefined
python
undefined

SpikeGLX (most common)

SpikeGLX(最常用)

recording = si.read_spikeglx('/path/to/data', stream_id='imec0.ap')
recording = si.read_spikeglx('/path/to/data', stream_id='imec0.ap')

Open Ephys (common for many labs)

Open Ephys(多个实验室常用)

recording = si.read_openephys('/path/to/Record_Node_101/')
recording = si.read_openephys('/path/to/Record_Node_101/')

Check available streams

查看可用流

streams, ids = si.get_neo_streams('spikeglx', '/path/to/data') print(streams) # ['imec0.ap', 'imec0.lf', 'nidq']
streams, ids = si.get_neo_streams('spikeglx', '/path/to/data') print(streams) # ['imec0.ap', 'imec0.lf', 'nidq']

For testing with subset of data

测试时使用数据子集

recording = recording.frame_slice(0, int(60 * recording.get_sampling_frequency()))
undefined
recording = recording.frame_slice(0, int(60 * recording.get_sampling_frequency()))
undefined

Complete Pipeline (One Command)

完整流程(一键执行)

python
undefined
python
undefined

Run full analysis pipeline

运行完整分析流程

results = npa.run_pipeline( recording, output_dir='output/', sorter='kilosort4', curation_method='allen', )
results = npa.run_pipeline( recording, output_dir='output/', sorter='kilosort4', curation_method='allen', )

Access results

访问结果

sorting = results['sorting'] metrics = results['metrics'] labels = results['labels']
undefined
sorting = results['sorting'] metrics = results['metrics'] labels = results['labels']
undefined

Standard Analysis Workflow

标准分析工作流

1. Preprocessing

1. 预处理

python
undefined
python
undefined

Recommended preprocessing chain

推荐的预处理链

rec = si.highpass_filter(recording, freq_min=400) rec = si.phase_shift(rec) # Required for Neuropixels 1.0 bad_ids, _ = si.detect_bad_channels(rec) rec = rec.remove_channels(bad_ids) rec = si.common_reference(rec, operator='median')
rec = si.highpass_filter(recording, freq_min=400) rec = si.phase_shift(rec) # Neuropixels 1.0必需 bad_ids, _ = si.detect_bad_channels(rec) rec = rec.remove_channels(bad_ids) rec = si.common_reference(rec, operator='median')

Or use our wrapper

或使用我们的封装函数

rec = npa.preprocess(recording)
undefined
rec = npa.preprocess(recording)
undefined

2. Check and Correct Drift

2. 检查并校正漂移

python
undefined
python
undefined

Check for drift (always do this!)

检查漂移(务必执行!)

motion_info = npa.estimate_motion(rec, preset='kilosort_like') npa.plot_drift(rec, motion_info, output='drift_map.png')
motion_info = npa.estimate_motion(rec, preset='kilosort_like') npa.plot_drift(rec, motion_info, output='drift_map.png')

Apply correction if needed

必要时应用校正

if motion_info['motion'].max() > 10: # microns rec = npa.correct_motion(rec, preset='nonrigid_accurate')
undefined
if motion_info['motion'].max() > 10: # 微米 rec = npa.correct_motion(rec, preset='nonrigid_accurate')
undefined

3. Spike Sorting

3. Spike分选

python
undefined
python
undefined

Kilosort4 (recommended, requires GPU)

Kilosort4(推荐,需要GPU)

sorting = si.run_sorter('kilosort4', rec, folder='ks4_output')
sorting = si.run_sorter('kilosort4', rec, folder='ks4_output')

CPU alternatives

CPU替代方案

sorting = si.run_sorter('tridesclous2', rec, folder='tdc2_output') sorting = si.run_sorter('spykingcircus2', rec, folder='sc2_output') sorting = si.run_sorter('mountainsort5', rec, folder='ms5_output')
sorting = si.run_sorter('tridesclous2', rec, folder='tdc2_output') sorting = si.run_sorter('spykingcircus2', rec, folder='sc2_output') sorting = si.run_sorter('mountainsort5', rec, folder='ms5_output')

Check available sorters

查看可用的分选器

print(si.installed_sorters())
undefined
print(si.installed_sorters())
undefined

4. Postprocessing

4. 后处理

python
undefined
python
undefined

Create analyzer and compute all extensions

创建分析器并计算所有扩展模块

analyzer = si.create_sorting_analyzer(sorting, rec, sparse=True)
analyzer.compute('random_spikes', max_spikes_per_unit=500) analyzer.compute('waveforms', ms_before=1.0, ms_after=2.0) analyzer.compute('templates', operators=['average', 'std']) analyzer.compute('spike_amplitudes') analyzer.compute('correlograms', window_ms=50.0, bin_ms=1.0) analyzer.compute('unit_locations', method='monopolar_triangulation') analyzer.compute('quality_metrics')
metrics = analyzer.get_extension('quality_metrics').get_data()
undefined
analyzer = si.create_sorting_analyzer(sorting, rec, sparse=True)
analyzer.compute('random_spikes', max_spikes_per_unit=500) analyzer.compute('waveforms', ms_before=1.0, ms_after=2.0) analyzer.compute('templates', operators=['average', 'std']) analyzer.compute('spike_amplitudes') analyzer.compute('correlograms', window_ms=50.0, bin_ms=1.0) analyzer.compute('unit_locations', method='monopolar_triangulation') analyzer.compute('quality_metrics')
metrics = analyzer.get_extension('quality_metrics').get_data()
undefined

5. Curation

5. 单元筛选

python
undefined
python
undefined

Allen Institute criteria (conservative)

Allen Institute标准(保守型)

good_units = metrics.query(""" presence_ratio > 0.9 and isi_violations_ratio < 0.5 and amplitude_cutoff < 0.1 """).index.tolist()
good_units = metrics.query(""" presence_ratio > 0.9 and isi_violations_ratio < 0.5 and amplitude_cutoff < 0.1 """).index.tolist()

Or use automated curation

或使用自动化筛选

labels = npa.curate(metrics, method='allen') # 'allen', 'ibl', 'strict'
undefined
labels = npa.curate(metrics, method='allen') # 'allen', 'ibl', 'strict'
undefined

6. AI-Assisted Curation (For Uncertain Units)

6. AI辅助筛选(针对不确定单元)

When using this skill with Claude Code, Claude can directly analyze waveform plots and provide expert curation decisions. For programmatic API access:
python
from anthropic import Anthropic
当与Claude Code配合使用时,Claude可直接分析波形图并提供专业筛选决策。对于程序化API访问:
python
from anthropic import Anthropic

Setup API client

配置API客户端

client = Anthropic()
client = Anthropic()

Analyze uncertain units visually

可视化分析不确定单元

uncertain = metrics.query('snr > 3 and snr < 8').index.tolist()
for unit_id in uncertain: result = npa.analyze_unit_visually(analyzer, unit_id, api_client=client) print(f"Unit {unit_id}: {result['classification']}") print(f" Reasoning: {result['reasoning'][:100]}...")

**Claude Code Integration**: When running within Claude Code, ask Claude to examine waveform/correlogram plots directly - no API setup required.
uncertain = metrics.query('snr > 3 and snr < 8').index.tolist()
for unit_id in uncertain: result = npa.analyze_unit_visually(analyzer, unit_id, api_client=client) print(f"单元 {unit_id}: {result['classification']}") print(f" 推理依据: {result['reasoning'][:100]}...")

**Claude Code集成**:在Claude Code中运行时,可直接要求Claude检查波形/相关图,无需配置API。

7. Generate Analysis Report

7. 生成分析报告

python
undefined
python
undefined

Generate comprehensive HTML report with visualizations

生成包含可视化内容的综合HTML报告

report_dir = npa.generate_analysis_report(results, 'output/')
report_dir = npa.generate_analysis_report(results, 'output/')

Opens report.html with summary stats, figures, and unit table

打开report.html查看汇总统计、图表和单元表格

Print formatted summary to console

在控制台打印格式化汇总信息

npa.print_analysis_summary(results)
undefined
npa.print_analysis_summary(results)
undefined

8. Export Results

8. 导出结果

python
undefined
python
undefined

Export to Phy for manual review

导出至Phy进行人工审核

si.export_to_phy(analyzer, output_folder='phy_export/', compute_pc_features=True, compute_amplitudes=True)
si.export_to_phy(analyzer, output_folder='phy_export/', compute_pc_features=True, compute_amplitudes=True)

Export to NWB

导出至NWB

from spikeinterface.exporters import export_to_nwb export_to_nwb(rec, sorting, 'output.nwb')
from spikeinterface.exporters import export_to_nwb export_to_nwb(rec, sorting, 'output.nwb')

Save quality metrics

保存质量指标

metrics.to_csv('quality_metrics.csv')
undefined
metrics.to_csv('quality_metrics.csv')
undefined

Common Pitfalls and Best Practices

常见误区与最佳实践

  1. Always check drift before spike sorting - drift > 10μm significantly impacts quality
  2. Use phase_shift for Neuropixels 1.0 probes (not needed for 2.0)
  3. Save preprocessed data to avoid recomputing - use
    rec.save(folder='preprocessed/')
  4. Use GPU for Kilosort4 - it's 10-50x faster than CPU alternatives
  5. Review uncertain units manually - automated curation is a starting point
  6. Combine metrics with AI - use metrics for clear cases, AI for borderline units
  7. Document your thresholds - different analyses may need different criteria
  8. Export to Phy for critical experiments - human oversight is valuable
  1. 务必在Spike分选前检查漂移 - 漂移>10μm会严重影响分选质量
  2. Neuropixels 1.0探针需使用phase_shift(2.0无需)
  3. 保存预处理后的数据避免重复计算 - 使用
    rec.save(folder='preprocessed/')
  4. Kilosort4使用GPU - 比CPU方案快10-50倍
  5. 人工审核不确定单元 - 自动化筛选仅作为起点
  6. 结合指标与AI - 明确案例用指标,边缘案例用AI
  7. 记录你的阈值设置 - 不同分析可能需要不同标准
  8. 关键实验导出至Phy - 人工监督很有价值

Key Parameters to Adjust

关键可调参数

Preprocessing

预处理

  • freq_min
    : Highpass cutoff (300-400 Hz typical)
  • detect_threshold
    : Bad channel detection sensitivity
  • freq_min
    : 高通滤波截止频率(典型值300-400 Hz)
  • detect_threshold
    : 坏通道检测灵敏度

Motion Correction

运动校正

  • preset
    : 'kilosort_like' (fast) or 'nonrigid_accurate' (better for severe drift)
  • preset
    : 'kilosort_like'(快速)或 'nonrigid_accurate'(严重漂移时效果更好)

Spike Sorting (Kilosort4)

Spike分选(Kilosort4)

  • batch_size
    : Samples per batch (30000 default)
  • nblocks
    : Number of drift blocks (increase for long recordings)
  • Th_learned
    : Detection threshold (lower = more spikes)
  • batch_size
    : 每批样本数(默认30000)
  • nblocks
    : 漂移块数量(长记录需增加)
  • Th_learned
    : 检测阈值(值越低,检测到的spike越多)

Quality Metrics

质量指标

  • snr_threshold
    : Signal-to-noise cutoff (3-5 typical)
  • isi_violations_ratio
    : Refractory violations (0.01-0.5)
  • presence_ratio
    : Recording coverage (0.5-0.95)
  • snr_threshold
    : 信噪比阈值(典型值3-5)
  • isi_violations_ratio
    : 不应期违规率(0.01-0.5)
  • presence_ratio
    : 记录覆盖率(0.5-0.95)

Bundled Resources

配套资源

scripts/preprocess_recording.py

scripts/preprocess_recording.py

Automated preprocessing script:
bash
python scripts/preprocess_recording.py /path/to/data --output preprocessed/
自动化预处理脚本:
bash
python scripts/preprocess_recording.py /path/to/data --output preprocessed/

scripts/run_sorting.py

scripts/run_sorting.py

Run spike sorting:
bash
python scripts/run_sorting.py preprocessed/ --sorter kilosort4 --output sorting/
运行Spike分选:
bash
python scripts/run_sorting.py preprocessed/ --sorter kilosort4 --output sorting/

scripts/compute_metrics.py

scripts/compute_metrics.py

Compute quality metrics and apply curation:
bash
python scripts/compute_metrics.py sorting/ preprocessed/ --output metrics/ --curation allen
计算质量指标并应用筛选:
bash
python scripts/compute_metrics.py sorting/ preprocessed/ --output metrics/ --curation allen

scripts/export_to_phy.py

scripts/export_to_phy.py

Export to Phy for manual curation:
bash
python scripts/export_to_phy.py metrics/analyzer --output phy_export/
导出至Phy进行人工筛选:
bash
python scripts/export_to_phy.py metrics/analyzer --output phy_export/

assets/analysis_template.py

assets/analysis_template.py

Complete analysis template. Copy and customize:
bash
cp assets/analysis_template.py my_analysis.py
完整分析模板,复制并自定义:
bash
cp assets/analysis_template.py my_analysis.py

Edit parameters and run

编辑参数并运行

python my_analysis.py
undefined
python my_analysis.py
undefined

reference/standard_workflow.md

reference/standard_workflow.md

Detailed step-by-step workflow with explanations for each stage.
详细分步工作流,含每个阶段的说明。

reference/api_reference.md

reference/api_reference.md

Quick function reference organized by module.
按模块组织的快速函数参考。

reference/plotting_guide.md

reference/plotting_guide.md

Comprehensive visualization guide for publication-quality figures.
用于发表级图表的综合可视化指南。

Detailed Reference Guides

详细参考指南

TopicReference
Full workflowreference/standard_workflow.md
API referencereference/api_reference.md
Plotting guidereference/plotting_guide.md
PreprocessingPREPROCESSING.md
Spike sortingSPIKE_SORTING.md
Motion correctionMOTION_CORRECTION.md
Quality metricsQUALITY_METRICS.md
Automated curationAUTOMATED_CURATION.md
AI-assisted curationAI_CURATION.md
Waveform analysisANALYSIS.md
主题参考文档
完整工作流reference/standard_workflow.md
API参考reference/api_reference.md
可视化指南reference/plotting_guide.md
预处理PREPROCESSING.md
Spike分选SPIKE_SORTING.md
运动校正MOTION_CORRECTION.md
质量指标QUALITY_METRICS.md
自动化筛选AUTOMATED_CURATION.md
AI辅助筛选AI_CURATION.md
波形分析ANALYSIS.md

Installation

安装

bash
undefined
bash
undefined

Core packages

核心包

pip install spikeinterface[full] probeinterface neo
pip install spikeinterface[full] probeinterface neo

Spike sorters

Spike分选器

pip install kilosort # Kilosort4 (GPU required) pip install spykingcircus # SpykingCircus2 (CPU) pip install mountainsort5 # Mountainsort5 (CPU)
pip install kilosort # Kilosort4(需要GPU) pip install spykingcircus # SpykingCircus2(CPU) pip install mountainsort5 # Mountainsort5(CPU)

Our toolkit

本工具包

pip install neuropixels-analysis
pip install neuropixels-analysis

Optional: AI curation

可选:AI筛选

pip install anthropic
pip install anthropic

Optional: IBL tools

可选:IBL工具

pip install ibl-neuropixel ibllib
undefined
pip install ibl-neuropixel ibllib
undefined

Project Structure

项目结构

project/
├── raw_data/
│   └── recording_g0/
│       └── recording_g0_imec0/
│           ├── recording_g0_t0.imec0.ap.bin
│           └── recording_g0_t0.imec0.ap.meta
├── preprocessed/           # Saved preprocessed recording
├── motion/                 # Motion estimation results
├── sorting_output/         # Spike sorter output
├── analyzer/               # SortingAnalyzer (waveforms, metrics)
├── phy_export/             # For manual curation
├── ai_curation/            # AI analysis reports
└── results/
    ├── quality_metrics.csv
    ├── curation_labels.json
    └── output.nwb
project/
├── raw_data/
│   └── recording_g0/
│       └── recording_g0_imec0/
│           ├── recording_g0_t0.imec0.ap.bin
│           └── recording_g0_t0.imec0.ap.meta
├── preprocessed/           # 保存的预处理后记录
├── motion/                 # 运动估计结果
├── sorting_output/         # Spike分选器输出
├── analyzer/               # SortingAnalyzer(波形、指标)
├── phy_export/             # 用于人工筛选
├── ai_curation/            # AI分析报告
└── results/
    ├── quality_metrics.csv
    ├── curation_labels.json
    └── output.nwb

Additional Resources

额外资源