File size: 11,256 Bytes
3f97185 aa6c487 3f97185 ec31236 3f97185 ec31236 3f97185 aa6c487 ec31236 aa6c487 03147a3 aa6c487 ec31236 aa6c487 03147a3 ec31236 03147a3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | import json
import numpy as np
import pandas as pd
import pytest
from clc_mini_bench.data import (
ROOT, assign_families, assign_folds, build, gene_candidates, grouped_folds,
load_protocol, merge_measurements, validate_dataset,
)
def test_duplicate_measurements_aggregate_in_pkd_space():
raw = pd.DataFrame([
{"clone_id": "a", "platform": "P", "VH": "ACDEF", "VL": "GGGG", "KD_M": 1e-9, "source_table": "5"},
{"clone_id": "b", "platform": "P", "VH": "ACDEF", "VL": "GGGG", "KD_M": 1e-7, "source_table": "5"},
])
frame = merge_measurements(raw)
assert len(frame) == 1
assert frame.iloc[0].pKD == pytest.approx(8.0)
assert frame.iloc[0].KD_M == pytest.approx(1e-8)
assert frame.iloc[0].clone_id == "a|b"
assert frame.iloc[0].measurement_count == 2
def test_invalid_affinity_and_duplicate_ids_rejected():
raw = pd.DataFrame([{"clone_id": "a", "platform": "P", "VH": "ACDEF", "VL": "GGGG", "KD_M": 0, "source_table": "5"}])
with pytest.raises(ValueError, match="positive"):
merge_measurements(raw)
raw.KD_M = 1e-8
with pytest.raises(ValueError, match="Duplicate clone"):
merge_measurements(pd.concat([raw, raw]))
def test_single_linkage_gene_and_length_constraints():
frame = pd.DataFrame([
{"sample_id": "a", "platform": "P", "V_gene": "V1;V2", "J_gene": "J1", "CDRH3": "AAAA"},
{"sample_id": "b", "platform": "P", "V_gene": "V2", "J_gene": "J1", "CDRH3": "AACC"},
{"sample_id": "c", "platform": "P", "V_gene": "V2", "J_gene": "J1", "CDRH3": "CCCC"},
{"sample_id": "d", "platform": "P", "V_gene": "V3", "J_gene": "J1", "CDRH3": "AAAA"},
{"sample_id": "e", "platform": "P", "V_gene": "V1", "J_gene": "J2", "CDRH3": "AAAA"},
{"sample_id": "f", "platform": "P", "V_gene": "V1", "J_gene": "J1", "CDRH3": "AAAAA"},
{"sample_id": "g", "platform": "Q", "V_gene": "V1", "J_gene": "J1", "CDRH3": "AAAA"},
])
result = assign_families(frame).set_index("sample_id")
assert result.loc["a", "family_id"] == result.loc["b", "family_id"] == result.loc["c", "family_id"]
assert result.family_id.nunique() == 5
assert gene_candidates("IGHV1-1*01_IGHV1-1*02_IGHV2-1*01") == {"IGHV1-1", "IGHV2-1"}
def test_folds_are_reproducible_group_disjoint_and_row_order_independent():
groups = ["a"] * 8 + ["b"] * 6 + ["c"] * 4 + ["d", "e", "f", "g", "h"]
ids = grouped_folds(groups, 5, 42)
assert np.array_equal(ids, grouped_folds(groups, 5, 42))
mapping = dict(zip(groups, ids))
shuffled = list(reversed(groups))
assert [mapping[g] for g in shuffled] == grouped_folds(shuffled, 5, 42).tolist()
assert set(ids) == set(range(5))
for g in set(groups):
assert len(set(ids[np.array(groups) == g])) == 1
def test_checked_in_source_data_and_prepared_data():
raw = pd.read_csv(ROOT / "data/raw/measurements.csv", dtype={"clone_id": str})
assert raw.groupby("platform").size().to_dict() == {"OmniClic": 170, "OmniFlic": 245}
assert not raw.duplicated(["platform", "clone_id"]).any()
expected = {"omniclic": 161, "omniflic": 213}
for name, n in expected.items():
frame = pd.read_csv(ROOT / f"data/processed/{name}_nkp46.csv")
validate_dataset(frame)
assert len(frame) == n
assert frame.fold_id.nunique() == 5
replay = assign_folds(frame.drop(columns="fold_id"), load_protocol())
assert np.array_equal(replay.fold_id, frame.fold_id)
excluded = pd.read_csv(ROOT / "data/processed/excluded.csv", dtype={"clone_id": str}).set_index("clone_id")
assert set(excluded.index) == {"Gen_1", "50"}
assert excluded.loc["Gen_1", "numbering_end"] == 121
assert excluded.loc["50", "exclusion_reason"] == "excluded_sequence_group"
def test_source_sequences_use_filed_xml_and_match_filed_cdrs():
import xml.etree.ElementTree as ET
root = ET.parse(ROOT / "data/raw/OMNI-002WO_SEQLIST.xml").getroot()
sequences = {int(e.attrib["sequenceIDNumber"]): e.findtext("INSDSeq/INSDSeq_sequence") for e in root.findall("SequenceData")}
raw = pd.read_csv(ROOT / "data/raw/measurements.csv", dtype={"clone_id": str})
for row in raw.itertuples(index=False):
assert sequences[row.vh_seq_id] == row.VH
assert sequences[row.vl_seq_id] == row.VL
assert sequences[row.cdr3_seq_id] == row.patent_CDRH3
assert row.patent_CDRH3 in row.VH
verification = json.loads((ROOT / "data/raw/full_vh_verification.json").read_text())
assert verification["verified_clone_to_full_VH_SEQ_ID_count"] == 415
def test_build_omniclic_uses_only_non_v2_measurements(tmp_path):
raw = pd.read_csv(ROOT / "data/raw/measurements.csv", dtype={"clone_id": str})
manifest = build(ROOT / "data/raw/measurements.csv", tmp_path)
frame = pd.read_csv(tmp_path / "omniclic_nkp46.csv", dtype={"clone_id": str})
original = raw.loc[raw.platform.eq("OmniClic") & ~raw.clone_id.str.endswith("_v2") & raw.clone_id.ne("50")].set_index("clone_id")
assert len(original) == len(frame) == 161
assert set(frame.clone_id) == set(original.index)
assert frame.measurement_count.eq(1).all()
assert not frame.clone_id.str.contains("_v2", regex=False).any()
np.testing.assert_allclose(frame.KD_M, original.loc[frame.clone_id, "KD_M"], rtol=1e-10, atol=0)
np.testing.assert_allclose(frame.pKD, -np.log10(original.loc[frame.clone_id, "KD_M"]), rtol=1e-10, atol=0)
expected_excluded = set(raw.loc[raw.platform.eq("OmniClic") & raw.clone_id.str.endswith("_v2"), "clone_id"])
excluded_all = pd.read_csv(tmp_path / "excluded_measurements.csv", dtype={"clone_id": str})
excluded = excluded_all.loc[excluded_all.platform.eq("OmniClic")]
assert len(excluded) == len(expected_excluded) == 8
assert set(excluded.clone_id) == expected_excluded
index = pd.read_csv(tmp_path / "clone_to_sample.csv", dtype={"clone_id": str})
assert not index.loc[index.clone_id.isin(expected_excluded), "included"].any()
assert index.loc[index.clone_id.isin(original.index) & index.platform.eq("OmniClic"), "included"].all()
assert manifest["datasets"]["OmniClic"]["included_measurement_count"] == 161
assert manifest["datasets"]["OmniClic"]["excluded_measurement_count"] == 9
for platform in ("omniclic", "omniflic"):
old = pd.read_csv(ROOT / f"data/processed/{platform}_nkp46.csv").set_index("sample_id")
new = pd.read_csv(tmp_path / f"{platform}_nkp46.csv").set_index("sample_id")
pd.testing.assert_frame_equal(new[["VH", "VL", "family_id", "fold_id"]], old[["VH", "VL", "family_id", "fold_id"]])
assert (tmp_path / "omniflic_nkp46.csv").read_bytes() == (ROOT / "data/processed/omniflic_nkp46.csv").read_bytes()
def test_omniclic_50_group_is_removed_without_changing_other_samples_or_partitions(tmp_path):
raw_path = ROOT / "data/raw/measurements.csv"
previous_protocol = load_protocol()
previous_protocol["version"] = "0.5.0"
previous_protocol["inclusion"].pop("excluded_sequence_groups")
previous_protocol["inclusion"].pop("sequence_group_exclusion_stage")
previous_path = tmp_path / "v0_5_0.json"
previous_path.write_text(json.dumps(previous_protocol))
build(raw_path, tmp_path / "previous", previous_path)
manifest = build(raw_path, tmp_path / "current")
previous = pd.read_csv(tmp_path / "previous/omniclic_nkp46.csv", dtype={"clone_id": str})
current = pd.read_csv(tmp_path / "current/omniclic_nkp46.csv", dtype={"clone_id": str})
removed = previous.loc[previous.clone_id.eq("50")].iloc[0]
assert len(previous) == 162 and len(current) == 161
pd.testing.assert_frame_equal(current.reset_index(drop=True), previous.loc[previous.clone_id.ne("50")].reset_index(drop=True))
assert not ((current.VH == removed.VH) & (current.VL == removed.VL)).any()
index = pd.read_csv(tmp_path / "current/clone_to_sample.csv", dtype={"clone_id": str})
pair = index.loc[index.platform.eq("OmniClic") & index.clone_id.isin(["50", "0050_v2"])]
assert len(pair) == 2 and not pair.included.any()
excluded = pd.read_csv(tmp_path / "current/excluded.csv", dtype={"clone_id": str}).set_index("clone_id")
assert excluded.loc["50", "sample_id"] == removed.sample_id
assert excluded.loc["50", "exclusion_reason"] == "excluded_sequence_group"
assert current.groupby("fold_id").size().to_dict() == {0: 27, 1: 28, 2: 43, 3: 28, 4: 35}
for chain in ("VH", "VL"):
assert removed.sample_id not in (tmp_path / f"current/omniclic_nkp46.{chain}.fasta").read_text()
assert (tmp_path / "previous/omniflic_nkp46.csv").read_bytes() == (tmp_path / "current/omniflic_nkp46.csv").read_bytes()
assert manifest["datasets"]["OmniClic"]["included_measurement_count"] == 161
def test_build_omniflic_prefers_rat_measurements(tmp_path):
raw = pd.read_csv(ROOT / "data/raw/measurements.csv", dtype={"clone_id": str})
source = raw.loc[raw.platform.eq("OmniFlic")]
rat = source.loc[source.clone_id.str.startswith("Rat_")]
numeric = source.loc[source.clone_id.str.fullmatch(r"\d+") & ~source.VH.isin(rat.VH)]
expected = pd.concat([rat, numeric]).set_index("clone_id")
assert len(rat) == 138 and len(numeric) == 75
manifest = build(ROOT / "data/raw/measurements.csv", tmp_path)
frame = pd.read_csv(tmp_path / "omniflic_nkp46.csv", dtype={"clone_id": str})
assert len(frame) == len(expected) == 213
assert set(frame.clone_id) == set(expected.index)
assert frame.measurement_count.eq(1).all()
np.testing.assert_allclose(frame.KD_M, expected.loc[frame.clone_id, "KD_M"], rtol=1e-10, atol=0)
np.testing.assert_allclose(frame.pKD, -np.log10(expected.loc[frame.clone_id, "KD_M"]), rtol=1e-10, atol=0)
assert frame.set_index("clone_id").loc["Rat_108", "KD_M"] == pytest.approx(73.1e-9, rel=1e-10, abs=0)
excluded = pd.read_csv(tmp_path / "excluded_measurements.csv", dtype={"clone_id": str})
superseded = excluded.loc[excluded.platform.eq("OmniFlic")]
assert len(superseded) == 31
assert superseded.exclusion_reason.eq("superseded_by_preferred_clone_id_prefix").all()
assert superseded.clone_id.str.fullmatch(r"\d+").all()
assert len(superseded.drop_duplicates(["VH", "VL"])) == 30
index = pd.read_csv(tmp_path / "clone_to_sample.csv", dtype={"clone_id": str})
assert not index.loc[index.platform.eq("OmniFlic") & index.clone_id.isin(superseded.clone_id), "included"].any()
assert index.loc[index.platform.eq("OmniFlic") & index.clone_id.isin(expected.index), "included"].all()
assert manifest["datasets"]["OmniFlic"]["included_measurement_count"] == 213
assert manifest["datasets"]["OmniFlic"]["excluded_measurement_count"] == 32
assert (tmp_path / "omniclic_nkp46.csv").read_bytes() == (ROOT / "data/processed/omniclic_nkp46.csv").read_bytes()
original = source.loc[source.clone_id.eq("9451")].copy()
ambiguous = original.copy()
ambiguous["clone_id"] = "unresolved_duplicate"
ambiguous["KD_M"] *= 2
ambiguous_path = tmp_path / "unresolved_raw.csv"
pd.concat([original, ambiguous]).to_csv(ambiguous_path, index=False)
with pytest.raises(ValueError, match="retain one original measurement"):
build(ambiguous_path, tmp_path / "unresolved_output")
|