关于 neuropixels-analysis
neuropixels-analysis 是面向神经科学研究者的技能,借助 SpikeInterface 分析高密度 Neuropixels 记录。它提供可运行脚本和可编辑模板,覆盖从预处理到单位整理与导出的流程。
主要功能
- 01读取 SpikeGLX、Open Ephys 和 NWB
- 02记录预处理与漂移校正
- 03支持多种尖峰排序器
- 04质量指标计算与单位筛选
- 05基于模型的单位分类
- 06导出至 Phy 或 NWB
适用场景
- 01检查通道并预处理原始记录
- 02对 Neuropixels 数据进行尖峰排序
- 03按指标或模型筛选单位
- 04导出整理结果以供人工复核
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ kalarislabs/ research-agent-skills --skill neuropixels-analysis安装后在 Claude Code 中输入/neuropixels-analysis确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
assets/analysis_template.pyreferences/AI_CURATION.mdANALYSIS.mdapi_reference.mdAUTOMATED_CURATION.mdMOTION_CORRECTION.mdplotting_guide.mdPREPROCESSING.mdQUALITY_METRICS.mdSPIKE_SORTING.mdstandard_workflow.mdscripts/compute_metrics.pyexplore_recording.pyexport_to_phy.pyneuropixels_pipeline.pypreprocess_recording.pyrun_sorting.py详细介绍
Neuropixels 数据分析
概述
使用来自 SpikeInterface、Allen Institute 和 International Brain Laboratory(IBL)的当前最佳实践,分析 Neuropixels 高密度神经记录的工具包。涵盖从原始数据到可用于发表的精选单元的完整工作流。
所有示例均使用真实的 SpikeInterface API(spikeinterface.full as si)以及配套的精选模块(spikeinterface.curation as sc)。该技能在 scripts/ 中提供可运行脚本,并在 assets/ 中提供可复制编辑的模板,直接基于 SpikeInterface 实现此工作流——除安装中列出的依赖项外,无需安装其他软件包。
何时使用此技能
在以下情况下应使用此技能:
- 处理 Neuropixels 记录(
.ap.bin、.lf.bin、.meta文件) - 从 SpikeGLX、Open Ephys 或 NWB 格式加载数据
- 预处理神经记录(滤波、公共参考、坏通道检测)
- 检测并校正运动/漂移
- 运行尖峰排序(Kilosort4、SpykingCircus2、Mountainsort5、Tridesclous2)
- 计算质量指标(SNR、ISI 违规、存在率、幅度截断)
- 精选单元(基于阈值、模型或 AI 辅助)
- 创建可视化内容并导出到 Phy 或 NWB
支持的硬件和格式
| 探针 | 电极数 | 通道数 | 备注 |
|---|---|---|---|
| Neuropixels 1.0 | 960 | 384 | 使用 phase_shift 进行 ADC 校正 |
| Neuropixels 2.0(单探针) | 1280 | 384 | 几何结构更密集 |
| Neuropixels 2.0(4-shank) | 5120 | 384 | 多区域记录 |
| 格式 | 扩展名 | 读取器 |
|---|---|---|
| SpikeGLX | .ap.bin、.lf.bin、.meta | si.read_spikeglx() |
| Open Ephys | .continuous、.oebin | si.read_openephys() |
| NWB | .nwb | si.read_nwb() |
快速开始
导入并配置并行处理
import spikeinterface.full as si
# Global job kwargs are reused by all parallelizable steps
si.set_global_job_kwargs(n_jobs=-1, chunk_duration="1s", progress_bar=True)
加载数据
# Inspect available streams first
stream_names, stream_ids = si.get_neo_streams("spikeglx", "/path/to/run_g0/")
print(stream_names) # e.g. ['imec0.ap', 'imec0.lf', 'nidq']
# SpikeGLX (most common) — select the AP stream by name
recording = si.read_spikeglx("/path/to/run_g0/", stream_name="imec0.ap", load_sync_channel=False)
# Open Ephys
recording = si.read_openephys("/path/to/Record_Node_101/")
# For quick iteration, slice the first 60 s
fs = recording.get_sampling_frequency()
recording_sub = recording.frame_slice(0, int(60 * fs))
完整流程(捆绑脚本)
此代码库提供了一个基于 SpikeInterface 构建的端到端流程:
python scripts/neuropixels_pipeline.py /path/to/spikeglx/data output/ --sorter kilosort4 --curation allen
该流程依次执行加载 → 预处理 → 漂移检查 → 可选运动校正 → 排序 → 后处理 → 质量指标 → 精选 → 导出。阅读下方步骤以交互方式运行或自定义流程。
标准分析工作流
1. 预处理
推荐处理链遵循 SpikeInterface Neuropixels 操作指南(IBL 风格的去条纹处理,包含通道移除和公共参考):
rec = si.highpass_filter(recording, freq_min=400.0)
bad_channel_ids, channel_labels = si.detect_bad_channels(rec)
rec = rec.remove_channels(bad_channel_ids)
rec = si.phase_shift(rec) # ADC phase correction (Neuropixels 1.0)
rec = si.common_reference(rec, operator="median", reference="global")
保存预处理后的记录(Kilosort 需要二进制文件,保存后也能加快重复使用):
rec = rec.save(folder="preprocessed/", format="binary")
2. 检查并校正漂移
排序前务必检查漂移:
from spikeinterface.sortingcomponents.peak_detection import detect_peaks
from spikeinterface.sortingcomponents.peak_localization import localize_peaks
noise_levels = si.get_noise_levels(rec, return_in_uV=False)
peaks = detect_peaks(rec, method="locally_exclusive", noise_levels=noise_levels,
detect_threshold=5, radius_um=50.0)
peak_locations = localize_peaks(rec, peaks, method="center_of_mass")
# Visualize the drift raster
si.plot_drift_raster_map(peaks=peaks, peak_locations=peak_locations,
recording=rec, clim=(-50, 50))
如有需要,应用校正(预设:rigid_fast、
kilosort_like、nonrigid_accurate、nonrigid_fast_and_accurate、dredge、dredge_fast):
rec_corrected = si.correct_motion(rec, preset="nonrigid_fast_and_accurate", folder="motion/")
3. 尖峰排序
# Kilosort4 (recommended, requires a CUDA GPU)
sorting = si.run_sorter("kilosort4", rec_corrected, folder="ks4_output")
# CPU alternatives (internally developed, no external install)
sorting = si.run_sorter("spykingcircus2", rec_corrected, folder="sc2_output")
sorting = si.run_sorter("tridesclous2", rec_corrected, folder="tdc2_output")
sorting = si.run_sorter("mountainsort5", rec_corrected, folder="ms5_output")
# External sorters can run in containers without local install
sorting = si.run_sorter("kilosort2_5", rec_corrected, folder="ks25_output", docker_image=True)
print(si.installed_sorters())
注意:
run_sorter使用folder=参数。旧参数output_folder=已弃用。
4. 后处理
analyzer = si.create_sorting_analyzer(sorting, rec_corrected, sparse=True,
format="binary_folder", folder="analyzer/")
analyzer.compute("random_spikes", method="uniform", max_spikes_per_unit=500)
analyzer.compute("waveforms", ms_before=1.0, ms_after=2.0)
analyzer.compute("templates", operators=["average", "std"])
analyzer.compute("noise_levels")
analyzer.compute("spike_amplitudes")
analyzer.compute("correlograms", window_ms=50.0, bin_ms=1.0)
analyzer.compute("unit_locations", method="monopolar_triangulation")
analyzer.compute("template_similarity")
metric_names = ["firing_rate", "presence_ratio", "snr", "isi_violation", "amplitude_cutoff"]
analyzer.compute("quality_metrics", metric_names=metric_names)
metrics = analyzer.get_extension("quality_metrics").get_data()
5. 基于指标阈值的精选
# Allen-style query (note: column is isi_violations_ratio)
query = "(amplitude_cutoff < 0.1) & (isi_violations_ratio < 0.5) & (presence_ratio > 0.9)"
good_unit_ids = metrics.query(query).index.values
如需使用 allen / ibl / strict 预设实现可复用的多阈值逻辑,请使用捆绑脚本 scripts/compute_metrics.py。详情以及 Bombcell / UnitMatch 工具请参阅
references/AUTOMATED_CURATION.md。
6. 基于模型的精选(UnitRefine)
SpikeInterface 可通过 spikeinterface.curation 模块,应用来自 Hugging Face 的预训练机器学习分类器。UnitRefine 模型基于真实 Neuropixels 数据(V1、SC、ALM)训练:
import spikeinterface.curation as sc
# 1) noise vs neural
noise_labels = sc.model_based_label_units(
sorting_analyzer=analyzer,
repo_id="SpikeInterface/UnitRefine_noise_neural_classifier",
trust_model=True,
)
neural = analyzer.remove_units(noise_labels[noise_labels["prediction"] == "noise"].index)
# 2) single-unit (sua) vs multi-unit (mua) on the surviving units
sua_mua_labels = sc.model_based_label_units(
sorting_analyzer=neural,
repo_id="SpikeInterface/UnitRefine_sua_mua_classifier",
trust_model=True,
)
每次调用都会返回一个 DataFrame,其中包含每个单元的 prediction 和 probability(置信度)。加载 .skops 模型需要设置 trust_model=True(或显式提供 trusted=[...] 列表)——只加载你信任来源的模型。在其他脑区/数据集上训练的模型可能无法迁移;请使用人工标注的子集进行验证。
7. AI 辅助整理(针对不确定的单元)
在 Cursor 或 Claude Code 等 Agent 中运行时,Agent 可以直接检查波形图和互相关图,并给出专家级解读——无需设置 API。生成图表,并请 Agent 评估分离质量。
如需以编程方式访问视觉模型,请从环境变量中读取 API 密钥——切勿在分析脚本中硬编码凭据(这些凭据会泄露到版本控制和日志中):
import os
from anthropic import Anthropic
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"]) # set this in your shell, not in code
完整流程(渲染单元摘要图像、构建提示词并解析响应)请参阅 references/AI_CURATION.md。
8. 导出结果
# Keep only good units, then export
analyzer_clean = analyzer.select_units(good_unit_ids, folder="analyzer_clean/", format="binary_folder")
# Phy for manual review
si.export_to_phy(analyzer_clean, output_folder="phy_export/",
compute_pc_features=True, compute_amplitudes=True)
# Figures report
si.export_report(analyzer_clean, "report/", format="png")
# NWB
from spikeinterface.exporters import export_to_nwb
export_to_nwb(analyzer_clean, "output.nwb")
# Metrics table
metrics.to_csv("quality_metrics.csv")
常见陷阱和最佳实践
- 进行尖峰分选前务必检查漂移——漂移超过约 10 μm 会显著降低质量。
- Neuropixels 1.0 使用
phase_shift修正 ADC 采样偏移。 - 使用
rec.save(folder=...)保存预处理后的记录,以避免重复计算(Kilosort 也需要二进制文件)。 - Kilosort4 使用 GPU——速度远快于 CPU 分选器。
- 检查不确定的单元——自动化或基于模型的整理只是起点,并非最终结论。
- 结合多种方法——明确的情况使用阈值,边界情况使用模型/AI。
- 记录阈值和模型仓库 ID,以确保结果可复现。
- 关键实验请导出到 Phy——人工监督很有价值。
需要调整的关键参数
预处理
freq_min:高通截止频率(通常为 300–400 Hz)detect_bad_channels:返回(bad_channel_ids, channel_labels)
运动校正
preset:nonrigid_fast_and_accurate(均衡)、nonrigid_accurate(严重漂移)、dredge(最先进)
尖峰分选(Kilosort4)
batch_size:每批的样本数(默认 60000)nblocks:漂移区块数(长时间且存在漂移的记录应增大此值)Th_universal/Th_learned:检测阈值(值越低 = 尖峰越多)
质量指标
snr:信噪比截止值(通常为 3–5)isi_violations_ratio:不应期违例(0.01–0.5)presence_ratio:记录覆盖率(0.5–0.95)
随附资源
scripts/explore_recording.py
快速检查记录(数据流、通道、时长、异常通道):
python scripts/explore_recording.py /path/to/data
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/
scripts/neuropixels_pipeline.py
完整的端到端流程(请参阅快速入门)。
assets/analysis_template.py
完整且可编辑的分析模板。复制并自定义:
cp assets/analysis_template.py my_analysis.py
# Edit the PARAMETERS section, then run
python my_analysis.py
详细参考指南
| 主题 | 参考文档 |
|---|---|
| 完整工作流 | references/standard_workflow.md |
| API 参考(SpikeInterface) | 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 |
安装
需要 Python ≥ 3.10。建议使用 uv。
# Core packages (SpikeInterface bundles the curation/model tooling)
uv pip install "spikeinterface[full]" probeinterface neo
# Spike sorters
uv pip install kilosort # Kilosort4 (CUDA GPU required)
uv pip install spykingcircus # SpykingCircus (legacy; SpykingCircus2 ships with SpikeInterface)
uv pip install mountainsort5 # Mountainsort5 (CPU)
# Model-based curation (UnitRefine) downloads from Hugging Face
uv pip install "huggingface_hub" skops
# Optional: AI-assisted visual curation
uv pip install anthropic
# Optional: IBL tools and Bombcell
uv pip install ibl-neuropixel ibllib bombcell
为确保环境可复现,请固定版本(截至 2026-06 的当前版本:spikeinterface==0.104.3、
kilosort==4.1.7、probeinterface==0.3.2、neo==0.14.4)。快速试验时可以不固定版本,
但生产流水线应固定版本。
项目结构
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
更多资源
- SpikeInterface 文档:https://spikeinterface.readthedocs.io/
- Neuropixels 教程:https://spikeinterface.readthedocs.io/en/stable/how_to/analyze_neuropixels.html
- 基于模型的整理教程:https://spikeinterface.readthedocs.io/en/stable/tutorials/curation/plot_1_automated_curation.html
- UnitRefine 模型(Hugging Face):https://huggingface.co/SpikeInterface
- 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
- Awesome Neuropixels:https://github.com/Julie-Fabre/awesome_neuropixels
Agent 操作流程
- **检查环境。**确认工具版本、参考基因组/注释版本,以及输入格式(FASTQ、BAM、VCF、h5ad)。
- **明确输入。**根据数据或用户提供的信息确认格式、标识符和参数。任何会改变结果的值都应询问,不要猜测。
- **先运行小规模版本。**先在小型子集(一个样本、一条染色体、几千个细胞)上运行流水线。
- 按照上述说明和参考资料执行完整任务。
- **验证结果。**在解读结果之前,检查 QC 指标、样本身份、基因组版本一致性和批次效应。
- **报告。**说明运行了什么(版本、命令、参数)、检查了什么,以及还有哪些不确定之处。
| 如果发生这种情况 | 请这样做 |
|---|---|
| 输入之间的基因组版本或标识符不匹配 | 停止并先统一(liftover、ID 映射),再继续。 |
| 这些说明中的函数、标志或端点在已安装版本中不存在 | 查阅已安装版本自己的文档(help()、--help、官方文档),进行适配并告知用户。切勿编造 API。 |
| 必需的输入、标识符或参数含糊不清 | 询问用户,或在运行前明确说明所采用的假设。 |
诚信规则
- 切勿捏造结果、参数、标识符、引用或统计数据。如果无法运行或验证某项内容,请如实说明。
- 不要作出超出统计数据支持范围的生物学意义解读;报告多重检验校正情况。
- 此处与版本相关的细节可能已经过时:请对照已安装版本的官方文档进行确认。
- 对于需要付费、占用共享 GPU 或云配额、涉及个人或患者数据,或无法撤销的操作,须事先征求同意。
相关技能
bids:使用 Brain Imaging Data Structure(BIDS)标准组织、查询、验证和转换神经科学及生物医学数据集,co…