Communitygithub.com

neuropixels-analysis

使用 SpikeInterface 对 Neuropixels 细胞外电生理记录进行端到端分析。涵盖 SpikeGLX/Open Ephys/NWB 数据加载、预处理、漂移/运动校正、Kilosort4(及 CPU)尖峰分选、质量指标和单元筛选(基于阈值、基于模型的 UnitRefine 以及 AI 辅助的视觉检查)。在处理 Neuropixels 1.0/2.0 记录、尖峰分选或细胞外电生理分析时使用。

neuropixels-analysis 是什么?

该技能提供了一个全面的分析工具包,专门用于处理 Neuropixels 高密度神经记录。它基于 SpikeInterface 库、Allen 研究所和国际大脑实验室的最佳实践,涵盖了从原始数据到可发表筛选单元的完整工作流程。支持加载常见数据格式(SpikeGLX、Open Ephys、NWB),并集成了预处理(滤波、参考、坏道检测)、漂移/运动校正、多种尖峰分选器(包括 GPU 加速的 Kilosort4 和 CPU 可用的替代方案)以及基于阈值或机器学习模型(UnitRefine,源自 Hugging Face)的自动筛选。此外,该技能还支持 AI 辅助筛选,允许用户通过视觉检查不确定的单元,并且能够导出数据到 Phy、NWB 或其他分析工具。它特别适用于处理 Neuropixels 1.0 和 2.0 探针数据的神经科学家和工程师,提供了一个标准化、可复现的分析流水线,并附带了完整的脚本和模板以简化使用。

兼容平台✓Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/neuropixels-analysis

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Neuropixels 数据分析

概述

用于分析 Neuropixels 高密度神经记录的工具包,遵循来自 SpikeInterface、Allen 研究所和国际大脑实验室 (IBL) 的最新最佳实践。它涵盖了从原始数据到可发表筛选单元的完整工作流程。

所有示例均使用真实的 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.0960384使用 phase_shift 进行 ADC 校正
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

# 全局任务参数会被所有可并行化的步骤重用
si.set_global_job_kwargs(n_jobs=-1, chunk_duration="1s", progress_bar=True)

加载数据

# 首先检查可用的数据流
stream_names, stream_ids = si.get_neo_streams("spikeglx", "/path/to/run_g0/")
print(stream_names)  # 例如 ['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))

完整管道(捆绑脚本)

该仓库提供了一个基于 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 相位校正 (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")

# 可视化漂移光栅图
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(推荐,需要 CUDA GPU)
sorting = si.run_sorter("kilosort4", rec_corrected, folder="ks4_output")

# CPU 替代方案(内部开发,无需外部安装)
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= 已弃用。

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 风格查询(注意:列名是 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) 噪声 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 模型所必需的——仅加载来自您信任源的模型。在其他大脑区域/数据集上训练的模型可能无法迁移;请在手动标记的子集上进行验证。

7. AI 辅助筛选(针对不确定的单元)

当在 Cursor 或 Claude Code 等智能体内部运行时,智能体可以直接检查波形/相关图并给出专家解读——无需 API 设置。生成图表并要求智能体评估隔离质量。

对于编程式视觉模型访问,从环境中读取 API 密钥——切勿在分析脚本中硬编码凭据(它们会泄露到版本控制和日志中):

import os
from anthropic import Anthropic

client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])  # 在您的 shell 中设置此变量,而不是在代码中

请参阅 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")

常见陷阱和最佳实践

  1. 在尖峰分选前务必检查漂移——大于约 10 μm 的漂移会显著降低质量。
  2. 对 Neuropixels 1.0 使用 phase_shift 以校正 ADC 采样偏移。
  3. 保存预处理后的记录,使用 rec.save(folder=...) 以避免重新计算(Kilosort 也需要一个二进制文件)。
  4. 为 Kilosort4 使用 GPU——它比 CPU 分选器快得多。
  5. 审查不确定的单元——自动化/基于模型的筛选是一个起点,而不是最终裁决。
  6. 结合多种方法——对明确情况使用阈值,对边界单元使用模型/AI。
  7. 记录阈值和模型 repo ID 以确保可重复性。
  8. 对于关键实验,导出到 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
# 编辑 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

安装

需要 Python ≥ 3.10。推荐使用 uv。

# 核心包(SpikeInterface 捆绑了筛选/模型工具)
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.lf.bin
├── preprocessed/
├── motion/
├── sorting/
│   └── ks4_output/
├── analyzer/
├── analyzer_clean/
├── phy_export/
├── report/
├── scripts/
│   ├── neuropixels_pipeline.py
│   ├── explore_recording.py
│   ├── preprocess_recording.py
│   ├── run_sorting.py
│   ├── compute_metrics.py
│   └── export_to_phy.py
├── assets/
│   └── analysis_template.py
├── references/
│   ├── standard_workflow.md
│   ├── api_reference.md
│   ├── plotting_guide.md
│   ├── PREPROCESSING.md
│   ├── SPIKE_SORTING.md
│   ├── MOTION_CORRECTION.md
│   ├── QUALITY_METRICS.md
│   ├── AUTOMATED_CURATION.md
│   ├── AI_CURATION.md
│   └── ANALYSIS.md
└── README.md

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

astropy

Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

biopython

Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use bioservices.

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

相关技能