airr_tcga / load.py
mikessh's picture
HLA: union TCGA PanImmune (primary) + OptiType fill -> 96.5% donor coverage
7ab8c78
Raw
History Blame Contribute Delete
2.17 kB
"""Minimal bootstrap loader for isalgo/airr_tcga.
pip install huggingface_hub pandas
Files are fetched (and cached) from the Hub on first use.
"""
import tarfile
import pandas as pd
from huggingface_hub import hf_hub_download
REPO = "isalgo/airr_tcga"
def load_metadata() -> pd.DataFrame:
"""One row per sample, keyed by ``sample_id`` (clinical + read counts)."""
path = hf_hub_download(REPO, "metadata.tsv", repo_type="dataset")
return pd.read_csv(path, sep="\t")
def load_hla() -> pd.DataFrame:
"""One row per donor, keyed by ``subject_id`` (HLA class-I, PanImmune ∪ OptiType). Join on ``subject_id``."""
path = hf_hub_download(REPO, "metadata.hla.tsv", repo_type="dataset")
return pd.read_csv(path, sep="\t")
def _tar() -> tarfile.TarFile:
path = hf_hub_download(REPO, "samples.tar.gz", repo_type="dataset")
return tarfile.open(path, "r:gz")
def load_sample(sample_id: str) -> pd.DataFrame:
"""AIRR clonotype table for one sample.
ponytail: reopens the tarball per call (fine for a few lookups; the file is
cached locally). For many samples use ``iter_samples`` — one pass, no rescan.
"""
with _tar() as t:
return pd.read_csv(t.extractfile(f"samples/{sample_id}.tsv"), sep="\t")
def iter_samples():
"""Yield ``(sample_id, DataFrame)`` for all samples, streaming once."""
with _tar() as t:
for m in t:
if m.name.endswith(".tsv"):
yield m.name.split("/")[-1][:-4], pd.read_csv(t.extractfile(m), sep="\t")
if __name__ == "__main__":
md = load_metadata()
print(f"metadata: {md.shape[0]} samples x {md.shape[1]} cols")
assert md.sample_id.is_unique and md.shape[0] == 9591
hla = load_hla()
print(f"hla: {hla.shape[0]} donors; {md.subject_id.isin(hla.subject_id).sum()}/{len(md)} samples covered")
assert hla.subject_id.is_unique and {"HLA-A_1", "HLA-B_1", "HLA-C_1"} <= set(hla.columns)
sid = md.sample_id.iloc[0]
s = load_sample(sid)
print(f"sample {sid}: {len(s)} clonotypes, loci={sorted(s.locus.unique())}")
assert {"junction_aa", "v_call", "duplicate_count"} <= set(s.columns)
print("OK")