Communitygithub.com

matchms

matchms を使用してタンデム質量スペクトルの処理、クリーニング、比較、検索を行います。MS/MS ファイル入出力、メタデータ調和、ピークフィルタリング、スペクトル類似度、ライブラリマッチング、スコア行列、分子類似性ネットワークに使用します。LC-MS の特徴検出やプロテオミクスパイプラインには pyopenms を使用してください。

matchms とは?

matchms は、タンデム質量スペクトル(MS/MS)データのインポート、クリーニング、処理、比較を行うための Python パッケージです。このスキルは matchms 0.33.1(2026-06-08 リリース)を対象としており、古いチュートリアルでは反映されていない複数の破壊的 API 変更に対応しています。MS/MS ライブラリ検索、メタデータ調和、ピークフィルタリング、コサイン類似度や修正コサイン類似度、ニュートラルロス類似度、エントロピースコアなど様々な類似度計算が可能です。また、構造化スコア行列、トップヒット抽出、スペクトルネットワークの構築、MGF/MSP/mzML/mzXML/JSON/mzSpecLib などの多様なファイル形式に対応しています。このスキルは、科学的なエージェントスキル(Scientific Agent Skills)に基づいており、開発者や AI エージェントユーザーが matchms を効果的に活用するための手順、API ガードレール、実装例、注意点を提供します。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

matchms は何をしますか?

目的と範囲

Matchms は、タンデム質量スペクトルのインポート、クリーニング、処理、比較を行うための Python パッケージです。このスキルは matchms 0.33.1(2026-06-08 リリース)を対象としており、古いチュートリアルでは反映されていない複数の破壊的 API 変更に対応しています。

matchms を使用するケース:

  • MS/MS ライブラリ検索とクエリ対リファレンスのスコアリング
  • メタデータ調和、付加体/プレカーサー処理、ピークフィルタリング
  • コサイン、修正コサイン、ニュートラルロス、近似、エントロピースコアリング
  • 構造化スコア行列、トップヒット抽出、スペクトルネットワーク
  • MGF、MSP、mzML、mzXML、JSON、mzSpecLib、メタボロミクス USI ワークフロー

matchms を以下の代替として使用しないでください:

  • 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 を検査し、結果とともに保存します。

ペアスコアリング

類似度クラスは、1つのリファレンス/クエリペアに対して 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 を読んでください。

大規模比較

1つのコレクションの全対全スコアリングには、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 の値が単なる float であると仮定しないでください。score_names を検査してください。
  • 高い類似度スコア単独で確認された同定として扱わないでください。
  • 信頼できない pickle データをデシリアライズしないでください。
  • ペア数を推定せずに、無制限の全ペア比較を開始しないでください。

科学的エージェントスキルの引用

このスキルは、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.

関連スキル