File size: 2,165 Bytes
0ecdb9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
086e6dd
7ab8c78
086e6dd
 
 
 
0ecdb9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
086e6dd
 
 
0ecdb9e
 
 
 
 
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
"""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")