Communitygithub.com

matchms

matchms를 사용하여 직렬 질량 스펙트럼(tandem mass spectra)을 처리, 정제, 비교 및 검색합니다. MS/MS 파일 입출력, 메타데이터 통합, 피크 필터링, 스펙트럼 유사도, 라이브러리 매칭, 점수 행렬 및 분자 유사도 네트워크에 사용됩니다. LC-MS 피처 탐지나 단백질체학 파이프라인에는 pyopenms를 대신 사용하세요.

matchms란 무엇인가요?

matchms는 직렬 질량 분석 스펙트럼(MS/MS)을 불러오고, 정제하고, 처리하며 비교하기 위한 Python 패키지입니다. 이 스킬은 2026-06-08에 출시된 matchms 0.33.1 버전을 대상으로 하며, 이전 튜토리얼에서 다루지 않은 여러 주요 API 변경 사항을 반영합니다. MS/MS 라이브러리 검색, 질의-참조 점수 계산, 메타데이터 통합, 다양한 유사도 측정(코사인, 수정 코사인, 중성 손실, 엔트로피 등), 점수 행렬, 최상위 히트 추출, 스펙트럼 네트워크 생성을 지원합니다. 또한 MGF, MSP, mzML, mzXML, JSON 등 여러 파일 형식을 읽고 쓸 수 있습니다. matchms는 LC-MS 피처 탐지, 크로마토그래피 정렬, 펩타이드 식별 또는 단백질 정량화에는 적합하지 않으며, 이러한 작업에는 pyopenms를 사용해야 합니다. 이 스킬은 API 사용 시 주의사항(예: `ModifiedCosine` 대신 `ModifiedCosineGreedy` 사용, `add_losses()` 호출 금지, `SpectrumProcessor` 클래스의 직접 호출 불가)을 명확히 제시하여 사용자 오류를 방지합니다. 대규모 스펙트럼 비교를 위한 효율적인 전략(예: `is_symmetric=True`, 선구자 이온 필터링)과 함께 유사도 방법 선택 가이드, 일괄 라이브러리 검색 CLI, 스펙트럼 객체 시각화 기능을 제공합니다. 타겟 독자는 이 도구가 메타볼로믹스, 환경 분석화학, 약물 대사 연구 등의 분야에서 MS/MS 데이터 분석을 자동화하고 표준화하는 데 핵심적인 역할을 한다는 점을 이해할 수 있습니다.

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

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

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

문서

matchms은(는) 무엇을 하나요?

목적 및 범위

Matchms는 직렬 질량 스펙트럼(tandem mass spectra)을 가져오고, 정제하고, 처리하고, 비교하기 위한 Python 패키지입니다. 이 스킬은 matchms 0.33.1(2026-06-08 출시)을 대상으로 하며, 이전 튜토리얼에는 반영되지 않은 몇 가지 주요 API 변경 사항을 수정합니다.

다음과 같은 작업에 matchms를 사용하세요:

  • MS/MS 라이브러리 검색 및 질의-참조 점수 계산
  • 메타데이터 통합, 부가물/전구체 처리, 피크 필터링
  • 코사인, 수정 코사인, 중성 손실, 근사, 엔트로피 점수 계산
  • 구조화된 점수 행렬, 최상위 히트 추출, 스펙트럼 네트워크
  • MGF, MSP, mzML, mzXML, JSON, mzSpecLib 및 메타볼로믹스-USI 워크플로

다음과 같은 용도로 대체하여 사용하지 마세요:

  • LC-MS 피처 탐지, 크로마토그래피 정렬, 펩타이드 식별 또는 단백질 정량화 — pyopenms 사용
  • 벤더 원시 파일 변환 — 먼저 mzML/mzXML로 변환하세요.
  • 검증된 화합물 식별 프로토콜 — 유사도는 증거일 뿐, 신원 확인 증거는 아닙니다.

검증된 릴리스 설치

가상 환경을 생성하거나 활성화한 후, 이 스킬에서 사용하는 릴리스를 설치하세요:

uv pip install "matchms==0.33.1"

런타임을 확인하세요:

uv run python -c "import matchms; print(matchms.__version__)"

Matchms 0.33.1은 Python 3.10-3.14를 지원하며 RDKit을 정식 종속성으로 설치합니다. 이전의 matchms[chemistry] 확장은 현재 패키지 메타데이터에 포함되지 않습니다.

작업 워크플로

  1. 입력을 검사합니다. 형식, 스펙트럼 개수, MS 레벨, 전구체 적용 범위, 이온 모드, 피크 개수 및 식별자 필드를 기록합니다.
  2. 메타데이터 통합을 활성화하고 로드합니다. 단, 소스 키를 의도적으로 유지해야 하는 경우는 예외입니다.
  3. 동일한 피크 처리 단계를 질의 및 참조 스펙트럼에 적용합니다. 참조 주석이 더 풍부한 경우 메타데이터 강화를 별도로 유지하세요.
  4. 유효하지 않은 스펙트럼은 명시적으로 제거합니다. 많은 require_* 필터가 None을 반환합니다.
  5. 과학적 질문에 따라 점수를 선택합니다. 편의에 따라 선택하지 마십시오. 수정 코사인 및 중성 손실 점수는 유효한 precursor_mz가 필요합니다.
  6. 점수 계산 전에 len(references) * len(queries)를 추정합니다. 희소 결과 컨테이너가 요청된 모든 쌍의 계산을 자동으로 방지하지는 않습니다.
  7. 점수 설정과 증거를 보고합니다. 공차, 전처리, 점수 이름, 일치하는 피크 수(가능한 경우), 후보 메타데이터를 포함합니다.
  8. 최상위 히트를 시각적 및 화학적으로 검증합니다. 미러 플롯, 전구체 일치, 이온/부가물 호환성 및 직교 증거를 사용합니다.

현재 API 가드레일

다음 사항은 0.33 이전 예제의 가장 일반적인 오류를 방지합니다:

  • ModifiedCosineGreedy 또는 ModifiedCosineHungarian을 사용하세요. ModifiedCosine는 0.32.0에서 제거되었습니다.
  • add_losses()를 호출하지 마세요. 0.27.0에서 제거되었습니다. 대신 spectrum.losses, spectrum.compute_losses(...) 또는 NeutralLossesCosine을 직접 사용하세요.
  • SpectrumProcessor는 호출 가능하지 않습니다. process_spectrum() 또는 process_spectra()를 사용하세요.
  • process_spectra()는 (processed_spectra, processing_report)를 반환합니다.
  • Scores.scores는 StackedSparseArray이며, 종종 CosineGreedy_score 및 CosineGreedy_matches와 같은 별도의 구조화된 필드가 있습니다.
  • scores_by_query()는 참조 인덱스가 아닌 (reference_spectrum, score_record) 쌍을 반환합니다.
  • 매개변수 이름에는 spectra를 선호하세요. 이전 철자인 spectrums는 더 이상 사용되지 않습니다.
  • 신뢰할 수 없는 출처의 pickle 파일을 절대 로드하지 마세요. 역직렬화는 코드를 실행할 수 있습니다.

완전한 이전-현재 매핑은 references/migration.md를 참조하세요.

빠른 시작: 라이브러리 정제 및 검색

from matchms import SpectrumProcessor, calculate_scores
from matchms.filtering import (
    default_filters,
    normalize_intensities,
    require_minimum_number_of_peaks,
    select_by_relative_intensity,
)
from matchms.importing import load_spectra
from matchms.similarity import ModifiedCosineGreedy


def load_and_process(path):
    spectra = [default_filters(spectrum) for spectrum in load_spectra(path)]
    processor = SpectrumProcessor(
        [
            normalize_intensities,
            (select_by_relative_intensity, {"intensity_from": 0.01}),
            (require_minimum_number_of_peaks, {"n_required": 5}),
        ]
    )
    processed, _ = processor.process_spectra(
        spectra,
        progress_bar=False,
        create_report=False,
    )
    return processed


references = load_and_process("library.msp")
queries = load_and_process("queries.mgf")

metric = ModifiedCosineGreedy(tolerance=0.02)
scores = calculate_scores(
    references=references,
    queries=queries,
    similarity_function=metric,
)

score_name = "ModifiedCosineGreedy_score"
matches_name = "ModifiedCosineGreedy_matches"
for query in queries:
    ranked = scores.scores_by_query(query, name=score_name, sort=True)
    for reference, values in ranked[:5]:
        print(
            query.get("spectrum_id", query.get("id")),
            reference.get("compound_name", reference.get("spectrum_id")),
            float(values[score_name]),
            int(values[matches_name]),
        )

SpectrumProcessor는 matchms의 필터 순서에 따라 내장 필터를 자동으로 정렬합니다. 집계된 default_filters 호출 가능은 해당 레지스트리에 없으므로 위와 같이 먼저 실행하거나 9개의 구성 필터를 확장하세요. processor.processing_steps를 검사하고 결과와 함께 보존하세요.

쌍 점수 계산

유사도 클래스는 하나의 참조/질의 쌍에 대해 pair()를 제공합니다. 코사인 계열 결과는 구조화된 NumPy 스칼라입니다:

from matchms.similarity import CosineGreedy

result = CosineGreedy(tolerance=0.02).pair(reference, query)
similarity = float(result["score"])
matched_peaks = int(result["matches"])

행렬 기반 메서드(예: FlashSimilarity)에는 calculate_scores()를 사용하세요. 단일 쌍 경로는 지원되지만 의도적으로 최적화된 경로는 아닙니다.

유사도 메서드 선택

  • CosineGreedy — 그리디 피크 할당을 사용한 표준 피크 코사인.
  • CosineHungarian — 정확한 할당; 더 느리지만 벤치마크에 유용합니다.
  • CosineLinear — 현재 선형 확장 코사인 구현.
  • ModifiedCosineGreedy — 전구체-델타 이동 일치 허용; 유사체 검색에 일반적.
  • ModifiedCosineHungarian — 정확한 수정 코사인 할당.
  • NeutralLossesCosine — 전구체와 단편으로부터 계산된 손실 비교.
  • BlinkCosine — 대규모 행렬을 위한 빠른 BLINK 스타일 코사인 근사.
  • FlashSimilarity — 스펙트럼 엔트로피 또는 코사인(단편, 중성 손실 또는 하이브리드 매칭 사용)을 사용한 최적화된 행렬 점수 계산.
  • BinnedEmbeddingSimilarity — 구간화된 스펙트럼 벡터 및 선택적 근사 최근접 이웃 인덱싱.
  • PrecursorMzMatch, ParentMassMatch, MetadataMatch — 후보 마스크 또는 메타데이터 제약 조건, 풍부한 스펙트럼 점수가 아님.
  • FingerprintSimilarity — 분자 구조 유사도; 스펙트럼 유사도가 아니며 유효한 구조로부터 준비된 지문이 필요합니다.

빠른 메서드를 선택하거나 점수를 결합하거나 구조화된 출력을 해석하기 전에 references/similarity.md를 읽으세요.

대규모 비교

하나의 컬렉션에 대해 전체-대-전체 점수를 계산하려면 is_symmetric=True로 설정하세요:

scores = calculate_scores(
    references=spectra,
    queries=spectra,
    similarity_function=CosineGreedy(tolerance=0.02),
    array_type="sparse",
    is_symmetric=True,
)

전구체 필터링 검색의 경우 먼저 PrecursorMzMatch를 계산하고 필터링한 다음, Pipeline 또는 Scores.calculate(...)를 통해 유지된 좌표에 대해서만 스펙트럼 메트릭을 계산하세요. references/workflows.md를 참조하세요.

보편적인 "식별 임계값"을 선택하지 마십시오. 점수 분포는 전처리, 질량 정확도, 충돌 조건, 라이브러리 품질 및 메트릭에 따라 달라집니다. 최소한 코사인 계열 메서드의 경우 점수와 일치하는 피크 개수를 모두 유지하세요.

번들 라이브러리 검색 CLI

scripts/library_search.py는 현재 점수 추출, 쌍 개수 제한, 전처리 및 CSV 출력이 포함된 재현 가능한 질의-대-라이브러리 검색을 제공합니다:

uv run python scripts/library_search.py \
  queries.mgf library.msp hits.csv \
  --metric modified \
  --tolerance 0.02 \
  --top-k 10 \
  --min-score 0.6 \
  --min-matches 5

빠른 메트릭, 전처리 옵션, 식별자 필드, 덮어쓰기 제어 및 명시적 대규모 행렬 재정의에 대해서는 --help를 실행하세요.

스펙트럼 객체 및 시각화

import numpy as np
from matchms import Spectrum

spectrum = Spectrum(
    mz=np.array([100.0, 150.0, 200.0]),
    intensities=np.array([0.2, 1.0, 0.4]),
    metadata={"spectrum_id": "query-1", "precursor_mz": 250.5},
)

print(spectrum.peaks.mz)
print(spectrum.get("precursor_mz"))
losses = spectrum.compute_losses(loss_mz_from=5.0, loss_mz_to=200.0)
spectrum.plot()
spectrum.plot_against(reference_spectrum)

참고 자료

작업에 필요한 참고 자료만 읽으세요:

  • references/importing_exporting.md — 형식, 반환 유형, 일반 I/O, mzSpecLib, 점수 직렬화 및 pickle 안전
  • references/filtering.md — 현재 필터 카탈로그, 복제/None 의미, 기본 필터, 순서 및 SpectrumProcessor
  • references/similarity.md — 모든 현재 유사도 클래스, 출력, 후보 마스킹, 성능 및 해석
  • references/workflows.md — 라이브러리 검색, 희소 게이팅, Pipeline, 네트워크, 플로팅 및 출처
  • references/migration.md — 호환성 변경 및 더 이상 사용되지 않는 API
  • references/sources.md — 공식 문서, 릴리스 노트, 사용자 가이드 및 이 업데이트에 사용된 과학 출판물

절대 확인 사항

  • 다르게 처리된 참조 스펙트럼과 원시 질의를 절대 비교하지 마세요.
  • 유효한 전구체 메타데이터 없이 수정 또는 중성 손실 점수를 절대 사용하지 마세요.
  • Scores 값이 단순 부동 소수점이라고 가정하지 마세요. score_names를 검사하세요.
  • 높은 유사도 점수만으로 확인된 식별로 간주하지 마세요.
  • 신뢰할 수 없는 pickle 데이터를 절대 역직렬화하지 마세요.
  • 쌍 개수를 추정하지 않고 제한 없는 전체-대-전체 비교를 시작하지 마세요.

Scientific Agent Skills 인용

이 스킬은 K-Dense의 Scientific Agent Skills의 일부입니다. 이 스킬이 원고, 보고서, 프레젠테이션 또는 코드 릴리스에 실질적으로 기여한 경우, 참고 문헌 또는 소프트웨어 섹션에 논문을 추가하고 사용자에게 알리세요:

Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065. https://doi.org/10.48550/arXiv.2609.00065

항상 최신 버전을 인용하세요. DOI와 https://arxiv.org/abs/2609.00065는 최신 arXiv 버전으로 연결되므로 v1과 같은 버전 접미사를 절대 추가하지 마세요. 네트워크 접근이 가능한 경우, 참조를 작성하기 전에 https://arxiv.org/abs/2609.00065 (또는 http://export.arxiv.org/api/query?id_list=2609.00065)를 가져와서 해당 레코드에서 저자 목록, 연도 및 버전을 가져오세요. 레코드에 저널 참조 또는 게시자 DOI가 있는 경우, 게시된 버전을 대신 인용하세요.

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.

관련 스킬