diff --git a/src/viewer/history_ui.py b/src/viewer/history_ui.py index 99550803..d386b85e 100644 --- a/src/viewer/history_ui.py +++ b/src/viewer/history_ui.py @@ -19,14 +19,15 @@ CONFIGURE_PAGE = Path("content", "workflow_configure.py") -def start_again(runs: RunManager, run_id: str) -> None: +def start_again(runs: RunManager, run_id: str, changes: dict | None = None, + note: str = "to start again") -> None: """Open Describe experiment with the settings ``run_id``'s experiment started - with and all of its files.""" + with and all of its files, ``changes`` (params.json keys) on top.""" from src.WorkflowTest import WorkflowTest # the page set up the workspace already root = runs.experiment_root(run_id) or run_id files = runs.experiment_files(root, history.FILES_KEY) - WorkflowTest().follow_up(root, changes={history.FILES_KEY: files} if files else None, - page=CONFIGURE_PAGE, note="to start again") + changes = {**({history.FILES_KEY: files} if files else {}), **(changes or {})} + WorkflowTest().follow_up(root, changes=changes or None, page=CONFIGURE_PAGE, note=note) def history_section(runs: RunManager, run_id: str, key: str) -> None: diff --git a/src/viewer/panels/qc.py b/src/viewer/panels/qc.py index 8164a656..ad95495a 100644 --- a/src/viewer/panels/qc.py +++ b/src/viewer/panels/qc.py @@ -7,11 +7,13 @@ from openms_insight import SeriesPlot from src.viz.identification import precursor_mass_error, score_distribution +from src.viz.identification.precursor_mass_error import window_findings from src.common.insight_tables import plot_cache from src.common.qc_plots import ( fdr_cutoff, mass_error_histogram, psm_qc_table, psms_per_file, score_histogram, ) -from src.common.results_helpers import get_run_dir, get_run_params, search_results_dir +from src.common.results_helpers import get_run_dir, get_run_params, get_run_id, get_runs, search_results_dir +from src.viewer import precursor_window_source as window_source from src.viewer.scope import heading, needs_results, scoped, shared_state, zoom @@ -88,3 +90,30 @@ def mass_error(ctx) -> None: "qc_mass_error", data, precursor_mass_error.settings(), detail=f"median {median:+.2f} ppm", note=f"Target PSMs at {fdr * 100:.3g} % PSM FDR, isotope errors removed.", ) + window_check(ctx, filtered) + + +def window_check(ctx, filtered: pd.DataFrame) -> None: + """Whether the precursor window searched fits the errors, with a start to search again.""" + workflow_params = get_run_params(ctx.workspace) + window = window_source.precursor_window(workflow_params) + if window is None: + return + errors = filtered.loc[~filtered["decoy"], "precursor_error_ppm"].dropna().tolist() + findings = window_findings(errors, window["lower"], window["upper"], + calibrated=window_source.calibrated(workflow_params)) + for i, finding in enumerate(findings): + with st.container(border=True): + st.markdown(f":material/warning: **{finding['check']}.** {finding['finding']}") + if finding["window"] and st.button( + finding["label"], icon=":material/replay:", key=scoped(f"qc_window_again_{i}"), + help="Open Describe experiment with this run's files and settings and this precursor " + "window. The new run is kept next to this one.", + ): + from src.viewer.history_ui import start_again + run_id = get_run_id(ctx.workspace) + if run_id: + lower, upper = finding["window"] + start_again(get_runs(ctx.workspace), run_id, + changes=window_source.window_changes(workflow_params, finding["window"]), + note=f"with a precursor window of −{lower:g} / +{upper:g} ppm") diff --git a/src/viewer/precursor_window_source.py b/src/viewer/precursor_window_source.py new file mode 100644 index 00000000..c929194c --- /dev/null +++ b/src/viewer/precursor_window_source.py @@ -0,0 +1,53 @@ +"""The precursor window a run's database search used, and the settings to +search again with another one. + +The findings themselves (off-centre, cut off at the edge, wider than needed) +come from the template's ``src/viz/identification/precursor_mass_error``. +Streamlit-free, so tests call it. +""" +from src.common.results_helpers import _tool_params + +LOWER = "Search:precursor:mass_tolerance_lower" +UPPER = "Search:precursor:mass_tolerance_upper" +UNIT = "Search:precursor:mass_tolerance_unit" +CALIBRATION = "Search:calibration:enabled" + + +def search_instance(workflow_params: dict) -> str: + """The ProSE instance that searched the run (label-free or TMT).""" + return "ProSE-TMT" if workflow_params.get("analysis-mode", "LFQ") == "TMT" else "ProSE" + + +def precursor_window(workflow_params: dict) -> dict | None: + """``{"lower", "upper"}`` (ppm) of the run's ProSE search. + + None for a window in Da (the errors are in ppm, so it cannot be compared + without each match's mass) and for runs searched before the switch to + ProSE, whose settings cannot be searched again with. + """ + instance = search_instance(workflow_params) + prose = _tool_params(workflow_params, instance) + if not prose: + return None + if str(prose.get(UNIT, "ppm")) != "ppm": + return None + try: + lower = float(prose.get(LOWER, 20.0)) + upper = float(prose.get(UPPER, 20.0)) + except (TypeError, ValueError): + return None + if lower <= 0 or upper <= 0: + return None + return {"lower": lower, "upper": upper} + + +def calibrated(workflow_params: dict) -> bool: + """Whether the search tightened its windows itself (ProSE's calibration pass).""" + value = _tool_params(workflow_params, search_instance(workflow_params)).get(CALIBRATION, False) + return value is True or str(value).lower() == "true" + + +def window_changes(workflow_params: dict, window: tuple[float, float]) -> dict: + """The params.json changes that search again with ``window`` (lower, upper ppm).""" + lower, upper = window + return {search_instance(workflow_params): {LOWER: float(lower), UPPER: float(upper), UNIT: "ppm"}} diff --git a/src/viz/catalog.py b/src/viz/catalog.py index 1447efdf..310d8358 100644 --- a/src/viz/catalog.py +++ b/src/viz/catalog.py @@ -91,7 +91,7 @@ ('predicted_spectrum', 'identification', 'Measured and predicted spectrum', 'settings', 'The measured spectrum of the picked PSM above, the spectrum predicted for its peptide mirrored below, the matched fragments labelled on both.'), ('precursor_mass_error', 'identification', 'Precursor mass error', 'settings', - 'How the precursor mass errors (ppm) of the PSMs are distributed, targets and decoys apart.'), + 'How the precursor mass errors (ppm) of the PSMs are distributed, targets and decoys apart, and whether the precursor window searched was off-centre, cut them off or was wider than needed.'), ('protein_table', 'identification', 'Protein table', 'settings', 'The identified proteins with their coverage, peptide and PSM counts and the replicates they were found in; contaminants hidden by a toggle, a search over accession, gene and name. A click picks the protein.'), ('protein_peptides', 'identification', 'Peptides of a protein', 'settings', diff --git a/src/viz/identification/precursor_mass_error.py b/src/viz/identification/precursor_mass_error.py index 74ec899b..75571e2f 100644 --- a/src/viz/identification/precursor_mass_error.py +++ b/src/viz/identification/precursor_mass_error.py @@ -3,12 +3,42 @@ a calibration offset; a wide one to a precursor tolerance wider than needed. Insight component: ``SeriesPlot``. Columns: ``x`` (error, ppm), ``y`` (count). + +``window_findings`` compares those errors with the precursor window the search +used and says whether the window was off-centre, cut the error distribution +(matches pile up at its edge) or was much wider than the errors need, each with +the window to search again with. """ from __future__ import annotations +import math + COMPONENT = "SeriesPlot" +# The median error is off-centre when it is more than this share of the window +# on its side: a third of the window lost to an offset leaves true matches with +# larger errors outside it. +OFFSET_SHARE = 1 / 3 +# Offsets below this (ppm) are noise on high-accuracy instruments. +MIN_OFFSET_PPM = 1.0 +# The outer part of the window (share of each side) watched for a pile-up. +EDGE_ZONE = 0.1 +# A pile-up: more than this share of the matches in the outer tenth. A normal +# error with the window at 2.5 standard deviations puts about 1 % there. +EDGE_SHARE = 0.02 +# The window is wider than needed when the errors need less than this share of it. +TOO_WIDE_RATIO = 0.5 +# A window wide enough for the errors: this share of them lie inside it ... +NEEDED_SHARE = 0.995 +# ... with this much room to spare. Taken from the errors rather than their +# spread, so a heavy tail of correct matches is not cut off. +NEEDED_MARGIN = 1.1 +# The wider window offered while an offset or a pile-up is suspected (ppm). +WIDE_PROBE_PPM = 50.0 +# Fewer matches than this give no reliable median or edge share. +MIN_MATCHES = 30 + def settings(noun: str = "PSMs", **overrides) -> dict: return dict( @@ -16,3 +46,88 @@ def settings(noun: str = "PSMs", **overrides) -> dict: y_range_mode="nonnegative", title="Precursor mass error", x_label="Precursor error (ppm)", y_label=noun, svg_filename="precursor-mass-error", ) | overrides + + +def _median(values: list[float]) -> float: + s = sorted(values) + n = len(s) + return s[n // 2] if n % 2 else (s[n // 2 - 1] + s[n // 2]) / 2 + + +def _ppm(value: float) -> str: + return f"{value:.3g} ppm" + + +def needed_window(errors_ppm) -> float | None: + """The symmetric window (ppm, rounded up) the errors need, None for too few.""" + errors = [float(e) for e in errors_ppm if e is not None and math.isfinite(float(e))] + if len(errors) < MIN_MATCHES: + return None + size = sorted(abs(e) for e in errors) + inside = size[min(len(size) - 1, math.ceil(NEEDED_SHARE * len(size)) - 1)] + return float(math.ceil(NEEDED_MARGIN * inside)) + + +def window_findings(errors_ppm, lower: float, upper: float, calibrated: bool = False) -> list[dict]: + """What the precursor errors say about the window the search used. + + ``errors_ppm`` are the precursor errors (ppm, isotope errors removed) of + the target matches that passed the FDR filter, ``lower`` and ``upper`` the + window below and above the precursor (ppm). ``calibrated`` says the search + tightened its windows itself, so a wide window set is not reported. + + Returns a list of ``{"check", "finding", "window", "label"}``: ``window`` + is the ``(lower, upper)`` window to search again with (None when there is + none to offer) and ``label`` the words for that. A wider window is offered + for an offset or a pile-up at the edge, never a narrower one, since the + errors seen are only those the window let through. Empty when nothing is + off or there are fewer than ``MIN_MATCHES`` errors. + """ + errors = [float(e) for e in errors_ppm if e is not None and math.isfinite(float(e))] + lower, upper = float(lower), float(upper) + if len(errors) < MIN_MATCHES or lower <= 0 or upper <= 0: + return [] + mid = _median(errors) + position = [e / (lower if e < 0 else upper) for e in errors] + offset = abs(_median(position)) > OFFSET_SHARE and abs(mid) >= MIN_OFFSET_PPM + edge = sum(abs(p) > 1 - EDGE_ZONE for p in position) / len(position) + clipped = edge > EDGE_SHARE + + widest = max(lower, upper) + wide = 2 * widest if widest >= WIDE_PROBE_PPM else WIDE_PROBE_PPM + wider = {"window": (wide, wide), "label": f"Search again with ±{wide:g} ppm"} + findings = [] + if offset: + findings.append({ + "check": "Off-centre", + "finding": ( + f"The median precursor error is {mid:+.3g} ppm, more than a third of the window on that " + f"side (−{lower:g} / +{upper:g} ppm). Matches with larger errors may have fallen outside " + "it. Search again with a wider window; a narrower one would lose more." + ), + **wider, + }) + if clipped: + findings.append({ + "check": "Cut off at the edge", + "finding": ( + f"{edge * 100:.1f} % of the matches lie in the outer tenth of the precursor window " + f"(−{lower:g} / +{upper:g} ppm): the window cuts the error distribution. " + "Search again with a wider window." + ), + **wider, + }) + if not offset and not clipped and not calibrated: + needed = needed_window(errors) + if needed is not None and needed < TOO_WIDE_RATIO * min(lower, upper): + findings.append({ + "check": "Wider than needed", + "finding": ( + f"The precursor window (−{lower:g} / +{upper:g} ppm) is more than twice what the " + f"errors need, about ±{_ppm(needed)}. A narrower window lets fewer wrong matches " + "compete, which separates targets from decoys better." + ), + "window": (needed, needed), + "label": f"Search again with ±{needed:g} ppm", + }) + return findings diff --git a/tests/test_precursor_window_source.py b/tests/test_precursor_window_source.py new file mode 100644 index 00000000..1b22046f --- /dev/null +++ b/tests/test_precursor_window_source.py @@ -0,0 +1,36 @@ +"""The precursor window of a run's search and the changes to search again.""" +from src.viewer.precursor_window_source import ( + LOWER, UNIT, UPPER, calibrated, precursor_window, window_changes, +) + + +def _params(mode="LFQ", **search): + instance = "ProSE-TMT" if mode == "TMT" else "ProSE" + return {"analysis-mode": mode, + "_defaults": {instance: {LOWER: 20.0, UPPER: 20.0, UNIT: "ppm"}}, + instance: search} + + +def test_defaults_and_user_values(): + assert precursor_window(_params()) == {"lower": 20.0, "upper": 20.0} + assert precursor_window(_params(**{UPPER: 10})) == {"lower": 20.0, "upper": 10.0} + + +def test_tmt_reads_its_own_instance(): + assert precursor_window(_params("TMT", **{LOWER: 4.5, UPPER: 4.5})) == {"lower": 4.5, "upper": 4.5} + + +def test_da_window_and_runs_without_prose_are_left_out(): + assert precursor_window(_params(**{UNIT: "Da"})) is None + assert precursor_window({"CometAdapter": {"precursor_mass_tolerance": 10}}) is None + + +def test_calibration_switch(): + assert not calibrated(_params()) + assert calibrated(_params(**{"Search:calibration:enabled": "true"})) + assert calibrated(_params(**{"Search:calibration:enabled": True})) + + +def test_changes_set_a_ppm_window_on_the_search_instance(): + assert window_changes(_params("TMT"), (50.0, 50.0)) == { + "ProSE-TMT": {LOWER: 50.0, UPPER: 50.0, UNIT: "ppm"}} diff --git a/tests/test_viz_precursor_window.py b/tests/test_viz_precursor_window.py new file mode 100644 index 00000000..dfa9afb8 --- /dev/null +++ b/tests/test_viz_precursor_window.py @@ -0,0 +1,77 @@ +"""Findings on the precursor window from the precursor errors of the matches.""" +import random + +from src.viz.identification.precursor_mass_error import ( + MIN_MATCHES, needed_window, window_findings, +) + + +def _normal(n, mean, sd, seed=1): + rng = random.Random(seed) + return [rng.gauss(mean, sd) for _ in range(n)] + + +def _checks(findings): + return [f["check"] for f in findings] + + +def test_well_centred_window_has_no_finding(): + assert window_findings(_normal(500, 0.2, 2.5), 10, 10) == [] + + +def test_too_few_matches_say_nothing(): + assert window_findings(_normal(MIN_MATCHES - 1, 8, 1), 10, 10) == [] + + +def test_offset_offers_a_wider_window(): + findings = window_findings(_normal(500, 5, 1), 10, 10) + assert _checks(findings) == ["Off-centre"] + assert findings[0]["window"] == (50.0, 50.0) + assert "+5" in findings[0]["finding"] + + +def test_small_offset_on_narrow_window_is_noise(): + # half the window, but below 1 ppm + assert window_findings(_normal(500, 0.8, 0.2), 1.5, 1.5) == [] + + +def test_pile_up_at_the_edge(): + errors = [e for e in _normal(2000, 0, 8) if abs(e) <= 10] + findings = window_findings(errors, 10, 10) + assert "Cut off at the edge" in _checks(findings) + assert all(f["window"][0] > 10 for f in findings) + + +def test_wide_window_is_reported_with_the_needed_one(): + errors = _normal(1000, 0, 1.5) + findings = window_findings(errors, 20, 20) + assert _checks(findings) == ["Wider than needed"] + needed = needed_window(errors) + assert findings[0]["window"] == (needed, needed) + assert needed < 10 + + +def test_wide_window_not_reported_when_the_search_calibrated(): + assert window_findings(_normal(1000, 0, 1.5), 20, 20, calibrated=True) == [] + + +def test_asymmetric_window_uses_its_side(): + # +6 ppm is within a third of a +20 ppm upper side + assert "Off-centre" not in _checks(window_findings(_normal(500, 6, 1), 5, 20)) + assert "Off-centre" in _checks(window_findings(_normal(500, 6, 1), 20, 5)) + + +def test_wider_than_fifty_is_doubled(): + findings = window_findings(_normal(500, 30, 3), 60, 60) + assert findings[0]["window"] == (120.0, 120.0) + + +def test_non_finite_errors_are_ignored(): + errors = _normal(500, 0.2, 2.5) + [float("nan"), None] + assert window_findings(errors, 10, 10) == [] + + +def test_needed_window_keeps_a_heavy_tail(): + # 99 % within ±2 ppm, but 1 % of correct matches out to 12 ppm + errors = _normal(990, 0, 0.7) + [12.0 if i % 2 else -12.0 for i in range(10)] + assert needed_window(errors) >= 12