Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 79 additions & 5 deletions src/cafaeval/evaluation.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,50 @@
_eval_logger.addHandler(logging.NullHandler())

# Return a mask for all the predictions (matrix) >= tau
class PerProteinSink:
"""Optional side channel for the per-protein vectors the kernels reduce away.

The confusion-matrix kernels build ``tp_at_tau`` and ``pred_at_tau`` with one
row per protein and then collapse them with ``.sum(axis=0)``. Everything
downstream sees only the collapsed number, so a caller wanting to report a
score stratified by a per-protein property (length, homology to the donor
bank, taxonomic distance) has nothing to stratify.

This is a sink rather than a return value on purpose. Changing the return
shape of the kernels would ripple through compute_metrics,
evaluate_prediction and cafa_eval, and every existing caller of each. An
optional keyword that defaults to None leaves all four signatures and all
four return types exactly as they were: when nobody passes a sink, nothing
in this module behaves differently.

The arrays handed over are the ones the aggregate was computed from, not a
recomputation, so a caller can verify that their column sums reproduce the
published totals. ``test_per_protein_sink`` does exactly that, because two
numbers describing the same quantity by different routes will drift unless
something checks.
"""

__slots__ = ("records",)

def __init__(self):
self.records = []

def record(self, *, tp_at_tau, pred_at_tau, n_gt, protein_rows=None):
"""Store one kernel's per-protein arrays.

Copies are taken: the kernels reuse and mutate their buffers, and a sink
holding a view would silently change under the caller.
"""
self.records.append(
{
"tp_at_tau": np.asarray(tp_at_tau, dtype=np.float64).copy(),
"pred_at_tau": np.asarray(pred_at_tau, dtype=np.float64).copy(),
"n_gt": np.asarray(n_gt).copy(),
"protein_rows": None if protein_rows is None else np.asarray(protein_rows).copy(),
}
)


def solidify_prediction(pred, tau):
return pred >= tau

Expand Down Expand Up @@ -146,7 +190,8 @@ def compute_confusion_matrix_exclude(tau_arr, g_perprotein, pred_matrix, toi_per

return metrics

def compute_confusion_matrix_sparse(tau_arr, g, pred_matrix, toi, n_gt, ic_arr=None):
def compute_confusion_matrix_sparse(tau_arr, g, pred_matrix, toi, n_gt, ic_arr=None,
per_protein_sink=None):
"""Sparse alternative to :func:`compute_confusion_matrix`.

Scatters each non-zero prediction into the highest tau bin at which it is
Expand Down Expand Up @@ -243,11 +288,17 @@ def compute_confusion_matrix_sparse(tau_arr, g, pred_matrix, toi, n_gt, ic_arr=N
recall = np.where(n_gt_col > 0, tp_at_tau / safe_gt, 0.0)
metrics[:, 5] = recall.sum(axis=0)

# Handed over BEFORE returning, and after the aggregate has been computed
# from these same arrays, so a caller can check the two agree.
if per_protein_sink is not None:
per_protein_sink.record(tp_at_tau=tp_at_tau, pred_at_tau=pred_at_tau, n_gt=n_gt)

return metrics


def compute_confusion_matrix_exclude_sparse(
tau_arr, pred_sub, gt_sub, toi_mask, excluded_mask, n_gt, ic_arr=None
tau_arr, pred_sub, gt_sub, toi_mask, excluded_mask, n_gt, ic_arr=None,
per_protein_sink=None,
):
"""Sparse alternative to :func:`compute_confusion_matrix_exclude`.

Expand Down Expand Up @@ -360,6 +411,15 @@ def compute_confusion_matrix_exclude_sparse(
recall = np.where(n_gt_col > 0, tp_at_tau / safe_gt, 0.0)
metrics[:, 5] = recall.sum(axis=0)

# PK also hands over which rows were eligible: this kernel can be given a
# protein subset, so a caller stratifying by protein needs to know which
# rows the arrays refer to rather than assuming they are the whole set.
if per_protein_sink is not None:
per_protein_sink.record(
tp_at_tau=tp_at_tau, pred_at_tau=pred_at_tau, n_gt=n_gt,
protein_rows=eligible_rows,
)

return metrics


Expand Down Expand Up @@ -406,7 +466,8 @@ def _cme_worker(tau_chunk):
tau_chunk, _CME_G, _CME_P, _CME_TOI, _CME_N_GT, _CME_IC
)

def compute_metrics(pred, gt_matrix, tau_arr, toi, gt_exclude=None, ic_arr=None, n_cpu=0):
def compute_metrics(pred, gt_matrix, tau_arr, toi, gt_exclude=None, ic_arr=None, n_cpu=0,
per_protein_sink=None):
"""
Takes the prediction and the ground truth and for each threshold in tau_arr
calculates the confusion matrix and returns the coverage,
Expand Down Expand Up @@ -551,11 +612,23 @@ def compute_metrics(pred, gt_matrix, tau_arr, toi, gt_exclude=None, ic_arr=None,
else:
n_gt = (g * ic_arr[toi]).sum(axis=1)

# The dense fallback fans tau chunks over a fork pool, so the per-protein
# arrays live in worker processes and never come back. Refuse rather than
# return an empty sink: a caller that asked for stratification and silently
# got none would publish a stratified table with no data behind it.
if per_protein_sink is not None and not use_sparse:
raise NotImplementedError(
"per_protein_sink is only supported by the sparse kernels; unset "
"CAFAEVAL_SPARSE=0 to use it."
)

t1 = time.time()
if gt_exclude is None and use_sparse:
# Sparse kernel: single-pass scatter + cumsum. No pool needed — the
# kernel is fast enough that fork overhead would dominate.
metrics = compute_confusion_matrix_sparse(tau_arr, g, p, toi, n_gt, ic_arr)
metrics = compute_confusion_matrix_sparse(
tau_arr, g, p, toi, n_gt, ic_arr, per_protein_sink=per_protein_sink
)
elif gt_exclude is None:
# Dense fallback kernel (opt-in, CAFAEVAL_SPARSE=0) needs a dense
# prediction; densify the CSR just for this path.
Expand All @@ -574,7 +647,8 @@ def compute_metrics(pred, gt_matrix, tau_arr, toi, gt_exclude=None, ic_arr=None,
else:
pred_sub = pred[proteins_has_gt, :]
metrics = compute_confusion_matrix_exclude_sparse(
tau_arr, pred_sub, gt_with_annots, toi_mask, excluded_mask, n_gt, ic_arr
tau_arr, pred_sub, gt_with_annots, toi_mask, excluded_mask, n_gt, ic_arr,
per_protein_sink=per_protein_sink,
)
else:
# Dense fallback: fan out tau chunks over a fork pool using the
Expand Down
108 changes: 108 additions & 0 deletions tests/test_per_protein_sink.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
"""The per-protein vectors must agree with the aggregate they were reduced into.

The kernels build ``tp_at_tau`` and ``pred_at_tau`` per protein and collapse them
with ``.sum(axis=0)``. Emitting the uncollapsed arrays lets a caller stratify a
score by a per-protein property, which is the whole reason the sink exists.

Two properties matter and neither is obvious from reading the code.

First, passing no sink must change nothing at all. An optional feature that
perturbs the default path is worse than no feature, because every number already
published would have to be re-derived to find out whether it moved.

Second, the emitted arrays must reproduce the published totals exactly. Two
routes to the same quantity drift unless something checks, and a stratified
table whose cells do not sum to the headline is worse than no stratified table.
"""

from __future__ import annotations

import numpy as np
from scipy.sparse import csr_matrix

from cafaeval.evaluation import (
PerProteinSink,
compute_confusion_matrix_sparse,
)


def _toy():
"""Five proteins, four terms, a handful of thresholds."""
rng = np.random.default_rng(0)
n_prot, n_terms = 5, 4
pred = csr_matrix(np.round(rng.random((n_prot, n_terms)), 2))
gt = (rng.random((n_prot, n_terms)) > 0.5).astype(np.float64)
toi = np.arange(n_terms)
n_gt = gt[:, toi].sum(axis=1)
tau = np.round(np.arange(0.1, 1.0, 0.1), 2)
return tau, gt, pred, toi, n_gt


class TestTheDefaultPathIsUntouched:
def test_no_sink_gives_the_same_metrics_as_before(self) -> None:
tau, gt, pred, toi, n_gt = _toy()
a = compute_confusion_matrix_sparse(tau, gt, pred, toi, n_gt)
b = compute_confusion_matrix_sparse(tau, gt, pred, toi, n_gt, None, None)
np.testing.assert_array_equal(a, b)

def test_passing_a_sink_does_not_change_the_metrics(self) -> None:
"""The sink observes; it must not participate."""
tau, gt, pred, toi, n_gt = _toy()
without = compute_confusion_matrix_sparse(tau, gt, pred, toi, n_gt)
sink = PerProteinSink()
with_sink = compute_confusion_matrix_sparse(
tau, gt, pred, toi, n_gt, per_protein_sink=sink
)
np.testing.assert_array_equal(without, with_sink)


class TestTheEmittedArraysReproduceTheAggregate:
def test_the_sink_receives_one_record(self) -> None:
tau, gt, pred, toi, n_gt = _toy()
sink = PerProteinSink()
compute_confusion_matrix_sparse(tau, gt, pred, toi, n_gt, per_protein_sink=sink)
assert len(sink.records) == 1

def test_the_shape_is_one_row_per_protein(self) -> None:
tau, gt, pred, toi, n_gt = _toy()
sink = PerProteinSink()
compute_confusion_matrix_sparse(tau, gt, pred, toi, n_gt, per_protein_sink=sink)
rec = sink.records[0]
assert rec["tp_at_tau"].shape == (gt.shape[0], len(tau))
assert rec["pred_at_tau"].shape == (gt.shape[0], len(tau))

def test_the_column_sums_are_the_published_totals(self) -> None:
"""The property the whole feature rests on."""
tau, gt, pred, toi, n_gt = _toy()
sink = PerProteinSink()
metrics = compute_confusion_matrix_sparse(
tau, gt, pred, toi, n_gt, per_protein_sink=sink
)
rec = sink.records[0]
tp_totals = rec["tp_at_tau"].sum(axis=0)
pred_totals = rec["pred_at_tau"].sum(axis=0)
np.testing.assert_allclose(metrics[:, 1], tp_totals, rtol=0, atol=1e-12)
np.testing.assert_allclose(metrics[:, 2], pred_totals - tp_totals, rtol=0, atol=1e-12)

def test_the_coverage_column_is_the_count_of_predicting_proteins(self) -> None:
tau, gt, pred, toi, n_gt = _toy()
sink = PerProteinSink()
metrics = compute_confusion_matrix_sparse(
tau, gt, pred, toi, n_gt, per_protein_sink=sink
)
rec = sink.records[0]
np.testing.assert_array_equal(
metrics[:, 0], (rec["pred_at_tau"] > 0).sum(axis=0)
)


class TestTheSinkOwnsItsData:
def test_the_arrays_are_copies_not_views(self) -> None:
"""The kernels reuse buffers; a view would change under the caller."""
tau, gt, pred, toi, n_gt = _toy()
sink = PerProteinSink()
compute_confusion_matrix_sparse(tau, gt, pred, toi, n_gt, per_protein_sink=sink)
rec = sink.records[0]
before = rec["tp_at_tau"].copy()
compute_confusion_matrix_sparse(tau, gt, pred, toi, n_gt, per_protein_sink=sink)
np.testing.assert_array_equal(rec["tp_at_tau"], before)
Loading