mcpField
N
neuropixels-analysis

neuropixels-analysis

github.com/crazymsnデータ・データベース2335 回インストール22 週間前に更新
リポジトリ

neuropixels-analysis について

neuropixels-analysisは、Neuropixels記録を分析する研究者向けのスキルです。前処理からユニットの選別・出力までを扱い、ドリフト補正、品質評価、レポート作成も支援します。

主な機能

  1. 01SpikeGLX、Open Ephys、NWBデータの読み込み
  2. 02前処理と不良チャンネル検出
  3. 03記録ドリフトの推定と補正
  4. 04スパイクソーティングと品質指標の計算
  5. 05ユニット選別とPhyまたはNWBへの出力

活用シーン

  1. 01生のNeuropixels記録の処理
  2. 02ソート済みユニットの比較と選別
  3. 03分析レポートと可視化の作成

インストール

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

$npx skills add https://github.com/crazymsn/academic-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 の高密度神経記録を解析するための包括的なツールキットです。生データから論文発表に対応できる整理済みユニットまで、ワークフロー全体をサポートします。

このスキルを使用するタイミング

このスキルは次のような場合に使用します。

  • Neuropixels の記録データ(.ap.bin、.lf.bin、.meta ファイル)を扱うとき
  • SpikeGLX、Open Ephys、または NWB 形式のデータを読み込むとき
  • 神経記録の前処理(フィルタリング、CAR、不良チャンネルの検出)を行うとき
  • 記録中のモーションやドリフトを検出して補正するとき
  • スパイクソーティング(Kilosort4、SpykingCircus2、Mountainsort5)を実行するとき
  • 品質指標(SNR、ISI 違反、プレゼンス比)を計算するとき
  • Allen/IBL の基準を用いてユニットを整理するとき
  • 神経データの可視化を作成するとき
  • 結果を Phy または NWB にエクスポートするとき

対応ハードウェアと形式

プローブ電極数チャンネル数備考
Neuropixels 1.0960384phase_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
import neuropixels_analysis as npa

# 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
results = npa.run_pipeline(
    recording,
    output_dir='output/',
    sorter='kilosort4',
    curation_method='allen',
)

# Access results
sorting = results['sorting']
metrics = results['metrics']
labels = results['labels']

標準的な解析ワークフロー

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 our wrapper
rec = npa.preprocess(recording)
2. ドリフトの確認と補正
# Check for drift (always do this!)
motion_info = npa.estimate_motion(rec, preset='kilosort_like')
npa.plot_drift(rec, motion_info, output='drift_map.png')

# Apply correction if needed
if motion_info['motion'].max() > 10:  # microns
    rec = npa.correct_motion(rec, preset='nonrigid_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
labels = npa.curate(metrics, method='allen')  # 'allen', 'ibl', 'strict'
6. AI 支援キュレーション(判断が難しいユニット向け)

このスキルを Claude Code で使用する場合、Claude が波形プロットを直接解析し、専門家としてのキュレーション判断を示すことができます。プログラムから API にアクセスする場合は次のとおりです。

from anthropic import Anthropic

# Setup API client
client = Anthropic()

# Analyze uncertain units visually
uncertain = metrics.query('snr > 3 and snr < 8').index.tolist()

for unit_id in uncertain:
    result = npa.analyze_unit_visually(analyzer, unit_id, api_client=client)
    print(f"Unit {unit_id}: {result['classification']}")
    print(f"  Reasoning: {result['reasoning'][:100]}...")

Claude Code との連携: Claude Code 内で実行している場合は、波形やコレログラムのプロットを直接確認するよう Claude に依頼してください。API の設定は不要です。

7. 解析レポートの生成
# Generate comprehensive HTML report with visualizations
report_dir = npa.generate_analysis_report(results, 'output/')
# Opens report.html with summary stats, figures, and unit table

# Print formatted summary to console
npa.print_analysis_summary(results)
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
from spikeinterface.exporters import export_to_nwb
export_to_nwb(rec, sorting, 'output.nwb')

# Save quality metrics
metrics.to_csv('quality_metrics.csv')

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

  1. スパイクソーティングの前に必ずドリフトを確認してください。ドリフトが 10μm を超えると品質に大きく影響します。
  2. Neuropixels 1.0 プローブでは phase_shift を使用してください(2.0 では不要です)。
  3. 再計算を避けるため、前処理済みデータを保存してください。rec.save(folder='preprocessed/') を使用します。
  4. Kilosort4 では GPU を使用してください。CPU を使う方法と比べて 10〜50 倍高速です。
  5. 判断が難しいユニットは手動で確認してください。自動キュレーションは出発点にすぎません。
  6. 指標と AI を組み合わせてください。明確なケースには指標を、境界付近のユニットには AI を使用します。
  7. 閾値を文書化してください。解析が異なれば、適切な基準も異なる場合があります。
  8. 重要な実験では 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
pip install spikeinterface[full] probeinterface neo

# Spike sorters
pip install kilosort          # Kilosort4 (GPU required)
pip install spykingcircus     # SpykingCircus2 (CPU)
pip install mountainsort5     # Mountainsort5 (CPU)

# Our toolkit
pip install neuropixels-analysis

# Optional: AI curation
pip install anthropic

# Optional: IBL tools
pip install ibl-neuropixel ibllib

プロジェクト構成

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

その他のリソース

コメント