"""Immunity 2020, doi 10.1016/j.immuni.2020.11.016 (GSE162086): CD154+ CD69+ CD4+ T cells after 7 h stimulation with SARS-CoV-2 peptide pools
(which pool per run is not stated), 14 COVID-19 patients and 6 unexposed donors.
Source: Seurat metadata. `cdr3` and `v_gene` are chains joined by '.', in no fixed order, in the same order as each other: each CDR3 is assigned to alpha or beta
from the name of its V gene (TRAV... / TRBV...). Checked against the Cell Ranger clonotype files of the same study: in the cells with a CDR3, no alpha
CDR3 is listed as TRB there and no beta CDR3 as TRA. 37,958 of the 104,417 cells have 'none' (no CDR3, the manifest says all have one): not loaded.
TRDV and TRGV chains are dropped. When a cell has several chains of one type, the first one in the listed order is kept. No J genes in the files.
Donor: only the 10x run (J number) is known, the J number to patient key is not in the files; donor = "run <J number>". Cells are not split by cluster."""
import pandas as pd
from atlas import SRC, clones


def parse():
    d = pd.read_csv(SRC / "Bacher2020/GSE162086_seurat_metadata.tsv.gz", sep="\t", low_memory=False, index_col=0)
    d = d[d.cdr3.ne("none")].copy()
    ch = pd.DataFrame({"cdr3": d.cdr3.str.split("."), "v": d.v_gene.str.split(".")}).explode(["cdr3", "v"])
    for k, p in (("a", "TRAV"), ("b", "TRBV")):
        x = ch[ch.v.str.startswith(p)].groupby(level=0, sort=False).first()
        d["CDR3" + k], d["TR%sV" % k.upper()] = x.cdr3, x.v
    d["donor"] = "run " + d["sample"]
    d["context"] = d.diagnosis.map({"COVID19": "COVID-19 patient", "Healthy": "unexposed healthy donor"}).fillna(d.diagnosis)
    r = clones(d[d.CDR3a.notna() | d.CDR3b.notna()], ["donor", "context"])
    return r.assign(source="Bacher 2020 (Immunity)", study="doi:10.1016/j.immuni.2020.11.016", species="human", cd4_evidence="sorted CD4+",
                    antigen="SARS-CoV-2 peptide pools", organism="SARS-CoV-2", specificity_evidence="CD154+ CD69+ after 7 h peptide pool stimulation", annotation_level="antigen")
