mcpField
N
neuropixels-analysis

neuropixels-analysis

github.com/kalarislabsデータ・データベース8441 回インストール1 日前に更新
リポジトリ

neuropixels-analysis について

neuropixels-analysisは、SpikeInterfaceを使って高密度Neuropixels記録を解析する研究者向けスキルです。実行可能なスクリプトと編集用テンプレートで、前処理からユニットのキュレーション、エクスポートまでを扱います。

主な機能

  1. 01SpikeGLX、Open Ephys、NWBの読み込み
  2. 02記録の前処理とドリフト補正
  3. 03複数のスパイクソーターに対応
  4. 04品質指標の計算とユニット選別
  5. 05モデルによるユニット分類
  6. 06PhyまたはNWBへのエクスポート

活用シーン

  1. 01チャンネルを確認して記録を前処理
  2. 02Neuropixelsデータのスパイクソーティング
  3. 03指標やモデルによるユニット選別
  4. 04整理した結果を手動レビュー用に出力

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/kalarislabs/research-agent-skills --skill neuropixels-analysis

インストール後、Claude Code で/neuropixels-analysisを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

assets/
analysis_template.py
references/
AI_CURATION.md
ANALYSIS.md
api_reference.md
AUTOMATED_CURATION.md
MOTION_CORRECTION.md
plotting_guide.md
PREPROCESSING.md
QUALITY_METRICS.md
SPIKE_SORTING.md
standard_workflow.md
scripts/
compute_metrics.py
explore_recording.py
export_to_phy.py
neuropixels_pipeline.py
preprocess_recording.py
run_sorting.py

詳細

Neuropixels データ解析

概要

SpikeInterface、Allen Institute、International Brain Laboratory(IBL)の最新のベストプラクティスを活用して、Neuropixels の高密度神経記録を解析するツールキットです。生データから、論文に掲載できる品質のキュレーション済みユニットまで、全ワークフローをカバーします。

すべての例で、SpikeInterface の実際の API(spikeinterface.full as si)と、付属のキュレーションモジュール(spikeinterface.curation as sc)を使用します。このスキルには、このワークフローを SpikeInterface 上で直接実行するスクリプトが scripts/ に、コピーして編集できるテンプレートが assets/ に含まれています。インストールに記載された依存関係以外に、別途インストールが必要なパッケージはありません。

このスキルを使用する場面

次のような場合に、このスキルを使用してください。

  • 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

# Global job kwargs are reused by all parallelizable steps
si.set_global_job_kwargs(n_jobs=-1, chunk_duration="1s", progress_bar=True)
データの読み込み
# Inspect available streams first
stream_names, stream_ids = si.get_neo_streams("spikeglx", "/path/to/run_g0/")
print(stream_names)  # e.g. ['imec0.ap', 'imec0.lf', 'nidq']

# SpikeGLX (most common) — select the AP stream by name
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/")

# For quick iteration, slice the first 60 s
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 phase correction (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")

# Visualize the drift raster
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 (recommended, requires a CUDA GPU)
sorting = si.run_sorter("kilosort4", rec_corrected, folder="ks4_output")

# CPU alternatives (internally developed, no external install)
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")

# External sorters can run in containers without local install
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-style query (note: column is 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) noise vs neural
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) single-unit (sua) vs multi-unit (mua) on the surviving units
sua_mua_labels = sc.model_based_label_units(
    sorting_analyzer=neural,
    repo_id="SpikeInterface/UnitRefine_sua_mua_classifier",
    trust_model=True,
)

各呼び出しは、ユニットごとの prediction と probability(信頼度)を含む DataFrame を返します。.skops モデルの読み込みには trust_model=True(または明示的な trusted=[...] リスト)が必要です。信頼できるソースのモデルのみを読み込んでください。他の脳領域やデータセットで学習されたモデルでは、期待どおりに機能しない場合があります。手動でラベル付けしたサブセットと照合して検証してください。

7. AI 支援によるキュレーション(ユニットの判定が不確かな場合)

Cursor や Claude Code などのエージェント内で実行する場合、エージェントは波形/コレログラムのプロットを直接確認し、専門家の視点で評価できます。API のセットアップは不要です。プロットを生成して、分離品質を評価するようエージェントに依頼してください。

プログラムからビジョンモデルにアクセスする場合は、API キーを環境変数から読み込んでください。解析スクリプトに認証情報をハードコードしないでください(バージョン管理やログに漏れる可能性があります)。

import os
from anthropic import Anthropic

client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])  # set this in your shell, not in code

詳しい手順(ユニットの概要画像のレンダリング、プロンプトの作成、応答の解析)については、references/AI_CURATION.md を参照してください。

8. 結果をエクスポートする
# Keep only good units, then export
analyzer_clean = analyzer.select_units(good_unit_ids, folder="analyzer_clean/", format="binary_folder")

# Phy for manual review
si.export_to_phy(analyzer_clean, output_folder="phy_export/",
                 compute_pc_features=True, compute_amplitudes=True)

# Figures report
si.export_report(analyzer_clean, "report/", format="png")

# NWB
from spikeinterface.exporters import export_to_nwb
export_to_nwb(analyzer_clean, "output.nwb")

# Metrics table
metrics.to_csv("quality_metrics.csv")

よくある落とし穴とベストプラクティス

  1. スパイクソーティングの前に必ずドリフトを確認してください。ドリフトが約 10 μm を超えると、品質が大きく低下します。
  2. Neuropixels 1.0 では、ADC サンプリングオフセットを補正するために phase_shift を使用してください。
  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
# Edit the PARAMETERS section, then run
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 の使用を推奨します。

# Core packages (SpikeInterface bundles the curation/model tooling)
uv pip install "spikeinterface[full]" probeinterface neo

# Spike sorters
uv pip install kilosort          # Kilosort4 (CUDA GPU required)
uv pip install spykingcircus     # SpykingCircus (legacy; SpykingCircus2 ships with SpikeInterface)
uv pip install mountainsort5     # Mountainsort5 (CPU)

# Model-based curation (UnitRefine) downloads from Hugging Face
uv pip install "huggingface_hub" skops

# Optional: AI-assisted visual curation
uv pip install anthropic

# Optional: IBL tools and 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/           # Saved preprocessed recording
├── motion/                 # Motion estimation results
├── sorting_output/         # Spike sorter output
├── analyzer/               # SortingAnalyzer (waveforms, metrics)
├── phy_export/             # For manual curation
├── ai_curation/            # AI analysis reports
└── results/
    ├── quality_metrics.csv
    ├── curation_labels.json
    └── output.nwb

追加リソース

エージェントの作業手順

  1. 環境を確認します。 ツールのバージョン、参照ゲノム/アノテーションのビルド、入力形式(FASTQ、BAM、VCF、h5ad)を確認します。
  2. 入力を特定します。 データまたはユーザーから、形式、識別子、パラメーターを確認します。結果に影響する値は推測せず、質問してください。
  3. まず小規模に実行します。 最初に小さなサブセット(サンプル1件、染色体1本、数千個の細胞)でパイプラインを実行します。
  4. 上記の手順と参考資料を使用して、タスク全体を実行します。
  5. 結果を検証します。 結果を解釈する前に、QC 指標、サンプルの同一性、ゲノムビルドの一貫性、バッチ効果を確認します。
  6. 報告します。 実行した内容(バージョン、コマンド、パラメーター)、確認した内容、未確定事項を明記します。
このような場合次の対応
入力間でゲノムビルドまたは識別子が一致しない続行する前に停止し、整合性を取ります(liftover、ID マッピング)。
手順に記載された関数、フラグ、エンドポイントがインストール済みバージョンに存在しないインストール済みバージョンのドキュメント(help()、--help、公式ドキュメント)を確認して適宜変更し、ユーザーに伝えます。API を捏造してはいけません。
必須の入力、識別子、パラメーターが曖昧ユーザーに確認するか、実行前に前提を明示します。

整合性に関するルール

  • 結果、パラメーター、識別子、引用文献、統計値を決して捏造しないでください。実行または検証できない場合は、その旨を明確に伝えます。
  • 統計的な裏付けを超えて生物学的な意義を解釈しないでください。多重検定補正について報告します。
  • ここに記載されたバージョン固有の情報は古くなっている可能性があるため、インストール済みバージョンの公式ドキュメントで確認してください。
  • 費用が発生する、共有 GPU やクラウドのクォータを消費する、個人データや患者データを扱う、または取り消せない操作を行う前に、ユーザーに確認してください。

関連スキル

  • bids: Brain Imaging Data Structure(BIDS)標準を使用して、神経科学および生物医学データセットを整理、検索、検証、変換します。続く…

コメント