File size: 16,065 Bytes
3f97185
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa6c487
 
03147a3
aa6c487
03147a3
 
 
 
 
 
 
 
 
 
 
 
aa6c487
 
3f97185
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa6c487
 
3f97185
 
 
 
 
 
 
 
 
 
 
 
 
 
aa6c487
03147a3
 
 
 
3f97185
 
 
 
 
 
 
 
 
ec31236
 
 
 
 
 
 
 
 
 
 
3f97185
 
 
aa6c487
3f97185
 
 
aa6c487
 
 
3f97185
 
 
 
 
 
 
 
aa6c487
3f97185
aa6c487
3f97185
 
 
 
 
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
"""Prepare labeled sequences, annotate, and make reproducible group folds."""

from __future__ import annotations

import hashlib
import json
import math
from collections import defaultdict
from pathlib import Path

import numpy as np
import pandas as pd
from rapidfuzz.distance import Levenshtein

AA = "ACDEFGHIKLMNPQRSTVWY"
ROOT = Path(__file__).resolve().parents[2]


def load_protocol(path: str | Path | None = None) -> dict:
    return json.loads(Path(path or ROOT / "configs/protocol.json").read_text())


def sha256_file(path: Path) -> str:
    with path.open("rb") as handle:
        return hashlib.file_digest(handle, "sha256").hexdigest()


def sample_id(platform: str, vh: str, vl: str) -> str:
    digest = hashlib.sha256(f"{vh}|{vl}".encode()).hexdigest()[:20]
    return f"{platform.lower()}_{digest}"


def canonical_sequence(value: str) -> str:
    value = "".join(str(value).split()).upper()
    if not value or set(value) - set(AA):
        raise ValueError(f"Noncanonical or empty amino acid sequence: {value!r}")
    return value


def select_measurements(raw: pd.DataFrame, protocol: dict) -> tuple[pd.DataFrame, pd.DataFrame]:
    """Apply clone-level exclusions before combining sequence-identical records."""
    reasons = pd.Series("", index=raw.index)
    for platform, suffixes in protocol["inclusion"].get("excluded_clone_id_suffixes", {}).items():
        excluded = raw.platform.eq(platform) & raw.clone_id.astype(str).str.endswith(tuple(suffixes))
        reasons.loc[excluded] = "excluded_clone_id_suffix"
    keys = pd.MultiIndex.from_frame(raw[["platform", "VH", "VL"]].assign(
        VH=raw.VH.map(canonical_sequence), VL=raw.VL.map(canonical_sequence)))
    for platform, prefixes in protocol["inclusion"].get("preferred_clone_id_prefixes", {}).items():
        eligible = raw.platform.eq(platform) & reasons.eq("")
        preferred = eligible & raw.clone_id.astype(str).str.startswith(tuple(prefixes))
        superseded = eligible & keys.isin(keys[preferred.to_numpy()]) & ~preferred
        reasons.loc[superseded] = "superseded_by_preferred_clone_id_prefix"
    rejected = raw.loc[reasons.ne("")].copy()
    rejected["exclusion_reason"] = reasons.loc[rejected.index]
    return raw.loc[reasons.eq("")].copy(), rejected


def merge_measurements(raw: pd.DataFrame) -> pd.DataFrame:
    """Collapse sequence-identical candidates within each platform in log space."""
    raw = raw.copy()
    required = {"clone_id", "platform", "VH", "VL", "KD_M", "source_table"}
    if required - set(raw):
        raise ValueError(f"Missing raw fields: {sorted(required - set(raw))}")
    if raw.duplicated(["platform", "clone_id"]).any():
        raise ValueError("Duplicate clone IDs; resolve source-table extraction first")
    raw["VH"] = raw["VH"].map(canonical_sequence)
    raw["VL"] = raw["VL"].map(canonical_sequence)
    raw["KD_M"] = pd.to_numeric(raw["KD_M"], errors="raise")
    if not np.isfinite(raw.KD_M).all() or (raw.KD_M <= 0).any():
        raise ValueError("Affinity regression needs finite positive numerical KD_M")
    raw["pKD"] = -np.log10(raw.KD_M)
    records = []
    for (platform, vh, vl), rows in raw.groupby(["platform", "VH", "VL"], sort=True):
        pkd = float(rows.pKD.mean())
        records.append({
            "sample_id": sample_id(platform, vh, vl),
            "clone_id": "|".join(sorted(rows.clone_id.astype(str))),
            "VH": vh, "VL": vl, "KD_M": 10.0 ** (-pkd), "pKD": pkd,
            "platform": platform, "measurement_count": len(rows),
            "pKD_min": float(rows.pKD.min()), "pKD_max": float(rows.pKD.max()),
            "source_table": "|".join(sorted(set(rows.source_table))),
            "vh_seq_id": "|".join(sorted(set(rows.vh_seq_id.astype(str)))) if "vh_seq_id" in rows else "",
            "vl_seq_id": "|".join(sorted(set(rows.vl_seq_id.astype(str)))) if "vl_seq_id" in rows else "",
        })
    return pd.DataFrame.from_records(records).sort_values("sample_id").reset_index(drop=True)


def gene_candidates(calls: str) -> set[str]:
    """Collapse tied alleles to gene names, retaining all equally good calls."""
    return {name.split("*")[0] for name in str(calls).replace(";", "_").split("_") if name}


def annotate(df: pd.DataFrame) -> tuple[pd.DataFrame, dict]:
    from antpack import SingleChainAnnotator, VJGeneTool
    from importlib.metadata import version

    aligner = SingleChainAnnotator(chains=["H"], scheme="imgt")
    germlines = VJGeneTool(scheme="imgt")
    records = []
    for row in df.itertuples(index=False):
        alignment = aligner.analyze_seq(row.VH)
        numbering, identity, chain, error = alignment
        if chain != "H" or len(numbering) != len(row.VH) or all(n == "-" for n in numbering):
            raise ValueError(f"Annotation failed for {row.sample_id}: {error}; chain={chain}")
        labels = aligner.assign_cdr_labels(numbering, chain)
        cdrs = {f"CDRH{i}": "".join(aa for aa, label in zip(row.VH, labels) if label == f"cdr{i}") for i in (1, 2, 3)}
        if not cdrs["CDRH3"]:
            raise ValueError(f"Empty CDRH3: {row.sample_id}")
        v, j, vi, ji, species = germlines.assign_vj_genes(alignment, row.VH, "human")
        if not v or not j:
            raise ValueError(f"No V/J annotation: {row.sample_id}")
        records.append({
            "sample_id": row.sample_id, **cdrs,
            "V_gene": ";".join(sorted(gene_candidates(v))),
            "J_gene": ";".join(sorted(gene_candidates(j))),
            "V_allele_candidates": v, "J_allele_candidates": j,
            "V_identity": float(vi), "J_identity": float(ji),
            "numbering_identity": float(identity),
            "annotation_warning": error,
            "numbering_imgt": json.dumps(numbering, separators=(",", ":")),
            "annotation_source": f"AntPack-{version('antpack')}-IMGT-human-AA",
        })
    return df.merge(pd.DataFrame(records), on="sample_id", validate="one_to_one"), {
        "tool": "antpack", "version": version("antpack"), "scheme": "imgt",
        "species": "human", "database_dates": germlines.retrieved_dates,
        "source": "inferred_from_amino_acid_sequence",
    }


class UnionFind:
    def __init__(self, n: int):
        self.parent = list(range(n))

    def find(self, i: int) -> int:
        while self.parent[i] != i:
            self.parent[i] = self.parent[self.parent[i]]
            i = self.parent[i]
        return i

    def union(self, a: int, b: int) -> None:
        ra, rb = self.find(a), self.find(b)
        self.parent[max(ra, rb)] = min(ra, rb)


def assign_families(df: pd.DataFrame, max_distance: int = 2) -> pd.DataFrame:
    """Single linkage; ambiguous V/J calls match if their candidate sets intersect."""
    result = df.sort_values("sample_id").reset_index(drop=True).copy()
    for platform, rows in result.groupby("platform", sort=True):
        indices = list(rows.index)
        uf = UnionFind(len(indices))
        for a, ia in enumerate(indices):
            for b in range(a):
                ib = indices[b]
                x, y = result.loc[ia], result.loc[ib]
                if len(x.CDRH3) != len(y.CDRH3):
                    continue
                if not gene_candidates(x.V_gene) & gene_candidates(y.V_gene):
                    continue
                if not gene_candidates(x.J_gene) & gene_candidates(y.J_gene):
                    continue
                if Levenshtein.distance(x.CDRH3, y.CDRH3, score_cutoff=max_distance) <= max_distance:
                    uf.union(a, b)
        components = defaultdict(list)
        for a, i in enumerate(indices):
            components[uf.find(a)].append(i)
        for members in components.values():
            digest = hashlib.sha256("|".join(result.loc[members, "sample_id"]).encode()).hexdigest()[:12]
            result.loc[members, "family_id"] = f"{platform.lower()}_f_{digest}"
    return result


def grouped_folds(groups: list[str], n_splits: int, seed: int) -> np.ndarray:
    """Balance by sample count with seeded tie breaks, without looking at labels."""
    counts = pd.Series(groups).value_counts().to_dict()
    if len(counts) < n_splits or n_splits < 2:
        raise ValueError(f"{len(counts)} groups cannot support {n_splits} folds")
    rng = np.random.default_rng(seed)
    order = list(sorted(counts))
    rng.shuffle(order)
    order.sort(key=lambda g: -counts[g])
    loads = np.zeros(n_splits, dtype=int)
    assignments = {}
    for group in order:
        choices = np.flatnonzero(loads == loads.min())
        fold = int(rng.choice(choices))
        assignments[group] = fold
        loads[fold] += counts[group]
    return np.array([assignments[g] for g in groups], dtype=int)


def assign_folds(df: pd.DataFrame, protocol: dict) -> pd.DataFrame:
    result = df.copy()
    result["fold_id"] = -1
    for platform, rows in result.groupby("platform", sort=True):
        count = rows.family_id.nunique()
        k = protocol["split"]["outer_folds"] if count >= protocol["split"]["outer_folds"] else protocol["split"]["fallback_folds"]
        if count < k:
            raise ValueError(f"{platform}: only {count} families; cannot create {k} grouped folds")
        result.loc[rows.index, "fold_id"] = grouped_folds(rows.family_id.tolist(), k, protocol["split"]["seed"])
    result["fold_id"] = result.fold_id.astype(int)
    return result


def validate_dataset(df: pd.DataFrame) -> None:
    for row in df.itertuples(index=False):
        if row.sample_id != sample_id(row.platform, canonical_sequence(row.VH), canonical_sequence(row.VL)):
            raise ValueError(f"Sample ID does not match its sequences: {row.sample_id}")
    if df.sample_id.duplicated().any() or df.duplicated(["platform", "VH", "VL"]).any():
        raise ValueError("Duplicate benchmark samples")
    if not np.isfinite(df.pKD).all() or not np.allclose(df.pKD, -np.log10(df.KD_M), atol=1e-10):
        raise ValueError("Invalid pKD transformation")
    for platform, rows in df.groupby("platform"):
        if rows.VL.nunique() != 1:
            raise ValueError(f"{platform}: expected exactly one fixed VL")
        if rows.groupby("family_id").fold_id.nunique().max() != 1:
            raise ValueError(f"{platform}: family crosses outer folds")
        if rows.fold_id.min() < 0:
            raise ValueError(f"{platform}: unassigned folds")
        if set(rows.fold_id) != set(range(rows.fold_id.nunique())):
            raise ValueError(f"{platform}: noncontiguous outer fold IDs")
        for fold, held in rows.groupby("fold_id"):
            if held.empty or rows[rows.fold_id != fold].family_id.nunique() < 2:
                raise ValueError(f"{platform} fold {fold}: insufficient inner-training families")


def write_fasta(df: pd.DataFrame, path: Path, column: str = "VH") -> None:
    path.write_text("".join(f">{row.sample_id}\n{getattr(row, column)}\n" for row in df.itertuples(index=False)))


def summary(df: pd.DataFrame, raw: pd.DataFrame) -> dict:
    result = {}
    for platform, rows in df.groupby("platform", sort=True):
        stats = rows.pKD.describe().to_dict()
        result[platform] = {
            "raw_clone_count": int((raw.platform == platform).sum()),
            "included_measurement_count": int((raw.platform.eq(platform) & raw.included).sum()),
            "excluded_measurement_count": int((raw.platform.eq(platform) & ~raw.included).sum()),
            "unique_VH_VL_count": len(rows), "unique_VH_count": rows.VH.nunique(),
            "unique_VL_count": rows.VL.nunique(), "family_count": rows.family_id.nunique(),
            "largest_family": int(rows.family_id.value_counts().max()),
            "fold_sample_counts": {str(k): int(v) for k, v in rows.fold_id.value_counts().sort_index().items()},
            "fold_family_counts": {str(k): int(g.family_id.nunique()) for k, g in rows.groupby("fold_id")},
            "KD_nM_range": [float(rows.KD_M.min() * 1e9), float(rows.KD_M.max() * 1e9)],
            "pKD": {k: float(v) for k, v in stats.items()},
        }
    return result


def build(raw_path: Path, output_dir: Path, protocol_path: Path | None = None) -> dict:
    raw = pd.read_csv(raw_path, dtype={"clone_id": str, "vh_seq_id": str, "vl_seq_id": str})
    protocol = load_protocol(protocol_path)
    selected, excluded_measurements = select_measurements(raw, protocol)
    merged = merge_measurements(selected)
    if protocol["duplicate_aggregation"] == "none_after_record_selection" and merged.measurement_count.ne(1).any():
        raise ValueError("Record selection must retain one original measurement per sequence")
    df, annotation_meta = annotate(merged)
    before_filter = df.groupby("platform").size().to_dict()
    df["numbering_start"] = df.numbering_imgt.map(lambda value: json.loads(value)[0])
    df["numbering_end"] = df.numbering_imgt.map(lambda value: json.loads(value)[-1])
    complete = (df.numbering_start == protocol["inclusion"]["required_first_IMGT_position"]) & (df.numbering_end == protocol["inclusion"]["required_last_IMGT_position"])
    excluded = df.loc[~complete].copy()
    excluded["exclusion_reason"] = "incomplete_VH_IMGT_terminal_positions"
    df = df.loc[complete].copy()
    df = assign_families(df, protocol["family"]["max_CDRH3_edit_distance"])
    df = assign_folds(df, protocol)
    # Curate complete sequence groups after partitioning to preserve existing folds.
    excluded_group_ids = set()
    for platform, clone_ids in protocol["inclusion"].get("excluded_sequence_groups", {}).items():
        references = raw.loc[raw.platform.eq(platform) & raw.clone_id.isin(clone_ids)]
        excluded_group_ids.update(sample_id(platform, canonical_sequence(row.VH), canonical_sequence(row.VL))
            for row in references.itertuples(index=False))
    curated_out = df.loc[df.sample_id.isin(excluded_group_ids)].copy()
    if not curated_out.empty:
        curated_out["exclusion_reason"] = "excluded_sequence_group"
        excluded = pd.concat([excluded, curated_out], ignore_index=True)
        df = df.loc[~df.sample_id.isin(excluded_group_ids)].copy()
    validate_dataset(df)
    output_dir.mkdir(parents=True, exist_ok=True)
    excluded.to_csv(output_dir / "excluded.csv", index=False, float_format="%.12g")
    excluded_measurements.to_csv(output_dir / "excluded_measurements.csv", index=False, float_format="%.12g")
    raw_index = raw.copy()
    raw_index["sample_id"] = [sample_id(p, canonical_sequence(vh), canonical_sequence(vl)) for p, vh, vl in zip(raw.platform, raw.VH, raw.VL)]
    raw_index["pKD"] = -np.log10(raw_index.KD_M.astype(float))
    raw_index["exclusion_reason"] = raw_index.sample_id.map(excluded.set_index("sample_id").exclusion_reason).fillna("")
    raw_index.loc[excluded_measurements.index, "exclusion_reason"] = excluded_measurements.exclusion_reason
    raw_index["included"] = raw_index.exclusion_reason.eq("")
    raw_index.to_csv(output_dir / "clone_to_sample.csv", index=False, float_format="%.12g")
    for platform, rows in df.groupby("platform", sort=True):
        stem = f"{platform.lower()}_nkp46"
        rows.to_csv(output_dir / f"{stem}.csv", index=False, float_format="%.12g")
        write_fasta(rows, output_dir / f"{stem}.VH.fasta")
        write_fasta(rows, output_dir / f"{stem}.VL.fasta", "VL")
    manifest = {"protocol": protocol, "raw_sha256": sha256_file(raw_path), "annotation": annotation_meta,
        "deduplicated_counts_before_completeness_filter": {k: int(v) for k, v in before_filter.items()},
        "excluded_measurements": excluded_measurements[["clone_id", "platform", "exclusion_reason"]].to_dict("records"),
        "excluded_sequences": excluded[["sample_id", "clone_id", "platform", "exclusion_reason"]].to_dict("records"),
        "datasets": summary(df, raw_index)}
    for path in sorted(output_dir.iterdir()):
        if path.is_file() and path.suffix in {".csv", ".fasta"}:
            manifest.setdefault("files", {})[path.name] = sha256_file(path)
    (output_dir / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n")
    return manifest