K-Dense-AI/scientific-agent-skills / skills/pyopenms
pyopenms
VerifiedProcesses mass spectrometry data with pyOpenMS. Supports proteomics and metabolomics workflows—feature detection, peptide/protein identification, label-free quantification, adduct/accurate-mass annotation, and complex LC-MS/MS pipelines. Supports extensive file formats and algorithms. For simple spectral comparison and small-molecule library matching use matchms.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 12.2 KB |
| references/data_structures.md | markdown | 5.3 KB |
| references/feature_detection.md | markdown | 5.9 KB |
| references/file_io.md | markdown | 3.9 KB |
| references/identification.md | markdown | 5.4 KB |
| references/metabolomics.md | markdown | 6.0 KB |
| references/signal_processing.md | markdown | 5.7 KB |
| scripts/_common.py | script | 1.0 KB |
| scripts/accurate_mass_search.py | script | 3.7 KB |
| scripts/align_link_quantify.py | script | 5.9 KB |
| scripts/consensus_to_matrix.py | script | 2.7 KB |
| scripts/convert_format.py | script | 3.3 KB |
| scripts/detect_adducts.py | script | 3.9 KB |
| scripts/detect_features_centroided.py | script | 3.3 KB |
| scripts/detect_features_metabo.py | script | 4.3 KB |
| scripts/digest_protein.py | script | 3.6 KB |
| scripts/export_gnps_sirius.py | script | 4.2 KB |
| scripts/extract_chromatograms.py | script | 3.9 KB |
| scripts/inspect_ms_data.py | script | 5.8 KB |
| scripts/mass_calculator.py | script | 3.5 KB |
| scripts/plot_ms_data.py | script | 3.9 KB |
| scripts/process_identifications.py | script | 6.4 KB |
| scripts/process_spectra.py | script | 4.8 KB |
| scripts/theoretical_spectrum.py | script | 3.1 KB |
scripts/process_identifications.py
View on GitHub#!/usr/bin/env python3
"""
Process Peptide/Protein Identifications
Post-process search-engine results (idXML): optionally re-index peptides against
a protein FASTA (assigns target/decoy + protein accessions), estimate FDR/q-values,
filter by FDR threshold, peptide length, and best-hit-per-spectrum, then export a
filtered idXML and a flat CSV of peptide hits.
Usage:
python process_identifications.py search.idXML --out filtered.idXML --csv hits.csv
python process_identifications.py search.idXML --fasta db.fasta --fdr 0.01 --out filt.idXML
python process_identifications.py search.idXML --fdr 0.05 --min-length 7 --best-per-spectrum
"""
import argparse
import os
import math
import sys
try:
import pyopenms as ms
except ImportError:
print("Error: pyopenms not installed. Install with: uv pip install pyopenms")
sys.exit(1)
def index_peptides(fasta, prot_ids, pep_ids, decoy_string="DECOY_"):
fasta_entries = []
ms.FASTAFile().load(fasta, fasta_entries)
indexer = ms.PeptideIndexing()
p = indexer.getParameters()
p.setValue("decoy_string", decoy_string)
p.setValue("missing_decoy_action", "error")
indexer.setParameters(p)
result = indexer.run(fasta_entries, prot_ids, pep_ids)
if result[0] != ms.PeptideIndexing.ExitCodes.EXECUTION_OK:
raise ValueError(f"Peptide indexing failed: {result[0]}")
print(f"Indexed against {len(fasta_entries)} proteins")
def filter_psm_qvalues(pep_ids, threshold):
"""Target-decoy q-values for comparable top-hit PSMs from one search run."""
if not math.isfinite(threshold) or not 0 <= threshold <= 1:
raise ValueError("q-value threshold must be finite and between 0 and 1")
contexts = set()
labels = set()
for pid in pep_ids:
hits = pid.getHits()
if not hits:
continue
if not pid.getScoreType() or pid.getScoreType().lower() in {"q-value", "fdr"}:
raise ValueError("FDR estimation needs original search scores, not existing q-values/FDR")
contexts.add((pid.getIdentifier(), pid.getScoreType(), pid.isHigherScoreBetter()))
for hit in hits:
if not math.isfinite(hit.getScore()) or not hit.metaValueExists("target_decoy"):
raise ValueError("Every hit needs a finite score and target_decoy annotation")
if hit.getMetaValue("target_decoy") not in {"target", "decoy", "target+decoy"}:
raise ValueError("Invalid target_decoy annotation")
best = max(hits, key=lambda h: h.getScore()) if pid.isHigherScoreBetter() else min(hits, key=lambda h: h.getScore())
labels.add(best.getMetaValue("target_decoy"))
if len(contexts) != 1:
raise ValueError("Process one search run with one score type/direction at a time")
if "decoy" not in labels or not labels.intersection({"target", "target+decoy"}):
raise ValueError("FDR estimation requires both target and decoy top-scoring PSMs")
fdr = ms.FalseDiscoveryRate()
p = fdr.getParameters()
p.setValue("no_qvalues", "false")
p.setValue("use_all_hits", "false")
p.setValue("add_decoy_peptides", "false")
fdr.setParameters(p)
fdr.apply(pep_ids)
ms.IDFilter().filterHitsByScore(pep_ids, threshold)
def main():
parser = argparse.ArgumentParser(description="Filter and export peptide identifications.")
parser.add_argument("input", help="Input idXML")
parser.add_argument("--decoy-prefix", default="DECOY_", help="FASTA decoy accession prefix for re-indexing")
parser.add_argument("--fasta", help="Protein FASTA (target+decoy) for re-indexing")
parser.add_argument("--out", help="Output filtered idXML")
parser.add_argument("--csv", help="Output CSV of peptide hits")
parser.add_argument("--fdr", type=float, help="FDR/q-value threshold (requires decoys)")
parser.add_argument("--min-length", type=int, help="Minimum peptide length")
parser.add_argument("--max-length", type=int, help="Maximum peptide length")
parser.add_argument("--best-per-spectrum", action="store_true",
help="Keep only the best hit per spectrum")
args = parser.parse_args()
if not os.path.exists(args.input):
print(f"Error: file not found: {args.input}")
sys.exit(1)
# In pyOpenMS 3.5+, idXML load/store require a PeptideIdentificationList
# (not a plain Python list) for the peptide IDs; protein IDs stay a list.
prot_ids = []
pep_ids = ms.PeptideIdentificationList()
ms.IdXMLFile().load(args.input, prot_ids, pep_ids)
print(f"Loaded {len(pep_ids)} spectra, "
f"{sum(len(p.getHits()) for p in pep_ids)} peptide hits")
if args.fasta:
index_peptides(args.fasta, prot_ids, pep_ids, args.decoy_prefix)
if args.fdr is not None:
filter_psm_qvalues(pep_ids, args.fdr)
print(f"Applied FDR filter (q <= {args.fdr})")
if args.best_per_spectrum:
ms.IDFilter().keepBestPeptideHits(pep_ids, False)
print("Kept best hit per spectrum")
if args.min_length is not None or args.max_length is not None:
lo = args.min_length or 0
hi = args.max_length or 0 # 0 = no upper bound in OpenMS
ms.IDFilter().filterPeptidesByLength(pep_ids, lo, hi)
print(f"Length filter ({lo}-{hi or 'inf'})")
# Drop now-empty identifications
ms.IDFilter().removeEmptyIdentifications(pep_ids)
remaining = sum(len(p.getHits()) for p in pep_ids)
print(f"Remaining: {len(pep_ids)} spectra, {remaining} peptide hits")
if args.out:
ms.IdXMLFile().store(args.out, prot_ids, pep_ids)
print(f"Wrote {args.out}")
if args.csv:
import csv
with open(args.csv, "w", newline="") as fh:
w = csv.writer(fh)
w.writerow(["rt", "mz", "sequence", "charge", "score", "score_type",
"target_decoy", "accessions"])
for pid in pep_ids:
rt = pid.getRT()
mz = pid.getMZ()
st = pid.getScoreType()
for hit in pid.getHits():
td = hit.getMetaValue("target_decoy") if hit.metaValueExists("target_decoy") else ""
accs = ";".join(a.decode() if isinstance(a, bytes) else a for a in hit.extractProteinAccessionsSet())
w.writerow([f"{rt:.2f}", f"{mz:.4f}", hit.getSequence().toString(),
hit.getCharge(), hit.getScore(), st, td, accs])
print(f"Wrote {args.csv}")
if __name__ == "__main__":
main()
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deployment | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy. | Stars: 119k | Updated | Claude CodeCodex | Verified | Install |
| childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |