Download src/clc_mini_bench/data.py from ImmunocanAI/CLC-mini-bench: direct link, hf CLI and curl.
- Browser
- Download file 16.1 kB
-
https://huggingface.co/datasets/ImmunocanAI/CLC-mini-bench/resolve/main/src/clc_mini_bench/data.py
- Command line
-
hf download hf://datasets/ImmunocanAI/CLC-mini-bench/src/clc_mini_bench/data.py
-
curl -L -o data.py https://huggingface.co/datasets/ImmunocanAI/CLC-mini-bench/resolve/main/src/clc_mini_bench/data.py
16.1 kB
| """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 | |