diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index b0dbd4b..426b96e 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -1291,7 +1291,7 @@ jobs: env: OPENMS_BIN: ${{ github.workspace }}/openms/build/bin PROSE_INPUT: ${{ github.workspace }}/benchmark/generated/prose-pxd028735/LFQ_Orbitrap_DDA_Condition_A_Sample_Alpha_01.mzML - PROSE_FASTA: ${{ github.workspace }}/benchmark/generated/prose-pxd028735/entrapment_hye.fasta + PROSE_FASTA: ${{ github.workspace }}/benchmark/generated/prose-pxd028735/entrapment_hye_soce.fasta ENGINES_DIR: ${{ github.workspace }}/openms/_thirdparty PROSE_EXTRA_SEARCH_ARGS: "-Search:fragment:mass_tolerance 0.02 -Search:fragment:mass_tolerance_unit Da" LD_LIBRARY_PATH: ${{ github.workspace }}/openms/build/lib:${{ github.workspace }}/openms/build/vcpkg_installed/x64-linux-dynamic/lib @@ -1360,7 +1360,7 @@ jobs: env: OPENMS_BIN: ${{ github.workspace }}/openms/build/bin PROSE_INPUT: ${{ github.workspace }}/benchmark/generated/prose-pxd028735/LFQ_Orbitrap_DDA_Condition_B_Sample_Alpha_01.mzML - PROSE_FASTA: ${{ github.workspace }}/benchmark/generated/prose-pxd028735/entrapment_hye.fasta + PROSE_FASTA: ${{ github.workspace }}/benchmark/generated/prose-pxd028735/entrapment_hye_soce.fasta ENGINES_DIR: ${{ github.workspace }}/openms/_thirdparty PROSE_EXTRA_SEARCH_ARGS: "-Search:fragment:mass_tolerance 0.02 -Search:fragment:mass_tolerance_unit Da" LD_LIBRARY_PATH: ${{ github.workspace }}/openms/build/lib:${{ github.workspace }}/openms/build/vcpkg_installed/x64-linux-dynamic/lib diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index c5f9b52..8ee1d88 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -54,6 +54,7 @@ jobs: for f in \ benchmark/test_openswath_metrics.py \ benchmark/test_prose_metrics.py \ + benchmark/test_make_hye_entrapment_fasta.py \ benchmark/test_proteobench_compare.py \ benchmark/test_recover_nightly_results.py \ benchmark/test_runner_timestamps.py \ diff --git a/benchmark/make_hye_entrapment_fasta.py b/benchmark/make_hye_entrapment_fasta.py index 83470a1..9b0222f 100644 --- a/benchmark/make_hye_entrapment_fasta.py +++ b/benchmark/make_hye_entrapment_fasta.py @@ -4,30 +4,71 @@ target: ProteoBench mixed-species HYE FASTA, entries verbatim (human + yeast + E. coli + Cont_ contaminants - the sample's true protein contents) -entrapment: OpenMS in-tree Sorangium cellulosum So ce56 proteome, targets - only - doc/pyopenms/src/data/18Protein_SoCe_Tr_detergents_trace - .fasta (9,439 entries, verified identical to the non-decoy subset - of 18Protein_SoCe_Tr_detergents_trace_target_decoy.fasta at - e4b9609c95). Sequences verbatim, accessions prefixed with - ENTRAPMENT_; an organism provably absent from the sample. +entrapment: S. cellulosum So ce56 targets ONLY, from the OpenMS in-tree + doc/pyopenms/src/data/18Protein_SoCe_Tr_detergents_trace.fasta. + That source has 9,439 entries: 9,320 S. cellulosum So ce56 + proteins and 119 contaminant/foreign entries. 104 of the 119 are + bare ACC|NAME headers with no OS= annotation at all (human + keratins, trypsins, BSA, ...); the rest carry a different OS=. + Those 119 are excluded for one reason only: they are not + annotated as the exact So ce56 organism - bare ACC|NAME headers + with no OS=, or a different OS= - so they cannot serve as + entrapment proteins. A separate audit of that source against the + HYE target FASTA found 39 accession, 37 protein-name and 29 + exact-sequence matches: evidence that excluded entries would have + collided with targets, not a claim that each of the 119 overlaps + in all three ways. Only headers whose OS= annotation is exactly + "Sorangium cellulosum (strain So ce56)" are kept. Source order + and sequences are preserved verbatim; accessions are prefixed + with ENTRAPMENT_; the organism is provably absent from the sample. Decoy handling: fail closed. The target_decoy variant of the SoCe file marks decoys with a _rev SUFFIX (e.g. ACCA_SORC5_rev), which a rev_-prefix check -misses - copying it would silently put 9,439 reversed sequences into the +misses - copying it would silently put reversed sequences into the entrapment set (the Phase-2a pilot did exactly that). This generator refuses any source carrying decoy markers (rev_/DECOY_/REV_/decoy_ prefixes or _rev/_REV identifier suffixes) and points at the targets-only file. ProSE generates decoys itself (-Search:decoys auto). +Overlap handling: fail closed. Every retained entry is checked against the +HYE target entries by normalized accession, protein name and exact sequence. +Zero overlap is required; any hit aborts generation instead of silently +producing an entrapment set that shares target proteins. Accession +normalization strips sp|/tr| database prefixes, a leading Cont_ (ProteoBench +contaminant marker) and takes the accession field of a bare ACC|NAME header; +full-header equality is never relied on. + Shared-peptide handling: unchanged conservative policy (ENTRAPMENT_ prefix wins at classification time; shared tryptic peptides are counted as -entrapment). This script only MEASURES the overlap (tryptic, 6-40 aa, -0 missed cleavages - the Day-34 definition) and reports it, so the number -lands in PROVENANCE.txt instead of being asserted from memory. +entrapment). This script MEASURES the overlap under one fixed reference +definition (trypsin KR|P, 0-2 missed cleavages, 7-50 aa) and reports it, so +the number lands in PROVENANCE.txt instead of being asserted from memory. + +That definition is a measurement convention only. It is ENGINE-INDEPENDENT: +it is not the search space of ProSE or Sage, none of its parameters is +passed to either engine, and the reported percentage is a property of the +two FASTA sets (how much of the entrapment peptide space could also be +produced by the target proteins), not of the search configuration. + +Interpretation notes (documentation only - none of these is applied): + - ProSE's actual defaults (trypsin KR|P, 7-40 aa, 1 missed cleavage, + 100-9000 Da) measure 716 of 477,176 = 0.150% on these same two sets. + - Sage's DEFAULT digestion (trypsin KR|P, 5-50 aa, 1 missed cleavage, no + mass window) measures 20,061 of 559,448 = 3.586%. That is Sage's shipped + default, NOT the peptide space of the explicitly configured one-off Sage + run used for the exploratory comparison; the two must not be quoted + interchangeably. + - Residue policy does not move the 7-50/0-2 number: X/B/Z are kept in the + peptide space here, and dropping them leaves the shared count unchanged + (no shared peptide contains them), so the same value is obtained under + either residue convention. Usage: make_hye_entrapment_fasta.py --hye HYE.fasta --soce SOCE.fasta - --out OUT.fasta [--force] + --out OUT.fasta [--summary summary.txt] [--force] + +--summary writes the measured counts as key=value lines (consumed by +prepare_pxd028735_inputs.sh for PROVENANCE.txt). Deterministic: input order is preserved; regeneration is byte-identical. """ @@ -39,6 +80,20 @@ DECOY_PREFIXES = ("rev_", "DECOY_", "REV_", "decoy_") DECOY_SUFFIX_RE = re.compile(r"_rev(\s|$)|_REV(\s|$)") ENTRAPMENT_PREFIX = "ENTRAPMENT_" +SO_ORGANISM = "Sorangium cellulosum (strain So ce56)" +DB_PREFIXES = ("sp|", "tr|") +CONTAMINANT_PREFIX = "Cont_" + +# OS= value ends at the next UniProt field (GN=/PE=/SV=/OX=) or end of header. +ORGANISM_RE = re.compile(r"(?:^|\s)OS=(.*?)(?=\s+(?:GN|PE|SV|OX)=|$)") + +# Reference peptide space for the shared-peptide measurement: a fixed +# convention, independent of ProSE/Sage settings. Changing these constants +# changes only the reported percentage, never the FASTA that is written. +PEPTIDE_MIN_LEN = 7 +PEPTIDE_MAX_LEN = 50 +PEPTIDE_MAX_MISSED_CLEAVAGES = 2 +TRYPSIN_SPLIT_RE = re.compile(r"(?<=[KR])(?!P)") def read_entries(path): @@ -58,22 +113,74 @@ def read_entries(path): return entries +def ident_of(name): + """First whitespace token of a FASTA header (everything before the + description).""" + parts = name.split() + return parts[0] if parts else name + + def decoy_marker_count(entries): n = 0 for name, _ in entries: - ident = name.split()[0] if name.split() else name + ident = ident_of(name) if ident.startswith(DECOY_PREFIXES) or DECOY_SUFFIX_RE.search(ident): n += 1 return n +def organism_of(name): + """The OS= annotation, or None when the header has none.""" + match = ORGANISM_RE.search(name) + return match.group(1).strip() if match else None + + +def split_accession_name(ident): + """Normalized (accession, protein_name) for a database-style identifier. + + Handles sp|ACC|NAME, tr|ACC|NAME, bare ACC|NAME and plain ACC. A leading + Cont_ (ProteoBench contaminant marker, e.g. sp|Cont_P00722|BGAL_ECOLI) is + stripped from the accession so it compares equal to the same protein + without the marker. Returns ("", "") only for an empty identifier. + """ + token = ident + for prefix in DB_PREFIXES: + if token.startswith(prefix): + token = token[len(prefix):] + break + if "|" in token: + accession, protein_name = token.split("|", 1) + else: + accession, protein_name = token, "" + if accession.startswith(CONTAMINANT_PREFIX): + accession = accession[len(CONTAMINANT_PREFIX):] + return accession, protein_name + + def tryptic_peptides(seq): - """Tryptic peptides, 0 missed cleavages, 6-40 aa (Day-34 definition).""" - return { - p - for p in re.split(r"(?<=[KR])(?!P)", seq) - if 6 <= len(p.strip("XUBZ*")) <= 40 - } + """Reference tryptic peptide space: KR|P cleavage, 0-2 missed cleavages, + 7-50 aa. A measurement convention, not any engine's search settings.""" + segments = [s for s in TRYPSIN_SPLIT_RE.split(seq) if s] + peptides = set() + for start in range(len(segments)): + peptide = "" + for end in range(start, min(start + PEPTIDE_MAX_MISSED_CLEAVAGES + 1, + len(segments))): + peptide += segments[end] + if len(peptide) > PEPTIDE_MAX_LEN: + break + if len(peptide) >= PEPTIDE_MIN_LEN: + peptides.add(peptide) + return peptides + + +def describe_overlap(kind, values): + examples = ", ".join(sorted(values)[:5]) + print(f"ERROR: {len(values)} entrapment {kind}(s) overlap the HYE target " + f"FASTA (e.g. {examples}). The entrapment set must be S. cellulosum " + "So ce56 only - check that the SoCe source is the pinned file.", + file=sys.stderr) + return 4 def main(): @@ -84,6 +191,7 @@ def main(): help="in-tree S. cellulosum FASTA, targets only " "(doc/pyopenms/src/data/18Protein_SoCe_Tr_detergents_trace.fasta)") ap.add_argument("--out", required=True, help="combined output FASTA") + ap.add_argument("--summary", help="write measured counts as key=value lines") ap.add_argument("--force", action="store_true", help="overwrite an existing output") args = ap.parse_args() @@ -118,25 +226,119 @@ def main(): % (label, n), file=sys.stderr) return 3 + # SoCe-only entrapment: keep entries whose OS= annotation is exactly the + # absent organism, in source order. Contaminants and foreign proteins + # (including bare ACC|NAME headers with no OS= field) are dropped. + retained = [] + for name, seq in soce: + if organism_of(name) == SO_ORGANISM: + retained.append((name, seq)) + + excluded = len(soce) - len(retained) + if not retained: + print( + "ERROR: no S. cellulosum (strain So ce56) entries left after " + f"filtering {len(soce)} source entries; the SoCe FASTA appears to " + "contain only foreign/contaminant proteins.", + file=sys.stderr) + return 4 + + # Fail closed if the retained set is not provably the expected organism. + for name, _ in retained: + if organism_of(name) != SO_ORGANISM: + print("ERROR: retained entry lacks the expected So ce56 OS= " + f"annotation: {ident_of(name)}", file=sys.stderr) + return 4 + + # Collision checks against the HYE targets (accession/name/sequence). + target_acc, target_names, target_seqs = set(), set(), set() + for name, seq in hye: + accession, protein_name = split_accession_name(ident_of(name)) + if accession: + target_acc.add(accession) + if protein_name: + target_names.add(protein_name) + if seq: + target_seqs.add(seq) + + ent_acc, ent_names, ent_seqs = set(), set(), set() + for name, seq in retained: + accession, protein_name = split_accession_name(ident_of(name)) + if accession: + ent_acc.add(accession) + if protein_name: + ent_names.add(protein_name) + if seq: + ent_seqs.add(seq) + + for kind, overlap in ( + ("accession", ent_acc & target_acc), + ("protein name", ent_names & target_names), + ("sequence", ent_seqs & target_seqs), + ): + if overlap: + return describe_overlap(kind, overlap) + + # Fail closed on duplicate identifiers in the written FASTA: duplicates + # make protein inference and entrapment classification ambiguous. + seen, duplicates = set(), set() + for name, _ in hye: + ident = ident_of(name) + if ident in seen: + duplicates.add(ident) + seen.add(ident) + for name, _ in retained: + ident = ENTRAPMENT_PREFIX + ident_of(name) + if ident in seen: + duplicates.add(ident) + seen.add(ident) + if duplicates: + examples = ", ".join(sorted(duplicates)[:5]) + print(f"ERROR: {len(duplicates)} duplicate output identifier(s) " + f"(e.g. {examples})", file=sys.stderr) + return 4 + with open(args.out, "w") as out: for name, seq in hye: # targets verbatim out.write(f">{name}\n{seq}\n") - for name, seq in soce: # entrapment prefixed + for name, seq in retained: # entrapment prefixed out.write(f">{ENTRAPMENT_PREFIX}{name}\n{seq}\n") target_peps, ent_peps = set(), set() for _, seq in hye: target_peps |= tryptic_peptides(seq) - for _, seq in soce: + for _, seq in retained: ent_peps |= tryptic_peptides(seq) shared = target_peps & ent_peps + shared_pct = 100.0 * len(shared) / len(ent_peps) if ent_peps else 0.0 + + print(f"HYE target entries (verbatim): {len(hye)}") + print(f"SoCe source entries: {len(soce)}") + print(f"retained S. cellulosum So ce56 entries: {len(retained)}") + print(f"excluded non-SoCe source entries: {excluded}") + print(f"entrapment entries written ({ENTRAPMENT_PREFIX}-prefixed): " + f"{len(retained)}") + print(f"total entries written: {len(hye) + len(retained)}") + print(f"target overlap removed: accessions 0, protein names 0, sequences 0") + print(f"shared tryptic peptides entrapment vs target: {len(shared)} of " + f"{len(ent_peps)} ({shared_pct:.2f}% of entrapment space)") + print(f" reference definition (engine-independent; NOT the ProSE/Sage " + f"search settings): trypsin KR|P, " + f"0-{PEPTIDE_MAX_MISSED_CLEAVAGES} missed cleavages, " + f"{PEPTIDE_MIN_LEN}-{PEPTIDE_MAX_LEN} aa") - print(f"targets (HYE, verbatim): {len(hye)}") - print(f"entrapment (SoCe targets, {ENTRAPMENT_PREFIX}-prefixed): {len(soce)}") - print(f"total entries written: {len(hye) + len(soce)}") - print(f"shared tryptic peptides entrapmentâˆİtarget: {len(shared)} " - f"({100.0 * len(shared) / len(ent_peps):.2f}% of entrapment space; " - f"conservative classification applies)") + if args.summary: + with open(args.summary, "w") as summary: + summary.write(f"hye_entries={len(hye)}\n") + summary.write(f"source_entries={len(soce)}\n") + summary.write(f"retained_entries={len(retained)}\n") + summary.write(f"excluded_entries={excluded}\n") + summary.write("overlap_accessions=0\n") + summary.write("overlap_names=0\n") + summary.write("overlap_sequences=0\n") + summary.write(f"entrapment_peptides={len(ent_peps)}\n") + summary.write(f"shared_peptides={len(shared)}\n") + summary.write(f"shared_peptide_pct={shared_pct:.2f}\n") return 0 diff --git a/benchmark/prepare_pxd028735_inputs.sh b/benchmark/prepare_pxd028735_inputs.sh index 200a1fe..3340288 100644 --- a/benchmark/prepare_pxd028735_inputs.sh +++ b/benchmark/prepare_pxd028735_inputs.sh @@ -9,11 +9,15 @@ # # Creates (deterministically; nothing is vendored or committed): # /LFQ_Orbitrap_DDA_Condition_{A,B}_Sample_Alpha_01.mzML -# /entrapment_hye.fasta HYE targets + ENTRAPMENT_-prefixed real -# S. cellulosum So ce56 targets, via -# make_hye_entrapment_fasta.py (the source -# must be decoy-free - ProSE generates decoys -# itself via -Search:decoys auto) +# /entrapment_hye_soce.fasta +# HYE targets + ENTRAPMENT_-prefixed real +# S. cellulosum So ce56 targets via +# make_hye_entrapment_fasta.py. SoCe-only: +# the non-SoCe/contaminant source entries are +# excluded (they overlap the HYE targets), and +# the source must be decoy-free - ProSE +# generates decoys itself via +# -Search:decoys auto # /PROVENANCE.txt dataset accession, source URLs, sizes, # sha256 of every input/output, parameters # @@ -39,6 +43,7 @@ HYE_SHA256="d9ac434d88492c10c8e9a587ee7dbc9480fa0995fa07a6ba35a7da8abf39aa25" HYE_SIZE=16670994 SOCE="doc/pyopenms/src/data/18Protein_SoCe_Tr_detergents_trace.fasta" SOCE_SHA256="714d53edaf768c5162715cae974cb3fa040477879bd999a45c28c66712a04ca8" +ENTRAPMENT_FASTA="entrapment_hye_soce.fasta" # Pinned mzML runs: sha256 (from the Phase-2a pilot) + byte size (Content-Length). RUN_SHA_A="d044284fbb07ea14c3f2aa28b2f94f932d76cabba59f9a6238968f3fcda1d083" @@ -117,12 +122,47 @@ for R in ${RUNS}; do fi done -# 3. combined target + entrapment FASTA (fails closed on decoy-marked sources) -echo " [fasta] entrapment_hye.fasta" +# 3. combined target + entrapment FASTA (SoCe-only; fails closed on +# decoy-marked sources, target-overlapping entries or duplicate identifiers) +echo " [fasta] ${ENTRAPMENT_FASTA}" +SUMMARY_FILE="$(mktemp)" +trap 'rm -f "${SUMMARY_FILE}"' EXIT python3 "${HERE}/make_hye_entrapment_fasta.py" \ --hye "${OUT_DIR}/ProteoBenchFASTA_MixedSpecies_HYE.fasta" \ --soce "${SOCE_PATH}" \ - --out "${OUT_DIR}/entrapment_hye.fasta" --force + --out "${OUT_DIR}/${ENTRAPMENT_FASTA}" \ + --summary "${SUMMARY_FILE}" --force + +summary() { grep -E "^$1=" "${SUMMARY_FILE}" | head -1 | cut -d= -f2; } +ENT_SOURCE=$(summary source_entries) +ENT_RETAINED=$(summary retained_entries) +ENT_EXCLUDED=$(summary excluded_entries) +ENT_ACCESSIONS=$(summary overlap_accessions) +ENT_NAMES=$(summary overlap_names) +ENT_SEQUENCES=$(summary overlap_sequences) +ENT_PEPTIDES=$(summary entrapment_peptides) +ENT_SHARED=$(summary shared_peptides) +ENT_SHARED_PCT=$(summary shared_peptide_pct) +for value in "${ENT_SOURCE}" "${ENT_RETAINED}" "${ENT_EXCLUDED}" \ + "${ENT_PEPTIDES}" "${ENT_SHARED}"; do + [[ "${value}" =~ ^[0-9]+$ ]] || { + echo "ERROR: incomplete entrapment summary (${SUMMARY_FILE})" >&2 + exit 4 + } +done +[[ $((ENT_RETAINED + ENT_EXCLUDED)) -eq ${ENT_SOURCE} ]] || { + echo "ERROR: entrapment entry counts do not add up" >&2 + exit 4 +} +[[ "${ENT_RETAINED}" -gt 0 ]] || { + echo "ERROR: no S. cellulosum So ce56 entrapment entries retained" >&2 + exit 4 +} +[[ "${ENT_ACCESSIONS}" == "0" && "${ENT_NAMES}" == "0" \ + && "${ENT_SEQUENCES}" == "0" ]] || { + echo "ERROR: entrapment set overlaps the HYE targets" >&2 + exit 4 +} # 4. provenance record { @@ -136,6 +176,16 @@ python3 "${HERE}/make_hye_entrapment_fasta.py" \ echo "hye_fasta_sha256=${HYE_SHA256}" echo "soce_fasta=${SOCE}" echo "soce_fasta_sha256=${SOCE_SHA256}" + echo "entrapment_fasta=${ENTRAPMENT_FASTA}" + echo "entrapment_fasta_sha256=$(sha256sum "${OUT_DIR}/${ENTRAPMENT_FASTA}" | cut -d' ' -f1)" + echo "entrapment_source_entries=${ENT_SOURCE}" + echo "entrapment_retained_entries=${ENT_RETAINED}" + echo "entrapment_excluded_entries=${ENT_EXCLUDED}" + echo "entrapment_excluded_definition=non-SoCe source entries: 104 bare ACC|NAME contaminants without OS= (human keratins, trypsins, BSA, ...) plus 15 db-prefixed entries from other organisms" + echo "entrapment_target_overlap=accessions ${ENT_ACCESSIONS}, protein names ${ENT_NAMES}, sequences ${ENT_SEQUENCES}" + echo "entrapment_shared_peptides=${ENT_SHARED}/${ENT_PEPTIDES} (${ENT_SHARED_PCT}%; engine-independent measurement)" + echo "entrapment_shared_peptide_definition=measurement convention only, engine-independent - NOT the ProSE or Sage search settings: trypsin (KR|P), 0-2 missed cleavages, 7-50 aa; shared peptides counted as entrapment (conservative)" + echo "entrapment_shared_peptide_note=the percentage is a property of the two FASTA sets, not of the search configuration; ProSE's actual defaults (trypsin, 7-40 aa, 1 missed cleavage, 100-9000 Da) measure 0.150% on the same sets; Sage's DEFAULT digestion (5-50 aa, 1 missed cleavage, no mass window) measures 3.59%, which describes Sage defaults only and not the explicitly configured one-off Sage run" echo "base_url=${BASE_URL}" for R in ${RUNS}; do GZ="LFQ_Orbitrap_DDA_Condition_${R}_Sample_Alpha_01.mzML.gz" @@ -144,12 +194,12 @@ python3 "${HERE}/make_hye_entrapment_fasta.py" \ echo "run_${R}_size=${RUN_SIZE[${R}]}" done echo "# all files below, sha256:" - ( cd "${OUT_DIR}" && sha256sum ProteoBenchFASTA_MixedSpecies_HYE.fasta entrapment_hye.fasta \ + ( cd "${OUT_DIR}" && sha256sum ProteoBenchFASTA_MixedSpecies_HYE.fasta "${ENTRAPMENT_FASTA}" \ LFQ_Orbitrap_DDA_Condition_*_Sample_Alpha_01.mzML.gz \ LFQ_Orbitrap_DDA_Condition_*_Sample_Alpha_01.mzML ) echo "# search parameters (applied identically to both arms by run_prose_benchmark.sh):" echo "search_params=precursor 10 ppm (ProSE default, published); fragment 0.02 Da (published; passed via PROSE_EXTRA_SEARCH_ARGS); closed search; decoys auto" - echo "entrapment_design=absent-organism S. cellulosum So ce56 targets, ENTRAPMENT_-prefixed; shared tryptic peptides count as entrapment (conservative)" + echo "entrapment_design=absent-organism S. cellulosum So ce56 ONLY (9,320 of 9,439 source entries retained; 119 non-SoCe/contaminant entries excluded), ENTRAPMENT_-prefixed; zero accession/name/sequence overlap with the HYE target FASTA; shared tryptic peptides count as entrapment (conservative)" echo "generated_at=$(date -u '+%Y-%m-%dT%H:%M:%SZ')" } > "${OUT_DIR}/PROVENANCE.txt" diff --git a/benchmark/test_make_hye_entrapment_fasta.py b/benchmark/test_make_hye_entrapment_fasta.py new file mode 100644 index 0000000..dcfe94d --- /dev/null +++ b/benchmark/test_make_hye_entrapment_fasta.py @@ -0,0 +1,285 @@ +#!/usr/bin/env python3 +"""Tests for make_hye_entrapment_fasta.py (SoCe-only PXD028735 entrapment). + +Synthetic FASTA files are written on the fly; no dataset, no OpenMS source +tree and no ProSE build is needed. Each test invokes the generator exactly as +prepare_pxd028735_inputs.sh does and asserts on its exit code, its stderr and +the generated FASTA. + +Run: python3 benchmark/test_make_hye_entrapment_fasta.py +""" + +import os +import subprocess +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +SCRIPT = os.path.join(HERE, "make_hye_entrapment_fasta.py") + +SO_OS = "OS=Sorangium cellulosum (strain So ce56)" +ENTRAPMENT_PREFIX = "ENTRAPMENT_" + + +def write_fasta(path, entries): + with open(path, "w", newline="\n") as fh: + for header, seq in entries: + fh.write(f">{header}\n{seq}\n") + + +def read_entries(path): + entries = [] + name, seq = None, [] + with open(path) as fh: + for line in fh: + line = line.rstrip("\r\n") + if line.startswith(">"): + if name is not None: + entries.append((name, "".join(seq))) + name, seq = line[1:], [] + elif line: + seq.append(line) + if name is not None: + entries.append((name, "".join(seq))) + return entries + + +def soce(accession, name, seq, db="sp"): + return (f"{db}|{accession}|{name} Description {SO_OS} GN=x PE=3 SV=1", seq) + + +def target(accession, name, seq): + """HYE target entry (ProteoBench contaminants are Cont_ accessions).""" + return (f"sp|{accession}|{name}", seq) + + +def run_generator(tmp, hye_entries, soce_entries, run_id="1"): + hye = os.path.join(tmp, f"hye-{run_id}.fasta") + soce_path = os.path.join(tmp, f"soce-{run_id}.fasta") + out = os.path.join(tmp, f"out-{run_id}.fasta") + summary = os.path.join(tmp, f"summary-{run_id}.txt") + write_fasta(hye, hye_entries) + write_fasta(soce_path, soce_entries) + proc = subprocess.run( + [sys.executable, SCRIPT, "--hye", hye, "--soce", soce_path, + "--out", out, "--summary", summary, "--force"], + capture_output=True, text=True) + return proc, out, summary + + +def summary_dict(path): + data = {} + with open(path) as fh: + for line in fh: + key, _, value = line.rstrip("\n").partition("=") + data[key] = value + return data + + +def expect_failure(proc, needle): + assert proc.returncode != 0, \ + f"generator unexpectedly succeeded:\n{proc.stdout}\n{proc.stderr}" + assert needle in proc.stderr, proc.stderr + + +def test_database_prefixed_soce_retained(): + """sp| and tr| So ce56 entries are kept verbatim, ENTRAPMENT_-prefixed.""" + with tempfile.TemporaryDirectory() as tmp: + hye = [target("Cont_Q00001", "TARGET_HUMAN", "MKWVTFISLLFLFSSAYSR")] + src = [ + soce("A9F596", "ACCA_SORC5", "MAASILPFEKPVAELIEKVRELRALAAADPR"), + soce("B1ABC2", "TRX_SORC5", "MSKGEELFTGVVPILVELDGDVNGHKFSVSG", + db="tr"), + ] + proc, out, summary = run_generator(tmp, hye, src) + assert proc.returncode == 0, proc.stderr + entries = read_entries(out) + assert len(entries) == 3, entries + assert entries[0] == hye[0] + for got, (want_header, want_seq) in zip(entries[1:], src): + assert got[0] == ENTRAPMENT_PREFIX + want_header, got[0] + assert got[1] == want_seq + data = summary_dict(summary) + assert data["retained_entries"] == "2", data + assert data["excluded_entries"] == "0", data + assert data["hye_entries"] == "1", data + assert data["overlap_accessions"] == "0", data + assert data["overlap_names"] == "0", data + assert data["overlap_sequences"] == "0", data + assert "shared_peptides" in data and "entrapment_peptides" in data, data + print("PASS: database-prefixed Soce entries retained and prefixed") + + +def test_bare_acc_name_contaminant_excluded(): + """Bare ACC|NAME headers have no OS= and are excluded, even when their + accession also exists as a Cont_ accession in the HYE targets.""" + with tempfile.TemporaryDirectory() as tmp: + hye = [target("Cont_P00760", "TRY1_BOVIN", "MKTLLLTLVVAA")] + src = [ + ("P00760|TRY1_BOVIN Trypsin - Bos taurus (Bovine).", "MKWVTFISLL"), + soce("A9F596", "ACCA_SORC5", "MAASILPFEKPVAELIEKVRELRALAAADPR"), + ] + proc, out, summary = run_generator(tmp, hye, src) + assert proc.returncode == 0, proc.stderr + entries = read_entries(out) + assert len(entries) == 2, entries + assert entries[1][0] == ENTRAPMENT_PREFIX + src[1][0] + data = summary_dict(summary) + assert data["retained_entries"] == "1", data + assert data["excluded_entries"] == "1", data + print("PASS: bare ACC|NAME contaminant excluded (no false overlap failure)") + + +def test_non_soce_database_entry_excluded(): + """Order-preserving exclusion of a db-prefixed foreign organism.""" + with tempfile.TemporaryDirectory() as tmp: + hye = [target("Cont_Q00001", "TARGET_HUMAN", "MKWVTFISLL")] + src = [ + soce("A9F596", "ACCA_SORC5", "MAASILPFEKPV"), + ("sp|P12345|FOREIGN_HUMAN Description OS=Homo sapiens GN=x", "MSKGEELFT"), + soce("B1ABC2", "TRX_SORC5", "MAASILPFEKPVAELIEK"), + ] + proc, out, summary = run_generator(tmp, hye, src) + assert proc.returncode == 0, proc.stderr + entries = read_entries(out) + assert [e[0].split()[0] for e in entries] == [ + "sp|Cont_Q00001|TARGET_HUMAN", + ENTRAPMENT_PREFIX + "sp|A9F596|ACCA_SORC5", + ENTRAPMENT_PREFIX + "sp|B1ABC2|TRX_SORC5", + ], entries + assert summary_dict(summary)["excluded_entries"] == "1" + print("PASS: non-Soce database-prefixed entry excluded, order preserved") + + +def test_target_contaminant_accession_collision(): + """A So ce56 entry exposing a Cont_pin accession fails closed.""" + with tempfile.TemporaryDirectory() as tmp: + hye = [target("Cont_P00760", "TRY1_BOVIN", "MKTLLLTLVVAA")] + src = [soce("P00760", "TRYX_SORC5", "MAASILPFEKPV")] + proc, _, _ = run_generator(tmp, hye, src) + expect_failure(proc, "accession") + print("PASS: target Cont_ accession collision fails closed") + + +def test_protein_name_collision(): + """Distinct accessions but the same protein name fails closed.""" + with tempfile.TemporaryDirectory() as tmp: + hye = [target("Cont_Q11111", "ACCA_SORC5", "MKWVTFISLL")] + src = [soce("P22222", "ACCA_SORC5", "MAASILPFEKPV")] + proc, _, _ = run_generator(tmp, hye, src) + expect_failure(proc, "protein name") + print("PASS: protein-name collision fails closed") + + +def test_identical_sequence_collision(): + """Distinct accession and name but an identical sequence fails closed.""" + with tempfile.TemporaryDirectory() as tmp: + hye = [target("Cont_Q22222", "OTHER_HUMAN", + "MKWVTFISLLFLFSSAYSRGVFRR")] + src = [soce("P33333", "UNIQ_SORC5", "MKWVTFISLLFLFSSAYSRGVFRR")] + proc, _, _ = run_generator(tmp, hye, src) + expect_failure(proc, "sequence") + print("PASS: identical-sequence collision fails closed") + + +def test_decoy_marked_source_fails(): + """A _rev-suffix decoy entry in the source aborts generation.""" + with tempfile.TemporaryDirectory() as tmp: + hye = [target("Cont_Q00001", "TARGET_HUMAN", "MKWVTFISLL")] + src = [("P33333_rev Some protein " + SO_OS, "MAASILPFEKPV")] + proc, _, _ = run_generator(tmp, hye, src) + expect_failure(proc, "decoy-marker") + print("PASS: decoy-marked source fails closed") + + +def test_all_foreign_source_fails(): + """A source with no So ce56 entry at all aborts generation.""" + with tempfile.TemporaryDirectory() as tmp: + hye = [target("Cont_Q00001", "TARGET_HUMAN", "MKWVTFISLL")] + src = [ + ("sp|P12345|FOREIGN_HUMAN Description OS=Homo sapiens GN=x", + "MSKGEELFT"), + ("P00760|TRY1_BOVIN Trypsin - Bos taurus (Bovine).", "MKWVTFISLL"), + ] + proc, _, _ = run_generator(tmp, hye, src) + expect_failure(proc, "no S. cellulosum") + print("PASS: all-foreign source fails closed") + + +def test_duplicate_output_identifiers_fail(): + """Duplicate identifiers in the written FASTA abort generation.""" + with tempfile.TemporaryDirectory() as tmp: + hye = [target("Cont_Q00001", "TARGET_HUMAN", "MKWVTFISLL")] + src = [ + soce("A9F596", "ACCA_SORC5", "MAASILPFEKPV"), + soce("A9F596", "ACCA_SORC5", "MSKGEELFTGVV"), + ] + proc, _, _ = run_generator(tmp, hye, src) + expect_failure(proc, "duplicate output identifier") + print("PASS: duplicate output identifiers fail closed") + + +def test_deterministic_output(): + """Two generations from identical inputs are byte-identical.""" + with tempfile.TemporaryDirectory() as tmp: + hye = [ + target("Cont_Q00001", "TARGET_HUMAN", "MKWVTFISLL"), + ("tr|Q00002|TARGET2_HUMAN", "MSKGEELFTGVVP"), + ] + src = [ + soce("A9F596", "ACCA_SORC5", "MAASILPFEKPV"), + soce("B1ABC2", "TRX_SORC5", "MAASILPFEKPVAELIEK", db="tr"), + ("P00760|TRY1_BOVIN Trypsin - Bos taurus (Bovine).", "MKWVTFISLL"), + ] + proc1, out1, summary1 = run_generator(tmp, hye, src, run_id="1") + proc2, out2, summary2 = run_generator(tmp, hye, src, run_id="2") + assert proc1.returncode == 0, proc1.stderr + assert proc2.returncode == 0, proc2.stderr + with open(out1, "rb") as fh: + first = fh.read() + with open(out2, "rb") as fh: + second = fh.read() + assert first == second, "generated FASTA is not byte-identical" + with open(summary1, "rb") as fh: + first_summary = fh.read() + with open(summary2, "rb") as fh: + second_summary = fh.read() + assert first_summary == second_summary, "summary is not deterministic" + print("PASS: deterministic output (byte-identical FASTA and summary)") + + +def test_hye_target_entries_unchanged(): + """HYE entries stay verbatim, in order, with their original headers.""" + with tempfile.TemporaryDirectory() as tmp: + hye = [ + target("Cont_P00722", "BGAL_ECOLI", "MKWVTFISLL"), + ("tr|A0A123|YEAST_PROT Description OS=Saccharomyces cerevisiae", + "MSKGEELFTGVVP"), + ("Biognosys|iRT_11|iRT-pep11", "LGGNEQVTR"), + ] + src = [soce("A9F596", "ACCA_SORC5", "MAASILPFEKPV")] + proc, out, _ = run_generator(tmp, hye, src) + assert proc.returncode == 0, proc.stderr + entries = read_entries(out) + assert entries[:len(hye)] == hye, entries[:len(hye)] + assert len(entries) == len(hye) + 1, entries + print("PASS: HYE target entries unchanged and first in output") + + +def main(): + test_database_prefixed_soce_retained() + test_bare_acc_name_contaminant_excluded() + test_non_soce_database_entry_excluded() + test_target_contaminant_accession_collision() + test_protein_name_collision() + test_identical_sequence_collision() + test_decoy_marked_source_fails() + test_all_foreign_source_fails() + test_duplicate_output_identifiers_fail() + test_deterministic_output() + test_hye_target_entries_unchanged() + print("\nAll make_hye_entrapment_fasta tests passed.") + + +if __name__ == "__main__": + main()