diff --git a/docs/prose-sage-pxd028735/.gitattributes b/docs/prose-sage-pxd028735/.gitattributes new file mode 100644 index 0000000..2e31adf --- /dev/null +++ b/docs/prose-sage-pxd028735/.gitattributes @@ -0,0 +1 @@ +*.sha256 text eol=lf diff --git a/docs/prose-sage-pxd028735/EXPERIMENT_REPORT.md b/docs/prose-sage-pxd028735/EXPERIMENT_REPORT.md new file mode 100644 index 0000000..f2c6887 --- /dev/null +++ b/docs/prose-sage-pxd028735/EXPERIMENT_REPORT.md @@ -0,0 +1,543 @@ +# ProSE vs Sage on PXD028735: a pinned, audited two-condition benchmark + +**Status.** Experiment complete: four primary searches, one per engine per condition, no repeats. +Metrics independently audited and reconciled against source and raw output. Results frozen; this +report is generated from the frozen outputs, not transcribed from them. + +**Date.** Runs and audit 2026-11-27; report 2026-11-28. + +**Scope.** A comparison of two search engines on one public dataset under a shared parameter set. +It reports what each engine output, why the raw summary figures differ, and how many target +identifications each engine recovered at a common nominal 1% PSM FDR. The last of these is a +sensitivity measurement for these two configured pipelines on this sample; it does not establish a +general ranking of the engines, because the two operating points are not equally stringent +(Section 4.1) and one injection per condition cannot support a generalisation. + +--- + +## 1. Question + +Two engines, ProSE (OpenMS) and Sage, were run on the two conditions of PXD028735 with the same +database, the same trypsin-family digestion rules apart from one proline rule that only ProSE +applied (Section 4.1), the same tolerances, the same fixed and variable modifications, and a common +nominal 1% PSM FDR target. The primary measurement is the number of target identifications each +engine recovers at that threshold (Section 9); the questions were: + +1. How many PSMs, peptides and proteins does each engine report at 1% FDR? +2. Do the engines' own summary figures agree with their serialized output? +3. Where they differ, is the difference a property of the search or a property of how the number is + counted and reported? + +Question 3 turned out to be the substantive one: two of the three headline discrepancies are +reporting artefacts, and one is a classification error in the first version of the comparison. +Settling them is a prerequisite for the comparison rather than a substitute for it: once every +figure is counted on a like-for-like basis, the identification yield in Section 9 stands on its own. + +## 2. Data + +| Item | Value | +|---|---| +| Dataset | PXD028735, LFQ Orbitrap DDA, *Sample Alpha 01* | +| Conditions | A and B, one mzML each | +| MS2 spectra | 109,507 (A), 111,088 (B) | +| Database | `entrapment_hye_soce.fasta`, 41,209 entries | +| Entrapment | HYE proteins, accessions prefixed `ENTRAPMENT_` (PR #34, merged) | +| Replicates | none — one injection per condition | + +The entrapment sequences are present in the search database and are treated by both engines as +ordinary target entries; they are separated at analysis time by accession prefix. Decoys were +generated internally by each engine and never supplied as a file. + +Because there is one injection per condition, every number here is a single observation. No +run-to-run variance can be estimated, and no significance test is meaningful. + +## 3. Engines and pins + +| Engine | Version | Binary SHA-256 | +|---|---|---| +| ProSE | OpenMS `ProSE`, PR #9975 build | `56958d4e428fa3c7af4b8501f63d08075d0d59bea5e371b3a77b580cf7a263dd` | +| Sage | 0.15.0-beta.2, prebuilt `x86_64-unknown-linux-gnu` | `d1a96a7d14836f0846a55cede74456595169399abdc6a12e468f234eb4fcf7c0` | + +Sage was installed as a release binary with no bundled source. Its behaviour was interpreted from +the upstream tag `v0.15.0-beta.2`; the tag-to-binary correspondence is inferred from the version +string the binary prints, not established cryptographically. This matters only for explanations +that cite Sage source (Section 8.1); every *count* in this report comes from Sage's own output. + +Environment: WSL2 Ubuntu 24.04, 4 vCPU, 11 GiB RAM. Both engines were given 4 threads. + +## 4. Parameter alignment + +The ProSE invocation was built flag by flag against the Sage configuration. Of the 23 rows below, +11 state a setting both engines executed, 11 are approximately comparable (same intent, different +semantics or a different stage of the search), and one has no counterpart. Two differences the table +cannot express are quantified in Section 4.1, and one row (fragment m/z window) records a setting +Sage silently discarded. Different internal algorithms are part of what is being compared; what the +table has to establish is that the search conditions match, and Section 4.1 states where they do not. + +| Parameter | ProSE setting | Sage setting | +|---|---|---| +| Enzyme | `Trypsin` (no cleavage before P) | `cleave_at = KR`, `c_terminal = true`, `restrict` unset (cleaves before P) | +| Specificity | `enzyme_specificity full` | `semi_enzymatic = false` | +| Peptide length | `min_size 7`, `max_size 50` | `min_len 7`, `max_len 50` | +| Missed cleavages | `2` | `2` | +| Peptide mass | `500`–`5000` | `500.0`–`5000.0` | +| Precursor tolerance | `±10 ppm` | `ppm [-10, 10]` | +| Precursor charge | `2`–`4` | `[2, 4]` | +| Isotope error | `-1`–`2` | `[-1, 2]` | +| Fragment tolerance | `0.02 Da` | `da [-0.02, 0.02]` | +| Fragment m/z window | `150`–`2000` | none applied — `fragment_min_mz`/`fragment_max_mz` are not fields of this Sage version and were ignored | +| Min. ion index | `2` | `2` | +| Max. fragment charge | `3` | `3` | +| Deisotope | `true` | `true` | +| Min. matched ions | `4` | `min_matched_peaks 4` | +| Fixed modification | `Carbamidomethyl (C)` | `C: 57.02146` | +| Variable modifications | `Oxidation (M)`, `Acetyl (Protein N-term)` | `M: 15.9949`, `[^: 42.010567` (input JSON: 42.010565) | +| Max. variable mods | `2` | `2` | +| Report top hits | `1` | `report_psms 1` | +| Decoys | internal, `DECOY_` prefix | internal, `rev_` tag | +| PSM FDR | `0.01` | 1% (`spectrum_q`) | +| Protein FDR | `0.01` | 1% (proteotypic peptides) | +| Protein grouping | not produced | `protein_grouping = true` at 1% peptide FDR | +| Quantification | none | LFQ disabled | + +Residual differences are internal to each engine and are part of what is being compared, not +configuration drift: ProSE's automatic resolution-aware peak cap versus Sage's `min_peaks 15 / +max_peaks 150`; both engines score at most 50 candidates per spectrum, although they select those +candidates differently: ProSE uses `scoring:max_candidates_per_spectrum`, whereas Sage retains the +top 50 by matched peaks; and each engine's own score (OpenMS HyperScore versus `SageHyperScore` +plus an LDA discriminant, which is also the score Sage's q-values rank on). + +### 4.1 Where the two searches were not identical + +Four differences are demonstrable from the frozen evidence, and they are the ones that put the two +1% cuts on slightly different footings: + +* **Digestion.** ProSE's `Trypsin` does not cleave before proline; this run's Sage configuration has + `restrict` unset and therefore does. The digestion difference affects approximately 1.0% of Sage + PSMs under the C-terminal pre-proline cleavage definition used for this estimate. This estimate + does not include additional peptides whose N-terminal cleavage context is also incompatible with + ProSE's digestion rule. The exact magnitude depends on the peptide-occurrence definition; + excluding the estimated affected subset does not eliminate Sage's higher observed PSM yield. +* **Fragment window.** ProSE restricted fragment ions to 150–2000 m/z; the keys that were meant to + set the same window for Sage are not fields of the version that ran and were ignored, so Sage + indexed every b/y ion. The effect on either count cannot be measured from the frozen outputs. +* **Score basis.** ProSE's q-values rank `ln(hyperscore)`; Sage's `spectrum_q` ranks the LDA + discriminant. Sorting by Sage's discriminant score produces a monotonic spectrum-q ordering apart + from 32 tie-level exceptions in condition A (105,726 rows) and 38 in condition B (107,623 rows). + These exceptions occur within groups sharing identical printed discriminant scores; the largest + observed discrepancies are 1.7 × 10⁻⁵ in A and 2.3 × 10⁻⁵ in B. Sorting by hyperscore produces + substantially more q-value ordering violations. The two 1% cuts therefore select different spectra + by construction, though both threshold the same nominal quantity. +* **Estimator.** OpenMS assigns q = D/T (decoys at or above the score, over targets at or above it); + Sage assigns (D + 1)/T. The pseudo-count admits at most one fewer decoy at these target counts + (~0.002 percentage points), in the conservative direction for Sage. + +None of these is a reason to withhold the comparison. Each is a property of the two configurations +that can be named, bounded where the evidence allows, and left as an open qualification where it +cannot. The PSM and peptide yields in Section 9 are therefore reported as observed, at a common +nominal threshold, with these differences stated rather than used to disqualify the numbers. + +## 5. Execution protocol + +* Strictly sequential: ProSE A → Sage A → ProSE B → Sage B, one process at a time. +* A guard re-verified the 11 pinned input/config/binary/script hashes before the first run and + aborted on any mismatch; it also refused to start if `results/` was non-empty, so no run could + overwrite another. +* Every run captured its exact command line, stdout, stderr, exit code and `/usr/bin/time -v` + record. All four exited 0. +* Sage was invoked with `--disable-telemetry-i-dont-want-to-improve-sage`. The flag is accepted and + documented by the binary, but this build prints no acknowledgement line; nothing in the logs + confirms the opt-out beyond the accepted argument. +* The FASTA hash was re-checked after the last run and was unchanged. + +## 6. Counting definitions + +Every figure in Tables 1–5 is recomputed from the serialized outputs by `emit_tables.py`, which +also asserts the identities in Table 5; no table entry is copied from an engine's summary +line without being reconstructed. The few numbers quoted only in the text come from the audit +scripts and are marked as such. + +* **PSM** — one `PeptideIdentification` element (ProSE idXML) or one TSV row (Sage). Both engines + emit exactly one hit per spectrum (`report:top_hits 1`; `report_psms 1`), so a PSM count in either + column is a count of spectra identified. +* **Threshold** — a common nominal 1% PSM FDR, inclusive (`q ≤ 0.01`), at each engine's native + PSM-level score (`score` under `score_type="q-value"` for ProSE; `spectrum_q` for Sage). *Nominal* + is meant literally: the two operating points share a target, which is not a demonstration that + they have identical statistical stringency, because they rank different candidate sets on + different scores. The estimators also differ — OpenMS assigns q = D/T, Sage (D + 1)/T — which at + these target counts moves the cut by at most one decoy. +* **Peptide** — distinct sequence string as the engine writes it. ProSE embeds modifications in + parentheses (`M(Oxidation)`); Sage uses bracketed mass shifts (`M[+15.9949]`). "Bare" means the + modification token is stripped. Bare sequences still differ in N-terminal annotation conventions, + so peptide identities are only ever compared within an engine. Peptide counts are compared across + engines on one basis only: distinct sequences carried by target-class PSMs at the common 1% PSM + threshold (Section 9). +* **Protein** — a surviving `ProteinHit` accession (ProSE) or an accession with + `protein_q ≤ 0.01` (Sage). ProSE protein hits and Sage protein groups are different objects and + are never pooled or ranked against each other. + +Each hit is assigned to exactly one class, evaluated in this order: + +| Class | Definition | +|---|---| +| `pure_target` | ≥1 accession, no entrapment, no decoy; ProSE `target_decoy = target` | +| `target_decoy_shared` | ProSE only: references both target and decoy proteins, none entrapment | +| `target_shared_entrapment` | ≥1 entrapment accession and ≥1 non-entrapment accession | +| `entrapment_only` | every accession is entrapment | +| `decoy` | every accession is a decoy (non-entrapment) | +| `decoy_entrapment` | every accession is a decoy of an entrapment protein | +| `no_protein_reference` | zero surviving accessions after protein-FDR finalization | + +**"Not observable" is not zero.** ProSE deletes decoy PSMs and then removes dangling protein +references during protein-FDR finalization, so decoy and decoy-entrapment evidence cannot be +counted in its output at all. Those cells are marked *not observable*; only Sage's decoy columns +are measurements. + +## 7. Results + +### Table 1 — PSM level + +All engine-native q thresholds are a common nominal 1% PSM FDR and inclusive; the shared target is not a claim that the two operating points have identical statistical stringency (Section 4.1). ProSE removes decoy PSMs and their protein references at protein-FDR finalization, so decoy rows cannot be observed in its output; Sage writes targets and decoys alike. + +| Metric | ProSE A | ProSE B | Sage A | Sage B | +|---|---:|---:|---:|---:| +| Engine log: PSM figure (as labelled by the engine) | 45,723 | 47,252 | 55,377 | 56,312 | +| Serialized rows, target class (engine-native threshold) | 45,723 | 47,252 | 54,830 | 55,756 | +| Serialized rows, all labels at threshold | not observable | not observable | 55,377 | 56,312 | +| **Pure target** | 44,807 | 46,352 | 54,654 | 55,614 | +| Target+decoy shared | 4 | 1 | — | — | +| Target-shared entrapment | 31 | 25 | 49 | 43 | +| Entrapment only | 19 | 18 | 127 | 99 | +| Target, no surviving protein reference | 862 | 856 | 0 | 0 | +| Decoy | not observable | not observable | 409 | 417 | +| Decoy-entrapment | not observable | not observable | 138 | 139 | + +![ProSE and Sage PSM yield at 1% nominal PSM FDR](figures/psm_yield_1pct.png) + +Figure 1. ProSE and Sage PSM yield at 1% nominal PSM FDR. Target PSM counts for ProSE and Sage on +PXD028735, conditions A and B. ProSE was run without Percolator or any other post-scoring. Sage +(LDA) is the stock Sage 0.15.0-beta.2 workflow, which unconditionally applies its built-in +20-feature linear discriminant analysis post-scoring before assigning target-decoy q-values. Sage +(hyperscore) is a derived re-ranking of the frozen Sage PSM tables on Sage's own pre-LDA hyperscore, +using Sage's q-value procedure; it is not an independent Sage execution with post-scoring disabled, +because the pinned binary exposes no such switch. Each condition was searched once per +configuration, and A and B are different pooled samples rather than replicates, so bars are single +measurements without error bars. The two Sage bars compare different ranking strategies applied to +the same frozen Sage search results. ProSE represents an independently executed search pipeline on +the same dataset. + +Table 1 and Figure 1 report the same counts for the configured-pipeline comparison. The first and +second bars are independently executed searches — ProSE as configured in Section 4, and stock Sage — +and that pair is the comparison this report is built on and the one Section 9 draws its conclusions +from. The third bar is not a third executed configuration. It is derived from the frozen Sage output +by re-ranking the identifications Sage already reported on its own pre-LDA hyperscore and recomputing +q-values with Sage's procedure; no Sage binary was run with post-scoring disabled, because the pinned +0.15.0-beta.2 build exposes no configuration, CLI or environment switch for it (Section 4.1, score +basis). The derived arm therefore adds no new spectra, scores or decoy evidence: it answers what +Sage's ranking yields without the LDA step, not what a no-rescoring Sage run would produce. The +distance between the two Sage bars is the contribution of that post-scoring step on this dataset — +a statement about ranking, which leaves the configured-pipeline comparison in Section 9 unchanged. + +### Table 2 — Distinct peptide sequences + +A peptide is counted once per class it appears in; the two engines write different sequence syntaxes, so sequence identities are only ever compared within an engine — counts are compared across engines in Section 9. *Modified* is the engine's own string (OpenMS `M(Oxidation)` vs Sage `M[+15.9949]`); *bare* has modification tokens stripped. + +| Metric | ProSE A | ProSE B | Sage A | Sage B | +|---|---:|---:|---:|---:| +| Engine log: unique peptides | 31,991 | 32,465 | 36,875 | 37,269 | +| Recomputed set behind that figure | 31,991 | 32,465 | 36,875 | 37,269 | +| Bare sequences in the same set | 30,991 | 31,206 | 35,732 | 35,835 | +| **Pure target, modified** | 31,094 | 31,586 | 36,767 | 37,190 | +| Pure target, bare | 30,094 | 30,328 | 35,624 | 35,756 | +| Target+decoy shared | 4 | 1 | — | — | +| Target-shared entrapment | 17 | 14 | 25 | 25 | +| Entrapment only | 19 | 17 | 122 | 95 | +| Target, no surviving protein reference | 857 | 847 | 0 | 0 | + +Rows 7–9 for Sage are taken at the PSM threshold (`spectrum_q ≤ 0.01`). The engine's reported peptide total and its pure-target part, however, come from Sage's separate peptide-level stage, so they are not on the same basis as the ProSE rows above them: at the common PSM threshold the same set is 38,181 (A) / 38,455 (B) distinct sequences, 1,306 / 1,186 more. Section 9 makes that like-for-like comparison; the `peptide_q` sets are: + +| Sage peptide set | Sage A | Sage B | +|---|---:|---:| +| Unique peptides, `peptide_q ≤ 0.01` | 36,875 | 37,269 | +| Pure target | 36,767 | 37,190 | +| Target-shared entrapment | 24 | 22 | +| Entrapment only | 84 | 57 | +| Unique peptides, `spectrum_q ≤ 0.01` | 38,181 | 38,455 | + +### Table 3 — Proteins and protein groups + +ProSE's protein count is a picked-protein list over complete protein sets with no grouping step in the output; Sage's is the picked protein list restricted to proteotypic peptides, plus a separate IDPicker-style grouping. The two protein columns are different quantities and are not compared. + +| Metric | ProSE A | ProSE B | Sage A | Sage B | +|---|---:|---:|---:|---:| +| Protein identifications at 1% FDR | 5,709 | 5,755 | 5,276 | 5,225 | +| — non-entrapment | 5,680 | 5,727 | 5,262 | 5,218 | +| — entrapment | 29 | 28 | 14 | 7 | +| Protein groups | not emitted (0 elements) | not emitted (0 elements) | 5,380 | 5,336 | +| — entrapment groups | — | — | 14 | 6 | + +### Table 4 — Runtime and resources + +From `/usr/bin/time -v` on the recorded runs; nothing was re-timed. Peak RSS is shown in MiB; the raw figures are 5,636,512 / 5,635,720 / 8,237,792 / 7,913,656 kB. + +| Metric | ProSE A | ProSE B | Sage A | Sage B | +|---|---:|---:|---:|---:| +| Wall clock | 2:47.23 | 2:55.83 | 3:28.38 | 4:49.09 | +| User CPU (s) | 500.82 | 558.20 | 536.65 | 824.97 | +| System CPU (s) | 30.57 | 21.79 | 33.62 | 35.45 | +| CPU utilisation | 317% | 329% | 273% | 297% | +| Peak RSS (MiB) | 5,504 | 5,504 | 8,045 | 7,728 | + +Engine-internal stages (from the same logs): ProSE index build 44.3 s / 38.8 s, search 86.9 s / 104.3 s, FDR 0.6 s / 0.9 s; Sage search 94.8 s / 163.0 s. + +### Table 5 — Log-to-output reconciliation + +Each engine summary figure is recomputed from the serialized output. A zero delta means the logged number is fully explained by the stated reconstruction. + +| Quantity | Logged | Reconstructed | Δ | +|---|---:|---:|---:| +| ProSE A PSMs (logged `Matched`) | 45,723 | 45,723 | 0 | +| ProSE A unique peptides | 31,991 | 31,991 | 0 | +| ProSE A proteins | 5,709 | 5,709 | 0 | +| Sage A PSM figure (all labels at threshold) | 55,377 | 55,377 | 0 | +| Sage A unique peptides (`peptide_q`) | 36,875 | 36,875 | 0 | +| Sage A proteins | 5,276 | 5,276 | 0 | +| Sage A protein groups | 5,380 | 5,380 | 0 | +| ProSE B PSMs (logged `Matched`) | 47,252 | 47,252 | 0 | +| ProSE B unique peptides | 32,465 | 32,465 | 0 | +| ProSE B proteins | 5,755 | 5,755 | 0 | +| Sage B PSM figure (all labels at threshold) | 56,312 | 56,312 | 0 | +| Sage B unique peptides (`peptide_q`) | 37,269 | 37,269 | 0 | +| Sage B proteins | 5,225 | 5,225 | 0 | +| Sage B protein groups | 5,336 | 5,336 | 0 | + +## 8. The three discrepancies, and how each resolves + +### 8.1 Sage's logged PSM figure includes decoys + +Sage logs `discovered 55377 target peptide-spectrum matches at 1% FDR` (A) and `56312` (B). The +serialized output contains 54,830 and 55,756 target rows at `spectrum_q ≤ 0.01`. The gap is exactly +the decoy rows that fall inside the same q block: 547 (A) and 556 (B). + +The mechanism is in `spectrum_q_value` (`crates/sage/src/ml/qvalue.rs`, tag `v0.15.0-beta.2`): the +returned counter is incremented for every feature whose cumulative-minimum q is ≤ 0.01, with no +test of `label == 1`. + +```rust +for score in scores.iter_mut().rev() { + q_min = q_min.min(score.spectrum_q); + score.spectrum_q = q_min; + if q_min <= 0.01 { passing += 1; } // no label test +} +passing +``` + +`runner.rs` logs that return value verbatim as "target peptide-spectrum matches". The arithmetic +closes to the unit on both runs (Table 5), so this is a reconciliation rather than a coincidence. + +The peptide-level counter in the same crate (`fdr.rs`, `Competition::assign_q_value`) does test +`!score.decoy`, which is why the 36,875 / 37,269 peptide figure is target-only; only the +spectrum-level counter lacks the test. + +**Consequence.** The logged figure is a counter over the target+decoy block. It is named here +**Sage logged PSM counter (includes decoys)** and is never used as a target count. The target +count — **Sage target PSMs from serialized TSV (label == 1, `spectrum_q ≤ 0.01`)** — is +54,830 / 55,756; the **Sage pure-target PSMs** figure, which also excludes entrapment-mapped +PSMs, is 54,654 / 55,614. + +### 8.2 ProSE target identifications without surviving protein references + +ProSE logs `45723 target / 0 decoy PSMs`. Of those 45,723, **862 (A) / 856 (B)** reference no +surviving protein: their proteins failed picked-protein FDR or were decoys, and +`removeDanglingProteinReferences` cleared the refs. They retain `target_decoy = "target"` and +q ≤ 0.01 (max 0.009995 (A) / 0.009968 (B), median 0.005033 / 0.004531, per +`audit/counts2.csv`), so they are genuine +target-classified peptide identifications — but no protein in the output supports them. + +The first version of this comparison counted them as protein-supported targets. They are now +reported separately as **target PSMs without surviving protein references**. They are not +discarded: the peptide evidence exists. They are not counted as pure target either: the output does +not attribute them to a protein. On the protein side they are already absent, which is why +ProSE's 5,709 / 5,755 protein hits do not shrink. + +The same correction applies at peptide level: 857 (A) / 847 (B) distinct sequences. + +### 8.3 ProSE's logged unique-peptide figure is a union over classes + +ProSE logs 31,991 (A) / 32,465 (B) unique peptides. That is the size of the union of *all* +post-FDR classes, not the pure-target set: + +| Run | Pure target | No protein ref | Shared entrapment | Entrapment only | Target+decoy | Sum | +|---|---:|---:|---:|---:|---:|---:| +| A | 31,094 | 857 | 17 | 19 | 4 | 31,991 | +| B | 31,586 | 847 | 14 | 17 | 1 | 32,465 | + +Both sums are exact, matching source: `updateFinalStats` accumulates every top hit without a class +filter. The engine summary is therefore internally consistent; it simply answers a different +question from "how many pure-target peptides were identified". + +### 8.4 A fourth difference, in structure rather than arithmetic + +Sage runs a separate peptide-level FDR stage (`peptide_q`) before protein inference. Its reported +36,875 / 37,269 peptides come from that stage, which is not a subset of the PSM-level set: it admits +3,200 (A) / 3,412 (B) rows that fail `spectrum_q ≤ 0.01` and excludes 1,318 / 1,199 that pass it +(measured by `audit/cross_threshold.py`, which is where those four numbers are reproduced). +ProSE has no peptide-level stage; its peptides inherit the PSM q-value. The two peptide totals are +therefore produced by different procedures even though both are "unique peptides at 1% FDR". + +## 9. What the numbers do and do not show + +Three descriptive observations survive the audit: + +1. Sage reports more target PSMs and more target peptides than ProSE in both conditions (on both + the target-class and the more conservative pure-target basis). +2. ProSE reports more non-entrapment protein identifications than Sage in both conditions. +3. The two engines attribute different amounts of evidence to the entrapment proteins. + +Observation 1 is the experiment's primary measurement, and it is like-for-like. Both engines emit +exactly one hit per spectrum, so these are counts of spectra identified at a common nominal 1% PSM +FDR, using target-only rows: + +| Condition | ProSE target PSMs | Sage target PSMs | Sage increase | +|---|---:|---:|---:| +| A | 45,723 | 54,830 | 19.9% | +| B | 47,252 | 55,756 | 18.0% | + +Figure 1 plots these two columns next to the derived hyperscore re-ranking of the frozen Sage tables +(Section 7). That third bar is a ranking variant of the Sage result, not another engine run, so it +informs the interpretation of the Sage figure without changing the configured-pipeline comparison +above. + +As a share of all MS2 spectra that is 41.8% / 42.5% (ProSE) against 50.1% / 50.2% (Sage), and as a +share of the spectra each engine scored at all, 47.0% / 47.7% against 51.9% / 51.8% — the difference +does not depend on the denominator. At the same threshold the peptide sets are 31,991 / 32,465 +against 38,181 / 38,455 (+19.4% / +18.5%). + +On this dataset, under these two configurations, Sage recovers more target identifications at 1% FDR +than ProSE. That is the comparison the experiment was built to make, and it is what the numbers +above show. What they do not show is a general ranking of the engines: there is one injection per +condition, two of the shared conditions did not carry over exactly (Section 4.1 — the proline-rule +difference affects approximately 1.0% of Sage's PSMs under the C-terminal pre-proline cleavage +definition used for this estimate), and scoring, candidate caps, peak selection, decoy generation, +peptide-level FDR and protein inference differ by design. Those are the algorithms under test, not +measurement errors, but they do mean the two 1% cuts are not equally strict. *Nominal* in the +threshold is therefore exact in both directions: same target, not same stringency. With no ground +truth for the endogenous peptides, these are yields, not correctness. + + +Two comparisons are explicitly *not* made: + +* **ProSE protein hits vs Sage protein groups.** ProSE serializes no grouping (0 `ProteinGroup` + elements) and counts any supporting peptide; Sage counts proteotypic-only support and then groups. + 5,709 / 5,755 and 5,380 / 5,336 are different quantities. +* **Peptide identities across engines.** The sequences use different modification syntaxes and + different N-terminal conventions, and no cross-engine identity mapping was computed, so overlap, + unique-to-either and per-sequence recovery are not reported. Counts at a common threshold are + compared above; the sets behind them are not. + +Entrapment counts are in the tens to low hundreds of PSMs. They are not precise false-discovery +estimates: with one injection per condition and a single decoy generation scheme per engine, they +support only the statement that entrapment evidence was detected and how much of it each engine +reported. + +## 10. Limitations + +1. **Sage source-to-binary correspondence is inferred.** The binary ships without source; the tag + was chosen from the version string. The numeric reconciliation makes a mismatch unlikely, but it + is not cryptographic. +2. **Sage telemetry suppression is unconfirmed by the binary.** The flag was passed and is + documented in `--help`; 0.15.0-beta.2 prints no acknowledgement. +3. **ProSE decoy evidence is unrecoverable.** Finalization deletes decoys and dangling references, + so decoy-level classes are *not observable*, not zero. +4. **The 862 / 856 unreferenced ProSE PSMs cannot be re-attributed** without rerunning the search + with protein inference retained, which was out of scope. +5. **One injection per condition, no repeats.** The experiment establishes observed results, not + run-to-run reproducibility. +6. **Entrapment denominators are small**, so entrapment ratios are coarse. +7. **Residual parameter differences remain** in peak handling, candidate generation and scoring, + by construction. Two settings the two configurations were meant to share also did not carry over: + Sage's fragment m/z window was ignored, and its digest lacked the proline rule. Section 4.1 + quantifies both where the frozen evidence allows and marks what it cannot. + +None of these invalidate the comparison; each bounds what it can be used to claim. + +## 11. Reproducing this report without rerunning any search + +Everything in this report is derived from the frozen outputs: the tables and this document by +`emit_tables.py` and `build_report.py`, Figure 1 by `plot_psm_yield.py`. The outputs themselves +remain unchanged. They stay in the run root used for the experiment, which is not part of this +repository: + +```bash +bash reproduce.sh /path/to/prose-sage-pxd028735 # defaults to ~/prose-sage-pxd028735 +``` + +`reproduce.sh` performs three independent checks and exits non-zero on any mismatch: + +1. `sha256sum -c hashes.sha256` over the four result files, two Sage JSON sidecars, the FASTA, both + mzML files, both Sage configs and both binaries — 13 items, no writes. Eleven entries are + relative to the run root; the last two are absolute paths to the pinned ProSE and Sage + binaries, which are not redistributed, so on another machine those two entries fail unless + the identical builds are present. +2. Re-runs `emit_tables.py`, which recomputes every table and every class count from the raw idXML + and TSV, asserts the 18 log-to-output identities, and diffs the regenerated tables against the + ones printed in Section 7. +3. Rebuilds this document from `EXPERIMENT_REPORT.template.md` plus the regenerated tables and diffs + it against the file on disk. + +Figure 1 is not regenerated by reproduce.sh; `plot_psm_yield.py --verify --data-root ` +re-derives its six values from the same frozen outputs. + +To regenerate the report after an intentional change, rebuild the table block and then the report: + +```bash +python3 emit_tables.py /path/to/prose-sage-pxd028735 tables.md +python3 build_report.py EXPERIMENT_REPORT.template.md tables.md EXPERIMENT_REPORT.md +``` + +Rerunning the searches themselves is neither required nor supported by this document; the run +scripts and the guard are archived in the run root under `scripts/` and `audit/` for provenance +only. + +## 12. Artifacts and hashes + +The experimental artifacts — results, logs, data, configurations and run scripts — live outside +the git worktree, which neither the experiment nor the audit modified: HEAD +`86ea502f1035990dc4f6eaa50abbafe89bdb6c39` at audit time and again on re-verification +(2026-11-28), six status entries that are CRLF-only, zero substantive changes. This report and +its generation scripts are the only additions to the repository; they read the frozen outputs +and never produce them. The raw outputs and the mzML inputs are not part of this repository. + +Raw results (SHA-256): + +``` +1ce35721a4dedc9878a76f0c753cc4ee5bf0ec0c6248d0948581ef348415c30b results/prose_A/ProSE_A.idXML +19f64705513e3d4cf904346c4e1f46018267a08d0d654f3e387a397ef600cb7f results/prose_B/ProSE_B.idXML +bf72afde43d0f495539bfc1dcefe8cf1281f824639889b3e6bf9d5447c034c1a results/sage_A/results.sage.tsv +1d9630969c788c9e2a093c20017f3280949357bf16434cb97a10ad1e9c3ae41f results/sage_B/results.sage.tsv +f144a889c8e100d166447e3373a91723ce3a2777a62156d975c368ff6ca74424 results/sage_A/results.json +8b3f8bfde3b21b4df0249ed8f19e698d67159b8e2f6d91243f80036c021389fd results/sage_B/results.json +``` + +Paths other than "this directory" are relative to the run root (`$HOME/prose-sage-pxd028735` on +the audit machine); they are provenance, not repository content. + +| Location | Contents | +|---|---| +| this directory | this report, its template, `emit_tables.py`, `build_report.py`, `plot_psm_yield.py`, `reproduce.sh`, `hashes.sha256`, `tables.md` (the generated Tables 1–5 block), `figures/` (Figure 1 in PNG, PDF and SVG) | +| `audit/REPORT.md` | the independent read-only audit, with per-claim evidence tags | +| `audit/counts2.csv` | authoritative per-class counts, one row per metric | +| `audit/counts.csv` | first audit pass, superseded classification, retained for provenance | +| `audit/freeze_manifest.txt` | 13 expected-vs-actual hashes, file sizes, mtimes, worktree state | +| `audit/COMMANDS.md` | exact audit commands | +| `logs/` | per-run command line, stdout, stderr, exit code, `/usr/bin/time -v` | +| `results/` | the six raw outputs listed above | +| `scripts/` | run scripts, parameter set, preflight guard | + +## Acknowledgements and Project Contributions + +All research decisions, experimental design, analysis, documentation, repository changes, and +commits were carried out by the project author. Codebuff and ChatGPT provided AI-assisted support +during the development, auditing, analysis, documentation, and reproducibility review of this +work. The project author retained responsibility for reviewing and approving the work and its +final results. diff --git a/docs/prose-sage-pxd028735/EXPERIMENT_REPORT.template.md b/docs/prose-sage-pxd028735/EXPERIMENT_REPORT.template.md new file mode 100644 index 0000000..0014702 --- /dev/null +++ b/docs/prose-sage-pxd028735/EXPERIMENT_REPORT.template.md @@ -0,0 +1,457 @@ +# ProSE vs Sage on PXD028735: a pinned, audited two-condition benchmark + +**Status.** Experiment complete: four primary searches, one per engine per condition, no repeats. +Metrics independently audited and reconciled against source and raw output. Results frozen; this +report is generated from the frozen outputs, not transcribed from them. + +**Date.** Runs and audit 2026-11-27; report 2026-11-28. + +**Scope.** A comparison of two search engines on one public dataset under a shared parameter set. +It reports what each engine output, why the raw summary figures differ, and how many target +identifications each engine recovered at a common nominal 1% PSM FDR. The last of these is a +sensitivity measurement for these two configured pipelines on this sample; it does not establish a +general ranking of the engines, because the two operating points are not equally stringent +(Section 4.1) and one injection per condition cannot support a generalisation. + +--- + +## 1. Question + +Two engines, ProSE (OpenMS) and Sage, were run on the two conditions of PXD028735 with the same +database, the same trypsin-family digestion rules apart from one proline rule that only ProSE +applied (Section 4.1), the same tolerances, the same fixed and variable modifications, and a common +nominal 1% PSM FDR target. The primary measurement is the number of target identifications each +engine recovers at that threshold (Section 9); the questions were: + +1. How many PSMs, peptides and proteins does each engine report at 1% FDR? +2. Do the engines' own summary figures agree with their serialized output? +3. Where they differ, is the difference a property of the search or a property of how the number is + counted and reported? + +Question 3 turned out to be the substantive one: two of the three headline discrepancies are +reporting artefacts, and one is a classification error in the first version of the comparison. +Settling them is a prerequisite for the comparison rather than a substitute for it: once every +figure is counted on a like-for-like basis, the identification yield in Section 9 stands on its own. + +## 2. Data + +| Item | Value | +|---|---| +| Dataset | PXD028735, LFQ Orbitrap DDA, *Sample Alpha 01* | +| Conditions | A and B, one mzML each | +| MS2 spectra | 109,507 (A), 111,088 (B) | +| Database | `entrapment_hye_soce.fasta`, 41,209 entries | +| Entrapment | HYE proteins, accessions prefixed `ENTRAPMENT_` (PR #34, merged) | +| Replicates | none — one injection per condition | + +The entrapment sequences are present in the search database and are treated by both engines as +ordinary target entries; they are separated at analysis time by accession prefix. Decoys were +generated internally by each engine and never supplied as a file. + +Because there is one injection per condition, every number here is a single observation. No +run-to-run variance can be estimated, and no significance test is meaningful. + +## 3. Engines and pins + +| Engine | Version | Binary SHA-256 | +|---|---|---| +| ProSE | OpenMS `ProSE`, PR #9975 build | `56958d4e428fa3c7af4b8501f63d08075d0d59bea5e371b3a77b580cf7a263dd` | +| Sage | 0.15.0-beta.2, prebuilt `x86_64-unknown-linux-gnu` | `d1a96a7d14836f0846a55cede74456595169399abdc6a12e468f234eb4fcf7c0` | + +Sage was installed as a release binary with no bundled source. Its behaviour was interpreted from +the upstream tag `v0.15.0-beta.2`; the tag-to-binary correspondence is inferred from the version +string the binary prints, not established cryptographically. This matters only for explanations +that cite Sage source (Section 8.1); every *count* in this report comes from Sage's own output. + +Environment: WSL2 Ubuntu 24.04, 4 vCPU, 11 GiB RAM. Both engines were given 4 threads. + +## 4. Parameter alignment + +The ProSE invocation was built flag by flag against the Sage configuration. Of the 23 rows below, +11 state a setting both engines executed, 11 are approximately comparable (same intent, different +semantics or a different stage of the search), and one has no counterpart. Two differences the table +cannot express are quantified in Section 4.1, and one row (fragment m/z window) records a setting +Sage silently discarded. Different internal algorithms are part of what is being compared; what the +table has to establish is that the search conditions match, and Section 4.1 states where they do not. + +| Parameter | ProSE setting | Sage setting | +|---|---|---| +| Enzyme | `Trypsin` (no cleavage before P) | `cleave_at = KR`, `c_terminal = true`, `restrict` unset (cleaves before P) | +| Specificity | `enzyme_specificity full` | `semi_enzymatic = false` | +| Peptide length | `min_size 7`, `max_size 50` | `min_len 7`, `max_len 50` | +| Missed cleavages | `2` | `2` | +| Peptide mass | `500`–`5000` | `500.0`–`5000.0` | +| Precursor tolerance | `±10 ppm` | `ppm [-10, 10]` | +| Precursor charge | `2`–`4` | `[2, 4]` | +| Isotope error | `-1`–`2` | `[-1, 2]` | +| Fragment tolerance | `0.02 Da` | `da [-0.02, 0.02]` | +| Fragment m/z window | `150`–`2000` | none applied — `fragment_min_mz`/`fragment_max_mz` are not fields of this Sage version and were ignored | +| Min. ion index | `2` | `2` | +| Max. fragment charge | `3` | `3` | +| Deisotope | `true` | `true` | +| Min. matched ions | `4` | `min_matched_peaks 4` | +| Fixed modification | `Carbamidomethyl (C)` | `C: 57.02146` | +| Variable modifications | `Oxidation (M)`, `Acetyl (Protein N-term)` | `M: 15.9949`, `[^: 42.010567` (input JSON: 42.010565) | +| Max. variable mods | `2` | `2` | +| Report top hits | `1` | `report_psms 1` | +| Decoys | internal, `DECOY_` prefix | internal, `rev_` tag | +| PSM FDR | `0.01` | 1% (`spectrum_q`) | +| Protein FDR | `0.01` | 1% (proteotypic peptides) | +| Protein grouping | not produced | `protein_grouping = true` at 1% peptide FDR | +| Quantification | none | LFQ disabled | + +Residual differences are internal to each engine and are part of what is being compared, not +configuration drift: ProSE's automatic resolution-aware peak cap versus Sage's `min_peaks 15 / +max_peaks 150`; both engines score at most 50 candidates per spectrum, although they select those +candidates differently: ProSE uses `scoring:max_candidates_per_spectrum`, whereas Sage retains the +top 50 by matched peaks; and each engine's own score (OpenMS HyperScore versus `SageHyperScore` +plus an LDA discriminant, which is also the score Sage's q-values rank on). + +### 4.1 Where the two searches were not identical + +Four differences are demonstrable from the frozen evidence, and they are the ones that put the two +1% cuts on slightly different footings: + +* **Digestion.** ProSE's `Trypsin` does not cleave before proline; this run's Sage configuration has + `restrict` unset and therefore does. The digestion difference affects approximately 1.0% of Sage + PSMs under the C-terminal pre-proline cleavage definition used for this estimate. This estimate + does not include additional peptides whose N-terminal cleavage context is also incompatible with + ProSE's digestion rule. The exact magnitude depends on the peptide-occurrence definition; + excluding the estimated affected subset does not eliminate Sage's higher observed PSM yield. +* **Fragment window.** ProSE restricted fragment ions to 150–2000 m/z; the keys that were meant to + set the same window for Sage are not fields of the version that ran and were ignored, so Sage + indexed every b/y ion. The effect on either count cannot be measured from the frozen outputs. +* **Score basis.** ProSE's q-values rank `ln(hyperscore)`; Sage's `spectrum_q` ranks the LDA + discriminant. Sorting by Sage's discriminant score produces a monotonic spectrum-q ordering apart + from 32 tie-level exceptions in condition A (105,726 rows) and 38 in condition B (107,623 rows). + These exceptions occur within groups sharing identical printed discriminant scores; the largest + observed discrepancies are 1.7 × 10⁻⁵ in A and 2.3 × 10⁻⁵ in B. Sorting by hyperscore produces + substantially more q-value ordering violations. The two 1% cuts therefore select different spectra + by construction, though both threshold the same nominal quantity. +* **Estimator.** OpenMS assigns q = D/T (decoys at or above the score, over targets at or above it); + Sage assigns (D + 1)/T. The pseudo-count admits at most one fewer decoy at these target counts + (~0.002 percentage points), in the conservative direction for Sage. + +None of these is a reason to withhold the comparison. Each is a property of the two configurations +that can be named, bounded where the evidence allows, and left as an open qualification where it +cannot. The PSM and peptide yields in Section 9 are therefore reported as observed, at a common +nominal threshold, with these differences stated rather than used to disqualify the numbers. + +## 5. Execution protocol + +* Strictly sequential: ProSE A → Sage A → ProSE B → Sage B, one process at a time. +* A guard re-verified the 11 pinned input/config/binary/script hashes before the first run and + aborted on any mismatch; it also refused to start if `results/` was non-empty, so no run could + overwrite another. +* Every run captured its exact command line, stdout, stderr, exit code and `/usr/bin/time -v` + record. All four exited 0. +* Sage was invoked with `--disable-telemetry-i-dont-want-to-improve-sage`. The flag is accepted and + documented by the binary, but this build prints no acknowledgement line; nothing in the logs + confirms the opt-out beyond the accepted argument. +* The FASTA hash was re-checked after the last run and was unchanged. + +## 6. Counting definitions + +Every figure in Tables 1–5 is recomputed from the serialized outputs by `emit_tables.py`, which +also asserts the identities in Table 5; no table entry is copied from an engine's summary +line without being reconstructed. The few numbers quoted only in the text come from the audit +scripts and are marked as such. + +* **PSM** — one `PeptideIdentification` element (ProSE idXML) or one TSV row (Sage). Both engines + emit exactly one hit per spectrum (`report:top_hits 1`; `report_psms 1`), so a PSM count in either + column is a count of spectra identified. +* **Threshold** — a common nominal 1% PSM FDR, inclusive (`q ≤ 0.01`), at each engine's native + PSM-level score (`score` under `score_type="q-value"` for ProSE; `spectrum_q` for Sage). *Nominal* + is meant literally: the two operating points share a target, which is not a demonstration that + they have identical statistical stringency, because they rank different candidate sets on + different scores. The estimators also differ — OpenMS assigns q = D/T, Sage (D + 1)/T — which at + these target counts moves the cut by at most one decoy. +* **Peptide** — distinct sequence string as the engine writes it. ProSE embeds modifications in + parentheses (`M(Oxidation)`); Sage uses bracketed mass shifts (`M[+15.9949]`). "Bare" means the + modification token is stripped. Bare sequences still differ in N-terminal annotation conventions, + so peptide identities are only ever compared within an engine. Peptide counts are compared across + engines on one basis only: distinct sequences carried by target-class PSMs at the common 1% PSM + threshold (Section 9). +* **Protein** — a surviving `ProteinHit` accession (ProSE) or an accession with + `protein_q ≤ 0.01` (Sage). ProSE protein hits and Sage protein groups are different objects and + are never pooled or ranked against each other. + +Each hit is assigned to exactly one class, evaluated in this order: + +| Class | Definition | +|---|---| +| `pure_target` | ≥1 accession, no entrapment, no decoy; ProSE `target_decoy = target` | +| `target_decoy_shared` | ProSE only: references both target and decoy proteins, none entrapment | +| `target_shared_entrapment` | ≥1 entrapment accession and ≥1 non-entrapment accession | +| `entrapment_only` | every accession is entrapment | +| `decoy` | every accession is a decoy (non-entrapment) | +| `decoy_entrapment` | every accession is a decoy of an entrapment protein | +| `no_protein_reference` | zero surviving accessions after protein-FDR finalization | + +**"Not observable" is not zero.** ProSE deletes decoy PSMs and then removes dangling protein +references during protein-FDR finalization, so decoy and decoy-entrapment evidence cannot be +counted in its output at all. Those cells are marked *not observable*; only Sage's decoy columns +are measurements. + +## 7. Results + +@@TABLES_UPTO_1@@ + +![ProSE and Sage PSM yield at 1% nominal PSM FDR](figures/psm_yield_1pct.png) + +Figure 1. ProSE and Sage PSM yield at 1% nominal PSM FDR. Target PSM counts for ProSE and Sage on +PXD028735, conditions A and B. ProSE was run without Percolator or any other post-scoring. Sage +(LDA) is the stock Sage 0.15.0-beta.2 workflow, which unconditionally applies its built-in +20-feature linear discriminant analysis post-scoring before assigning target-decoy q-values. Sage +(hyperscore) is a derived re-ranking of the frozen Sage PSM tables on Sage's own pre-LDA hyperscore, +using Sage's q-value procedure; it is not an independent Sage execution with post-scoring disabled, +because the pinned binary exposes no such switch. Each condition was searched once per +configuration, and A and B are different pooled samples rather than replicates, so bars are single +measurements without error bars. The two Sage bars compare different ranking strategies applied to +the same frozen Sage search results. ProSE represents an independently executed search pipeline on +the same dataset. + +Table 1 and Figure 1 report the same counts for the configured-pipeline comparison. The first and +second bars are independently executed searches — ProSE as configured in Section 4, and stock Sage — +and that pair is the comparison this report is built on and the one Section 9 draws its conclusions +from. The third bar is not a third executed configuration. It is derived from the frozen Sage output +by re-ranking the identifications Sage already reported on its own pre-LDA hyperscore and recomputing +q-values with Sage's procedure; no Sage binary was run with post-scoring disabled, because the pinned +0.15.0-beta.2 build exposes no configuration, CLI or environment switch for it (Section 4.1, score +basis). The derived arm therefore adds no new spectra, scores or decoy evidence: it answers what +Sage's ranking yields without the LDA step, not what a no-rescoring Sage run would produce. The +distance between the two Sage bars is the contribution of that post-scoring step on this dataset — +a statement about ranking, which leaves the configured-pipeline comparison in Section 9 unchanged. + +@@TABLES_FROM_2@@ + +## 8. The three discrepancies, and how each resolves + +### 8.1 Sage's logged PSM figure includes decoys + +Sage logs `discovered 55377 target peptide-spectrum matches at 1% FDR` (A) and `56312` (B). The +serialized output contains 54,830 and 55,756 target rows at `spectrum_q ≤ 0.01`. The gap is exactly +the decoy rows that fall inside the same q block: 547 (A) and 556 (B). + +The mechanism is in `spectrum_q_value` (`crates/sage/src/ml/qvalue.rs`, tag `v0.15.0-beta.2`): the +returned counter is incremented for every feature whose cumulative-minimum q is ≤ 0.01, with no +test of `label == 1`. + +```rust +for score in scores.iter_mut().rev() { + q_min = q_min.min(score.spectrum_q); + score.spectrum_q = q_min; + if q_min <= 0.01 { passing += 1; } // no label test +} +passing +``` + +`runner.rs` logs that return value verbatim as "target peptide-spectrum matches". The arithmetic +closes to the unit on both runs (Table 5), so this is a reconciliation rather than a coincidence. + +The peptide-level counter in the same crate (`fdr.rs`, `Competition::assign_q_value`) does test +`!score.decoy`, which is why the 36,875 / 37,269 peptide figure is target-only; only the +spectrum-level counter lacks the test. + +**Consequence.** The logged figure is a counter over the target+decoy block. It is named here +**Sage logged PSM counter (includes decoys)** and is never used as a target count. The target +count — **Sage target PSMs from serialized TSV (label == 1, `spectrum_q ≤ 0.01`)** — is +54,830 / 55,756; the **Sage pure-target PSMs** figure, which also excludes entrapment-mapped +PSMs, is 54,654 / 55,614. + +### 8.2 ProSE target identifications without surviving protein references + +ProSE logs `45723 target / 0 decoy PSMs`. Of those 45,723, **862 (A) / 856 (B)** reference no +surviving protein: their proteins failed picked-protein FDR or were decoys, and +`removeDanglingProteinReferences` cleared the refs. They retain `target_decoy = "target"` and +q ≤ 0.01 (max 0.009995 (A) / 0.009968 (B), median 0.005033 / 0.004531, per +`audit/counts2.csv`), so they are genuine +target-classified peptide identifications — but no protein in the output supports them. + +The first version of this comparison counted them as protein-supported targets. They are now +reported separately as **target PSMs without surviving protein references**. They are not +discarded: the peptide evidence exists. They are not counted as pure target either: the output does +not attribute them to a protein. On the protein side they are already absent, which is why +ProSE's 5,709 / 5,755 protein hits do not shrink. + +The same correction applies at peptide level: 857 (A) / 847 (B) distinct sequences. + +### 8.3 ProSE's logged unique-peptide figure is a union over classes + +ProSE logs 31,991 (A) / 32,465 (B) unique peptides. That is the size of the union of *all* +post-FDR classes, not the pure-target set: + +| Run | Pure target | No protein ref | Shared entrapment | Entrapment only | Target+decoy | Sum | +|---|---:|---:|---:|---:|---:|---:| +| A | 31,094 | 857 | 17 | 19 | 4 | 31,991 | +| B | 31,586 | 847 | 14 | 17 | 1 | 32,465 | + +Both sums are exact, matching source: `updateFinalStats` accumulates every top hit without a class +filter. The engine summary is therefore internally consistent; it simply answers a different +question from "how many pure-target peptides were identified". + +### 8.4 A fourth difference, in structure rather than arithmetic + +Sage runs a separate peptide-level FDR stage (`peptide_q`) before protein inference. Its reported +36,875 / 37,269 peptides come from that stage, which is not a subset of the PSM-level set: it admits +3,200 (A) / 3,412 (B) rows that fail `spectrum_q ≤ 0.01` and excludes 1,318 / 1,199 that pass it +(measured by `audit/cross_threshold.py`, which is where those four numbers are reproduced). +ProSE has no peptide-level stage; its peptides inherit the PSM q-value. The two peptide totals are +therefore produced by different procedures even though both are "unique peptides at 1% FDR". + +## 9. What the numbers do and do not show + +Three descriptive observations survive the audit: + +1. Sage reports more target PSMs and more target peptides than ProSE in both conditions (on both + the target-class and the more conservative pure-target basis). +2. ProSE reports more non-entrapment protein identifications than Sage in both conditions. +3. The two engines attribute different amounts of evidence to the entrapment proteins. + +Observation 1 is the experiment's primary measurement, and it is like-for-like. Both engines emit +exactly one hit per spectrum, so these are counts of spectra identified at a common nominal 1% PSM +FDR, using target-only rows: + +| Condition | ProSE target PSMs | Sage target PSMs | Sage increase | +|---|---:|---:|---:| +| A | 45,723 | 54,830 | 19.9% | +| B | 47,252 | 55,756 | 18.0% | + +Figure 1 plots these two columns next to the derived hyperscore re-ranking of the frozen Sage tables +(Section 7). That third bar is a ranking variant of the Sage result, not another engine run, so it +informs the interpretation of the Sage figure without changing the configured-pipeline comparison +above. + +As a share of all MS2 spectra that is 41.8% / 42.5% (ProSE) against 50.1% / 50.2% (Sage), and as a +share of the spectra each engine scored at all, 47.0% / 47.7% against 51.9% / 51.8% — the difference +does not depend on the denominator. At the same threshold the peptide sets are 31,991 / 32,465 +against 38,181 / 38,455 (+19.4% / +18.5%). + +On this dataset, under these two configurations, Sage recovers more target identifications at 1% FDR +than ProSE. That is the comparison the experiment was built to make, and it is what the numbers +above show. What they do not show is a general ranking of the engines: there is one injection per +condition, two of the shared conditions did not carry over exactly (Section 4.1 — the proline-rule +difference affects approximately 1.0% of Sage's PSMs under the C-terminal pre-proline cleavage +definition used for this estimate), and scoring, candidate caps, peak selection, decoy generation, +peptide-level FDR and protein inference differ by design. Those are the algorithms under test, not +measurement errors, but they do mean the two 1% cuts are not equally strict. *Nominal* in the +threshold is therefore exact in both directions: same target, not same stringency. With no ground +truth for the endogenous peptides, these are yields, not correctness. + + +Two comparisons are explicitly *not* made: + +* **ProSE protein hits vs Sage protein groups.** ProSE serializes no grouping (0 `ProteinGroup` + elements) and counts any supporting peptide; Sage counts proteotypic-only support and then groups. + 5,709 / 5,755 and 5,380 / 5,336 are different quantities. +* **Peptide identities across engines.** The sequences use different modification syntaxes and + different N-terminal conventions, and no cross-engine identity mapping was computed, so overlap, + unique-to-either and per-sequence recovery are not reported. Counts at a common threshold are + compared above; the sets behind them are not. + +Entrapment counts are in the tens to low hundreds of PSMs. They are not precise false-discovery +estimates: with one injection per condition and a single decoy generation scheme per engine, they +support only the statement that entrapment evidence was detected and how much of it each engine +reported. + +## 10. Limitations + +1. **Sage source-to-binary correspondence is inferred.** The binary ships without source; the tag + was chosen from the version string. The numeric reconciliation makes a mismatch unlikely, but it + is not cryptographic. +2. **Sage telemetry suppression is unconfirmed by the binary.** The flag was passed and is + documented in `--help`; 0.15.0-beta.2 prints no acknowledgement. +3. **ProSE decoy evidence is unrecoverable.** Finalization deletes decoys and dangling references, + so decoy-level classes are *not observable*, not zero. +4. **The 862 / 856 unreferenced ProSE PSMs cannot be re-attributed** without rerunning the search + with protein inference retained, which was out of scope. +5. **One injection per condition, no repeats.** The experiment establishes observed results, not + run-to-run reproducibility. +6. **Entrapment denominators are small**, so entrapment ratios are coarse. +7. **Residual parameter differences remain** in peak handling, candidate generation and scoring, + by construction. Two settings the two configurations were meant to share also did not carry over: + Sage's fragment m/z window was ignored, and its digest lacked the proline rule. Section 4.1 + quantifies both where the frozen evidence allows and marks what it cannot. + +None of these invalidate the comparison; each bounds what it can be used to claim. + +## 11. Reproducing this report without rerunning any search + +Everything in this report is derived from the frozen outputs: the tables and this document by +`emit_tables.py` and `build_report.py`, Figure 1 by `plot_psm_yield.py`. The outputs themselves +remain unchanged. They stay in the run root used for the experiment, which is not part of this +repository: + +```bash +bash reproduce.sh /path/to/prose-sage-pxd028735 # defaults to ~/prose-sage-pxd028735 +``` + +`reproduce.sh` performs three independent checks and exits non-zero on any mismatch: + +1. `sha256sum -c hashes.sha256` over the four result files, two Sage JSON sidecars, the FASTA, both + mzML files, both Sage configs and both binaries — 13 items, no writes. Eleven entries are + relative to the run root; the last two are absolute paths to the pinned ProSE and Sage + binaries, which are not redistributed, so on another machine those two entries fail unless + the identical builds are present. +2. Re-runs `emit_tables.py`, which recomputes every table and every class count from the raw idXML + and TSV, asserts the 18 log-to-output identities, and diffs the regenerated tables against the + ones printed in Section 7. +3. Rebuilds this document from `EXPERIMENT_REPORT.template.md` plus the regenerated tables and diffs + it against the file on disk. + +Figure 1 is not regenerated by reproduce.sh; `plot_psm_yield.py --verify --data-root ` +re-derives its six values from the same frozen outputs. + +To regenerate the report after an intentional change, rebuild the table block and then the report: + +```bash +python3 emit_tables.py /path/to/prose-sage-pxd028735 tables.md +python3 build_report.py EXPERIMENT_REPORT.template.md tables.md EXPERIMENT_REPORT.md +``` + +Rerunning the searches themselves is neither required nor supported by this document; the run +scripts and the guard are archived in the run root under `scripts/` and `audit/` for provenance +only. + +## 12. Artifacts and hashes + +The experimental artifacts — results, logs, data, configurations and run scripts — live outside +the git worktree, which neither the experiment nor the audit modified: HEAD +`86ea502f1035990dc4f6eaa50abbafe89bdb6c39` at audit time and again on re-verification +(2026-11-28), six status entries that are CRLF-only, zero substantive changes. This report and +its generation scripts are the only additions to the repository; they read the frozen outputs +and never produce them. The raw outputs and the mzML inputs are not part of this repository. + +Raw results (SHA-256): + +``` +1ce35721a4dedc9878a76f0c753cc4ee5bf0ec0c6248d0948581ef348415c30b results/prose_A/ProSE_A.idXML +19f64705513e3d4cf904346c4e1f46018267a08d0d654f3e387a397ef600cb7f results/prose_B/ProSE_B.idXML +bf72afde43d0f495539bfc1dcefe8cf1281f824639889b3e6bf9d5447c034c1a results/sage_A/results.sage.tsv +1d9630969c788c9e2a093c20017f3280949357bf16434cb97a10ad1e9c3ae41f results/sage_B/results.sage.tsv +f144a889c8e100d166447e3373a91723ce3a2777a62156d975c368ff6ca74424 results/sage_A/results.json +8b3f8bfde3b21b4df0249ed8f19e698d67159b8e2f6d91243f80036c021389fd results/sage_B/results.json +``` + +Paths other than "this directory" are relative to the run root (`$HOME/prose-sage-pxd028735` on +the audit machine); they are provenance, not repository content. + +| Location | Contents | +|---|---| +| this directory | this report, its template, `emit_tables.py`, `build_report.py`, `plot_psm_yield.py`, `reproduce.sh`, `hashes.sha256`, `tables.md` (the generated Tables 1–5 block), `figures/` (Figure 1 in PNG, PDF and SVG) | +| `audit/REPORT.md` | the independent read-only audit, with per-claim evidence tags | +| `audit/counts2.csv` | authoritative per-class counts, one row per metric | +| `audit/counts.csv` | first audit pass, superseded classification, retained for provenance | +| `audit/freeze_manifest.txt` | 13 expected-vs-actual hashes, file sizes, mtimes, worktree state | +| `audit/COMMANDS.md` | exact audit commands | +| `logs/` | per-run command line, stdout, stderr, exit code, `/usr/bin/time -v` | +| `results/` | the six raw outputs listed above | +| `scripts/` | run scripts, parameter set, preflight guard | + +## Acknowledgements and Project Contributions + +All research decisions, experimental design, analysis, documentation, repository changes, and +commits were carried out by the project author. Codebuff and ChatGPT provided AI-assisted support +during the development, auditing, analysis, documentation, and reproducibility review of this +work. The project author retained responsibility for reviewing and approving the work and its +final results. diff --git a/docs/prose-sage-pxd028735/build_report.py b/docs/prose-sage-pxd028735/build_report.py new file mode 100644 index 0000000..6fe95d0 --- /dev/null +++ b/docs/prose-sage-pxd028735/build_report.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""Splice the generated tables into the report template. + +usage: build_report.py TEMPLATE TABLES OUT + +Markers are addressed by each generated table's "### Table N" heading: + + @@TABLES@@ every table, in order + @@TABLES_UPTO_1@@ tables 1..1 + @@TABLES_FROM_2@@ tables 2..N + +The ranged form lets the template keep prose and figures between two tables. +Every generated table must be emitted exactly once: a table covered twice, or +not at all, is an error rather than a silently missing section. +""" +import re +import sys + +MARKER = re.compile(r"@@TABLES(?:_UPTO_(\d+)|_FROM_(\d+))?@@") +HEADING = re.compile(r"^### Table (\d+)", re.M) + + +def split_tables(text): + """Split the generated tables on their '### Table N' headings.""" + starts = [(int(m.group(1)), m.start()) for m in HEADING.finditer(text)] + if not starts: + raise SystemExit("generated tables contain no '### Table N' heading") + chunks = [] + for i, (num, pos) in enumerate(starts): + end = starts[i + 1][1] if i + 1 < len(starts) else len(text) + chunks.append((num, text[pos:end].rstrip("\n"))) + return chunks + + +def main(): + if len(sys.argv) != 4: + raise SystemExit("usage: build_report.py TEMPLATE TABLES OUT") + tmpl_path, tables_path, out_path = sys.argv[1:4] + tmpl = open(tmpl_path, encoding="utf-8").read() + chunks = split_tables(open(tables_path, encoding="utf-8").read()) + numbers = [n for n, _ in chunks] + + if not MARKER.search(tmpl): + raise SystemExit("template contains no @@TABLES@@ marker") + + covered = [] + + def replace(match): + lo, hi = 1, float("inf") + if match.group(1): + hi = int(match.group(1)) + elif match.group(2): + lo = int(match.group(2)) + picked = [(n, t) for n, t in chunks if lo <= n <= hi] + if not picked: + raise SystemExit("marker %s selects no table" % match.group(0)) + covered.extend(n for n, _ in picked) + return "\n\n".join(t for _, t in picked) + + report = MARKER.sub(replace, tmpl) + + missing = [n for n in numbers if n not in covered] + repeated = sorted({n for n in covered if covered.count(n) > 1}) + if missing or repeated: + raise SystemExit("table coverage is not exactly once: missing=%s repeated=%s" + % (missing, repeated)) + + with open(out_path, "w", encoding="utf-8", newline="\n") as fh: + fh.write(report) + print("wrote %s (%d bytes)" % (out_path, len(report))) + + +if __name__ == "__main__": + main() diff --git a/docs/prose-sage-pxd028735/emit_tables.py b/docs/prose-sage-pxd028735/emit_tables.py new file mode 100644 index 0000000..cb8699a --- /dev/null +++ b/docs/prose-sage-pxd028735/emit_tables.py @@ -0,0 +1,454 @@ +#!/usr/bin/env python3 +"""Regenerate every results table of EXPERIMENT_REPORT.md from frozen outputs. + +Inputs (read only): /results/** and /logs/** +Output: Markdown tables, to the file given as argv[2] or to stdout. + +Exit status is non-zero if any internal consistency check fails, so the report +cannot silently drift from the raw data. Checks are written to stderr. +""" +import csv +import os +import re +import sys +import xml.etree.ElementTree as ET + +Q = 0.01 +ENT = "ENTRAPMENT_" +DEC = "DECOY_" +DEC_ENT = "DECOY_ENTRAPMENT_" +PAREN_MOD = re.compile(r"\([^)]*\)") # OpenMS embedded modification +BRACKET_MOD = re.compile(r"\[[^\]]*\]") # Sage bracketed mass shift + +CHECKS = [] + + +def check(ok, label, detail=""): + CHECKS.append((bool(ok), label, detail)) + print(("PASS " if ok else "FAIL ") + label + ((" " + detail) if detail else ""), + file=sys.stderr) + + +def classify(accs, td): + """One category per hit; order is the one used throughout the audit.""" + if not accs: + return "no_protein_reference" + ent = [a for a in accs if a.startswith(ENT)] + dec_ent = [a for a in accs if a.startswith(DEC_ENT)] + dec = [a for a in accs if a.startswith(DEC)] + if dec_ent: + return "decoy_entrapment" + if dec and not any(not a.startswith(DEC) for a in accs): + return "decoy" + if ent and any(not a.startswith(ENT) and not a.startswith(DEC) for a in accs): + return "target_shared_entrapment" + if ent and all(a.startswith(ENT) for a in accs): + return "entrapment_only" + if td == "target+decoy": + return "target_decoy_shared" + return "pure_target" + + +def undecoy(a): + """Strip the engine's decoy tag so the underlying accession can be tested.""" + for p in (DEC, "rev_"): + if a.startswith(p): + return a[len(p):] + return a + + +def prose(root, cond): + path = os.path.join(root, "results", "prose_%s" % cond, "ProSE_%s.idXML" % cond) + el = ET.parse(path).getroot() + id2acc = {} + for pr in el.iter("ProteinIdentification"): + for ph in pr.iter("ProteinHit"): + id2acc[ph.get("id")] = ph.get("accession") or "" + + cls, seq, bare = {}, {}, {} + total = 0 + ref_ids = set() + for pid in el.iter("PeptideIdentification"): + hit = pid.find("PeptideHit") + total += 1 + q = float(hit.get("score")) + refs = (hit.get("protein_refs") or "").split() + ref_ids.update(refs) + accs = [id2acc.get(r, r) for r in refs] + up = hit.find('UserParam[@name="target_decoy"]') + c = classify(accs, up.get("value") if up is not None else "") + s = hit.get("sequence") or "" + if q <= Q: + cls[c] = cls.get(c, 0) + 1 + seq.setdefault(c, set()).add(s) + bare.setdefault(c, set()).add(PAREN_MOD.sub("", s)) + + union_mod = {x for st in seq.values() for x in st} + union_bare = {x for st in bare.values() for x in st} + + accs_all = list(id2acc.values()) + log = open(os.path.join(root, "logs", "prose_%s.stdout.log" % cond)).read() + m = re.search(r"Matched\s*:\s*(\d+) / (\d+) spectra", log) + log_matched, spectra = int(m.group(1)), int(m.group(2)) + m = re.search(r"Peptides/prot:\s*(\d+) unique peptides \| (\d+) unique proteins", log) + log_pep, log_prot = int(m.group(1)), int(m.group(2)) + m = re.search(r"search ([\d.]+)s \| fdr ([\d.]+)s \| index\(shared\) ([\d.]+)s", log) + timings = [float(m.group(1)), float(m.group(2)), float(m.group(3))] + + check(total == sum(cls.values()), "ProSE %s: every row passes the q filter" % cond, + "rows=%d kept=%d" % (total, sum(cls.values()))) + check(sum(cls.values()) == log_matched, "ProSE %s: kept rows == logged Matched" % cond, + "%d vs %d" % (sum(cls.values()), log_matched)) + check(len(union_mod) == log_pep, "ProSE %s: peptide union == logged unique peptides" % cond, + "%d vs %d" % (len(union_mod), log_pep)) + check(len(ref_ids) == log_prot, "ProSE %s: referenced proteins == logged proteins" % cond, + "%d vs %d" % (len(ref_ids), log_prot)) + + return { + "total": total, "spectra": spectra, + "cls": cls, "seq": seq, "bare": bare, + "union_mod": union_mod, "union_bare": union_bare, + "prot_total": len(accs_all), + "prot_nonent": sum(1 for a in accs_all if not a.startswith((ENT, DEC))), + "prot_ent": sum(1 for a in accs_all if a.startswith(ENT)), + "prot_dec": sum(1 for a in accs_all if a.startswith(DEC)), + "groups": len(list(el.iter("ProteinGroup"))), + "log_pep": log_pep, "log_prot": log_prot, "log_matched": log_matched, + "internal": timings, + } + + +def sage(root, cond): + path = os.path.join(root, "results", "sage_%s" % cond, "results.sage.tsv") + sq_cls, sq_seq, sq_bare = {}, {}, {} + pq_cls, pq_seq, pq_bare = {}, {}, {} + all_label_at_q = 0 + dec_cls = {"decoy": 0, "decoy_entrapment": 0} + prots, ent_prots, groups, ent_groups = set(), set(), set(), set() + + with open(path, newline="") as fh: + for r in csv.DictReader(fh, delimiter="\t"): + accs = [p for p in (r["proteins"] or "").split(";") if p] + try: + sq = float(r["spectrum_q"]) + except (TypeError, ValueError): + sq = None + if r["label"] == "1": + c = classify(accs, "target") + s = r["peptide"] or "" + if sq is not None and sq <= Q: + all_label_at_q += 1 + sq_cls[c] = sq_cls.get(c, 0) + 1 + sq_seq.setdefault(c, set()).add(s) + sq_bare.setdefault(c, set()).add(BRACKET_MOD.sub("", s)) + try: + pq = float(r["peptide_q"]) + except (TypeError, ValueError): + pq = None + if pq is not None and pq <= Q: + pq_cls[c] = pq_cls.get(c, 0) + 1 + pq_seq.setdefault(c, set()).add(s) + pq_bare.setdefault(c, set()).add(BRACKET_MOD.sub("", s)) + try: + prq = float(r["protein_q"]) + except (TypeError, ValueError): + prq = None + if prq is not None and prq <= Q: + prots.update(accs) + ent_prots.update(a for a in accs if a.startswith(ENT)) + try: + gq = float(r["protein_group_q"]) + except (TypeError, ValueError): + gq = None + if gq is not None and gq <= Q: + gids = {g for g in (r["protein_groups"] or "").split(";") if g} + groups.update(gids) + if accs and all(a.startswith(ENT) for a in accs): + ent_groups.update(gids) + else: + if sq is not None and sq <= Q: + all_label_at_q += 1 + if any(undecoy(a).startswith(ENT) for a in accs): + dec_cls["decoy_entrapment"] += 1 + else: + dec_cls["decoy"] += 1 + + pq_union = {x for st in pq_seq.values() for x in st} + pq_union_bare = {x for st in pq_bare.values() for x in st} + sq_union = {x for st in sq_seq.values() for x in st} + + log = open(os.path.join(root, "logs", "sage_%s.stderr.log" % cond)).read() + def grab(pat): + mm = re.search(pat, log) + return int(mm.group(1)) if mm else None + log_psm = grab(r"discovered (\d+) target peptide-spectrum matches") + log_pep = grab(r"discovered (\d+) target peptides") + log_prot = grab(r"discovered (\d+) target proteins") + log_grp = grab(r"discovered (\d+) target protein groups") + m = re.search(r"- search:\s+(\d+) ms", log) + search_ms = int(m.group(1)) if m else None + + check(all_label_at_q == log_psm, + "Sage %s: all-label rows at spectrum_q<=0.01 == logged PSM figure" % cond, + "%d vs %d" % (all_label_at_q, log_psm)) + check(all_label_at_q == sum(sq_cls.values()) + sum(dec_cls.values()), + "Sage %s: all-label count == target classes + decoy classes" % cond, + "%d vs %d" % (all_label_at_q, sum(sq_cls.values()) + sum(dec_cls.values()))) + check(len(pq_union) == log_pep, "Sage %s: peptide_q set size == logged peptides" % cond, + "%d vs %d" % (len(pq_union), log_pep)) + check(len(prots) == log_prot, "Sage %s: protein set == logged proteins" % cond, + "%d vs %d" % (len(prots), log_prot)) + check(len(groups) == log_grp, "Sage %s: group set == logged groups" % cond, + "%d vs %d" % (len(groups), log_grp)) + + return { + "spectra": None, "all_label_at_q": all_label_at_q, "dec": dec_cls, + "sq_cls": sq_cls, "sq_seq": sq_seq, "sq_bare": sq_bare, "sq_union": sq_union, + "pq_cls": pq_cls, "pq_seq": pq_seq, "pq_bare": pq_bare, + "pq_union": pq_union, "pq_union_bare": pq_union_bare, + "prot": prots, "ent_prot": ent_prots, "grp": groups, "ent_grp": ent_groups, + "log_psm": log_psm, "log_pep": log_pep, "log_prot": log_prot, "log_grp": log_grp, + "search_ms": search_ms, + } + + +def times(root, prefix, cond): + txt = open(os.path.join(root, "logs", "%s_%s.time.txt" % (prefix, cond))).read() + def grab(pat, cast=str): + m = re.search(pat, txt) + return cast(m.group(1)) if m else None + return { + "wall": grab(r"Elapsed \(wall clock\) time \(h:mm:ss or m:ss\):\s*(\S+)"), + "user": grab(r"User time \(seconds\):\s*([\d.]+)", float), + "sys": grab(r"System time \(seconds\):\s*([\d.]+)", float), + "cpu": grab(r"Percent of CPU this job got:\s*(\d+)", int), + "rss": grab(r"Maximum resident set size \(kbytes\):\s*(\d+)", int), + } + + +def num(v): + return f"{v:,}" if isinstance(v, int) else ("—" if v is None else str(v)) + + +def table(headers, rows): + out = ["| " + " | ".join(headers) + " |", + "|" + "|".join(["---"] + ["---:"] * (len(headers) - 1)) + "|"] + for r in rows: + out.append("| " + " | ".join(str(c) for c in r) + " |") + return "\n".join(out) + + +def get(d, cls_key, metric): + """metric: 'psm' or 'pep' -> count for class cls_key, 0 when absent.""" + return d["cls" if metric == "psm" else "seq"].get(cls_key, 0) + + +def main(): + root = sys.argv[1] + out_path = sys.argv[2] if len(sys.argv) > 2 else None + P = {c: prose(root, c) for c in "AB"} + S = {c: sage(root, c) for c in "AB"} + T = {(e, c): times(root, e, c) for e in ("prose", "sage") for c in "AB"} + + L = [] + A = L.append + + # ---------- Table 1: PSMs ---------- + A("### Table 1 — PSM level\n") + A("All engine-native q thresholds are a common nominal 1% PSM FDR and inclusive; the shared " + "target is not a claim that the two operating points have identical statistical stringency " + "(Section 4.1). ProSE removes decoy PSMs and their " + "protein references at protein-FDR finalization, so decoy rows cannot be observed in its output; " + "Sage writes targets and decoys alike.\n") + rows = [ + ["Engine log: PSM figure (as labelled by the engine)", + num(P["A"]["total"]), num(P["B"]["total"]), num(S["A"]["log_psm"]), num(S["B"]["log_psm"])], + ["Serialized rows, target class (engine-native threshold)", + num(P["A"]["total"]), num(P["B"]["total"]), + num(sum(S["A"]["sq_cls"].values())), num(sum(S["B"]["sq_cls"].values()))], + ["Serialized rows, all labels at threshold", + "not observable", "not observable", num(S["A"]["all_label_at_q"]), num(S["B"]["all_label_at_q"])], + ["**Pure target**", + num(P["A"]["cls"].get("pure_target", 0)), num(P["B"]["cls"].get("pure_target", 0)), + num(S["A"]["sq_cls"].get("pure_target", 0)), num(S["B"]["sq_cls"].get("pure_target", 0))], + ["Target+decoy shared", + num(P["A"]["cls"].get("target_decoy_shared", 0)), num(P["B"]["cls"].get("target_decoy_shared", 0)), + "—", "—"], + ["Target-shared entrapment", + num(P["A"]["cls"].get("target_shared_entrapment", 0)), + num(P["B"]["cls"].get("target_shared_entrapment", 0)), + num(S["A"]["sq_cls"].get("target_shared_entrapment", 0)), + num(S["B"]["sq_cls"].get("target_shared_entrapment", 0))], + ["Entrapment only", + num(P["A"]["cls"].get("entrapment_only", 0)), num(P["B"]["cls"].get("entrapment_only", 0)), + num(S["A"]["sq_cls"].get("entrapment_only", 0)), num(S["B"]["sq_cls"].get("entrapment_only", 0))], + ["Target, no surviving protein reference", + num(P["A"]["cls"].get("no_protein_reference", 0)), + num(P["B"]["cls"].get("no_protein_reference", 0)), + num(S["A"]["sq_cls"].get("no_protein_reference", 0)), + num(S["B"]["sq_cls"].get("no_protein_reference", 0))], + ["Decoy", + "not observable", "not observable", + num(S["A"]["dec"]["decoy"]), num(S["B"]["dec"]["decoy"])], + ["Decoy-entrapment", + "not observable", "not observable", + num(S["A"]["dec"]["decoy_entrapment"]), num(S["B"]["dec"]["decoy_entrapment"])], + ] + A(table(["Metric", "ProSE A", "ProSE B", "Sage A", "Sage B"], rows)) + A("") + + # ---------- Table 2: peptides ---------- + A("### Table 2 — Distinct peptide sequences\n") + A("A peptide is counted once per class it appears in; the two engines write different sequence " + "syntaxes, so sequence identities are only ever compared within an engine — counts are compared " + "across engines in Section 9. *Modified* is the engine's own string " + "(OpenMS `M(Oxidation)` vs Sage `M[+15.9949]`); *bare* has modification tokens stripped.\n") + rows = [ + ["Engine log: unique peptides", num(P["A"]["log_pep"]), num(P["B"]["log_pep"]), + num(S["A"]["log_pep"]), num(S["B"]["log_pep"])], + ["Recomputed set behind that figure", num(len(P["A"]["union_mod"])), num(len(P["B"]["union_mod"])), + num(len(S["A"]["pq_union"])), num(len(S["B"]["pq_union"]))], + ["Bare sequences in the same set", num(len(P["A"]["union_bare"])), num(len(P["B"]["union_bare"])), + num(len(S["A"]["pq_union_bare"])), num(len(S["B"]["pq_union_bare"]))], + ["**Pure target, modified**", + num(len(P["A"]["seq"].get("pure_target", ()))), num(len(P["B"]["seq"].get("pure_target", ()))), + num(len(S["A"]["pq_seq"].get("pure_target", ()))), num(len(S["B"]["pq_seq"].get("pure_target", ())))], + ["Pure target, bare", + num(len(P["A"]["bare"].get("pure_target", ()))), num(len(P["B"]["bare"].get("pure_target", ()))), + num(len(S["A"]["pq_bare"].get("pure_target", ()))), num(len(S["B"]["pq_bare"].get("pure_target", ())))], + ["Target+decoy shared", + num(len(P["A"]["seq"].get("target_decoy_shared", ()))), + num(len(P["B"]["seq"].get("target_decoy_shared", ()))), "—", "—"], + ["Target-shared entrapment", + num(len(P["A"]["seq"].get("target_shared_entrapment", ()))), + num(len(P["B"]["seq"].get("target_shared_entrapment", ()))), + num(len(S["A"]["sq_seq"].get("target_shared_entrapment", ()))), + num(len(S["B"]["sq_seq"].get("target_shared_entrapment", ())))], + ["Entrapment only", + num(len(P["A"]["seq"].get("entrapment_only", ()))), + num(len(P["B"]["seq"].get("entrapment_only", ()))), + num(len(S["A"]["sq_seq"].get("entrapment_only", ()))), + num(len(S["B"]["sq_seq"].get("entrapment_only", ())))], + ["Target, no surviving protein reference", + num(len(P["A"]["seq"].get("no_protein_reference", ()))), + num(len(P["B"]["seq"].get("no_protein_reference", ()))), + num(len(S["A"]["sq_seq"].get("no_protein_reference", ()))), + num(len(S["B"]["sq_seq"].get("no_protein_reference", ())))], + ] + A(table(["Metric", "ProSE A", "ProSE B", "Sage A", "Sage B"], rows)) + A("") + A("Rows 7–9 for Sage are taken at the PSM threshold (`spectrum_q ≤ 0.01`). The engine's reported " + "peptide total and its pure-target part, however, come from Sage's separate peptide-level " + "stage, so they are not on the same basis as the ProSE rows above them: at the common PSM " + "threshold the same set is %s (A) / %s (B) distinct sequences, %s / %s more. Section 9 makes " + "that like-for-like comparison; the `peptide_q` sets are:\n" + % (num(len(S["A"]["sq_union"])), num(len(S["B"]["sq_union"])), + num(len(S["A"]["sq_union"]) - len(S["A"]["pq_union"])), + num(len(S["B"]["sq_union"]) - len(S["B"]["pq_union"])))) + rows = [ + ["Unique peptides, `peptide_q ≤ 0.01`", num(len(S["A"]["pq_union"])), num(len(S["B"]["pq_union"]))], + ["Pure target", num(len(S["A"]["pq_seq"].get("pure_target", ()))), + num(len(S["B"]["pq_seq"].get("pure_target", ())))], + ["Target-shared entrapment", num(len(S["A"]["pq_seq"].get("target_shared_entrapment", ()))), + num(len(S["B"]["pq_seq"].get("target_shared_entrapment", ())))], + ["Entrapment only", num(len(S["A"]["pq_seq"].get("entrapment_only", ()))), + num(len(S["B"]["pq_seq"].get("entrapment_only", ())))], + ["Unique peptides, `spectrum_q ≤ 0.01`", num(len(S["A"]["sq_union"])), num(len(S["B"]["sq_union"]))], + ] + A(table(["Sage peptide set", "Sage A", "Sage B"], rows)) + A("") + + # ---------- Table 3: proteins ---------- + A("### Table 3 — Proteins and protein groups\n") + A("ProSE's protein count is a picked-protein list over complete protein sets with no grouping " + "step in the output; Sage's is the picked protein list restricted to proteotypic peptides, " + "plus a separate IDPicker-style grouping. The two protein columns are different quantities " + "and are not compared.\n") + rows = [ + ["Protein identifications at 1% FDR", + num(P["A"]["prot_total"] - P["A"]["prot_dec"]), + num(P["B"]["prot_total"] - P["B"]["prot_dec"]), + num(len(S["A"]["prot"])), num(len(S["B"]["prot"]))], + ["— non-entrapment", + num(P["A"]["prot_nonent"]), num(P["B"]["prot_nonent"]), + num(len(S["A"]["prot"]) - len(S["A"]["ent_prot"])), + num(len(S["B"]["prot"]) - len(S["B"]["ent_prot"]))], + ["— entrapment", + num(P["A"]["prot_ent"]), num(P["B"]["prot_ent"]), + num(len(S["A"]["ent_prot"])), num(len(S["B"]["ent_prot"]))], + ["Protein groups", "not emitted (0 elements)", "not emitted (0 elements)", + num(len(S["A"]["grp"])), num(len(S["B"]["grp"]))], + ["— entrapment groups", "—", "—", + num(len(S["A"]["ent_grp"])), num(len(S["B"]["ent_grp"]))], + ] + A(table(["Metric", "ProSE A", "ProSE B", "Sage A", "Sage B"], rows)) + A("") + + # ---------- Table 4: runtime ---------- + A("### Table 4 — Runtime and resources\n") + A("From `/usr/bin/time -v` on the recorded runs; nothing was re-timed. Peak RSS is shown in " + "MiB; the raw figures are %s / %s / %s / %s kB.\n" + % (num(T[("prose", "A")]["rss"]), num(T[("prose", "B")]["rss"]), + num(T[("sage", "A")]["rss"]), num(T[("sage", "B")]["rss"]))) + rows = [] + for label, key in (("Wall clock", "wall"), ("User CPU (s)", "user"), ("System CPU (s)", "sys"), + ("CPU utilisation", "cpu"), ("Peak RSS (MiB)", "rss")): + vals = [] + for e, c in (("prose", "A"), ("prose", "B"), ("sage", "A"), ("sage", "B")): + t = T[(e, c)][key] + if key == "rss": + vals.append(num(round(t / 1024)) if t else "—") + elif key == "cpu": + vals.append(f"{t}%" if t else "—") + elif key in ("user", "sys"): + vals.append(f"{t:.2f}" if t else "—") + else: + vals.append(t or "—") + rows.append([label] + vals) + A(table(["Metric", "ProSE A", "ProSE B", "Sage A", "Sage B"], rows)) + A("") + A("Engine-internal stages (from the same logs): ProSE index build %.1f s / %.1f s, search %.1f s / " + "%.1f s, FDR %.1f s / %.1f s; Sage search %.1f s / %.1f s." + % (P["A"]["internal"][2], P["B"]["internal"][2], + P["A"]["internal"][0], P["B"]["internal"][0], + P["A"]["internal"][1], P["B"]["internal"][1], + S["A"]["search_ms"] / 1000.0, S["B"]["search_ms"] / 1000.0)) + A("") + + # ---------- Table 5: reconciliation ---------- + A("### Table 5 — Log-to-output reconciliation\n") + A("Each engine summary figure is recomputed from the serialized output. A zero delta means the " + "logged number is fully explained by the stated reconstruction.\n") + rows = [] + + def rec(label, logged, got): + rows.append([label, num(logged), num(got), num(got - logged)]) + + for c in "AB": + rec("ProSE %s PSMs (logged `Matched`)" % c, P[c]["log_matched"], + sum(P[c]["cls"].values())) + rec("ProSE %s unique peptides" % c, P[c]["log_pep"], len(P[c]["union_mod"])) + rec("ProSE %s proteins" % c, P[c]["log_prot"], + P[c]["prot_total"] - P[c]["prot_dec"]) + rec("Sage %s PSM figure (all labels at threshold)" % c, S[c]["log_psm"], + S[c]["all_label_at_q"]) + rec("Sage %s unique peptides (`peptide_q`)" % c, S[c]["log_pep"], len(S[c]["pq_union"])) + rec("Sage %s proteins" % c, S[c]["log_prot"], len(S[c]["prot"])) + rec("Sage %s protein groups" % c, S[c]["log_grp"], len(S[c]["grp"])) + A(table(["Quantity", "Logged", "Reconstructed", "Δ"], rows)) + A("") + + txt = "\n".join(L) + if out_path: + with open(out_path, "w", newline="\n") as fh: + fh.write(txt) + else: + sys.stdout.write(txt) + + bad = [c for c in CHECKS if not c[0]] + print("\n%d checks, %d failed" % (len(CHECKS), len(bad)), file=sys.stderr) + return 1 if bad else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/prose-sage-pxd028735/figures/psm_yield_1pct.pdf b/docs/prose-sage-pxd028735/figures/psm_yield_1pct.pdf new file mode 100644 index 0000000..c3f3398 Binary files /dev/null and b/docs/prose-sage-pxd028735/figures/psm_yield_1pct.pdf differ diff --git a/docs/prose-sage-pxd028735/figures/psm_yield_1pct.png b/docs/prose-sage-pxd028735/figures/psm_yield_1pct.png new file mode 100644 index 0000000..2a40e73 Binary files /dev/null and b/docs/prose-sage-pxd028735/figures/psm_yield_1pct.png differ diff --git a/docs/prose-sage-pxd028735/figures/psm_yield_1pct.svg b/docs/prose-sage-pxd028735/figures/psm_yield_1pct.svg new file mode 100644 index 0000000..a04540e --- /dev/null +++ b/docs/prose-sage-pxd028735/figures/psm_yield_1pct.svg @@ -0,0 +1,467 @@ + + + + + + + + image/svg+xml + + + Matplotlib v3.11.2, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + ProSE + + + + + + + + + + Sage + (LDA post-scoring) + + + + + + + + + + Sage + (hyperscore) + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + 10 + + + + + + + + + + + + + 20 + + + + + + + + + + + + + 30 + + + + + + + + + + + + + 40 + + + + + + + + + + + + + 50 + + + + + + + + + + + + + 60 + + + + Target PSMs at 1% nominal FDR (thousands) + + + + + + + + + + + + + + + + + + + Condition A + + + 45,723 + + + 54,830 + + + 29,538 + + + + + + + + + + + + + + + ProSE + + + + + + + + + + Sage + (LDA post-scoring) + + + + + + + + + + Sage + (hyperscore) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Condition B + + + 47,252 + + + 55,756 + + + 31,019 + + + + ProSE and Sage PSM yield at 1% nominal FDR + + + Single measurement per condition and configuration; no replicates, so no error bars. Sage (hyperscore) is a re-ranking of the frozen Sage tables, not a Sage run + with post-scoring disabled. Counts read from the frozen PXD028735 run; see plot_psm_yield.py --verify. + + + + + + + ProSE + + + + + + Sage (LDA) + + + + + + Sage (hyperscore) + + + + + + + + + + + + diff --git a/docs/prose-sage-pxd028735/hashes.sha256 b/docs/prose-sage-pxd028735/hashes.sha256 new file mode 100644 index 0000000..c1a76b3 --- /dev/null +++ b/docs/prose-sage-pxd028735/hashes.sha256 @@ -0,0 +1,13 @@ +1ce35721a4dedc9878a76f0c753cc4ee5bf0ec0c6248d0948581ef348415c30b results/prose_A/ProSE_A.idXML +19f64705513e3d4cf904346c4e1f46018267a08d0d654f3e387a397ef600cb7f results/prose_B/ProSE_B.idXML +bf72afde43d0f495539bfc1dcefe8cf1281f824639889b3e6bf9d5447c034c1a results/sage_A/results.sage.tsv +1d9630969c788c9e2a093c20017f3280949357bf16434cb97a10ad1e9c3ae41f results/sage_B/results.sage.tsv +f144a889c8e100d166447e3373a91723ce3a2777a62156d975c368ff6ca74424 results/sage_A/results.json +8b3f8bfde3b21b4df0249ed8f19e698d67159b8e2f6d91243f80036c021389fd results/sage_B/results.json +6e9cd025740408d5d936fc72ccd54787f0511b702b7c20a25a3f7865b61371f4 data/entrapment_hye_soce.fasta +13610321d79c934ed16430cf373e810256774c1540f2556bf518263d51ab7742 data/LFQ_Orbitrap_DDA_Condition_A_Sample_Alpha_01.mzML +ed338c23d801b6fb737742b3e142568cf9095807422408918eef6048bf6eebb9 data/LFQ_Orbitrap_DDA_Condition_B_Sample_Alpha_01.mzML +f0c55500a18ca8cc719b13d5d8d1fbc259cdf4d3560bc672fd63021f479745fa cfg/sage_A.json +042211094f51489c25e9f5158862336e761b4ce5f190b198dc7b50e91f67fabd cfg/sage_B.json +56958d4e428fa3c7af4b8501f63d08075d0d59bea5e371b3a77b580cf7a263dd /home/nej1gotnochill/openms-pr9975/build/bin/ProSE +d1a96a7d14836f0846a55cede74456595169399abdc6a12e468f234eb4fcf7c0 /home/nej1gotnochill/sage-pxd/bin/sage-v0.15.0-beta.2-x86_64-unknown-linux-gnu/sage diff --git a/docs/prose-sage-pxd028735/plot_psm_yield.py b/docs/prose-sage-pxd028735/plot_psm_yield.py new file mode 100644 index 0000000..b668ff8 --- /dev/null +++ b/docs/prose-sage-pxd028735/plot_psm_yield.py @@ -0,0 +1,251 @@ +#!/usr/bin/env python3 +"""Target PSM yield at 1% nominal PSM FDR, ProSE vs Sage, PXD028735 conditions A and B. + +Three bars per condition: + + ProSE ProSE 3.x, no Percolator / no post-scoring. Count = the engine's own + logged "Matched : N / M spectra" after its internal 1% PSM FDR, which + emit_tables.py cross-checks against the number of passing rows in + results/prose_/ProSE_.idXML (they are equal). + Sage (LDA) Sage 0.15.0-beta.2 as shipped: unconditional 20-feature LDA post-scoring + in crates/sage-cli/src/runner.rs::spectrum_fdr, then target-decoy + q-values. Count = rows with label == 1 and spectrum_q <= 0.01 in + results/sage_/results.sage.tsv. + Sage (hyperscore) DERIVED, not a Sage execution. The frozen TSV still carries Sage's own + pre-LDA hyperscore, so the same PSMs are re-ranked on hyperscore and + q-values recomputed with Sage's own procedure (decoy counter starts at 1, + q = D/T, reverse cumulative minimum). This is what the run would report + if the post-scoring step were removed; no Sage binary was run without it. + +Every number below was validated against the frozen run: the same re-ranking applied to +`sage_discriminant_score` reproduces the published spectrum_q row for row and the published +1% target counts exactly, which is what licenses the hyperscore arm. `--verify` re-derives all +six counts from the frozen outputs and asserts they equal the constants below. + +Only one measured run exists per condition and method (logs/ holds exactly one output per arm; +logs/attempt1_launch_failed/ is a launch failure with no measurement), and A and B are two +different pooled samples, not replicates. The figure therefore shows single measurements: no +per-run dots, no error bars, no geometric means. + +Usage: + python3 plot_psm_yield.py --verify --data-root ~/prose-sage-pxd028735 + python3 plot_psm_yield.py --data-root ~/prose-sage-pxd028735 + python3 plot_psm_yield.py --caption +""" +import argparse +import csv +import datetime +import os +import re +import sys + +# --- Authoritative plotted values (target PSMs at 1% nominal PSM FDR) --------------------- +# Source: frozen run root, results/sage_{A,B}/results.sage.tsv and logs/prose_{A,B}.stdout.log. +# See module docstring for how each arm is counted; `--verify` re-derives all of them. +DATA = { + "A": {"ProSE": 45723, "Sage (LDA)": 54830, "Sage (hyperscore)": 29538}, + "B": {"ProSE": 47252, "Sage (LDA)": 55756, "Sage (hyperscore)": 31019}, +} + +ARM_ORDER = ["ProSE", "Sage (LDA)", "Sage (hyperscore)"] +COLORS = { + "ProSE": "#2f6db5", + "Sage (LDA)": "#3f9b52", + "Sage (hyperscore)": "#e08214", +} +EDGE = "#2b2b2b" + +TITLE = "ProSE and Sage PSM yield at 1% nominal FDR" + +CAPTION = """\ +Figure 1. ProSE and Sage PSM yield at 1% nominal PSM FDR. Target PSM counts for ProSE and Sage on +PXD028735, conditions A and B. ProSE was run without Percolator or any other post-scoring. Sage +(LDA) is the stock Sage 0.15.0-beta.2 workflow, which unconditionally applies its built-in +20-feature linear discriminant analysis post-scoring before assigning target-decoy q-values. Sage +(hyperscore) is a derived re-ranking of the frozen Sage PSM tables on Sage's own pre-LDA hyperscore, +using Sage's q-value procedure; it is not an independent Sage execution with post-scoring disabled, +because the pinned binary exposes no such switch. Each condition was searched once per +configuration, and A and B are different pooled samples rather than replicates, so bars are single +measurements without error bars. The two Sage bars compare different ranking strategies applied to +the same frozen Sage search results. ProSE represents an independently executed search pipeline on +the same dataset.""" + + +# --- Verification against the frozen run --------------------------------------------------- +def sage_q_values(rows, key): + """Sage's spectrum-level TDC q-values: decoy counter starts at 1, q = D/T, reverse cum-min.""" + ordered = sorted(rows, key=lambda r: -r[key]) + decoy, target, q = 1, 0, [] + for r in ordered: + if r["label"] == -1: + decoy += 1 + else: + target += 1 + q.append(decoy / target if target else float("inf")) + q_min = 1.0 + for i in range(len(q) - 1, -1, -1): + q_min = min(q_min, q[i]) + q[i] = q_min + for r, v in zip(ordered, q): + r["_q"] = v + + +def load_sage(path): + rows = [] + with open(path, newline="") as fh: + for r in csv.DictReader(fh, delimiter="\t"): + r["label"] = int(r["label"]) + r["hyperscore"] = float(r["hyperscore"]) + r["sage_discriminant_score"] = float(r["sage_discriminant_score"]) + r["spectrum_q"] = float(r["spectrum_q"]) + rows.append(r) + return rows + + +def count_at(rows, threshold=0.01): + return sum(1 for r in rows if r["label"] == 1 and r["_q"] <= threshold) + + +def verify(root): + failures = 0 + print("verifying against frozen run: %s" % root) + for cond in ("A", "B"): + tsv = os.path.join(root, "results", "sage_%s" % cond, "results.sage.tsv") + log = os.path.join(root, "logs", "prose_%s.stdout.log" % cond) + rows = load_sage(tsv) + + published = sum(1 for r in rows if r["label"] == 1 and r["spectrum_q"] <= 0.01) + + sage_q_values(rows, "sage_discriminant_score") + relaid = count_at(rows) + agree = sum(1 for r in rows if abs(r["_q"] - r["spectrum_q"]) < 1e-6) + + sage_q_values(rows, "hyperscore") + hyper = count_at(rows) + + with open(log) as fh: + m = re.search(r"Matched\s*:\s*(\d+) / (\d+) spectra", fh.read()) + prose = int(m.group(1)) if m else None + + checks = [ + ("ProSE %s logged Matched" % cond, prose, DATA[cond]["ProSE"]), + ("Sage %s published spectrum_q<=0.01" % cond, published, DATA[cond]["Sage (LDA)"]), + ("Sage %s re-ranked LDA" % cond, relaid, DATA[cond]["Sage (LDA)"]), + ("Sage %s hyperscore re-ranking" % cond, hyper, DATA[cond]["Sage (hyperscore)"]), + ("Sage %s row-level q agreement" % cond, agree, len(rows)), + ] + for label, got, want in checks: + ok = got == want + failures += 0 if ok else 1 + print(" %-42s %8s %s" % (label, "{:,}".format(got), + "ok" if ok else "MISMATCH (expected %s)" % "{:,}".format(want))) + print(" -> %s" % ("VERIFIED" if failures == 0 else "%d FAILED" % failures)) + return failures + + +# --- Figure -------------------------------------------------------------------------------- +def render(outdir, dpi): + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + from matplotlib.patches import Patch + from matplotlib.ticker import FuncFormatter + + plt.rcParams.update({ + "font.family": "sans-serif", + "font.sans-serif": ["DejaVu Sans"], + "font.size": 8, + "axes.linewidth": 0.8, + "axes.edgecolor": EDGE, + "axes.labelsize": 9, + "xtick.labelsize": 8, + "ytick.labelsize": 8, + "legend.fontsize": 8, + "pdf.fonttype": 42, + "ps.fonttype": 42, + "svg.fonttype": "none", + # Fixed salt keeps the generated element ids stable between runs. + "svg.hashsalt": "openms-benchmarking-psm-yield", + }) + + fig, axes = plt.subplots(1, 2, figsize=(7.2, 4.3), sharey=True, + gridspec_kw={"wspace": 0.10}) + bar_w = 0.62 + xs = range(len(ARM_ORDER)) + ymax = float(max(max(v.values()) for v in DATA.values())) + + for ax, cond in zip(axes, ("A", "B")): + vals = [DATA[cond][arm] for arm in ARM_ORDER] + ax.bar(list(xs), vals, width=bar_w, + color=[COLORS[a] for a in ARM_ORDER], + edgecolor=EDGE, linewidth=0.7, zorder=3) + for x, v in zip(xs, vals): + ax.text(x, v + ymax * 0.018, "{:,}".format(v), ha="center", va="bottom", + fontsize=7, color=EDGE, zorder=4) + ax.set_xticks(list(xs)) + ax.set_xticklabels(["ProSE", "Sage\n(LDA post-scoring)", "Sage\n(hyperscore)"]) + ax.set_title("Condition %s" % cond, fontsize=9, fontweight="bold", pad=6) + ax.set_ylim(0, ymax * 1.16) + ax.yaxis.set_major_formatter(FuncFormatter(lambda v, _: "%d" % (v / 1000.0))) + ax.grid(axis="y", color="#d9d9d9", linewidth=0.6, zorder=0) + ax.set_axisbelow(True) + for side in ("top", "right"): + ax.spines[side].set_visible(False) + ax.tick_params(length=3, width=0.8, colors=EDGE) + + axes[0].set_ylabel("Target PSMs at 1% nominal FDR (thousands)") + + handles = [Patch(facecolor=COLORS[a], edgecolor=EDGE, + linewidth=0.7, label=a) for a in ARM_ORDER] + fig.legend(handles=handles, loc="upper center", ncol=3, frameon=False, + bbox_to_anchor=(0.5, 0.925), handlelength=1.1, columnspacing=1.6) + fig.suptitle(TITLE, fontsize=10.5, fontweight="bold", y=0.968) + fig.text(0.5, 0.022, + "Single measurement per condition and configuration; no replicates, so no error bars. " + "Sage (hyperscore) is a re-ranking of the frozen Sage tables, not a Sage run\n" + "with post-scoring disabled. Counts read from the frozen PXD028735 run; see " + "plot_psm_yield.py --verify.", + ha="center", va="bottom", fontsize=6.3, color="#444444") + + fig.subplots_adjust(left=0.095, right=0.985, top=0.815, bottom=0.185) + os.makedirs(outdir, exist_ok=True) + written = [] + # Fixed metadata so repeated runs are byte-identical. + meta = { + "png": {"Date": None}, + "pdf": {"CreationDate": datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc), + "ModDate": datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc)}, + "svg": {"Date": None}, + } + for ext, extra in (("png", {"dpi": dpi}), ("pdf", {}), ("svg", {})): + path = os.path.join(outdir, "psm_yield_1pct.%s" % ext) + fig.savefig(path, facecolor="white", metadata=meta[ext], **extra) + written.append(path) + plt.close(fig) + return written + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--data-root", default=os.path.expanduser("~/prose-sage-pxd028735"), + help="frozen run root (results/, logs/) used by --verify") + ap.add_argument("--outdir", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), + "figures")) + ap.add_argument("--dpi", type=int, default=600) + ap.add_argument("--verify", action="store_true", help="re-derive the plotted values and exit") + ap.add_argument("--caption", action="store_true", help="print the proposed caption and exit") + args = ap.parse_args(argv) + + if args.caption: + print(CAPTION) + return 0 + if args.verify: + return 1 if verify(args.data_root) else 0 + + for path in render(args.outdir, args.dpi): + print("wrote %s (%d bytes)" % (path, os.path.getsize(path))) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/prose-sage-pxd028735/reproduce.sh b/docs/prose-sage-pxd028735/reproduce.sh new file mode 100644 index 0000000..7b9ed06 --- /dev/null +++ b/docs/prose-sage-pxd028735/reproduce.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# Verify that this report is exactly what the frozen outputs produce. +# Read-only with respect to results/, logs/, inputs and executables. +set -uo pipefail +ROOT="${1:-$HOME/prose-sage-pxd028735}" +REP="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +TMP="$(mktemp -d)" +rc=0 + +echo "== 1/3 frozen artifacts (13 hashes, read-only)" +if ( cd "$ROOT" && sha256sum -c "$REP/hashes.sha256" ); then + echo "hashes: OK" +else + echo "hashes: MISMATCH" + rc=1 +fi + +echo +echo "== 2/3 regenerate the results tables from the raw outputs" +if python3 "$REP/emit_tables.py" "$ROOT" "$TMP/tables.md"; then + : +else + echo "emit_tables.py: FAILED (consistency check or parse error)" + rc=1 +fi +if diff -u "$REP/tables.md" "$TMP/tables.md"; then + echo "tables: identical to the ones in the report" +else + echo "tables: DIFFER" + rc=1 +fi + +echo +echo "== 3/3 rebuild the report from template + tables" +python3 "$REP/build_report.py" "$REP/EXPERIMENT_REPORT.template.md" \ + "$TMP/tables.md" "$TMP/report.md" || rc=1 +if diff -u "$REP/EXPERIMENT_REPORT.md" "$TMP/report.md"; then + echo "report: identical" +else + echo "report: DIFFERS" + rc=1 +fi + +rm -rf "$TMP" +echo +if [ "$rc" -eq 0 ]; then + echo "REPRODUCED: hashes, tables and report all match the frozen outputs." +else + echo "NOT REPRODUCED: see the diffs above." +fi +exit "$rc" diff --git a/docs/prose-sage-pxd028735/tables.md b/docs/prose-sage-pxd028735/tables.md new file mode 100644 index 0000000..4dc7661 --- /dev/null +++ b/docs/prose-sage-pxd028735/tables.md @@ -0,0 +1,89 @@ +### Table 1 — PSM level + +All engine-native q thresholds are a common nominal 1% PSM FDR and inclusive; the shared target is not a claim that the two operating points have identical statistical stringency (Section 4.1). ProSE removes decoy PSMs and their protein references at protein-FDR finalization, so decoy rows cannot be observed in its output; Sage writes targets and decoys alike. + +| Metric | ProSE A | ProSE B | Sage A | Sage B | +|---|---:|---:|---:|---:| +| Engine log: PSM figure (as labelled by the engine) | 45,723 | 47,252 | 55,377 | 56,312 | +| Serialized rows, target class (engine-native threshold) | 45,723 | 47,252 | 54,830 | 55,756 | +| Serialized rows, all labels at threshold | not observable | not observable | 55,377 | 56,312 | +| **Pure target** | 44,807 | 46,352 | 54,654 | 55,614 | +| Target+decoy shared | 4 | 1 | — | — | +| Target-shared entrapment | 31 | 25 | 49 | 43 | +| Entrapment only | 19 | 18 | 127 | 99 | +| Target, no surviving protein reference | 862 | 856 | 0 | 0 | +| Decoy | not observable | not observable | 409 | 417 | +| Decoy-entrapment | not observable | not observable | 138 | 139 | + +### Table 2 — Distinct peptide sequences + +A peptide is counted once per class it appears in; the two engines write different sequence syntaxes, so sequence identities are only ever compared within an engine — counts are compared across engines in Section 9. *Modified* is the engine's own string (OpenMS `M(Oxidation)` vs Sage `M[+15.9949]`); *bare* has modification tokens stripped. + +| Metric | ProSE A | ProSE B | Sage A | Sage B | +|---|---:|---:|---:|---:| +| Engine log: unique peptides | 31,991 | 32,465 | 36,875 | 37,269 | +| Recomputed set behind that figure | 31,991 | 32,465 | 36,875 | 37,269 | +| Bare sequences in the same set | 30,991 | 31,206 | 35,732 | 35,835 | +| **Pure target, modified** | 31,094 | 31,586 | 36,767 | 37,190 | +| Pure target, bare | 30,094 | 30,328 | 35,624 | 35,756 | +| Target+decoy shared | 4 | 1 | — | — | +| Target-shared entrapment | 17 | 14 | 25 | 25 | +| Entrapment only | 19 | 17 | 122 | 95 | +| Target, no surviving protein reference | 857 | 847 | 0 | 0 | + +Rows 7–9 for Sage are taken at the PSM threshold (`spectrum_q ≤ 0.01`). The engine's reported peptide total and its pure-target part, however, come from Sage's separate peptide-level stage, so they are not on the same basis as the ProSE rows above them: at the common PSM threshold the same set is 38,181 (A) / 38,455 (B) distinct sequences, 1,306 / 1,186 more. Section 9 makes that like-for-like comparison; the `peptide_q` sets are: + +| Sage peptide set | Sage A | Sage B | +|---|---:|---:| +| Unique peptides, `peptide_q ≤ 0.01` | 36,875 | 37,269 | +| Pure target | 36,767 | 37,190 | +| Target-shared entrapment | 24 | 22 | +| Entrapment only | 84 | 57 | +| Unique peptides, `spectrum_q ≤ 0.01` | 38,181 | 38,455 | + +### Table 3 — Proteins and protein groups + +ProSE's protein count is a picked-protein list over complete protein sets with no grouping step in the output; Sage's is the picked protein list restricted to proteotypic peptides, plus a separate IDPicker-style grouping. The two protein columns are different quantities and are not compared. + +| Metric | ProSE A | ProSE B | Sage A | Sage B | +|---|---:|---:|---:|---:| +| Protein identifications at 1% FDR | 5,709 | 5,755 | 5,276 | 5,225 | +| — non-entrapment | 5,680 | 5,727 | 5,262 | 5,218 | +| — entrapment | 29 | 28 | 14 | 7 | +| Protein groups | not emitted (0 elements) | not emitted (0 elements) | 5,380 | 5,336 | +| — entrapment groups | — | — | 14 | 6 | + +### Table 4 — Runtime and resources + +From `/usr/bin/time -v` on the recorded runs; nothing was re-timed. Peak RSS is shown in MiB; the raw figures are 5,636,512 / 5,635,720 / 8,237,792 / 7,913,656 kB. + +| Metric | ProSE A | ProSE B | Sage A | Sage B | +|---|---:|---:|---:|---:| +| Wall clock | 2:47.23 | 2:55.83 | 3:28.38 | 4:49.09 | +| User CPU (s) | 500.82 | 558.20 | 536.65 | 824.97 | +| System CPU (s) | 30.57 | 21.79 | 33.62 | 35.45 | +| CPU utilisation | 317% | 329% | 273% | 297% | +| Peak RSS (MiB) | 5,504 | 5,504 | 8,045 | 7,728 | + +Engine-internal stages (from the same logs): ProSE index build 44.3 s / 38.8 s, search 86.9 s / 104.3 s, FDR 0.6 s / 0.9 s; Sage search 94.8 s / 163.0 s. + +### Table 5 — Log-to-output reconciliation + +Each engine summary figure is recomputed from the serialized output. A zero delta means the logged number is fully explained by the stated reconstruction. + +| Quantity | Logged | Reconstructed | Δ | +|---|---:|---:|---:| +| ProSE A PSMs (logged `Matched`) | 45,723 | 45,723 | 0 | +| ProSE A unique peptides | 31,991 | 31,991 | 0 | +| ProSE A proteins | 5,709 | 5,709 | 0 | +| Sage A PSM figure (all labels at threshold) | 55,377 | 55,377 | 0 | +| Sage A unique peptides (`peptide_q`) | 36,875 | 36,875 | 0 | +| Sage A proteins | 5,276 | 5,276 | 0 | +| Sage A protein groups | 5,380 | 5,380 | 0 | +| ProSE B PSMs (logged `Matched`) | 47,252 | 47,252 | 0 | +| ProSE B unique peptides | 32,465 | 32,465 | 0 | +| ProSE B proteins | 5,755 | 5,755 | 0 | +| Sage B PSM figure (all labels at threshold) | 56,312 | 56,312 | 0 | +| Sage B unique peptides (`peptide_q`) | 37,269 | 37,269 | 0 | +| Sage B proteins | 5,225 | 5,225 | 0 | +| Sage B protein groups | 5,336 | 5,336 | 0 |