Communitygithub.com

neuropixels-analysis

使用 SpikeInterface 分析 Neuropixels 細胞外電生理記錄的端到端工具。涵蓋載入 SpikeGLX/Open Ephys/NWB 資料、前處理、漂移/運動校正、Kilosort4(及 CPU)尖峰分類、品質指標以及單元篩選(閾值型、模型型 UnitRefine 及 AI 輔助視覺檢查)。適用於 Neuropixels 1.0/2.0 記錄、尖峰分類或細胞外電生理分析。

neuropixels-analysis 是什麼?

這個技能提供了一個基於 SpikeInterface、用於 Neuropixels 高密度神經記錄的完整分析工作流程。它支援從 SpikeGLX、Open Ephys 和 NWB 格式載入資料,並透過標準的前處理鏈進行處理,包括高通濾波、壞通道偵測、相位偏移校正及全域共同參考。該技能特別強調漂移偵測與修正,提供多種預設模式(如非剛體快速精確)來處理記錄過程中的運動偽影。 在尖峰分類方面,它支援 Kilosort4(需 GPU)以及多種 CPU 型分類器(SpykingCircus2、Tridesclous2、Mountainsort5),並可透過 Docker 容器執行外部分類器。後續處理會計算全面的品質指標(如 SNR、ISI 違規、存在率等),並提供三種篩選方式:閾值型(使用 Allen 或 IBL 標準)、模型型(透過 Hugging Face 的 UnitRefine 分類器將單元區分為雜訊、多單元或單一單元),以及 AI 輔助檢查(針對不確定的單元產生圖表並諮詢人類專家或視覺模型)。 此技能適用於 Cursor 或 Claude Code 等代理平台,並在 SKILL.md 中詳述了完整的 Python 程式碼範例。它附帶了可直接執行的腳本和可自訂的範本,涵蓋從資料探索到匯出至 Phy 或 NWB 的完整流程。為了確保可再現性,所有功能皆基於 SpikeInterface 的標準 API。

相容平台✓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 Institute 和 International Brain Laboratory (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 探針)5120384多區域記錄
格式副檔名讀取器
SpikeGLX.ap.bin, .lf.bin, .metasi.read_spikeglx()
Open Ephys.continuous, .oebinsi.read_openephys()
NWB.nwbsi.read_nwb()

快速開始

匯入並設定並行處理

import spikeinterface.full as si

# 全域 job kwargs 會被所有可並行化的步驟重複使用
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。詳情請參閱 references/AUTOMATED_CURATION.md 以及 Bombcell / UnitMatch 工具。

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. 使用 GPU 執行 Kilosort4 —— 它遠比 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/
│   └── (運動校正檔案)
├── ks4_output/
│   └── (Kilosort4 分類結果)
├── analyzer/
│   └── (分析器檔案)
├── phy_export/
│   └── (Phy 匯出檔案)
├── scripts/
│   ├── explore_recording.py
│   ├── preprocess_recording.py
│   ├── run_sorting.py
│   ├── compute_metrics.py
│   ├── export_to_phy.py
│   └── neuropixels_pipeline.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
└── output/
    └── quality_metrics.csv

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.

相關技能