mcpField
A
alterlab-neuropixels

alterlab-neuropixels

github.com/alterlab-ieu数据与数据库7867 次安装5 周前更新
代码仓库

关于 alterlab-neuropixels

面向使用 SpikeInterface 分析 Neuropixels 神经记录的研究者,覆盖从原始数据到单元分选、筛选和导出的流程,并提供配套脚本。

主要功能

  1. 01读取 SpikeGLX、Open Ephys 和 NWB 记录
  2. 02预处理记录并检测异常通道
  3. 03检查并校正记录漂移
  4. 04使用多种分选器进行尖峰分选
  5. 05计算质量指标并筛选单元
  6. 06导出结果至 Phy 或 NWB

适用场景

  1. 01处理原始 Neuropixels 记录
  2. 02分选尖峰并评估单元质量
  3. 03通过图表复核不确定单元
  4. 04整理筛选结果以供后续分析

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/alterlab-ieu/alterlab-academic-skills --skill alterlab-neuropixels

安装后在 Claude Code 中输入/alterlab-neuropixels确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

assets/
analysis_template.py
evals/
evals.json
references/
AI_CURATION.md
ANALYSIS.md
api_reference.md
AUTOMATED_CURATION.md
MOTION_CORRECTION.md
plotting_guide.md
PREPROCESSING.md
QUALITY_METRICS.md
SPIKE_SORTING.md
standard_workflow.md
scripts/
compute_metrics.py
explore_recording.py
export_to_phy.py
neuropixels_pipeline.py
preprocess_recording.py
run_sorting.py

详细介绍

Neuropixels 数据分析

概述

用于分析 Neuropixels 高密度神经记录的综合工具包,采用 SpikeInterface、Allen Institute 和 International Brain Laboratory(IBL)的当前最佳实践。支持从原始数据到可用于发表的整理后单元的完整工作流。

何时使用此技能

以下情况应使用此技能:

  • 处理 Neuropixels 记录(.ap.bin、.lf.bin、.meta 文件)
  • 从 SpikeGLX、Open Ephys 或 NWB 格式加载数据
  • 预处理神经记录(滤波、CAR、坏通道检测)
  • 检测并校正记录中的运动/漂移
  • 运行 spike sorting(Kilosort4、SpykingCircus2、Mountainsort5)
  • 计算质量指标(SNR、ISI 违规率、存在率)
  • 根据 Allen/IBL 标准整理单元
  • 创建神经数据可视化
  • 将结果导出到 Phy 或 NWB
不适用的情况
场景改用
单细胞或整体转录组学,而非电生理学alterlab-scanpy / alterlab-rnaseq-quant
流式/质谱细胞术 FCS 文件alterlab-flowio
对已提取的 spike 特征进行通用时间序列统计或 MLalterlab-statistical-analysis / alterlab-scikit-learn
根据已有数据绘制任意图表alterlab-matplotlib / alterlab-scientific-viz
对连接矩阵进行网络/图分析alterlab-networkx

支持的硬件和格式

探针电极数通道数备注
Neuropixels 1.0960384需要进行 phase_shift 校正
Neuropixels 2.0(单探针)1280384几何结构更密集
Neuropixels 2.0(4-shank)5120384多区域记录
格式扩展名读取器
SpikeGLX.ap.bin、.lf.bin、.metasi.read_spikeglx()
Open Ephys.continuous、.oebinsi.read_openephys()
NWB.nwbsi.read_nwb()

快速入门

基本导入和设置
import spikeinterface.full as si

# Bundled helper functions live in scripts/neuropixels_pipeline.py
from scripts.neuropixels_pipeline import (
    load_recording, preprocess, check_drift, correct_motion,
    run_spike_sorting, postprocess, curate_units, export_results, run_pipeline,
)

# Configure parallel processing
job_kwargs = dict(n_jobs=-1, chunk_duration='1s', progress_bar=True)
加载数据
# SpikeGLX (most common)
recording = si.read_spikeglx('/path/to/data', stream_id='imec0.ap')

# Open Ephys (common for many labs)
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']

# For testing with subset of data
recording = recording.frame_slice(0, int(60 * recording.get_sampling_frequency()))
完整流程(单条命令)
# Run full analysis pipeline (writes all outputs under output_path/)
from scripts.neuropixels_pipeline import run_pipeline

run_pipeline(
    data_path='/path/to/data',
    output_path='output/',
    sorter='kilosort4',
    stream_name='imec0.ap',
    apply_motion_correction=True,
    curation_method='allen',
)

# Results are written to disk:
#   output/sorting_output/    spike sorter output
#   output/analyzer/          SortingAnalyzer (waveforms, metrics)
#   output/quality_metrics.csv
#   output/curation_labels.json

也可以从命令行运行:

python scripts/neuropixels_pipeline.py /path/to/data output/ --sorter kilosort4 --curation allen

标准分析工作流

1. 预处理
# 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')

# Or use the bundled wrapper (returns the preprocessed recording + bad channel ids)
from scripts.neuropixels_pipeline import preprocess
rec, bad_channels = preprocess(recording)
2. 检查并校正漂移
from scripts.neuropixels_pipeline import check_drift, correct_motion

# Check for drift (always do this!) — detects/localizes peaks and saves
# a drift plot to <output_folder>/drift_check.png, returns a dict with
# 'drift_estimate' (μm range).
drift_info = check_drift(rec, output_folder='output/')

# Apply correction if needed
if drift_info['drift_estimate'] > 20:  # microns
    rec = correct_motion(rec, output_folder='output/', preset='nonrigid_fast_and_accurate')
3. Spike sorting
# Kilosort4 (recommended, requires GPU)
sorting = si.run_sorter('kilosort4', rec, folder='ks4_output')

# CPU alternatives
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())
4. 后处理
# 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()
5. 整理
# Allen Institute criteria (conservative)
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 (returns {unit_id: 'good'|'mua'|'noise'})
from scripts.neuropixels_pipeline import curate_units
labels = curate_units(metrics, method='allen')  # 'allen', 'ibl', 'strict'
6. AI 辅助整理(适用于不确定的单元)

在使用此技能和 Claude Code 时,Claude 可以直接分析波形图,并提供专业的整理判断。建议的工作流是使用 SpikeInterface 生成每个单元的汇总图,再让 Claude 检查这些图:

import spikeinterface.widgets as sw
import matplotlib.pyplot as plt

# Find borderline units worth a visual look
uncertain = metrics.query('snr > 3 and snr < 8').index.tolist()

# Render a summary figure per uncertain unit (waveform + correlogram + amplitudes)
for unit_id in uncertain:
    sw.plot_unit_summary(analyzer, unit_id=unit_id)
    plt.savefig(f'ai_curation/unit_{unit_id}_summary.png', dpi=150, bbox_inches='tight')
    plt.close()

Claude Code 集成:在 Claude Code 中运行时,可让 Claude 直接检查保存的波形/自相关图——无需设置 API。

7. 生成分析报告
# The bundled run_pipeline writes a machine-readable summary.json
# (sampling rate, duration, channel count, unit counts) into output_path/.
import json
with open('output/summary.json') as f:
    summary = json.load(f)
print(summary)

# For a browsable HTML report of waveforms/metrics, use SpikeInterface's exporter:
si.export_report(analyzer, output_folder='output/report/')
# Open output/report/index.html for figures and the per-unit table
8. 导出结果
# Export to Phy for manual review
si.export_to_phy(analyzer, output_folder='phy_export/',
                 compute_pc_features=True, compute_amplitudes=True)

# Export to NWB (via NeuroConv — SpikeInterface has no native NWB exporter)
# pip install neuroconv
from neuroconv.tools.spikeinterface import write_sorting, write_recording
write_recording(recording=rec, nwbfile_path='output.nwb', overwrite=True)
write_sorting(sorting=sorting, nwbfile_path='output.nwb')

# Save quality metrics
metrics.to_csv('quality_metrics.csv')

常见问题与最佳实践

  1. Spike sorting 前务必检查漂移——漂移超过 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——人工监督很有价值

需要调整的关键参数

预处理
  • freq_min:高通截止频率(通常为 300-400 Hz)
  • detect_threshold:坏通道检测灵敏度
运动校正
  • preset:'kilosort_like'(快速)或 'nonrigid_accurate'(更适合严重漂移)
Spike Sorting(Kilosort4)
  • batch_size:每个批次的样本数(默认值为 30000)
  • nblocks:漂移区块数(长时间记录可增大此值)
  • Th_learned:检测阈值(越低,检测到的尖峰越多)
质量指标
  • snr_threshold:信噪比阈值(通常为 3-5)
  • isi_violations_ratio:不应期违规比例(0.01-0.5)
  • presence_ratio:记录覆盖率(0.5-0.95)

捆绑资源

scripts/preprocess_recording.py

自动化预处理脚本:

python scripts/preprocess_recording.py /path/to/data --output preprocessed/
scripts/run_sorting.py

运行尖峰排序:

python scripts/run_sorting.py preprocessed/ --sorter kilosort4 --output sorting/
scripts/compute_metrics.py

计算质量指标并进行整理:

python scripts/compute_metrics.py sorting/ preprocessed/ --output metrics/ --curation allen
scripts/export_to_phy.py

导出到 Phy 以进行手动整理:

python scripts/export_to_phy.py metrics/analyzer --output phy_export/
assets/analysis_template.py

完整的分析模板。复制并自定义:

cp assets/analysis_template.py my_analysis.py
# Edit parameters and run
python my_analysis.py
references/standard_workflow.md

详细的分步工作流,附有各阶段的说明。

references/api_reference.md

按模块整理的函数速查参考。

references/plotting_guide.md

全面的可视化指南,助你制作适用于出版物的高质量图表。

详细参考指南

主题参考文档
完整工作流references/standard_workflow.md
API 参考references/api_reference.md
绘图指南references/plotting_guide.md
预处理references/PREPROCESSING.md
尖峰排序references/SPIKE_SORTING.md
运动校正references/MOTION_CORRECTION.md
质量指标references/QUALITY_METRICS.md
自动整理references/AUTOMATED_CURATION.md
AI 辅助整理references/AI_CURATION.md
波形分析references/ANALYSIS.md

安装

# Core packages
uv pip install "spikeinterface[full]" probeinterface neo

# External sorters (separate packages, run via si.run_sorter)
uv pip install kilosort            # Kilosort4 (CUDA GPU required)
uv pip install mountainsort5       # Mountainsort5 (CPU)

# Internal sorters ship INSIDE spikeinterface — install the extra, not a
# standalone package. There is no `spykingcircus` package for SpykingCircus2.
uv pip install "spikeinterface[spykingcircus2]"
uv pip install "spikeinterface[tridesclous2]"

# Our toolkit ships as local scripts (scripts/) — no pip install needed;
# run them directly or import from scripts.neuropixels_pipeline

# Optional: AI curation
uv pip install anthropic

# Optional: IBL tools
uv pip install ibl-neuropixel ibllib
SpikeInterface 0.105 — 值得了解的不兼容变更

0.105.0(2026-09-21)对许多接口进行了重命名。旧版本保存的对象仍可加载,但基于 0.104 编写的脚本可能无法运行:

  • 分析 API 中已移除 peak_sign。 创建 SortingAnalyzer 时现在会固定主通道和峰值符号,并将其存储为 main_channel_id 排序属性,因此 compute_quality_metrics、compute_template_metrics、compute_spike_amplitudes、compute_spike_locations 和 compute_unit_locations 不再接受该参数。compute_snrs(..., peak_sign=, peak_mode=) 已改为 compute_snrs(..., method=)。
  • get_template_extremum_channel() -> SortingAnalyzer.get_main_channels()(旧名称仍作为已弃用的兼容接口保留)。
  • estimate_sparsity() 的默认值现在从 "neg" 改为 peak_sign="both" —— 结果会悄然改变,而不是报错,因此请重新检查依赖稀疏度的输出。
  • 探针处理:set_probe()/set_probegroup() 会原地操作并返回 None;要获取新的 recording,请使用 select_channels_with_probe()。reset_probe() -> remove_probe()。
  • ChunkRecordingExecutor -> TimeSeriesChunkExecutor; BaseExtractor.load_from_folder() 已移除,改用 si.load()。
  • 0.105 中新增:作为外部排序器的 dartsort、SortingAnalyzer 的 lazy 和 read_only 模式、预处理功能 detect_and_remove_artifacts,以及用于从 Kilosort4 输出文件夹构建 Motion 对象的 read_kilosort4_motion()。

对于任何计划复现的分析,请固定 SpikeInterface 版本,并在方法部分记录该版本——不同次要版本之间的指标定义已有变更。

项目结构

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

Additional Resources

评论

支持 Markdown