neuropixels-analysis
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNeuropixels 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
支持的硬件与格式
| Probe | Electrodes | Channels | Notes |
|---|---|---|---|
| Neuropixels 1.0 | 960 | 384 | Requires phase_shift correction |
| Neuropixels 2.0 (single) | 1280 | 384 | Denser geometry |
| Neuropixels 2.0 (4-shank) | 5120 | 384 | Multi-region recording |
| Format | Extension | Reader |
|---|---|---|
| SpikeGLX | | |
| Open Ephys | | |
| NWB | | |
| 探针 | 电极数 | 通道数 | 说明 |
|---|---|---|---|
| Neuropixels 1.0 | 960 | 384 | 需要phase_shift校正 |
| Neuropixels 2.0 (单针) | 1280 | 384 | 更密集的几何结构 |
| Neuropixels 2.0 (4针) | 5120 | 384 | 多区域记录 |
| 格式 | 扩展名 | 读取函数 |
|---|---|---|
| SpikeGLX | | |
| Open Ephys | | |
| NWB | | |
Quick Start
快速开始
Basic Import and Setup
基础导入与设置
python
import spikeinterface.full as si
import neuropixels_analysis as npapython
import spikeinterface.full as si
import neuropixels_analysis as npaConfigure parallel processing
配置并行处理
job_kwargs = dict(n_jobs=-1, chunk_duration='1s', progress_bar=True)
undefinedjob_kwargs = dict(n_jobs=-1, chunk_duration='1s', progress_bar=True)
undefinedLoading Data
加载数据
python
undefinedpython
undefinedSpikeGLX (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()))
undefinedrecording = recording.frame_slice(0, int(60 * recording.get_sampling_frequency()))
undefinedComplete Pipeline (One Command)
完整流程(一键执行)
python
undefinedpython
undefinedRun 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']
undefinedsorting = results['sorting']
metrics = results['metrics']
labels = results['labels']
undefinedStandard Analysis Workflow
标准分析工作流
1. Preprocessing
1. 预处理
python
undefinedpython
undefinedRecommended 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)
undefinedrec = npa.preprocess(recording)
undefined2. Check and Correct Drift
2. 检查并校正漂移
python
undefinedpython
undefinedCheck 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')
undefinedif motion_info['motion'].max() > 10: # 微米
rec = npa.correct_motion(rec, preset='nonrigid_accurate')
undefined3. Spike Sorting
3. Spike分选
python
undefinedpython
undefinedKilosort4 (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())
undefinedprint(si.installed_sorters())
undefined4. Postprocessing
4. 后处理
python
undefinedpython
undefinedCreate 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()
undefinedanalyzer = 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()
undefined5. Curation
5. 单元筛选
python
undefinedpython
undefinedAllen 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'
undefinedlabels = npa.curate(metrics, method='allen') # 'allen', 'ibl', 'strict'
undefined6. 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 AnthropicSetup 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
undefinedpython
undefinedGenerate 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)
undefinednpa.print_analysis_summary(results)
undefined8. Export Results
8. 导出结果
python
undefinedpython
undefinedExport 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')
undefinedmetrics.to_csv('quality_metrics.csv')
undefinedCommon Pitfalls and Best Practices
常见误区与最佳实践
- Always check drift before spike sorting - drift > 10μm significantly impacts quality
- Use phase_shift for Neuropixels 1.0 probes (not needed for 2.0)
- Save preprocessed data to avoid recomputing - use
rec.save(folder='preprocessed/') - Use GPU for Kilosort4 - it's 10-50x faster than CPU alternatives
- Review uncertain units manually - automated curation is a starting point
- Combine metrics with AI - use metrics for clear cases, AI for borderline units
- Document your thresholds - different analyses may need different criteria
- Export to Phy for critical experiments - human oversight is valuable
- 务必在Spike分选前检查漂移 - 漂移>10μm会严重影响分选质量
- Neuropixels 1.0探针需使用phase_shift(2.0无需)
- 保存预处理后的数据避免重复计算 - 使用
rec.save(folder='preprocessed/') - Kilosort4使用GPU - 比CPU方案快10-50倍
- 人工审核不确定单元 - 自动化筛选仅作为起点
- 结合指标与AI - 明确案例用指标,边缘案例用AI
- 记录你的阈值设置 - 不同分析可能需要不同标准
- 关键实验导出至Phy - 人工监督很有价值
Key Parameters to Adjust
关键可调参数
Preprocessing
预处理
- : Highpass cutoff (300-400 Hz typical)
freq_min - : Bad channel detection sensitivity
detect_threshold
- : 高通滤波截止频率(典型值300-400 Hz)
freq_min - : 坏通道检测灵敏度
detect_threshold
Motion Correction
运动校正
- : 'kilosort_like' (fast) or 'nonrigid_accurate' (better for severe drift)
preset
- : 'kilosort_like'(快速)或 'nonrigid_accurate'(严重漂移时效果更好)
preset
Spike Sorting (Kilosort4)
Spike分选(Kilosort4)
- : Samples per batch (30000 default)
batch_size - : Number of drift blocks (increase for long recordings)
nblocks - : Detection threshold (lower = more spikes)
Th_learned
- : 每批样本数(默认30000)
batch_size - : 漂移块数量(长记录需增加)
nblocks - : 检测阈值(值越低,检测到的spike越多)
Th_learned
Quality Metrics
质量指标
- : Signal-to-noise cutoff (3-5 typical)
snr_threshold - : Refractory violations (0.01-0.5)
isi_violations_ratio - : Recording coverage (0.5-0.95)
presence_ratio
- : 信噪比阈值(典型值3-5)
snr_threshold - : 不应期违规率(0.01-0.5)
isi_violations_ratio - : 记录覆盖率(0.5-0.95)
presence_ratio
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 allenscripts/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.pyEdit parameters and run
编辑参数并运行
python my_analysis.py
undefinedpython my_analysis.py
undefinedreference/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
详细参考指南
| Topic | Reference |
|---|---|
| Full workflow | reference/standard_workflow.md |
| API reference | reference/api_reference.md |
| Plotting guide | reference/plotting_guide.md |
| Preprocessing | PREPROCESSING.md |
| Spike sorting | SPIKE_SORTING.md |
| Motion correction | MOTION_CORRECTION.md |
| Quality metrics | QUALITY_METRICS.md |
| Automated curation | AUTOMATED_CURATION.md |
| AI-assisted curation | AI_CURATION.md |
| Waveform analysis | ANALYSIS.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
undefinedbash
undefinedCore 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
undefinedpip install ibl-neuropixel ibllib
undefinedProject 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.nwbproject/
├── 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.nwbAdditional Resources
额外资源
- SpikeInterface Docs: https://spikeinterface.readthedocs.io/
- Neuropixels Tutorial: https://spikeinterface.readthedocs.io/en/stable/how_to/analyze_neuropixels.html
- Kilosort4 GitHub: https://github.com/MouseLand/Kilosort
- IBL Neuropixel Tools: https://github.com/int-brain-lab/ibl-neuropixel
- Allen Institute ecephys: https://github.com/AllenInstitute/ecephys_spike_sorting
- Bombcell (Automated QC): https://github.com/Julie-Fabre/bombcell
- SpikeAgent (AI Curation): https://github.com/SpikeAgent/SpikeAgent
- SpikeInterface文档: https://spikeinterface.readthedocs.io/
- Neuropixels教程: https://spikeinterface.readthedocs.io/en/stable/how_to/analyze_neuropixels.html
- Kilosort4 GitHub: https://github.com/MouseLand/Kilosort
- IBL Neuropixel工具: https://github.com/int-brain-lab/ibl-neuropixel
- Allen Institute ecephys: https://github.com/AllenInstitute/ecephys_spike_sorting
- Bombcell(自动化QC): https://github.com/Julie-Fabre/bombcell
- SpikeAgent(AI筛选): https://github.com/SpikeAgent/SpikeAgent ",