alterlab-neuropixels について
SpikeInterfaceを使ってNeuropixelsの神経記録を解析する研究者向けのスキルです。生データからスパイクソーティング、ユニットの選別、可視化、エクスポートまでを扱います。
主な機能
- 01SpikeGLX、Open Ephys、NWBの記録を読み込み
- 02記録を前処理し不良チャンネルを検出
- 03記録のドリフトを確認・補正
- 04複数のソーターでスパイクソーティング
- 05品質指標を計算しユニットを選別
- 06結果をPhyまたはNWBにエクスポート
活用シーン
- 01生のNeuropixels記録を処理
- 02スパイクを分類しユニット品質を評価
- 03プロットで判定が難しいユニットを確認
- 04選別結果を後続解析用にまとめる
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ alterlab-ieu/ alterlab-academic-skills --skill alterlab-neuropixelsインストール後、Claude Code で/alterlab-neuropixelsを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
assets/analysis_template.pyevals/evals.jsonreferences/AI_CURATION.mdANALYSIS.mdapi_reference.mdAUTOMATED_CURATION.mdMOTION_CORRECTION.mdplotting_guide.mdPREPROCESSING.mdQUALITY_METRICS.mdSPIKE_SORTING.mdstandard_workflow.mdscripts/compute_metrics.pyexplore_recording.pyexport_to_phy.pyneuropixels_pipeline.pypreprocess_recording.pyrun_sorting.py詳細
Neuropixels データ解析
概要
SpikeInterface、Allen Institute、International Brain Laboratory(IBL)で採用されている最新のベストプラクティスに基づいて、Neuropixels の高密度神経記録を解析するための包括的なツールキットです。生データから、公開可能な品質にキュレーションされたユニットまで、全ワークフローをサポートします。
このスキルを使用する場面
次のような場合にこのスキルを使用してください:
- Neuropixels の記録(.ap.bin、.lf.bin、.meta ファイル)を扱う場合
- SpikeGLX、Open Ephys、NWB 形式のデータを読み込む場合
- 神経記録を前処理する場合(フィルタリング、CAR、不良チャンネル検出)
- 記録の動きやドリフトを検出、補正する場合
- スパイクソーティングを実行する場合(Kilosort4、SpykingCircus2、Mountainsort5)
- 品質メトリクスを算出する場合(SNR、ISI 違反、存在比率)
- Allen/IBL の基準を使用してユニットをキュレーションする場合
- 神経データを可視化する場合
- 結果を Phy または NWB にエクスポートする場合
対象外
| シナリオ | 代わりに使用 |
|---|---|
| 電気生理ではなく、単一細胞またはバルクのトランスクリプトミクス | alterlab-scanpy / alterlab-rnaseq-quant |
| フロー/質量サイトメトリーの FCS ファイル | alterlab-flowio |
| 抽出済みスパイク特徴量に対する一般的な時系列統計や ML | alterlab-statistical-analysis / alterlab-scikit-learn |
| 既存のデータから任意の図をプロットする | alterlab-matplotlib / alterlab-scientific-viz |
| コネクティビティ行列のネットワーク/グラフ解析 | alterlab-networkx |
対応ハードウェアと形式
| プローブ | 電極数 | チャンネル数 | 備考 |
|---|---|---|---|
| Neuropixels 1.0 | 960 | 384 | phase_shift 補正が必要です |
| Neuropixels 2.0(単一) | 1280 | 384 | より高密度な配置 |
| Neuropixels 2.0(4 シャンク) | 5120 | 384 | 複数領域の記録 |
| 形式 | 拡張子 | リーダー |
|---|---|---|
| SpikeGLX | .ap.bin、.lf.bin、.meta | si.read_spikeglx() |
| Open Ephys | .continuous、.oebin | si.read_openephys() |
| NWB | .nwb | si.read_nwb() |
クイックスタート
基本的なインポートとセットアップ
import spikeinterface.full as si
# Bundled helper functions live in scripts/neuropixels_pipeline.py
from scripts.neuropixels_pipeline import (
load_recording, preprocess, check_drift, correct_motion,
run_spike_sorting, postprocess, curate_units, export_results, run_pipeline,
)
# Configure parallel processing
job_kwargs = dict(n_jobs=-1, chunk_duration='1s', progress_bar=True)
データの読み込み
# SpikeGLX (most common)
recording = si.read_spikeglx('/path/to/data', stream_id='imec0.ap')
# Open Ephys (common for many labs)
recording = si.read_openephys('/path/to/Record_Node_101/')
# Check available streams
streams, ids = si.get_neo_streams('spikeglx', '/path/to/data')
print(streams) # ['imec0.ap', 'imec0.lf', 'nidq']
# For testing with subset of data
recording = recording.frame_slice(0, int(60 * recording.get_sampling_frequency()))
完全なパイプライン(1 つのコマンド)
# Run full analysis pipeline (writes all outputs under output_path/)
from scripts.neuropixels_pipeline import run_pipeline
run_pipeline(
data_path='/path/to/data',
output_path='output/',
sorter='kilosort4',
stream_name='imec0.ap',
apply_motion_correction=True,
curation_method='allen',
)
# Results are written to disk:
# output/sorting_output/ spike sorter output
# output/analyzer/ SortingAnalyzer (waveforms, metrics)
# output/quality_metrics.csv
# output/curation_labels.json
または、コマンドラインから実行します:
python scripts/neuropixels_pipeline.py /path/to/data output/ --sorter kilosort4 --curation allen
標準的な解析ワークフロー
1. 前処理
# Recommended preprocessing chain
rec = si.highpass_filter(recording, freq_min=400)
rec = si.phase_shift(rec) # Required for Neuropixels 1.0
bad_ids, _ = si.detect_bad_channels(rec)
rec = rec.remove_channels(bad_ids)
rec = si.common_reference(rec, operator='median')
# Or use the bundled wrapper (returns the preprocessed recording + bad channel ids)
from scripts.neuropixels_pipeline import preprocess
rec, bad_channels = preprocess(recording)
2. ドリフトの確認と補正
from scripts.neuropixels_pipeline import check_drift, correct_motion
# Check for drift (always do this!) — detects/localizes peaks and saves
# a drift plot to <output_folder>/drift_check.png, returns a dict with
# 'drift_estimate' (μm range).
drift_info = check_drift(rec, output_folder='output/')
# Apply correction if needed
if drift_info['drift_estimate'] > 20: # microns
rec = correct_motion(rec, output_folder='output/', preset='nonrigid_fast_and_accurate')
3. スパイクソーティング
# Kilosort4 (recommended, requires GPU)
sorting = si.run_sorter('kilosort4', rec, folder='ks4_output')
# CPU alternatives
sorting = si.run_sorter('tridesclous2', rec, folder='tdc2_output')
sorting = si.run_sorter('spykingcircus2', rec, folder='sc2_output')
sorting = si.run_sorter('mountainsort5', rec, folder='ms5_output')
# Check available sorters
print(si.installed_sorters())
4. 後処理
# Create analyzer and compute all extensions
analyzer = si.create_sorting_analyzer(sorting, rec, sparse=True)
analyzer.compute('random_spikes', max_spikes_per_unit=500)
analyzer.compute('waveforms', ms_before=1.0, ms_after=2.0)
analyzer.compute('templates', operators=['average', 'std'])
analyzer.compute('spike_amplitudes')
analyzer.compute('correlograms', window_ms=50.0, bin_ms=1.0)
analyzer.compute('unit_locations', method='monopolar_triangulation')
analyzer.compute('quality_metrics')
metrics = analyzer.get_extension('quality_metrics').get_data()
5. キュレーション
# Allen Institute criteria (conservative)
good_units = metrics.query("""
presence_ratio > 0.9 and
isi_violations_ratio < 0.5 and
amplitude_cutoff < 0.1
""").index.tolist()
# Or use automated curation (returns {unit_id: 'good'|'mua'|'noise'})
from scripts.neuropixels_pipeline import curate_units
labels = curate_units(metrics, method='allen') # 'allen', 'ibl', 'strict'
6. AI 支援キュレーション(判定が難しいユニット向け)
このスキルを Claude Code と使用すると、Claude は波形プロットを直接解析し、専門的なキュレーション判定を提示できます。推奨されるワークフローは、SpikeInterface でユニットごとのサマリープロットを生成し、Claude に確認させることです:
import spikeinterface.widgets as sw
import matplotlib.pyplot as plt
# Find borderline units worth a visual look
uncertain = metrics.query('snr > 3 and snr < 8').index.tolist()
# Render a summary figure per uncertain unit (waveform + correlogram + amplitudes)
for unit_id in uncertain:
sw.plot_unit_summary(analyzer, unit_id=unit_id)
plt.savefig(f'ai_curation/unit_{unit_id}_summary.png', dpi=150, bbox_inches='tight')
plt.close()
Claude Code との連携:Claude Code 内で実行する場合は、保存済みの波形/コレログラムのプロットを直接確認するよう Claude に依頼してください。API のセットアップは不要です。
7. 解析レポートの生成
# The bundled run_pipeline writes a machine-readable summary.json
# (sampling rate, duration, channel count, unit counts) into output_path/.
import json
with open('output/summary.json') as f:
summary = json.load(f)
print(summary)
# For a browsable HTML report of waveforms/metrics, use SpikeInterface's exporter:
si.export_report(analyzer, output_folder='output/report/')
# Open output/report/index.html for figures and the per-unit table
8. 結果のエクスポート
# Export to Phy for manual review
si.export_to_phy(analyzer, output_folder='phy_export/',
compute_pc_features=True, compute_amplitudes=True)
# Export to NWB (via NeuroConv — SpikeInterface has no native NWB exporter)
# pip install neuroconv
from neuroconv.tools.spikeinterface import write_sorting, write_recording
write_recording(recording=rec, nwbfile_path='output.nwb', overwrite=True)
write_sorting(sorting=sorting, nwbfile_path='output.nwb')
# Save quality metrics
metrics.to_csv('quality_metrics.csv')
よくある落とし穴とベストプラクティス
- スパイクソーティングの前に必ずドリフトを確認してください。10 μm を超えるドリフトは品質に大きく影響します
- Neuropixels 1.0 プローブでは
phase_shiftを使用してください(2.0 では不要です) - 再計算を避けるため、前処理済みデータを保存してください。
rec.save(folder='preprocessed/')を使用します - Kilosort4 では GPU を使用してください。CPU の代替手段より 10〜50 倍高速です
- 判定が難しいユニットは手動で確認してください。自動キュレーションは出発点です
- メトリクスと AI を組み合わせてください。明確なケースにはメトリクスを、判断が分かれるユニットには AI を使用します
- しきい値を記録してください。解析によって異なる基準が必要になる場合があります
- 重要な実験では Phy にエクスポートしてください。人による確認が有用です
調整する主なパラメーター
前処理
freq_min:ハイパスのカットオフ(通常 300〜400 Hz)detect_threshold:不良チャンネル検出の感度
動きの補正
preset:'kilosort_like'(高速)または'nonrigid_accurate'(深刻なドリフトに適しています)
スパイクソーティング(Kilosort4)
batch_size:バッチあたりのサンプル数(デフォルトは30000)nblocks:ドリフトブロックの数(長時間の記録では増やします)Th_learned:検出閾値(低いほどスパイク数が増えます)
品質メトリクス
snr_threshold:信号対雑音比の閾値(通常は3~5)isi_violations_ratio:不応期違反(0.01~0.5)presence_ratio:記録カバー率(0.5~0.95)
同梱リソース
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/
assets/analysis_template.py
完全な解析テンプレートです。コピーしてカスタマイズしてください:
cp assets/analysis_template.py my_analysis.py
# Edit parameters and run
python my_analysis.py
references/standard_workflow.md
各段階の説明を含む、詳細なステップごとのワークフローです。
references/api_reference.md
モジュール別にまとめた関数の簡易リファレンスです。
references/plotting_guide.md
出版品質の図を作成するための、包括的な可視化ガイドです。
詳細なリファレンスガイド
| トピック | リファレンス |
|---|---|
| 全ワークフロー | references/standard_workflow.md |
| API リファレンス | 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 |
インストール
# Core packages
uv pip install "spikeinterface[full]" probeinterface neo
# External sorters (separate packages, run via si.run_sorter)
uv pip install kilosort # Kilosort4 (CUDA GPU required)
uv pip install mountainsort5 # Mountainsort5 (CPU)
# Internal sorters ship INSIDE spikeinterface — install the extra, not a
# standalone package. There is no `spykingcircus` package for SpykingCircus2.
uv pip install "spikeinterface[spykingcircus2]"
uv pip install "spikeinterface[tridesclous2]"
# Our toolkit ships as local scripts (scripts/) — no pip install needed;
# run them directly or import from scripts.neuropixels_pipeline
# Optional: AI curation
uv pip install anthropic
# Optional: IBL tools
uv pip install ibl-neuropixel ibllib
SpikeInterface 0.105 — 知っておきたい重大な変更
0.105.0(2026-09-21)では、多くの公開 API が変更されました。旧バージョンで保存されたオブジェクトは引き続き読み込めますが、0.104 向けに書かれたスクリプトは動作しない場合があります。
- 解析 API から
peak_signが削除されました。 メインチャネルとピーク符号は、SortingAnalyzerの作成時に確定され、main_channel_idソーティングプロパティに保存されます。そのため、compute_quality_metrics、compute_template_metrics、compute_spike_amplitudes、compute_spike_locations、compute_unit_locationsでは受け付けなくなりました。compute_snrs(..., peak_sign=, peak_mode=)はcompute_snrs(..., method=)に変更されました。 get_template_extremum_channel()->SortingAnalyzer.get_main_channels()(旧名称も非推奨の互換用ラッパーとして残っています)。estimate_sparsity()のデフォルトがpeak_sign="neg"ではなくpeak_sign="both"になりました。これはエラーではなく、結果が通知なしに変わるため、スパース性に依存する出力を再確認してください。- プローブの処理:
set_probe()/set_probegroup()はインプレースで動作し、Noneを返します。新しいレコーディングを取得するにはselect_channels_with_probe()を使用してください。reset_probe()はremove_probe()に変更されました。 ChunkRecordingExecutor->TimeSeriesChunkExecutor。BaseExtractor.load_from_folder()は削除され、代わりにsi.load()を使用します。- 0.105での新機能:外部ソーターとしての
dartsort、SortingAnalyzerのlazyモードとread_onlyモード、前処理機能detect_and_remove_artifacts、およびKilosort4の出力フォルダーからMotionオブジェクトを作成するread_kilosort4_motion()。
再現を意図する解析ではSpikeInterfaceのバージョンを固定し、メソッドのセクションに記録してください。メトリクスの定義はマイナーリリース間で変更されています。
プロジェクト構成
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
Additional Resources
- SpikeInterface Docs: https://spikeinterface.readthedocs.io/
- Neuropixels Tutorial: https://spikeinterface.readthedocs.io/en/stable/how_to/analyze_neuropixels.html
- Kilosort4 GitHub: https://github.com/MouseLand/Kilosort
- IBL Neuropixel Tools: https://github.com/int-brain-lab/ibl-neuropixel
- Allen Institute ecephys: https://github.com/AllenInstitute/ecephys_spike_sorting
- Bombcell (Automated QC): https://github.com/Julie-Fabre/bombcell
- SpikeAgent (AI Curation): https://github.com/SpikeAgent/SpikeAgent