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.0 | 960 | 384 | ADC 보정을 위해 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
# 전역 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) # e.g. ['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")
일반적인 함정 및 모범 사례
- 스파이크 소팅 전에 항상 드리프트를 확인하십시오 — 드리프트가 ~10 μm 이상이면 품질이 현저히 저하됩니다.
- Neuropixels 1.0에는
phase_shift를 사용하여 ADC 샘플링 오프셋을 보정하십시오. - 전처리된 기록을
rec.save(folder=...)로 저장하여 재계산을 방지하십시오 (Kilosort에도 바이너리 파일이 필요합니다). - Kilosort4에는 GPU를 사용하십시오 — CPU 소터보다 훨씬 빠릅니다.
- 불확실한 유닛을 검토하십시오 — 자동화/모델 기반 큐레이션은 시작점일 뿐 최종 판단이 아닙니다.
- 접근 방식 결합 — 명확한 경우 임계값, 경계선 유닛은 모델/AI를 사용하십시오.
- 재현성을 위해 임계값 및 모델 리포지토리 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년 6월 기준 현재: 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/ # 전처리된 데이터
└── output/ # 분석 결과
├── motion/ # 모션 보정 결과
├── ks4_output/ # Kilosort4 출력
├── analyzer/ # SortingAnalyzer 저장
├── phy_export/ # Phy 내보내기
└── report/ # 보고서 출력
[나머지 내용 축약됨]