"""Science 2021, doi 10.1126/science.abe6474 (GSE156728): pan-cancer T cell atlas, 10x cells whose `meta.cluster` starts with CD4.
(per-cell cluster annotation, not a sort). TCR contigs joined to the metadata on cell barcode AND library (cellID = barcode, libraryID = library.id).
Productive TRA and TRB contigs only, top-UMI chain per cell, cells with both chains only (the manifest counts paired cells). Smart-seq2 cells have
no TCR in this file. Donor = `patient`. Context = cancer type, tissue (loc: T tumour, N normal, P blood, per the manifest) and cluster.
No antigen specificity."""
import pandas as pd
from atlas import SRC, clones, pair_contigs


def parse():
    m = pd.read_csv(SRC / "Zheng2021/GSE156728_metadata.txt.gz", sep="\t")
    m = m[m["meta.cluster"].str.startswith("CD4.") & m.platform.eq("10X")]
    v = pd.read_csv(SRC / "Zheng2021/GSE156728_10X_VDJ.merge.txt.gz", sep="\t", usecols=["barcode", "chain", "v_gene", "j_gene", "productive", "cdr3", "umis", "library.id"])
    v = v[v.productive.eq(True)].rename(columns={"barcode": "cellID", "library.id": "libraryID"})
    d = pair_contigs(v, ["cellID", "libraryID"])
    d = d[d.CDR3a.notna() & d.CDR3b.notna()].merge(m, on=["cellID", "libraryID"])
    d["donor"] = d.patient
    d["context"] = d.cancerType + ", " + d["loc"].map({"T": "tumour", "N": "normal tissue", "P": "blood"}) + ", " + d["meta.cluster"]
    d = clones(d, ["donor", "context"])
    return d.assign(source="Zheng 2021 (Science)", study="GEO:GSE156728", species="human", cd4_evidence="CD4 cluster (single cell)", specificity_evidence="none", annotation_level="none")
