基于 SpikeInterface 的 Neuropixels 高密度神经记录全流程分析指南——scientific-agent-skills 的 neuropixels-analysis 技能详解
【免费下载链接】scientific-agent-skillsTurn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 190,000+ scientists worldwide. 165 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.项目地址: https://gitcode.com/GitHub_Trending/cl/scientific-agent-skills
导读
本文是围绕开源仓库 scientific-agent-skills 中skills/neuropixels-analysis技能编写的技术指南,完整讲解如何基于 SpikeInterface 对 Neuropixels 1.0/2.0 高密度细胞外电生理记录执行端到端分析:从 SpikeGLX / Open Ephys / NWB 数据加载、IBL 风格预处理、漂移(motion/drift)检测与修正,到 Kilosort4 等尖峰排序器、质量指标计算,再到阈值 / 模型(UnitRefine)/ AI 辅助三种单元(unit)筛选策略与 Phy、NWB 导出。读完本文,你将掌握一套可复制、可运行的 Neuropixels 分析管线,并能理解仓库中配套脚本与测试对关键阈值的源码级校验逻辑。
技能定位与适用场景
scientific-agent-skills/neuropixels-analysis是一套面向 AI Agent(如 Cursor、Claude Code)的技能(Skill),其目标是把"从原始数据到可发表级 curated units"的完整工作流沉淀为可直接调用的工具。依据 SKILL.md 的元信息,它适用于以下场景:
- 处理 Neuropixels 记录文件(
.ap.bin、.lf.bin、.meta); - 从 SpikeGLX、Open Ephys 或 NWB 格式加载数据;
- 神经信号预处理(滤波、公共参考、坏通道检测);
- 漂移检测与运动校正;
- 运行尖峰排序(Kilosort4、SpykingCircus2、Mountainsort5、Tridesclous2);
- 计算质量指标(SNR、ISI violation、presence ratio、amplitude cutoff);
- 单元筛选(阈值、模型、AI 辅助三种方式);
- 生成可视化并导出到 Phy 或 NWB。
所有示例都直接使用真实 SpikeInterface API(import spikeinterface.full as si)及配套的 curation 模块(import spikeinterface.curation as sc)。技能自带scripts/下 6 个可直接运行的脚本,以及assets/analysis_template.py可复制编辑模板,除此之外无需额外安装单独的工具包,只需安装依赖即可。
支持的硬件与数据格式
Neuropixels 探针
| 探针 | 电极数 | 通道数 | 备注 |
|---|---|---|---|
| Neuropixels 1.0 | 960 | 384 | 需使用phase_shift做 ADC 校正 |
| Neuropixels 2.0(单柄) | 1280 | 384 | 更致密的几何排布 |
| Neuropixels 2.0(4 柄) | 5120 | 384 | 支持多脑区同步记录 |
数据格式与读取接口
| 格式 | 扩展名 | 读取函数 |
|---|---|---|
| SpikeGLX | .ap.bin、.lf.bin、.meta | si.read_spikeglx() |
| Open Ephys | .continuous、.oebin | si.read_openephys() |
| NWB | .nwb | si.read_nwb() |
仓库中的 preprocess_recording.py 展示了这三种读取方式的实际用法,并且支持--format auto自动探测:当路径中出现imec时按 SpikeGLX 处理,否则依次尝试 Open Ephys、NWB 与si.load_extractor()。
快速开始
导入并配置并行计算
import spikeinterface.full as si # 全局 job kwargs 会被所有可并行步骤复用 si.set_global_job_kwargs(n_jobs=-1, chunk_duration="1s", progress_bar=True)n_jobs=-1表示使用所有 CPU 核心;chunk_duration="1s"控制并行处理的块大小;progress_bar=True在长任务中输出进度。
加载数据
# 先检查可用的数据流 stream_names, stream_ids = si.get_neo_streams("spikeglx", "/path/to/run_g0/") print(stream_names) # e.g. ['imec0.ap', 'imec0.lf', 'nidq'] # SpikeGLX(最常见)——按名称选择 AP 数据流 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/") # 快速迭代时,先切片前 60 秒 fs = recording.get_sampling_frequency() recording_sub = recording.frame_slice(0, int(60 * fs))load_sync_channel=False可避免把同步通道当作记录通道读入。加载后可验证记录属性:get_num_channels()、get_total_duration()、get_sampling_frequency()、get_probe()、get_channel_locations()。
一键运行完整管线
仓库在 scripts/neuropixels_pipeline.py 中提供了基于 SpikeInterface 的端到端管线脚本:
python skills/neuropixels-analysis/scripts/neuropixels_pipeline.py /path/to/spikeglx/data output/ --sorter kilosort4 --curation allen该脚本内部按"加载 → 预处理 → 漂移检查 → 可选运动校正 → 排序 → 后处理 → 质量指标 → 筛选 → 导出"的顺序执行,并支持以下命令行参数(见 neuropixels_pipeline.py):
| 参数 | 默认值 | 说明 |
|---|---|---|
data_path/output_path | 必填 | 输入数据目录 / 输出目录 |
--sorter | kilosort4 | 可选kilosort4、kilosort3、spykingcircus2、mountainsort5 |
--stream | imec0.ap | SpikeGLX 数据流名 |
--no-motion-correction | 关闭 | 跳过运动校正 |
--curation | allen | 可选allen、ibl、strict |
标准分析工作流
1. 预处理
推荐链路遵循 SpikeInterface 的 Neuropixels how-to(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 相位校正(Neuropixels 1.0) rec = si.common_reference(rec, operator="median", reference="global")保存预处理结果(Kilosort 需要二进制文件,且可避免重复计算):
rec = rec.save(folder="preprocessed/", format="binary")standard_workflow.md 还给出了两种替代方案:
- 显式带通替代:
si.bandpass_filter(recording, freq_min=300.0, freq_max=6000.0)后接 phase shift、坏通道剔除与公共中位数参考; - 空间去条带(强伪影场景):
si.highpass_spatial_filter(rec)用于处理条带噪声,适合伪影较重的记录。
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") # 可视化漂移光栅图 si.plot_drift_raster_map(peaks=peaks, peak_locations=peak_locations, recording=rec, clim=(-50, 50))如需校正,可一键调用预设(preset):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/")在 neuropixels_pipeline.py 中,漂移检测还会生成drift_check.png散点图,并用np.percentile(peak_locations['y'], 95) - np.percentile(peak_locations['y'], 5)估算漂移范围;当漂移估计超过 20 μm 时才自动触发运动校正(drift_estimate > 20的判断见 neuropixels_pipeline.py)。注意correct_motion默认只返回校正后的记录对象;如需同时拿到运动信息字典,应传入output_motion_info=True。
3. 尖峰排序
# Kilosort4(推荐,需要 CUDA GPU) sorting = si.run_sorter("kilosort4", rec_corrected, folder="ks4_output") # CPU 备选(SpikeInterface 内部实现,无需外部安装) 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") # 外部排序器可运行在容器中,无需本地安装 sorting = si.run_sorter("kilosort2_5", rec_corrected, folder="ks25_output", docker_image=True) print(si.installed_sorters())注意:
run_sorter使用folder=参数,旧的output_folder=已废弃。
run_sorting.py 中为每个排序器预置了与预处理链衔接的默认参数,其核心原则是避免二次预处理:kilosort3关闭do_CAR(公共平均参考已在预处理阶段完成)、spykingcircus2关闭apply_preprocessing、mountainsort5关闭filter与whiten。这些预设被 tests/neuropixels-analysis/test_scripts.py 显式验证,因为对已滤波、已参考、已剔除坏通道的记录再次滤波/白化会扭曲待聚类的波形。
Kilosort4 的默认参数在该脚本中为batch_size=30000、nblocks=1、Th_universal=9、Th_learned=8(其中Th_universal > Th_learned,即检测阈值高于接受阈值,保证检测范围广于接受范围,测试见 test_scripts.py)。若需多排序器对比,可使用si.compare_multiple_sorters()与get_agreement_sorting(minimum_agreement_count=2)得到一致性排序结果。
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()sparse=True表示只计算每个单元附近的通道,可显著降低内存与计算开销。扩展(extension)的计算顺序有依赖关系:random_spikes→waveforms→templates→ 各类派生指标。
5. 基于指标阈值的单元筛选
# Allen 风格查询(注意列名为 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若需要可复用的多阈值逻辑,可使用捆绑的 compute_metrics.py,它内置allen/ibl/strict三套预设:
CURATION_CRITERIA = { 'allen': {'snr': 3.0, 'isi_violations_ratio': 0.5, 'presence_ratio': 0.9, 'amplitude_cutoff': 0.1}, 'ibl': {'snr': 4.0, 'isi_violations_ratio': 0.1, 'presence_ratio': 0.9, 'amplitude_cutoff': 0.1}, 'strict': {'snr': 5.0, 'isi_violations_ratio': 0.01, 'presence_ratio': 0.95, 'amplitude_cutoff': 0.05}, }其中snr与presence_ratio为下限(越大越严格),isi_violations_ratio与amplitude_cutoff为上限(越小越严格),三套预设严格程度依次递增(strict≥ibl≥allen)。tests/neuropixels-analysis/test_scripts.py 用大量边界用例校验了这些阈值:例如 ISI violations 为 0.3 的单元在 Allen 标准下为 good、在 IBL 标准下为 mua;snr < 1.5一律判为 noise(噪声门控先于任何预设执行);每个单元必须且只能获得一个标签;未知的 curation 方法必须抛ValueError而不是静默丢掉单元(否则会导致导出阶段报告 0 个 good units,见 neuropixels_pipeline.py)。
神经科学的指标阈值依据可进一步参考 QUALITY_METRICS.md:Allen Visual Coding 使用isi_violations_ratio < 0.5,IBL 的 reproducible-ephys 标准收紧到< 0.1,严格单单元标准则要求< 0.01。
6. 基于模型的单元筛选(UnitRefine)
SpikeInterface 可以通过spikeinterface.curation模块加载 Hugging Face 上预训练的机器学习分类器。UnitRefine 模型在真实 Neuropixels 数据(V1、SC、ALM 脑区)上训练:
import spikeinterface.curation as sc # 1) 噪声 vs 神经信号 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) 单单元(sua)vs 多单元(mua),作用于筛选后的存活单元 sua_mua_labels = sc.model_based_label_units( sorting_analyzer=neural, repo_id="SpikeInterface/UnitRefine_sua_mua_classifier", trust_model=True, )每次调用返回一个 DataFrame,包含每个单元的prediction与probability(置信度)。trust_model=True(或显式trusted=[...]列表)是加载.skops模型所必需的——务必只加载你信任来源的模型。在其它脑区/数据集上训练的模型可能不具备迁移性,应在手工标注子集上验证。更多细节参见 references/AUTOMATED_CURATION.md,其中还介绍了 Bombcell(4 分类:单单元/MUA/噪声/非胞体)与 UnitMatch(跨会话单元追踪)等工具。
7. AI 辅助筛选(用于不确定单元)
在 Cursor 或 Claude Code 等 Agent 中运行时,Agent 可以直接查看波形 / correlogram 图并给出专家级判断,无需配置任何 API。生成图像后让 Agent 评估单元隔离质量即可。
对于程序化视觉模型访问,务必从环境变量读取 API key,绝不要硬编码到分析脚本中(会泄漏到版本控制与日志):
import os from anthropic import Anthropic client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"]) # 在 shell 中设置,而非写进代码SKILL.md 元信息中声明的ANTHROPIC_API_KEY环境变量即为此用途(required: false,仅在需要调用 Claude API 时设置)。完整的模式(渲染单元摘要图、构造 prompt、解析响应)见 references/AI_CURATION.md。
8. 导出结果
# 仅保留优质单元后导出 analyzer_clean = analyzer.select_units(good_unit_ids, folder="analyzer_clean/", format="binary_folder") # Phy 用于人工复核 si.export_to_phy(analyzer_clean, output_folder="phy_export/", compute_pc_features=True, compute_amplitudes=True) # 图表报告 si.export_report(analyzer_clean, "report/", format="png") # NWB from spikeinterface.exporters import export_to_nwb export_to_nwb(analyzer_clean, "output.nwb") # 指标表 metrics.to_csv("quality_metrics.csv")仓库的 export_to_phy.py 会自动补齐缺失的扩展(spike_amplitudes、principal_components,后者默认n_components=5, mode='by_channel_local'),导出完成后提示用phy template-gui {output}/params.py打开。此外,neuropixels_pipeline.py 还会额外产出unit_labels.json(单元标签)、quality_metrics.csv与summary.json(总单元数、good 单元数、总尖峰数、时长、通道数)。
常见陷阱与最佳实践
- 排序前务必检查漂移——漂移超过约 10 μm 会明显劣化排序质量;
- Neuropixels 1.0 必须使用
phase_shift校正 ADC 采样偏移; - 用
rec.save(folder=...)保存预处理记录,避免重复计算(Kilosort 也需要二进制文件); - Kilosort4 应使用 GPU——远快于 CPU 排序器;
- 不确定单元要人工复核——自动 / 模型筛选只是起点,不是最终结论;
- 多种方法结合——明确情况用阈值,边缘单元用模型 / AI;
- 记录阈值与模型 repo ID,保证可复现;
- 关键实验导出到 Phy——人工监督很有价值。
关键参数速查
预处理
freq_min:高通截止频率(通常 300–400 Hz);注意管线主脚本默认 400 Hz,而preprocess_recording.py与analysis_template.py默认 300 Hz 并配合freq_max=6000构成带通;detect_bad_channels:返回(bad_channel_ids, channel_labels)元组。
运动校正
preset:nonrigid_fast_and_accurate(均衡)、nonrigid_accurate(严重漂移)、dredge(目前最先进)。
尖峰排序(Kilosort4)
batch_size:每批采样数(默认 60000,仓库脚本默认 30000);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 --plot --output figs/ |
| scripts/preprocess_recording.py | 自动化预处理(带通、phase shift、坏通道、公共中位数参考) | 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 | 完整端到端管线 | python scripts/neuropixels_pipeline.py /path/to/data output/ --sorter kilosort4 --curation allen |
assets/analysis_template.py 是一份完整、可编辑的分析模板,顶部集中了全部可调参数(数据路径、格式、滤波频率、是否 phase shift / CMR / 坏通道检测、运动校正预设、排序器与参数、筛选方法、并行数),复制后只需修改PARAMETERS区即可运行:
cp skills/neuropixels-analysis/assets/analysis_template.py my_analysis.py # 编辑 PARAMETERS 区后运行 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 |
质量指标深度解读
QUALITY_METRICS.md 从三个维度系统定义了单元质量评估框架:
| 类别 | 回答的问题 | 关键指标 |
|---|---|---|
| 污染(I 型错误) | 尖峰是否来自多个神经元? | ISI violations、SNR、isolation distance、L-ratio、D-prime |
| 完整性(II 型错误) | 是否遗漏尖峰? | amplitude cutoff、presence ratio |
| 稳定性 | 单元是否随时间稳定? | drift_ptp、drift_std、drift_mad、amplitude CV |
常用判读阈值:isi_violations_ratio小于 0.01 为优秀单单元、0.01–0.1 良好、0.1–0.5 可能为 MUA、大于 0.5 基本可判为多单元;snr大于 10 优秀、5–10 良好、2–5 可接受、小于 2 可能为噪声;amplitude_cutoff小于 0.01 近乎完整(精确时间分析建议用此标准);presence_ratio大于 0.99 优秀、0.9–0.99 良好、小于 0.8 可能已漂移出记录范围。涉及 PCA 的指标(isolation distance、L-ratio、D-prime、nn_hit_rate 等)需要先计算principal_components扩展。
该文档还给出了不同实验目的的过滤查询模板:Allen 默认、IBL 标准、严格单单元、以及包含 MUA 的宽松标准,并演示了si.plot_quality_metrics(analyzer)、si.plot_unit_summary(analyzer, unit_id=0)等可视化手段,以及用qm['custom_score'] = qm['snr'] * qm['presence_ratio'] / (qm['isi_violations_ratio'] + 0.001)构造自定义指标的方式。
安装与环境
要求 Python ≥ 3.10,推荐使用uv:
# 核心包(SpikeInterface 自带 curation/模型工具) uv pip install "spikeinterface[full]" probeinterface neo # 尖峰排序器 uv pip install kilosort # Kilosort4(需要 CUDA GPU) uv pip install spykingcircus # SpykingCircus(旧版;SpykingCircus2 随 SpikeInterface 发布) uv pip install mountainsort5 # Mountainsort5(CPU) # 模型筛选(UnitRefine 从 Hugging Face 下载) uv pip install "huggingface_hub" skops # 可选:AI 辅助视觉筛选 uv pip install anthropic # 可选:IBL 工具与 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/ # 保存的预处理记录 ├── motion/ # 运动估计结果 ├── sorting_output/ # 排序器输出 ├── analyzer/ # SortingAnalyzer(波形、指标) ├── phy_export/ # 人工筛选用 ├── ai_curation/ # AI 分析报告 └── results/ ├── quality_metrics.csv ├── curation_labels.json └── output.nwb源码级验证:为什么阈值值得信任
一个值得强调的工程细节:本技能的 curation 逻辑并非"写了就算数",而是有测试强约束的。仓库 tests/neuropixels-analysis/test_scripts.py 明确说明:这些脚本大部分是对 SpikeInterface 的薄封装,但"哪些单元能进入最终发表结果"是纯逻辑(阈值及其分类),因此测试对每个分类阈值做双侧边界验证、验证未知 curation 方法必须抛错而非静默丢弃单元、验证排序器预设不会导致预处理被执行两次、验证 384 通道探针的波形图会抽稀到 20 条而非全画。这类"静默科学错误"(如阈值漂移、预设名互换)比崩溃更危险——它不会报错,但会让错误单元进入论文。这正是本技能相对手工分析脚本的核心价值:把经验阈值固化为可测试、可复现的代码资产。
总结
scientific-agent-skills/neuropixels-analysis提供了一条从原始 Neuropixels 记录到精选单元的完整、可复现分析路径:加载 → 预处理 → 漂移检测/校正 → 排序 → 后处理 → 质量指标 → 阈值/模型/AI 筛选 → 导出。通过真实 SpikeInterface API、可运行的脚本族、可编辑的模板以及被测试锁定的 curation 阈值,它把 Allen Institute、IBL 的最佳实践工程化,可直接嵌入 Agent 工作流中,帮助研究人员把精力集中在科学问题而非管道调试上。动手实践时,推荐顺序为:先用explore_recording.py熟悉数据,再用neuropixels_pipeline.py跑通全流程,最后针对你的脑区与实验目标调整analysis_template.py中的参数。
【免费下载链接】scientific-agent-skillsTurn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 190,000+ scientists worldwide. 165 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.项目地址: https://gitcode.com/GitHub_Trending/cl/scientific-agent-skills
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考