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.0 | 960 | 384 | 使用 phase_shift 進行 ADC 校正 |
| 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
# 全域 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")
常見陷阱與最佳實踐
- 在尖峰分類前務必檢查漂移 —— 漂移 > ~10 μm 會明顯降低品質。
- 對 Neuropixels 1.0 使用
phase_shift以校正 ADC 取樣偏移。 - 使用
rec.save(folder=...)儲存前處理後的記錄 以避免重複計算(Kilosort 也需要二進位檔案)。 - 使用 GPU 執行 Kilosort4 —— 它遠比 CPU 分類器快。
- 審查不確定的單元 —— 自動化/模型型篩選是起點,而非最終裁決。
- 結合各種方法 —— 明確的情況使用閾值,邊界的單元使用模型/AI。
- 記錄閾值和模型 repo ID 以確保可再現性。
- 對於關鍵實驗,匯出至 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