diff --git a/protea/core/operations/_run_cafa_eval_driver.py b/protea/core/operations/_run_cafa_eval_driver.py index bf82974e..e802fa78 100644 --- a/protea/core/operations/_run_cafa_eval_driver.py +++ b/protea/core/operations/_run_cafa_eval_driver.py @@ -110,13 +110,36 @@ def _write_setting_predictions( return pred_dir + + +def _new_per_protein_sink() -> Any: + """Build the sink, failing loudly if the installed cafaeval cannot make one. + + Imported through a function rather than inline because the only caller sits + inside ``_run_cafaeval_for_setting``'s broad ``except Exception``. An + ImportError raised there would be swallowed and reported as "this setting + produced no results", so a wrong dependency version would look exactly like + an evaluation that legitimately scored nothing. This raises a message that + names the actual problem instead. + """ + try: + from cafaeval.evaluation import PerProteinSink + except ImportError as exc: # pragma: no cover - depends on the installed pin + raise RuntimeError( + "the installed cafaeval cannot emit per-protein scores; the pin in " + "pyproject expects a build with PerProteinSink. Reinstall the " + "dependency rather than reading this run's empty settings as a result." + ) from exc + return PerProteinSink() + + def _invoke_cafaeval_signal_safe( *, ctx: CafaEvalRunContext, pred_dir: str, gt_file: str, known_file: str | None, -) -> tuple[Any, Any]: +) -> tuple[Any, Any, Any]: """Run ``cafa_eval`` with default SIGTERM/SIGINT handlers restored. Our ``_handle_stop`` handler only sets a flag without calling @@ -126,10 +149,16 @@ def _invoke_cafaeval_signal_safe( """ from cafaeval.evaluation import cafa_eval + # Collected on every run rather than behind a flag. The cost is one array + # per namespace held for the length of the call, and the alternative is a + # setting that is off exactly when someone wants to stratify a result that + # has already been computed. + sink = _new_per_protein_sink() + old_sigterm = signal.signal(signal.SIGTERM, signal.SIG_DFL) old_sigint = signal.signal(signal.SIGINT, signal.SIG_DFL) try: - return cafa_eval( + df, dfs_best = cafa_eval( ctx.obo_path, pred_dir, gt_file, @@ -142,7 +171,9 @@ def _invoke_cafaeval_signal_safe( max_terms=ctx.max_terms, th_step=ctx.th_step, n_cpu=1, + per_protein_sink=sink, ) + return df, dfs_best, sink finally: signal.signal(signal.SIGTERM, old_sigterm) signal.signal(signal.SIGINT, old_sigint) @@ -164,6 +195,64 @@ def _persist_setting_artifacts( _write_results(df, dfs_best, str(setting_dir)) + + +def _persist_per_protein( + ctx: CafaEvalRunContext, + setting: str, + sink: Any, + result: dict[str, Any], + emit: EmitFn, +) -> None: + """Write the per-protein scores beside the setting's other artefacts. + + Never fatal. A run whose aggregate is sound should not be discarded because + the extra table could not be written, and the failure is emitted rather than + swallowed so an absent file is distinguishable from one nobody asked for. + """ + # ``result`` is keyed by the short CAFA code (BPO/MFO/CCO); the sink reports + # cafaeval's long namespace ("biological_process"). Invert the project's own + # mapping rather than writing a second one, so the two cannot drift. + from protea.core.operations._run_cafa_helpers import _NS_LABELS + from protea.core.operations._run_cafa_per_protein import rows_from_sink + + long_for_short = {short: long for long, short in _NS_LABELS.items()} + tau_by_ns = { + long_for_short[ns]: float(v["tau"]) + for ns, v in (result or {}).items() + if ns in long_for_short and isinstance(v, dict) and v.get("tau") is not None + } + try: + rows = rows_from_sink(sink, th_step=ctx.th_step, tau_by_ns=tau_by_ns) + if not rows: + emit( + "run_cafa_evaluation.per_protein_empty", + None, + {"setting": setting, "namespaces": sorted(tau_by_ns)}, + "warning", + ) + return + import pandas as pd + + setting_dir = ctx.artifacts_root / setting + setting_dir.mkdir(parents=True, exist_ok=True) + out = setting_dir / "per_protein.parquet" + pd.DataFrame(rows).to_parquet(out, index=False) + emit( + "run_cafa_evaluation.per_protein_written", + None, + {"setting": setting, "rows": len(rows), "path": str(out)}, + "info", + ) + except Exception as exc: + emit( + "run_cafa_evaluation.per_protein_failed", + None, + {"setting": setting, "error": str(exc)}, + "warning", + ) + + def _run_cafaeval_for_setting( *, setting: str, @@ -179,11 +268,12 @@ def _run_cafaeval_for_setting( """ emit("run_cafa_evaluation.evaluating", None, {"setting": setting}, "info") try: - df, dfs_best = _invoke_cafaeval_signal_safe( + df, dfs_best, sink = _invoke_cafaeval_signal_safe( ctx=ctx, pred_dir=pred_dir, gt_file=gt_file, known_file=known_file ) result = _artifacts.parse_results(dfs_best) _persist_setting_artifacts(ctx, setting, df, dfs_best) + _persist_per_protein(ctx, setting, sink, result, emit) emit( "run_cafa_evaluation.setting_done", None, diff --git a/tests/test_lafa_frame_parity.py b/tests/test_lafa_frame_parity.py index 1e6769ca..87e4683e 100644 --- a/tests/test_lafa_frame_parity.py +++ b/tests/test_lafa_frame_parity.py @@ -200,7 +200,7 @@ class TestSyntheticFrameParity: def test_nk_driver_matches_lafa_invocation(self, synthetic_frame): ctx = _make_ctx(synthetic_frame) - _df, dfs_best = driver._invoke_cafaeval_signal_safe( + _df, dfs_best, _sink = driver._invoke_cafaeval_signal_safe( ctx=ctx, pred_dir=synthetic_frame["pred_dir"], gt_file=synthetic_frame["gt"], @@ -215,7 +215,7 @@ def test_nk_driver_matches_lafa_invocation(self, synthetic_frame): def test_pk_driver_matches_lafa_invocation_with_known_exclusion(self, synthetic_frame): ctx = _make_ctx(synthetic_frame) - _df, dfs_best = driver._invoke_cafaeval_signal_safe( + _df, dfs_best, _sink = driver._invoke_cafaeval_signal_safe( ctx=ctx, pred_dir=synthetic_frame["pred_dir"], gt_file=synthetic_frame["gt"], @@ -232,13 +232,13 @@ def test_known_exclusion_changes_the_score(self, synthetic_frame): floor (which would silently turn PK into NK). """ ctx = _make_ctx(synthetic_frame) - _df_nk, best_nk = driver._invoke_cafaeval_signal_safe( + _df_nk, best_nk, _sink_nk = driver._invoke_cafaeval_signal_safe( ctx=ctx, pred_dir=synthetic_frame["pred_dir"], gt_file=synthetic_frame["gt"], known_file=None, ) - _df_pk, best_pk = driver._invoke_cafaeval_signal_safe( + _df_pk, best_pk, _sink_pk = driver._invoke_cafaeval_signal_safe( ctx=ctx, pred_dir=synthetic_frame["pred_dir"], gt_file=synthetic_frame["gt"], @@ -256,13 +256,13 @@ def test_th_step_is_load_bearing(self, synthetic_frame): """ ctx_lafa = _make_ctx(synthetic_frame, th_step=0.01) ctx_fine = _make_ctx(synthetic_frame, th_step=0.001) - _d1, best_lafa = driver._invoke_cafaeval_signal_safe( + _d1, best_lafa, _sink_lafa = driver._invoke_cafaeval_signal_safe( ctx=ctx_lafa, pred_dir=synthetic_frame["pred_dir"], gt_file=synthetic_frame["gt"], known_file=None, ) - _d2, best_fine = driver._invoke_cafaeval_signal_safe( + _d2, best_fine, _sink_fine = driver._invoke_cafaeval_signal_safe( ctx=ctx_fine, pred_dir=synthetic_frame["pred_dir"], gt_file=synthetic_frame["gt"], @@ -335,7 +335,7 @@ def test_real_lafa_leaderboard_parity(tmp_path: Path): toi_path=toi, shared_pred_dir=str(pred_dir), ) - _df, dfs_best = driver._invoke_cafaeval_signal_safe( + _df, dfs_best, _sink = driver._invoke_cafaeval_signal_safe( ctx=ctx, pred_dir=str(pred_dir), gt_file=gt, known_file=known ) got = _f_micro_w_by_ns(dfs_best) diff --git a/tests/test_per_protein_wiring.py b/tests/test_per_protein_wiring.py new file mode 100644 index 00000000..6efd8d5c --- /dev/null +++ b/tests/test_per_protein_wiring.py @@ -0,0 +1,86 @@ +"""The per-protein table has to actually get written by a real run. + +The transformation layer has its own tests. This one covers the wiring, which +has a different failure mode: everything succeeds, the aggregate is correct, and +the extra table is silently absent or empty. Three ways that happens. + +The namespace keys disagree. ``parse_results`` returns the short CAFA code and +the sink reports cafaeval's long namespace, so a mismatch yields an empty tau +map, no rows, and no file, with nothing anywhere saying why. + +A failure in the extra work takes down the run. The aggregate is the product; a +supplementary table that cannot be written must not discard a sound evaluation. + +An absent file looks the same as one nobody asked for. Both empty and failed +emit, so the two are distinguishable after the fact. +""" + +from __future__ import annotations + +from pathlib import Path +from unittest.mock import MagicMock + +from protea.core.operations._run_cafa_eval_driver import _persist_per_protein +from protea.core.operations._run_cafa_helpers import _NS_LABELS + + +class _Ctx: + def __init__(self, root: Path, th_step: float = 0.01): + self.artifacts_root = root + self.th_step = th_step + + +def _events(emit: MagicMock) -> list[str]: + return [c.args[0] for c in emit.call_args_list] + + +class TestTheNamespaceKeysLineUp: + def test_the_short_codes_parse_results_returns_all_invert(self) -> None: + """If this drifts, the tau map is empty and no table is ever written.""" + short_codes = set(_NS_LABELS.values()) + assert short_codes == {"BPO", "MFO", "CCO"} + assert len(set(_NS_LABELS.keys())) == len(short_codes) + + def test_an_empty_sink_says_so_rather_than_passing_quietly(self, tmp_path) -> None: + emit = MagicMock() + sink = MagicMock(records=[]) + _persist_per_protein( + _Ctx(tmp_path), "nk", sink, {"BPO": {"tau": 0.3}}, emit + ) + assert "run_cafa_evaluation.per_protein_empty" in _events(emit) + assert not list(tmp_path.glob("**/per_protein.parquet")) + + +class TestTheExtraTableNeverTakesDownTheRun: + def test_a_failure_is_emitted_and_swallowed(self, tmp_path) -> None: + """The aggregate is the product; this table is supplementary.""" + emit = MagicMock() + broken = MagicMock() + type(broken).records = property(lambda self: (_ for _ in ()).throw(RuntimeError("boom"))) + _persist_per_protein(_Ctx(tmp_path), "nk", broken, {"BPO": {"tau": 0.3}}, emit) + assert "run_cafa_evaluation.per_protein_failed" in _events(emit) + + def test_a_result_without_any_tau_does_not_raise(self, tmp_path) -> None: + emit = MagicMock() + _persist_per_protein(_Ctx(tmp_path), "nk", MagicMock(records=[]), {}, emit) + assert "run_cafa_evaluation.per_protein_empty" in _events(emit) + + +class TestAWrittenTableIsAnnounced: + def test_it_writes_the_parquet_and_says_where(self, tmp_path) -> None: + import numpy as np + + emit = MagicMock() + sink = MagicMock(records=[{ + "tp_at_tau": np.array([[1.0]]), + "pred_at_tau": np.array([[2.0]]), + "n_gt": np.array([2.0]), + "ids": {"P00001": 0}, + "row_index": np.array([0]), + "ns": "biological_process", + "variant": "weighted", + }]) + _persist_per_protein(_Ctx(tmp_path, th_step=0.5), "nk", sink, + {"BPO": {"tau": 0.5}}, emit) + assert "run_cafa_evaluation.per_protein_written" in _events(emit) + assert (tmp_path / "nk" / "per_protein.parquet").exists()