Download tests/test_evaluation.py from ImmunocanAI/CLC-mini-bench: direct link, hf CLI and curl.
- Browser
- Download file 5.94 kB
-
https://huggingface.co/datasets/ImmunocanAI/CLC-mini-bench/resolve/main/tests/test_evaluation.py
- Command line
-
hf download hf://datasets/ImmunocanAI/CLC-mini-bench/tests/test_evaluation.py
-
curl -L -o test_evaluation.py https://huggingface.co/datasets/ImmunocanAI/CLC-mini-bench/resolve/main/tests/test_evaluation.py
5.94 kB
| import json | |
| import sys | |
| import types | |
| import numpy as np | |
| import pandas as pd | |
| import pytest | |
| from clc_mini_bench.data import ROOT, grouped_folds, load_protocol, sample_id, validate_dataset | |
| from clc_mini_bench.embeddings import mean_pool, extract_embeddings | |
| from clc_mini_bench.evaluation import evaluate_matrix, inner_fold_splits, load_features | |
| def synthetic_dataset(n_outer=5): | |
| # Synthetic numbers only: no encoder or real NKp46 evaluation is run here. | |
| aas = "ACDEFGHIKLMNPQRSTVWY" | |
| records = [] | |
| for i in range(24): | |
| vh = "ACDEFG" + aas[i // 20] + aas[i % 20] | |
| p = 6.0 + i / 20 | |
| records.append({"sample_id": sample_id("synthetic", vh, "GGGG"), | |
| "clone_id": str(i), "VH": vh, "VL": "GGGG", "platform": "synthetic", | |
| "pKD": p, "KD_M": 10 ** -p, "family_id": f"f_{i // 2}"}) | |
| frame = pd.DataFrame(records) | |
| frame["fold_id"] = grouped_folds(frame.family_id.tolist(), n_outer, 42) | |
| return frame | |
| def test_outer_test_labels_cannot_affect_its_predictions_or_selected_alpha(n_outer): | |
| df = synthetic_dataset(n_outer) | |
| x = np.random.default_rng(12).normal(size=(len(df), 5)) | |
| protocol = load_protocol() | |
| protocol["evaluation"]["ridge_alphas"] = [0.1, 10] | |
| original, report = evaluate_matrix(df, x, protocol) | |
| altered = df.copy() | |
| held = altered.fold_id.eq(0) | |
| altered.loc[held, "pKD"] += 4 | |
| altered.loc[held, "KD_M"] = 10 ** -altered.loc[held, "pKD"] | |
| poisoned, _ = evaluate_matrix(altered, x, protocol) | |
| assert np.allclose(original.loc[held, "prediction"], poisoned.loc[held, "prediction"]) | |
| assert np.array_equal(original.loc[held, "selected_alpha"], poisoned.loc[held, "selected_alpha"]) | |
| assert not original.prediction.isna().any() | |
| assert report["pooled_out_of_fold"]["n"] == len(df) | |
| for fold_report in report["outer_folds"]: | |
| assert fold_report["inner_folds"] == n_outer - 1 | |
| assert fold_report["inner_validation_fold_ids"] == sorted(set(df.fold_id) - {fold_report["fold_id"]}) | |
| def test_real_data_inner_validation_reuses_remaining_outer_folds_without_family_overlap(platform): | |
| # Inspect actual split membership only; fit no predictor on the benchmark data. | |
| df = pd.read_csv(ROOT / f"data/processed/{platform}_nkp46.csv") | |
| validate_dataset(df) | |
| for held in range(5): | |
| pool = df.loc[df.fold_id != held].reset_index(drop=True) | |
| outer_test = df.loc[df.fold_id == held] | |
| splits = inner_fold_splits(pool.fold_id.to_numpy()) | |
| assert len(splits) == 4 | |
| validation_rows = [] | |
| for val_fold, (train, val) in zip(sorted(set(range(5)) - {held}), splits): | |
| expected_ids = set(df.loc[df.fold_id == val_fold, "sample_id"]) | |
| assert set(pool.iloc[val].sample_id) == expected_ids | |
| assert set(pool.iloc[train].fold_id) == set(range(5)) - {held, val_fold} | |
| assert set(train).isdisjoint(val) | |
| assert set(train) | set(val) == set(range(len(pool))) | |
| assert set(pool.iloc[train].family_id).isdisjoint(pool.iloc[val].family_id) | |
| assert set(pool.family_id).isdisjoint(outer_test.family_id) | |
| validation_rows.extend(val) | |
| assert sorted(validation_rows) == list(range(len(pool))) | |
| def test_embedding_alignment_uses_ids_and_rejects_missing_or_extra_ids(tmp_path): | |
| df = synthetic_dataset() | |
| path = tmp_path / "features.npz" | |
| values = np.arange(len(df) * 3).reshape(len(df), 3) | |
| np.savez(path, sample_ids=df.sample_id.to_numpy(dtype=str)[::-1], embeddings=values[::-1]) | |
| assert np.array_equal(load_features(path, df), values) | |
| np.savez(path, sample_ids=df.sample_id.to_numpy(dtype=str)[:-1], embeddings=values[:-1]) | |
| with pytest.raises(ValueError, match="match this dataset"): | |
| load_features(path, df) | |
| def test_pooling_excludes_special_tokens_and_padding(): | |
| states = np.array([[[1000, 1000], [1, 3], [3, 5], [1000, 1000], [5000, 5000]]], dtype=float) | |
| mask = np.array([[False, True, True, False, False]]) | |
| assert np.allclose(mean_pool(states, mask), [[2, 4]]) | |
| with pytest.raises(ValueError, match="Empty"): | |
| mean_pool(states, np.zeros_like(mask)) | |
| def test_custom_adapter_gets_only_sequences_and_preserves_sample_alignment(tmp_path, monkeypatch): | |
| df = synthetic_dataset() | |
| dataset = tmp_path / "synthetic.csv" | |
| df.to_csv(dataset, index=False) | |
| output = tmp_path / "synthetic.npz" | |
| calls = [] | |
| module = types.ModuleType("synthetic_adapter") | |
| def encode(records, *, batch_size): | |
| calls.append(batch_size) | |
| assert all(set(row) == {"sample_id", "VH", "VL"} for row in records) | |
| return [[ord(row["VH"][-1]), len(row["VH"])] for row in records] | |
| module.encode = encode | |
| monkeypatch.setitem(sys.modules, "synthetic_adapter", module) | |
| meta = extract_embeddings(dataset, output, adapter="synthetic_adapter:encode", batch_size=7) | |
| expected = [[ord(vh[-1]), len(vh)] for vh in df.VH] | |
| assert np.array_equal(load_features(output, df), expected) | |
| assert meta["dimensions"] == 2 | |
| assert json.loads(output.with_suffix(".json").read_text()) == meta | |
| with pytest.raises(ValueError, match="new embedding output"): | |
| extract_embeddings(dataset, output, adapter="synthetic_adapter:encode") | |
| assert calls == [7] | |
| def test_empty_custom_embeddings_are_rejected_before_writing(tmp_path, monkeypatch): | |
| dataset = tmp_path / "synthetic.csv" | |
| synthetic_dataset().to_csv(dataset, index=False) | |
| module = types.ModuleType("empty_adapter") | |
| module.encode = lambda records, **kwargs: np.empty((len(records), 0)) | |
| monkeypatch.setitem(sys.modules, "empty_adapter", module) | |
| output = tmp_path / "empty.npz" | |
| with pytest.raises(ValueError, match="finite N x D"): | |
| extract_embeddings(dataset, output, adapter="empty_adapter:encode") | |
| assert not output.exists() | |