Communitygithub.com

neuropixels-analysis

SpikeInterface를 사용한 Neuropixels 세포외 기록(extracellular recordings)의 종단간 분석. SpikeGLX/Open Ephys/NWB 데이터 로딩, 전처리, 드리프트/모션 보정, Kilosort4(및 CPU) 스파이크 소팅, 품질 지표, 및 유닛 큐레이션(임계값 기반, 모델 기반 UnitRefine, AI 지원 시각 검토)을 포함합니다. Neuropixels 1.0/2.0 기록, 스파이크 소팅, 또는 세포외 전기생리학 분석 시 사용하세요.

neuropixels-analysis란 무엇인가요?

이 스킬은 SpikeInterface 라이브러리를 기반으로 Neuropixels 고밀도 신경 기록 데이터를 분석하기 위한 종합적인 도구 모음입니다. SpikeGLX, Open Ephys, NWB 등 다양한 데이터 형식의 로딩, 고역 통과 필터링 및 공통 기준 전극 참조와 같은 전처리, 드리프트 감지 및 모션 보정, Kilosort4, SpykingCircus2, Mountainsort5, Tridesclous2와 같은 여러 스파이크 소터 실행, SNR 및 ISI 위반과 같은 품질 지표 계산, 임계값 기반, 모델 기반(UnitRefine) 또는 AI 지원 큐레이션을 통한 유닛 선별까지 전체 워크플로우를 다룹니다. 이 스킬은 Claude Code, Cursor, Codex와 같은 AI 에이전트 환경에서 사용할 수 있으며, 제공된 스크립트와 템플릿을 통해 사용자는 최소한의 설정으로 바로 분석을 실행하거나 세부 매개변수를 조정할 수 있습니다. GPU가 권장되지만 CPU 기반 대안도 제공되어 다양한 하드웨어 환경에서 유연하게 사용할 수 있습니다.

지원 대상✓Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/neuropixels-analysis

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

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.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

# 전역 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")

일반적인 함정 및 모범 사례

  1. 스파이크 소팅 전에 항상 드리프트를 확인하십시오 — 드리프트가 ~10 μm 이상이면 품질이 현저히 저하됩니다.
  2. Neuropixels 1.0에는 phase_shift를 사용하여 ADC 샘플링 오프셋을 보정하십시오.
  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
# 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/               # 보고서 출력

[나머지 내용 축약됨]

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

astropy

Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

biopython

Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use bioservices.

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

관련 스킬