Communitygithub.com

neuropixels-analysis

SpikeInterfaceを使用したNeuropixels細胞外記録のエンドツーエンド解析。SpikeGLX/Open Ephys/NWBデータの読み込み、前処理、ドリフト/モーション補正、Kilosort4(およびCPU)スパイクソーティング、品質指標、ユニットキュレーション(閾値ベース、モデルベースUnitRefine、AI支援ビジュアルレビュー)をカバーします。Neuropixels 1.0/2.0記録、スパイクソーティング、または細胞外電気生理学解析に使用します。

neuropixels-analysis とは?

このスキルは、Neuropixels高密度神経記録の解析のための包括的なツールキットであり、SpikeInterface、Allen Institute、International Brain Laboratory (IBL) のベストプラクティスに基づいています。生データから出版可能なキュレーションユニットまでの全ワークフローをカバーし、SpikeGLX、Open Ephys、NWB形式の読み込み、フィルタリングや共通リファレンスなどの前処理、ドリフト/モーション補正、Kilosort4(CUDA GPU)やSpykingCircus2(CPU)などのスパイクソーター、SNRやISI違反などの品質指標計算、閾値ベースおよびモデルベース(UnitRefine)のキュレーション、AI支援のビジュアルレビューを提供します。このスキルはClaude Code、Cursor、CodexなどのAIエージェントで動作し、SpikeInterfaceの実際のAPI(spikeinterface.full as si)とキュレーションモジュール(spikeinterface.curation as sc)を使用します。主な利点は、最小限のセットアップでエンドツーエンドの解析を可能にし、スクリプトとテンプレートを同梱していること、さらにAIエージェントが波形や相関図を直接検査して不確かなユニットの専門家評価を提供できることです。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

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.0960384ADC補正にはphase_shiftを使用
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

# グローバルジョブ引数は、並列化可能なすべてのステップで再利用されます
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,
)

各呼び出しは、ユニットごとに prediction と probability(信頼度)を含むDataFrameを返します。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"])  # シェルで設定し、コードには記述しない

完全なパターン(ユニットサマリー画像のレンダリング、プロンプトの構築、応答の解析)については、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. 再現性のために閾値とモデルリポジトリ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/
│   └── (spikeinterface バイナリフォルダ)
├── motion/
│   └── (モーション補正ファイル)
├── ks4_output/
│   └── (Kilosort4 結果)
├── analyzer/
│   └── (ソーティングアナライザ)
├── analyzer_clean/
│   └── (キュレーション後のソーティングアナライザ)
├── phy_export/
│   └── (Phy フォルダ)
├── report/
│   └── (品質レポートの図)
├── quality_metrics.csv
├── output.nwb
├── 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

ライセンス

このプロジェクトはMITライセンスの下で配布されています。詳細については LICENSE ファイルを参照してください。

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.

関連スキル