Neuropixels 数据分析的 SpikeInterface 完整 API 速查实战指南(scientific-agent-skills)

Neuropixels 数据分析的 SpikeInterface 完整 API 速查实战指南(scientific-agent-skills) Neuropixels 数据分析的 SpikeInterface 完整 API 速查实战指南scientific-agent-skills【免费下载链接】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 仓库中neuropixels-analysis技能的 SpikeInterface API 参考面向从事 Neuropixels 1.0/2.0 细胞外电生理记录的开发者与研究人员。它以真实 SpikeInterface API 为骨架覆盖从数据加载、预处理、漂移校正、尖峰排序、后处理分析、质量评估到单元筛选与导出的全链路核心函数读完本文你将能独立编写一条端到端的 Neuropixels 分析流水线并理解每个关键参数对结果的实际影响。所有示例代码都基于 SpikeInterface ≥ 0.104 版本编写并可与仓库中已提供的脚本如 neuropixels_pipeline.py、compute_metrics.py相互对照直接复制使用。导入方式与全局并行配置本 skill 全部围绕 SpikeInterface 的三个核心模块展开完整功能入口spikeinterface.full、模型驱动的筛选工具spikeinterface.curation、以及可视化组件spikeinterface.widgets。在脚本开头统一导入import spikeinterface.full as si import spikeinterface.curation as sc import spikeinterface.widgets as swSpikeInterface 中凡是可并行化的计算步骤滤波、坏通道检测、峰值检测、波形提取、质量指标等都复用同一套作业参数。推荐在程序入口一次性设置全局并行参数后续所有步骤自动继承无需逐个函数重复指定si.set_global_job_kwargs(n_jobs-1, chunk_duration1s, progress_barTrue)其中n_jobs-1表示使用全部 CPU 核心chunk_duration1s按 1 秒数据块切分并行任务progress_barTrue在长耗时步骤显示进度条。这一做法在仓库的流水线脚本中得到了完整印证——neuropixels_pipeline.py 中保存预处理数据时同样显式传入了n_jobs8, chunk_duration1s, progress_barTrue的作业参数。数据加载Loading检查数据流Neuropixels 采集系统SpikeGLX的单个实验目录下往往同时存在多个数据流行动作电位ap、局部场电位lf以及同步通道nidq。加载前应先用get_neo_streams查看可用流再按名称精确选择stream_names, stream_ids si.get_neo_streams(spikeglx, /path/to/run_g0/) # stream_names - [imec0.ap, imec0.lf, nidq]三种读取器si.read_spikeglx(folder_path, stream_nameimec0.ap, load_sync_channelFalse) si.read_openephys(folder_path, stream_nameNone) si.read_nwb(file_path)加载时的选择依据如下数据来源典型扩展名读取函数说明SpikeGLX.ap.bin、.lf.bin、.metasi.read_spikeglx()最常用需指定stream_nameOpen Ephys.continuous、.oebinsi.read_openephys()可指定或自动选择流NWB.nwbsi.read_nwb()标准神经数据容器格式实践要点优先使用stream_name来自get_neo_streams的返回值而不是stream_id选择数据流因为流名称在数据集间语义更稳定。加载 SpikeGLX 时通常设置load_sync_channelFalse将同步通道排除在神经数据分析之外。仓库的 neuropixels_pipeline.py 实现了一套自动格式探测逻辑目录中存在*.ap.bin或*.ap.meta时走 SpikeGLX 分支先调用get_neo_streams打印可用流再按stream_name加载存在*.oebin时走 Open Ephys 分支否则抛出ValueError可直接作为你自己的数据加载骨架。录制对象内省无论来自哪种格式加载后得到的都是一个统一接口的录制Recording对象可调用如下方法了解数据全貌recording.get_num_channels() recording.get_total_duration() # seconds recording.get_sampling_frequency() # Hz recording.get_channel_locations() recording.get_probe() recording.frame_slice(start_frame, end_frame)其中frame_slice按采样帧切片数据常用来截取前几十秒做快速迭代。例如先取采样率fs recording.get_sampling_frequency()再recording.frame_slice(0, int(60 * fs))即可只保留前 60 秒数据验证整条流水线见 SKILL.md。预处理Preprocessing预处理是决定尖峰排序质量的第一道关口。SpikeInterface 提供了从滤波、坏通道处理到参考化的完整工具链si.highpass_filter(recording, freq_min400.0) si.bandpass_filter(recording, freq_min300.0, freq_max6000.0) si.phase_shift(recording) # ADC phase correction (NP 1.0) si.detect_bad_channels(recording) # - (bad_channel_ids, channel_labels) recording.remove_channels(bad_channel_ids) si.common_reference(recording, operatormedian, referenceglobal) si.highpass_spatial_filter(recording) # IBL-style destriping si.get_noise_levels(recording, return_in_uVFalse) recording.save(folderpreprocessed/, formatbinary)各函数的作用与关键参数highpass_filter(recording, freq_min400.0)高通滤波去除低频漂移。Neuropixels 场景常用 300–400 Hz 截止频率仓库 analysis_template.py 的默认参数为FREQ_MIN 300、FREQ_MAX 6000对应 bandpass 用法。detect_bad_channels自动识别坏通道噪声过大、饱和或断线的通道返回一个二元组(bad_channel_ids, channel_labels)。务必同时解包两个返回值然后交给remove_channels移除。phase_shift针对 Neuropixels 1.0 的 ADC 采样时序偏移做相位校正2.0 无需调用。common_reference(recording, operatormedian, referenceglobal)全局中位数参考可显著消除共用噪声。这是 Allen Institute / IBL 推荐链路中的标准步骤。highpass_spatial_filterIBL 风格的去条纹空间滤波用于进一步抑制跨通道共模伪迹。get_noise_levels(recording, return_in_uVFalse)估算每个通道的噪声水平后续峰值检测需要作为输入。recording.save(folder..., formatbinary)把内存中的处理链固化到磁盘二进制格式避免重复计算同时 Kilosort 系列排序器本身就要求输入二进制录制文件。推荐的处理链与仓库 neuropixels_pipeline.py 中preprocess()的实现完全一致是高通滤波 → 检测并移除坏通道 → 相位校正仅 NP 1.0→ 全局中位数参考最后save落盘rec si.highpass_filter(recording, freq_min400.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, operatormedian, referenceglobal) rec rec.save(folderpreprocessed/, formatbinary)漂移检测与运动校正在体长时程记录中探针与组织间的相对位移会使同一神经元的波形特征在深度维度上缓慢漂移严重劣化排序质量。因此排序前务必先检测漂移。检测漂移峰值检测 定位from spikeinterface.sortingcomponents.peak_detection import detect_peaks from spikeinterface.sortingcomponents.peak_localization import localize_peaks peaks detect_peaks(rec, methodlocally_exclusive, noise_levelsnoise_levels, detect_threshold5, radius_um50.0) peak_locations localize_peaks(rec, peaks, methodcenter_of_mass)detect_peaks的locally_exclusive方法在给定半径radius_um50.0内保留局部极大值detect_threshold5表示以噪声水平noise_levels的 5 倍标准差作为检测阈值随后localize_peaks用center_of_mass质心法估算每个峰的空间位置。有了峰的时间sample_index与深度y即可绘制漂移栅格图drift raster直观判断si.plot_drift_raster_map(peakspeaks, peak_locationspeak_locations, recordingrec, clim(-50, 50))一键运动校正SpikeInterface 提供了封装完整的correct_motion只需选择一个预设preset即可完成估计位移场 按位移场重新采样通道的全过程rec_corrected si.correct_motion(rec, presetnonrigid_fast_and_accurate, foldermotion/)预设选项Preset适用场景rigid_fast全局刚性位移追求速度kilosort_like复现 Kilosort 内部的位移估计策略nonrigid_accurate严重漂移深度依赖的非刚性形变精度优先nonrigid_fast_and_accurate推荐默认速度与精度的平衡dredge/dredge_fast基于深度学习的前沿方法质量上限最高仓库的流水线脚本给出了漂移的量化判定标准check_drift() 用峰深度的 P95 与 P5 百分位之差作为漂移幅度估计并在run_pipeline()中当漂移幅度超过 20 μm 时才自动触发运动校正见 neuropixels_pipeline.py漂移较小时直接跳过以节省算力。这一工程化取舍与 SKILL.md 中漂移 ~10 μm 即显著影响质量的经验阈值相互呼应建议作为你自己的判定起点。补充如果需要把位移场可视化出来correct_motion(..., output_motion_infoTrue)会返回(recording, motion_info)二元组可直接用sw.plot_motion_info(motion_info, recordingrecording)绘制漂移栅格与位移场叠加图细节见 plotting_guide.md。尖峰排序Spike Sorting排序器管理与默认参数si.installed_sorters() si.available_sorters() si.get_default_sorter_params(kilosort4)installed_sorters()当前环境已安装的排序器available_sorters()SpikeInterface 支持但未必已安装的全部排序器get_default_sorter_params(kilosort4)查看某个排序器的默认参数字典便于复制后局部修改。运行排序器sorting si.run_sorter( kilosort4, # sorter name recording, folderks4_output, # NOT output_folder (deprecated) verboseTrue, # sorter-specific kwargs, e.g. Th_universal9, Th_learned8, nblocks5, batch_size60000 )重要新版本中输出目录参数是folder旧参数名output_folder已废弃。这一约定在仓库脚本中也有明确注释印证见 run_sorting.py 与 SKILL.md。容器化运行外部排序器——如果某个排序器如 Kilosort 2.5本地未安装可以让 SpikeInterface 自动拉取容器镜像运行无需本地安装si.run_sorter(kilosort2_5, recording, folderks25/, docker_imageTrue)读回已运行的排序结果——排序输出目录本身可以被直接重新加载为 Sorting 对象便于跨会话继续分析sorting si.read_sorter_folder(ks4_output)仓库 run_sorting.py 内置了各排序器的推荐默认参数是调参的实用起点排序器默认参数说明kilosort4batch_size30000, nblocks1, Th_learned8, Th_universal9CUDA GPU 推荐速度最快kilosort3do_CARFalse预处理阶段已做过共模参考避免重复spykingcircus2apply_preprocessingFalseCPU 可跑内部自带预处理开关mountainsort5filterFalse, whitenFalseCPU 可跑同样避免重复预处理其中 Kilosort4 是默认推荐Th_universal/Th_learned是检测阈值调低会检测到更多峰代价是噪声单元增多nblocks控制漂移分块数长时程、漂移明显的记录应增大batch_size是每批处理的采样点数。Sorting 对象内省sorting.unit_ids sorting.get_total_num_spikes() sorting.get_unit_spike_train(unit_id) sorting.select_units(unit_ids) sorting.to_spike_vector()select_units用于按单元子集过滤排序结果是后续筛选的基本工具to_spike_vector()返回一个结构化数组包含unit_index、sample_index等字段是快速访问全部峰事件的底层接口。后处理SortingAnalyzer排序器输出的只是哪个单元在哪一帧放电所有需要波形、模板、指标的分析都必须先基于排序结果与原始录制构建SortingAnalyzeranalyzer si.create_sorting_analyzer( sorting, recording, sparseTrue, formatbinary_folder, # or memory / zarr folderanalyzer/, )sparseTrue只为每个单元保留邻近通道的波形Neuropixels 高密度记录下的关键省内存选项format存储后端可选binary_folder默认推荐、memory纯内存适合小数据或zarr适合云/分布式folder持久化目录。扩展计算顺序很重要SortingAnalyzer 的核心设计是扩展extension体系——每个分析结果波形、模板、指标都是一个扩展且存在依赖关系必须先计算random_spikes才能算waveforms先有waveforms才能算templates其余扩展大多依赖模板或峰信息。仓库 neuropixels_pipeline.py 中的postprocess()严格遵循了这一顺序analyzer.compute(random_spikes, methoduniform, max_spikes_per_unit500) analyzer.compute(waveforms, ms_before1.0, ms_after2.0) analyzer.compute(templates, operators[average, std]) analyzer.compute(noise_levels) analyzer.compute(spike_amplitudes) analyzer.compute(correlograms, window_ms50.0, bin_ms1.0) analyzer.compute(unit_locations, methodmonopolar_triangulation) analyzer.compute(spike_locations, methodcenter_of_mass) analyzer.compute(template_similarity) analyzer.compute(principal_components, n_components5, modeby_channel_local)各扩展的含义与关键参数扩展参数示例作用random_spikesmethoduniform, max_spikes_per_unit500抽取每单元随机峰供波形提取使用waveformsms_before1.0, ms_after2.0提取峰前后时间窗的原始波形片段templatesoperators[average, std]由波形聚合出平均模板与标准差noise_levels—各通道噪声水平spike_amplitudes—逐峰幅度correlogramswindow_ms50.0, bin_ms1.0自/互相关图数据unit_locationsmethodmonopolar_triangulation单极三角定位法估计单元深度位置spike_locationsmethodcenter_of_mass逐峰质心定位template_similarity—单元模板两两相似度去冗余用principal_componentsn_components5, modeby_channel_local局部通道 PCAPCA 类指标的前置依赖也可以一次提交多个扩展SpikeInterface 会按内部依赖自动排序analyzer.compute([random_spikes, waveforms, templates, noise_levels])访问、持久化与子集化analyzer.get_extension(quality_metrics).get_data() analyzer.get_extension(templates).get_unit_template(unit_id, operatoraverage) si.load_sorting_analyzer(analyzer/) analyzer.select_units(unit_ids, folderanalyzer_clean/, formatbinary_folder) analyzer.remove_units(unit_ids)get_extension(...).get_data()是取回扩展结果的标准入口select_units生成只含指定单元的干净 analyzer 副本如筛选后导出remove_units则在原对象上删除单元常用于模型筛选后保留存活的单元继续下游分析见下文 UnitRefine 用法。质量指标Quality Metrics有了波形、模板与相关图扩展后即可一次性计算整套质量指标用于客观评估每个单元的单单元纯净度metric_names [firing_rate, presence_ratio, snr, isi_violation, amplitude_cutoff, amplitude_cv, sliding_rp_violation] analyzer.compute(quality_metrics, metric_namesmetric_names) metrics analyzer.get_extension(quality_metrics).get_data() # Equivalent standalone helper metrics si.compute_quality_metrics(analyzer, metric_namesmetric_names)两种写法等价通过扩展机制缓存结果或用独立的si.compute_quality_metrics一次性函数仓库 compute_metrics.py 使用的就是后者。返回值是一个以单元 ID 为索引的 pandas DataFrame。常见指标列snr信噪比、firing_rate放电率、presence_ratio在记录全程的出现比例反映单元是否持续放电、amplitude_cutoff幅度分布截断比例高值说明漏检峰、isi_violations_ratio不应期违反率衡量多单元污染、isi_violations_count违反次数。PCA 类指标前置条件isolation_distance、l_ratio、d_prime、nn_hit_rate等基于特征空间的指标必须先计算principal_components扩展analyzer.compute(principal_components)才能计算否则会报错或缺失。单元筛选Curation阈值法Allen 风格查询得到指标 DataFrame 后最直接的筛选方式就是用 pandas 查询语法组合多个阈值。仓库 compute_metrics.py 与 SKILL.md 均以 Allen Institute / IBL 的经典标准为例query (amplitude_cutoff 0.1) (isi_violations_ratio 0.5) (presence_ratio 0.9) good_unit_ids metrics.query(query).index.values clean sorting.select_units(good_unit_ids)注意列名细节指标 DataFrame 中不应期违反的列名是isi_violations_ratio而非扩展名中的isi_violation写查询时不要拼错。仓库进一步把阈值沉淀为三种可复用预设见 compute_metrics.py可直接用--curation参数切换预设snrisi_violations_ratiopresence_ratioamplitude_cutoff来源allen≥ 3.0 0.5 0.9 0.1Allen Visual Codingibl≥ 4.0 0.1 0.9 0.1IBL reproducible-ephysstrict≥ 5.0 0.01 0.95 0.05严格单单元标准对应命令行python skills/neuropixels-analysis/scripts/compute_metrics.py sorting/ preprocessed/ --output metrics/ --curation ibl模型法UnitRefineHugging Face 预训练分类器spikeinterface.curation模块可以加载在真实 Neuropixels 数据V1、SC、ALM 脑区上训练的机器学习分类器自动给每个单元打标签import spikeinterface.curation as sc labels sc.model_based_label_units( sorting_analyzeranalyzer, repo_idSpikeInterface/UnitRefine_noise_neural_classifier, trust_modelTrue, ) # labels - DataFrame with prediction and probability columns典型的两阶段用法先用UnitRefine_noise_neural_classifier剔除噪声单元再对存活单元用UnitRefine_sua_mua_classifier区分单单元sua与多单元mua详见 SKILL.md。每次调用返回的 DataFrame 包含每个单元的prediction类别与probability置信度。如果想显式加载模型对象以检查其属性例如查看训练时的特征列feature_names_in_可以使用model, model_info sc.load_model(repo_idSpikeInterface/toy_tetrode_model, trusted[numpy.dtype])安全提示trust_modelTrue或显式传入trusted[...]列表是加载.skops模型所必需的只应加载来自可信来源的模型。此外在不同脑区/数据集上训练的模型迁移能力有限正式实验前建议与人工标注子集交叉验证。手动编辑CurationSorting对自动筛选拿不准的单元可以直接用CurationSorting做命令式手动修改from spikeinterface.curation import CurationSorting cur CurationSorting(sorting) cur.remove_units(noise_unit_ids) sorting_curated cur.sorting可视化Widgetsspikeinterface.widgets为流水线各阶段提供一站式绘图函数sw.plot_probe_map(recording, with_channel_idsTrue) sw.plot_traces({filtered: rec1, cmr: rec2}, backendmatplotlib, clim(-50, 50)) si.plot_drift_raster_map(peakspeaks, peak_locationspeak_locations, recordingrec, clim(-50, 50)) sw.plot_unit_waveforms(analyzer, unit_ids[0]) sw.plot_unit_templates(analyzer, unit_ids[0, 1, 2]) sw.plot_autocorrelograms(analyzer, unit_ids[0]) sw.plot_amplitudes(analyzer, unit_ids[0], plot_histogramsTrue) sw.plot_unit_locations(analyzer) si.plot_sorting_summary(analyzer, backendsortingview) # web-based viewerplot_probe_map绘制探针通道布局with_channel_idsTrue标注通道号plot_traces对比处理前后的原始轨迹传入字典可为不同处理阶段命名clim控制幅度显示范围plot_unit_waveforms/plot_unit_templates单元波形与平均模板plot_autocorrelograms自相关图肉眼评估不应期与多单元污染的利器plot_amplitudes幅度随时间散点 直方图检测幅度漂移与截断plot_unit_locations单元在探针上的空间分布plot_sorting_summary(analyzer, backendsortingview)在浏览器中打开交互式排序总览支持缩放、点选单元逐项审查。更完整的出版级绘图配方含plot_unit_summary单单元总览面板、plot_crosscorrelograms交叉相关、ISI 分布、指标分布与 colorblind 友好配色等参见仓库的 plotting_guide.md。结果导出Export筛选出好单元后analyzer_clean analyzer.select_units(good_unit_ids, ...)可按需导出为多种下游格式si.export_to_phy(analyzer, output_folderphy_export/, compute_pc_featuresTrue, compute_amplitudesTrue, copy_binaryTrue) si.export_report(analyzer, report/, formatpng) from spikeinterface.exporters import export_to_nwb export_to_nwb(analyzer, output.nwb) si.read_phy(phy_export/) # load Phy curation backPhyexport_to_phy生成params.py与特征文件可在 Phy 图形界面中人工检查单元并重新标注compute_pc_featuresTrue, compute_amplitudesTrue生成人工审查所需的特征copy_binaryTrue将原始数据复制到导出目录使其自包含。仓库 analysis_template.py 给出了用phy template-gui phy_export/params.py打开导出的完整命令。报告export_report把波形、模板、相关图等一揽子渲染为 PNG 报告适合快速留档。NWBexport_to_nwb导出为标准神经数据格式便于共享与归档。read_phy把 Phy 中人工筛选后的结果读回为 Sorting 对象衔接自动筛选 → 人工复审闭环。参数命名区分export_to_phy和export_report使用output_folder这是正确用法与run_sorter/create_sorting_analyzer的folder不同两者不要混淆。把 API 串成一条完整流水线API 速查的最终价值在于串联。仓库 neuropixels_pipeline.py 把上述全部环节封装为一条端到端流水线加载 → 预处理 → 漂移检查 → 按需运动校正 → 排序 → 后处理 → 质量指标 → 筛选 → 导出一键运行python skills/neuropixels-analysis/scripts/neuropixels_pipeline.py /path/to/spikeglx/data output/ --sorter kilosort4 --curation allen命令行参数包括--sorterkilosort4/kilosort3/spykingcircus2/mountainsort5、--stream默认imec0.ap、--no-motion-correction跳过运动校正与--curationallen/ibl/strict。配套的分步脚本同样可独立运行适合分阶段调试脚本用途示例命令explore_recording.py快速检查录制信息流、通道、时长、坏通道python .../explore_recording.py /path/to/datapreprocess_recording.py自动化预处理python .../preprocess_recording.py /path/to/data --output preprocessed/run_sorting.py运行排序python .../run_sorting.py preprocessed/ --sorter kilosort4 --output sorting/compute_metrics.py指标计算与阈值筛选python .../compute_metrics.py sorting/ preprocessed/ --output metrics/ --curation allenexport_to_phy.py导出 Phy 人工复审python .../export_to_phy.py metrics/analyzer --output phy_export/对希望完全掌控每一步的研究者analysis_template.py 提供了带完整PARAMETERS配置区的可编辑模板顶部集中设置路径、滤波频率FREQ_MIN/FREQ_MAX、是否相位校正APPLY_PHASE_SHIFT、是否共模参考APPLY_CMR、运动校正预设MOTION_PRESET、排序器与参数SORTER_PARAMS、筛选预设CURATION_METHOD以及并行核数N_JOBS-1复制后改参数即可运行。关键参数调优速查预处理freq_min高通截止频率Neuropixels 典型值 300–400 Hz400 Hz 更激进300 Hz 保留更多低频能量。运动校正preset按漂移严重程度选择——nonrigid_fast_and_accurate是通用默认严重漂移用nonrigid_accurate追求最高质量用dredge。Kilosort4batch_size默认 60000 采样点可下调至 30000 控制显存、nblocks漂移分块长且漂移大的记录调高、Th_universal/Th_learned阈值调低 → 检出更多峰噪声单元增多。质量指标阈值snr典型 3–5见上表预设isi_violations_ratio0.01–0.5越严越接近单单元presence_ratio0.5–0.95低值说明单元只在部分时段放电。实践忠告自动阈值与模型筛选只是起点而非终审——对边界单元应结合波形、自相关图与人工或 AI 辅助复查Phy 导出用于关键实验的人工把关同时务必在分析记录中写明所用阈值与模型 repo ID保证结果可复现。详细的筛选策略与 Bombcell / UnitMatch 工具对比可进一步阅读 AUTOMATED_CURATION.mdAI 辅助审查的模式参见 AI_CURATION.md完整流程详见 standard_workflow.md。【免费下载链接】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),仅供参考