diff --git a/poetry.lock b/poetry.lock index 3f6fba47..29c45627 100644 --- a/poetry.lock +++ b/poetry.lock @@ -674,8 +674,8 @@ test = ["pytest (>=7)"] [package.source] type = "git" url = "https://github.com/frapercan/cafaeval-protea.git" -reference = "7335b5b779a7d99bc754df5c6a1895b1c502bc8e" -resolved_reference = "7335b5b779a7d99bc754df5c6a1895b1c502bc8e" +reference = "2cb2e66dcde80f22d9fed14f9d5b3a147e1fc160" +resolved_reference = "2cb2e66dcde80f22d9fed14f9d5b3a147e1fc160" [[package]] name = "certifi" @@ -7026,4 +7026,4 @@ files = [ [metadata] lock-version = "2.1" python-versions = ">=3.12,<4.0" -content-hash = "b43c938870a15e48a2b3225e6ce56d4b121e3dc8d1c8a01f63e6e01be53a720c" +content-hash = "d12d5ca14b91d14463eeec3853c80694133666677069314e86a4365f96fc5016" diff --git a/protea/core/operations/_run_cafa_per_protein.py b/protea/core/operations/_run_cafa_per_protein.py new file mode 100644 index 00000000..5f0b2439 --- /dev/null +++ b/protea/core/operations/_run_cafa_per_protein.py @@ -0,0 +1,105 @@ +"""Persist the per-protein scores cafaeval would otherwise reduce away. + +The evaluation reports one number per (category, aspect) cell. Three of the axes +this project is required to report, sequence length, identity to the nearest +donor and taxonomic relation to it, are properties of a PROTEIN, not of a cell, +so none of them can be recovered from the stored aggregate however it is sliced. + +cafaeval computes the per-protein vectors and collapses them with +``.sum(axis=0)``. Its ``PerProteinSink`` hands them over before that happens. +This module turns one sink into a parquet artifact next to the run's other +outputs, keyed by accession so it joins to ``protein.length`` and to the donor +identities in ``go_prediction``. + +A parquet artifact rather than a table on purpose: a table would need a +migration, and migrations here are validated offline and never applied to the +live store as a side effect of an evaluation. +""" + +from __future__ import annotations + +from typing import Any + +import numpy as np + + +#: cafaeval builds its thresholds as ``np.arange(th_step, 1, th_step)``. We +#: rebuild the same vector to find which column the reported tau sits in, and +#: assert the width matches rather than trusting the reconstruction: a silent +#: off-by-one here would attribute every protein the score of a neighbouring +#: threshold, which reads as a plausible number. +def _tau_array(th_step: float) -> np.ndarray: + return np.arange(th_step, 1, th_step) + + +class PerProteinShapeError(RuntimeError): + """The rebuilt threshold vector does not match the emitted arrays.""" + + +def _column_for_tau(th_step: float, width: int, tau: float) -> int: + tau_arr = _tau_array(th_step) + if len(tau_arr) != width: + raise PerProteinShapeError( + f"rebuilt {len(tau_arr)} thresholds from th_step={th_step} but the " + f"emitted arrays are {width} wide; refusing to guess which column " + f"the reported tau is in" + ) + return int(np.argmin(np.abs(tau_arr - tau))) + + +def _accessions_for(record: dict[str, Any], n_rows: int) -> list[str] | None: + """Name each array row, or return None when the record cannot be keyed. + + ``ids`` maps accession to the ground truth's row number; ``row_index`` maps + array row to that same numbering, and the two differ whenever the kernel was + handed a subset. Both are required: a record carrying one without the other + cannot be joined and is dropped rather than written under a guess. + """ + ids, row_index = record.get("ids"), record.get("row_index") + if not ids or row_index is None or len(row_index) != n_rows: + return None + by_index = {int(v): k for k, v in ids.items()} + out = [by_index.get(int(i)) for i in row_index] + return None if any(a is None for a in out) else out # type: ignore[return-value] + + +def rows_from_sink(sink: Any, *, th_step: float, tau_by_ns: dict[str, float]) -> list[dict]: + """Flatten a sink into per-(namespace, protein) rows at the reported tau. + + Only the weighted variant is kept: it is the one carrying ``f_micro_w``, + which is the metric every published cell in this project reports. + """ + rows: list[dict] = [] + for rec in getattr(sink, "records", []): + if rec.get("variant") != "weighted": + continue + ns = rec.get("ns") + tau = tau_by_ns.get(str(ns)) + if tau is None: + continue + tp, pred = rec["tp_at_tau"], rec["pred_at_tau"] + col = _column_for_tau(th_step, tp.shape[1], tau) + accs = _accessions_for(rec, tp.shape[0]) + if accs is None: + continue + n_gt = np.asarray(rec["n_gt"], dtype=np.float64) + tp_c, pred_c = tp[:, col], pred[:, col] + prec = np.where(pred_c > 0, tp_c / np.where(pred_c > 0, pred_c, 1.0), 0.0) + rec_c = np.where(n_gt > 0, tp_c / np.where(n_gt > 0, n_gt, 1.0), 0.0) + denom = prec + rec_c + f = np.where(denom > 0, 2 * prec * rec_c / np.where(denom > 0, denom, 1.0), 0.0) + for i, acc in enumerate(accs): + rows.append( + { + "protein_accession": acc, + "namespace": str(ns), + "tau": float(tau), + "tp_w": float(tp_c[i]), + "pred_w": float(pred_c[i]), + "n_gt_w": float(n_gt[i]), + "precision_w": float(prec[i]), + "recall_w": float(rec_c[i]), + "f_w": float(f[i]), + } + ) + return rows diff --git a/pyproject.toml b/pyproject.toml index 5c2121a0..8fc3c22e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,7 +29,7 @@ dependencies = [ "faiss-cpu (>=1.7.0)", "parasail (>=1.3.4)", "ete3 (>=3.1.3)", - "cafaeval-protea @ git+https://github.com/frapercan/cafaeval-protea.git@7335b5b779a7d99bc754df5c6a1895b1c502bc8e", + "cafaeval-protea @ git+https://github.com/frapercan/cafaeval-protea.git@2cb2e66dcde80f22d9fed14f9d5b3a147e1fc160", "lightgbm (>=4.6.0,<5.0.0)", "pyarrow (>=23.0.1,<24.0.0)", "httpx (>=0.28.1,<0.29.0)", diff --git a/tests/test_per_protein_scores.py b/tests/test_per_protein_scores.py new file mode 100644 index 00000000..727778e0 --- /dev/null +++ b/tests/test_per_protein_scores.py @@ -0,0 +1,128 @@ +"""Per-protein scores must be keyed, aligned, and refuse to guess. + +This is the layer that turns cafaeval's per-protein vectors into something +joinable to sequence length, donor identity and taxonomic relation. Three ways +it could quietly produce a wrong table, and a test for each: + +1. reading the wrong threshold column, which gives every protein a neighbouring + threshold's score; +2. naming rows by the wrong protein, which is the positional misalignment that + cost this project a fortnight in its neighbour search; +3. writing rows for a record it cannot key, which produces a table that looks + complete and is not. +""" + +from __future__ import annotations + +import numpy as np +import pytest + +from protea.core.operations._run_cafa_per_protein import ( + PerProteinShapeError, + _column_for_tau, + rows_from_sink, +) + + +class _Sink: + def __init__(self, records): + self.records = records + + +def _record(*, tp, pred, n_gt, ids=None, row_index=None, ns="biological_process", + variant="weighted"): + return { + "tp_at_tau": np.asarray(tp, dtype=float), + "pred_at_tau": np.asarray(pred, dtype=float), + "n_gt": np.asarray(n_gt, dtype=float), + "ids": ids, + "row_index": None if row_index is None else np.asarray(row_index), + "ns": ns, + "variant": variant, + } + + +class TestTheThresholdColumnIsFoundNotGuessed: + def test_it_locates_the_reported_tau(self) -> None: + # th_step 0.25 gives thresholds 0.25, 0.50, 0.75 + assert _column_for_tau(0.25, 3, 0.50) == 1 + + def test_a_width_mismatch_raises_rather_than_picking_a_column(self) -> None: + """A silent off-by-one would score every protein at the wrong threshold.""" + with pytest.raises(PerProteinShapeError, match="refusing to guess"): + _column_for_tau(0.25, 7, 0.50) + + +class TestRowsAreKeyedByTheRightProtein: + def test_row_index_maps_arrays_back_to_accessions(self) -> None: + """The PK kernel is handed a subset, so array row 0 is not protein 0.""" + rec = _record( + tp=[[2.0]], pred=[[4.0]], n_gt=[4.0], + ids={"P00001": 0, "P00002": 1, "P00003": 2}, + row_index=[2], # the array holds only the third protein + ) + rows = rows_from_sink(_Sink([rec]), th_step=0.5, tau_by_ns={"biological_process": 0.5}) + assert [r["protein_accession"] for r in rows] == ["P00003"] + + def test_a_record_without_identity_is_dropped_not_invented(self) -> None: + rec = _record(tp=[[1.0]], pred=[[2.0]], n_gt=[2.0], ids=None, row_index=None) + assert rows_from_sink(_Sink([rec]), th_step=0.5, tau_by_ns={"biological_process": 0.5}) == [] + + def test_a_row_index_of_the_wrong_length_is_dropped(self) -> None: + """Better no rows than rows whose keys do not line up with their scores.""" + rec = _record(tp=[[1.0], [1.0]], pred=[[2.0], [2.0]], n_gt=[2.0, 2.0], + ids={"P1": 0, "P2": 1}, row_index=[0]) + assert rows_from_sink(_Sink([rec]), th_step=0.5, tau_by_ns={"biological_process": 0.5}) == [] + + +class TestOnlyTheMetricWeReportIsKept: + def test_the_unweighted_variant_is_skipped(self) -> None: + """Every published cell in this project reports f_micro_w.""" + rec = _record(tp=[[1.0]], pred=[[2.0]], n_gt=[2.0], ids={"P1": 0}, + row_index=[0], variant="unweighted") + assert rows_from_sink(_Sink([rec]), th_step=0.5, tau_by_ns={"biological_process": 0.5}) == [] + + def test_a_namespace_with_no_reported_tau_is_skipped(self) -> None: + rec = _record(tp=[[1.0]], pred=[[2.0]], n_gt=[2.0], ids={"P1": 0}, row_index=[0]) + assert rows_from_sink(_Sink([rec]), th_step=0.5, tau_by_ns={}) == [] + + +class TestTheArithmeticIsTheOneTheAggregateUses: + def test_precision_recall_and_f_are_the_standard_definitions(self) -> None: + rec = _record(tp=[[3.0]], pred=[[4.0]], n_gt=[6.0], ids={"P1": 0}, row_index=[0]) + row = rows_from_sink(_Sink([rec]), th_step=0.5, tau_by_ns={"biological_process": 0.5})[0] + assert row["precision_w"] == pytest.approx(0.75) + assert row["recall_w"] == pytest.approx(0.5) + assert row["f_w"] == pytest.approx(2 * 0.75 * 0.5 / 1.25) + + def test_a_protein_that_predicted_nothing_scores_zero_not_nan(self) -> None: + """NaN would propagate into every stratum mean that contains it.""" + rec = _record(tp=[[0.0]], pred=[[0.0]], n_gt=[3.0], ids={"P1": 0}, row_index=[0]) + row = rows_from_sink(_Sink([rec]), th_step=0.5, tau_by_ns={"biological_process": 0.5})[0] + assert row["precision_w"] == 0.0 + assert row["f_w"] == 0.0 + + def test_a_protein_with_no_ground_truth_scores_zero_not_nan(self) -> None: + rec = _record(tp=[[0.0]], pred=[[2.0]], n_gt=[0.0], ids={"P1": 0}, row_index=[0]) + row = rows_from_sink(_Sink([rec]), th_step=0.5, tau_by_ns={"biological_process": 0.5})[0] + assert row["recall_w"] == 0.0 + assert row["f_w"] == 0.0 + + +def test_the_column_sums_reproduce_what_the_aggregate_would_report() -> None: + """The property that makes a stratified table trustworthy. + + If the per-protein rows do not sum to the totals the aggregate is built + from, the strata and the headline are two different measurements wearing one + name. Here the sum of tp and pred across proteins must equal the column the + kernel reduced. + """ + # th_step 0.4 gives thresholds 0.4 and 0.8, so two columns. Picking a + # th_step whose threshold count does not match the array width is what the + # shape guard exists to catch, and it caught an earlier draft of this test. + tp = np.array([[1.0, 2.0], [3.0, 4.0]]) + pred = np.array([[2.0, 4.0], [4.0, 8.0]]) + rec = _record(tp=tp, pred=pred, n_gt=[2.0, 4.0], ids={"P1": 0, "P2": 1}, row_index=[0, 1]) + rows = rows_from_sink(_Sink([rec]), th_step=0.4, tau_by_ns={"biological_process": 0.4}) + assert sum(r["tp_w"] for r in rows) == tp[:, 0].sum() + assert sum(r["pred_w"] for r in rows) == pred[:, 0].sum()