Skip to content

Database Annotation API

Match clonotypes against VDJdb, IEDB, and CEDAR epitope references, separate canonical protein/antigen labels (db_protein_canonical, e.g. NY-ESO-1, LAGE-1, MART-1, TRP-2, CEA) from official HGNC/MGI encoding gene symbols (db_antigen_gene, e.g. CTAG1A/CTAG1B, CTAG2, MLANA/Mlana, DCT/Dct, CEACAM5; None for viral or exogenous proteins such as chicken OVA), and track donor host species (db_host_species, host_species_filter).

annotate

TCR annotation using public databases for TCRsift.

Matches TCRs against VDJdb, IEDB, and CEDAR to identify known specificities.

VIRAL_SPECIES_PATTERNS module-attribute

VIRAL_SPECIES_PATTERNS = ['cmv', 'cytomegalovirus', 'mcmv', 'ebv', 'epstein-barr', 'epstein barr', 'hiv', 'human immunodeficiency', 'htlv', 'flu', 'influenza', 'sars', 'coronavirus', 'herpes', 'hsv', 'hpv', 'papilloma', 'hepatitis', 'hbv', 'hcv', 'dengue', 'zika', 'yellow fever', 'west nile', 'lcmv', 'lymphocytic choriomeningitis', 'mammarenavirus choriomeningitidis', 'vesicular stomatitis', 'vsv', 'sendai', 'murine respirovirus', 'respirovirus', 'vaccinia', 'ectromelia', 'murine leukemia', 'mulv', 'polyomavirus', 'adenovirus', 'norovirus', 'rotavirus', 'parvovirus']

load_vdjdb

load_vdjdb(path: str | Path, verbose: bool = True) -> pd.DataFrame

Load VDJdb database.

VDJdb ships two on-disk shapes with different row semantics:

  • vdjdb_full.txt — paired-chain format: one row per clonotype, with cdr3.alpha and cdr3.beta as separate columns. This is what αβ matching needs.
  • vdjdb.txt — long/slim format: one row per chain, keyed by complex.id and gene (TRA/TRB). Output rows are restricted to gene == TRB so cdr3_beta only carries actual β-CDR3s; when complex.id > 0 links a TRB row to a paired TRA row, cdr3_alpha and v_alpha are reconstructed onto that row (unpaired complex.id == 0 rows keep cdr3_alpha = pd.NA).

When given a directory, looks for canonical filenames in priority order (vdjdb_full.txt, vdjdb.txt, vdjdb.slim.txt, or a date-stamped vdjdb-YYYY-MM-DD.txt). Other sidecar files in the directory (.meta.txt, .scored.txt, etc.) are ignored.

Parameters:

Name Type Description Default
path str or Path

Path to VDJdb directory or single file.

required
verbose bool

Print progress information.

True

Returns:

Type Description
DataFrame

VDJdb entries with standardized columns (cdr3_alpha, cdr3_beta, epitope, antigen_gene, species, mhc_allele, database, is_viral).

Source code in tcrsift/annotate.py
def load_vdjdb(path: str | Path, verbose: bool = True) -> pd.DataFrame:
    """
    Load VDJdb database.

    VDJdb ships two on-disk shapes with **different row semantics**:

    - ``vdjdb_full.txt`` — *paired-chain* format: one row per
      clonotype, with ``cdr3.alpha`` and ``cdr3.beta`` as separate
      columns. This is what αβ matching needs.
    - ``vdjdb.txt`` — *long/slim* format: one row per **chain**, keyed
      by ``complex.id`` and ``gene`` (``TRA``/``TRB``). Output rows are
      restricted to ``gene == TRB`` so ``cdr3_beta`` only carries actual
      β-CDR3s; when ``complex.id > 0`` links a ``TRB`` row to a paired
      ``TRA`` row, ``cdr3_alpha`` and ``v_alpha`` are reconstructed onto
      that row (unpaired ``complex.id == 0`` rows keep ``cdr3_alpha = pd.NA``).

    When given a directory, looks for canonical filenames in priority
    order (``vdjdb_full.txt``, ``vdjdb.txt``, ``vdjdb.slim.txt``, or a
    date-stamped ``vdjdb-YYYY-MM-DD.txt``). Other sidecar files in the
    directory (``.meta.txt``, ``.scored.txt``, etc.) are ignored.

    Parameters
    ----------
    path : str or Path
        Path to VDJdb directory or single file.
    verbose : bool
        Print progress information.

    Returns
    -------
    pd.DataFrame
        VDJdb entries with standardized columns (``cdr3_alpha``,
        ``cdr3_beta``, ``epitope``, ``antigen_gene``, ``species``,
        ``mhc_allele``, ``database``, ``is_viral``).
    """
    path = Path(path)

    relational_pair: tuple[Path, Path] | None = None
    if path.is_dir():
        resolved_source = _pick_vdjdb_source(path)
        if isinstance(resolved_source, tuple):
            relational_pair = resolved_source
            db_file = relational_pair[0]
        else:
            db_file = resolved_source
    else:
        db_file = validate_file_exists(path, "VDJdb database file")
        lower_name = db_file.name.lower()
        if lower_name in ("chains.tsv.gz", "chains.tsv", "records.tsv.gz", "records.tsv"):
            parent = db_file.parent
            chains_cand = next(
                (parent / n for n in ("chains.tsv.gz", "chains.tsv") if (parent / n).is_file()),
                None,
            )
            records_cand = next(
                (parent / n for n in ("records.tsv.gz", "records.tsv") if (parent / n).is_file()),
                None,
            )
            if chains_cand is not None and records_cand is not None:
                relational_pair = (chains_cand, records_cand)
                db_file = chains_cand

    if verbose:
        logger.info(
            f"Loading VDJdb from {relational_pair[0].parent if relational_pair else db_file}"
        )

    if relational_pair is not None:
        chains_path, records_path = relational_pair
        try:
            chains_df = pd.read_csv(chains_path, sep="\t", low_memory=False)
            records_df = pd.read_csv(records_path, sep="\t", low_memory=False)
        except Exception as e:
            raise TCRsiftValidationError(
                f"Failed to read VDJdb relational tables in {chains_path.parent}",
                hint=f"Error: {e}. Expected valid TSV/TSV.GZ files for chains and records.",
            ) from e
        if len(chains_df) == 0 or len(records_df) == 0:
            raise TCRsiftValidationError(
                f"VDJdb relational tables are empty in {chains_path.parent}",
                hint="Re-run `tcrsift data download --db vdjdb --force`.",
            )
        df = _normalize_vdjdb_relational(chains_df, records_df)
        if verbose:
            n_paired = int(df["cdr3_alpha"].notna().sum()) if "cdr3_alpha" in df.columns else 0
            logger.info(
                f"  Relational VDJdb format: loaded {len(df):,} TRB entries "
                f"({n_paired:,} paired αβ via record_id)."
            )
    elif db_file.name.lower().endswith(".parquet"):
        try:
            pq_df = pd.read_parquet(db_file)
        except Exception as e:
            raise TCRsiftValidationError(
                f"Failed to read VDJdb parquet file: {db_file}",
                hint=f"Error: {e}. Ensure pyarrow or fastparquet is installed.",
            ) from e
        if len(pq_df) == 0:
            raise TCRsiftValidationError(
                f"VDJdb file is empty: {db_file}",
                hint="Download a fresh copy from https://vdjdb.cdr3.net/",
            )
        if "cdr3.beta" in pq_df.columns:
            df = _normalize_vdjdb_paired(pq_df)
        elif "record_id" in pq_df.columns and "cdr3" in pq_df.columns and "gene" in pq_df.columns:
            df = _normalize_vdjdb_relational(pq_df, None)
        elif "cdr3" in pq_df.columns and "gene" in pq_df.columns:
            df = _normalize_vdjdb_long(pq_df)
        else:
            raise TCRsiftValidationError(
                f"Unrecognized VDJdb schema in {db_file}",
                hint=(
                    "Expected paired-chain columns (`cdr3.alpha` + `cdr3.beta`), "
                    "long-format columns (`cdr3` + `gene`), or relational `record_id` + `cdr3` + `gene`. Got: "
                    f"{list(pq_df.columns[:10])}"
                ),
            )
    else:
        try:
            df = pd.read_csv(db_file, sep="\t", low_memory=False)
        except Exception as e:
            raise TCRsiftValidationError(
                f"Failed to read VDJdb file: {db_file}",
                hint=f"Error: {e}. Make sure the file is a valid TSV file.",
            )

        if len(df) == 0:
            raise TCRsiftValidationError(
                f"VDJdb file is empty: {db_file}",
                hint="Download a fresh copy from https://vdjdb.cdr3.net/",
            )

        # Format-specific normalization, dispatched by column presence:
        # the paired file has ``cdr3.beta``, the long file has
        # ``cdr3`` + ``gene`` (+ ``record_id`` in 2026+ or ``complex.id`` in legacy).
        if "cdr3.beta" in df.columns:
            df = _normalize_vdjdb_paired(df)
        elif "record_id" in df.columns and "cdr3" in df.columns and "gene" in df.columns:
            sibling_rec = None
            if "antigen_epitope" not in df.columns and "antigen.epitope" not in df.columns:
                rec_cand = next(
                    (
                        db_file.parent / n
                        for n in ("records.tsv.gz", "records.tsv")
                        if (db_file.parent / n).is_file()
                    ),
                    None,
                )
                if rec_cand is not None:
                    sibling_rec = pd.read_csv(rec_cand, sep="\t", low_memory=False)
            df = _normalize_vdjdb_relational(df, sibling_rec)
        elif "cdr3" in df.columns and "gene" in df.columns:
            n_total = len(df)
            df = _normalize_vdjdb_long(df)
            n_paired = int(df["cdr3_alpha"].notna().sum()) if "cdr3_alpha" in df.columns else 0
            if verbose:
                logger.info(
                    f"  Long/slim VDJdb format: kept {len(df):,} TRB rows "
                    f"({n_paired:,} paired αβ via complex.id) out of {n_total:,} total rows."
                )
        else:
            raise TCRsiftValidationError(
                f"Unrecognized VDJdb schema in {db_file}",
                hint=(
                    "Expected paired-chain columns (`cdr3.alpha` + `cdr3.beta`), "
                    "long-format columns (`cdr3` + `gene`), or relational `chains`/`records` tables. Got: "
                    f"{list(df.columns)[:10]}{'...' if len(df.columns) > 10 else ''}"
                ),
            )

    df["database"] = "VDJdb"
    df["is_viral"] = _flag_viral(df)

    if verbose:
        logger.info(f"  Loaded {len(df):,} VDJdb entries ({df['is_viral'].sum():,} viral)")
    return df

load_iedb

load_iedb(path: str | Path, epitope_path: str | Path | None = None) -> pd.DataFrame

Load IEDB TCR database.

Handles two on-disk shapes:

  1. The current receptor_full_v3.zip export (cached as tcr_full_v3.csv): comma-separated with a two-row hierarchical header — top row is the section (Receptor/Epitope/ Assay/Chain 1/Chain 2…), second row is the field (e.g. CDR3 Curated, Source Organism).
  2. Older flat-TSV exports kept around for compatibility.

The format is sniffed from the first byte of the file rather than the extension, so a user-supplied path is treated correctly regardless of suffix.

Parameters:

Name Type Description Default
path str or Path

Path to IEDB receptor file (v3 CSV or legacy flat TSV).

required
epitope_path str or Path

Path to the IEDB epitope-level CSV (epitope_full_v3.csv — companion to the receptor file, cached by tcrsift data download --db iedb_epitope). When provided, the receptor file's antigen_gene / species fields are overridden with the epitope table's values wherever the epitope table has them. Empirically, the epitope-table names are shorter and more publication-canonical (e.g. Protein Tax-1 vs the receptor file's transcriptional activator Tax), which reduces downstream synonym sprawl (#54).

None

Returns:

Type Description
DataFrame

IEDB entries with standardized columns (cdr3_alpha, cdr3_beta, epitope, antigen_gene, species, mhc_allele, is_viral, database).

Source code in tcrsift/annotate.py
def load_iedb(
    path: str | Path,
    epitope_path: str | Path | None = None,
) -> pd.DataFrame:
    """
    Load IEDB TCR database.

    Handles two on-disk shapes:

    1. The current `receptor_full_v3.zip` export (cached as
       ``tcr_full_v3.csv``): comma-separated with a two-row hierarchical
       header — top row is the section (``Receptor``/``Epitope``/
       ``Assay``/``Chain 1``/``Chain 2``…), second row is the field
       (e.g. ``CDR3 Curated``, ``Source Organism``).
    2. Older flat-TSV exports kept around for compatibility.

    The format is sniffed from the first byte of the file rather than
    the extension, so a user-supplied path is treated correctly
    regardless of suffix.

    Parameters
    ----------
    path : str or Path
        Path to IEDB receptor file (v3 CSV or legacy flat TSV).
    epitope_path : str or Path, optional
        Path to the IEDB epitope-level CSV
        (``epitope_full_v3.csv`` — companion to the receptor file,
        cached by ``tcrsift data download --db iedb_epitope``).
        When provided, the receptor file's ``antigen_gene`` / ``species``
        fields are overridden with the epitope table's values
        wherever the epitope table has them. Empirically, the
        epitope-table names are shorter and more publication-canonical
        (e.g. ``Protein Tax-1`` vs the receptor file's
        ``transcriptional activator Tax``), which reduces downstream
        synonym sprawl (#54).

    Returns
    -------
    pd.DataFrame
        IEDB entries with standardized columns (``cdr3_alpha``,
        ``cdr3_beta``, ``epitope``, ``antigen_gene``, ``species``,
        ``mhc_allele``, ``is_viral``, ``database``).
    """
    path = Path(path)
    logger.info(f"Loading IEDB from {path}")

    if _looks_like_iedb_v3(path):
        df = _load_iedb_v3(path)
    else:
        df = _load_iedb_legacy_tsv(path)

    if epitope_path is not None:
        df = _apply_iedb_epitope_overrides(df, Path(epitope_path))

    df["database"] = "IEDB"
    df["is_viral"] = _flag_viral(df)

    logger.info(f"Loaded {len(df)} IEDB entries ({df['is_viral'].sum()} viral)")
    return df

load_cedar

load_cedar(path: str | Path) -> pd.DataFrame

Load the CEDAR TCR database.

Handles two on-disk shapes, sniffed from the file's first line (not the extension):

  1. The bulk receptor export (doc/receptor_full_v3.zip → tcr_full_v3.csv, cached by tcrsift data download --db cedar): comma-separated with the same v3 two-row hierarchical header as IEDB, so it is parsed by the shared :func:_load_iedb_v3.
  2. A manual web-UI export cedar.tsv — tab-separated, flat header with fields like cdr3_b_aa / epitope_sequence (the original supported shape; kept for back-compat).

Parameters:

Name Type Description Default
path str or Path

Path to a CEDAR receptor file (bulk v3 CSV or manual flat TSV).

required

Returns:

Type Description
DataFrame

CEDAR entries with standardized columns (cdr3_alpha, cdr3_beta, epitope, antigen_gene, species, is_viral, database).

Source code in tcrsift/annotate.py
def load_cedar(path: str | Path) -> pd.DataFrame:
    """
    Load the CEDAR TCR database.

    Handles two on-disk shapes, sniffed from the file's first line (not the
    extension):

    1. The **bulk** receptor export (``doc/receptor_full_v3.zip`` →
       ``tcr_full_v3.csv``, cached by ``tcrsift data download --db cedar``):
       comma-separated with the same v3 two-row hierarchical header as IEDB, so
       it is parsed by the shared :func:`_load_iedb_v3`.
    2. A **manual web-UI export** ``cedar.tsv`` — tab-separated, flat header with
       fields like ``cdr3_b_aa`` / ``epitope_sequence`` (the original supported
       shape; kept for back-compat).

    Parameters
    ----------
    path : str or Path
        Path to a CEDAR receptor file (bulk v3 CSV or manual flat TSV).

    Returns
    -------
    pd.DataFrame
        CEDAR entries with standardized columns (``cdr3_alpha``, ``cdr3_beta``,
        ``epitope``, ``antigen_gene``, ``species``, ``is_viral``, ``database``).
    """
    path = Path(path)
    logger.info(f"Loading CEDAR from {path}")

    if _looks_like_iedb_v3(path):
        # CEDAR's bulk export IS the IEDB v3 receptor schema (cancer-scoped).
        df = _load_iedb_v3(path)
    else:
        df = pd.read_csv(path, sep="\t", low_memory=False)
        # Standardize the manual web-export columns.
        column_mapping = {
            "cdr3_b_aa": "cdr3_beta",
            "cdr3_a_aa": "cdr3_alpha",
            "epitope_sequence": "epitope",
            "antigen_name": "antigen_gene",
            "organism": "species",
        }
        for old, new in column_mapping.items():
            if old in df.columns:
                df[new] = df[old]

    df["database"] = "CEDAR"
    df["is_viral"] = _flag_viral(df)

    logger.info(f"Loaded {len(df)} CEDAR entries ({df['is_viral'].sum()} viral)")
    return df

load_databases

load_databases(vdjdb_path: str | Path | None = None, iedb_path: str | Path | None = None, cedar_path: str | Path | None = None, iedb_epitope_path: str | Path | None = None, verbose: bool = True) -> pd.DataFrame

Load and combine multiple TCR databases.

Parameters:

Name Type Description Default
vdjdb_path str or Path

Path to VDJdb

None
iedb_path str or Path

Path to IEDB receptor table

None
cedar_path str or Path

Path to CEDAR

None
iedb_epitope_path str or Path

Path to IEDB epitope-level table (companion to iedb_path). When provided, load_iedb defers to its shorter/more canonical antigen and organism names — see :func:load_iedb.

None
verbose bool

Print progress information.

True

Returns:

Type Description
DataFrame

Combined database with standardized columns

Source code in tcrsift/annotate.py
def load_databases(
    vdjdb_path: str | Path | None = None,
    iedb_path: str | Path | None = None,
    cedar_path: str | Path | None = None,
    iedb_epitope_path: str | Path | None = None,
    verbose: bool = True,
) -> pd.DataFrame:
    """
    Load and combine multiple TCR databases.

    Parameters
    ----------
    vdjdb_path : str or Path, optional
        Path to VDJdb
    iedb_path : str or Path, optional
        Path to IEDB receptor table
    cedar_path : str or Path, optional
        Path to CEDAR
    iedb_epitope_path : str or Path, optional
        Path to IEDB epitope-level table (companion to ``iedb_path``).
        When provided, ``load_iedb`` defers to its shorter/more
        canonical antigen and organism names — see :func:`load_iedb`.
    verbose : bool
        Print progress information.

    Returns
    -------
    pd.DataFrame
        Combined database with standardized columns
    """
    dfs = []

    if vdjdb_path:
        dfs.append(load_vdjdb(vdjdb_path, verbose=verbose))
    if iedb_path:
        dfs.append(load_iedb(iedb_path, epitope_path=iedb_epitope_path))
    if cedar_path:
        dfs.append(load_cedar(cedar_path))

    if not dfs:
        raise ValueError("At least one database path must be provided")

    # Combine and deduplicate
    combined = pd.concat(dfs, ignore_index=True)

    # Keep only rows with at least a beta CDR3
    combined = combined[combined["cdr3_beta"].notna() & (combined["cdr3_beta"] != "")]

    if verbose:
        logger.info(f"Combined database has {len(combined)} entries")
    return combined

canonicalize_antigen

canonicalize_antigen(antigen: str | None, species: str | None = None) -> str | None

Map a raw antigen/protein string to its canonical protein/antigen label.

Strictly word-bounded and organism-aware:

  • Distinguishes proteins/proteoforms from encoding genes: both CTAG1A and CTAG1B canonicalize to "NY-ESO-1", whereas CTAG2 canonicalizes to "LAGE-1"; CEACAM5 and Carcinoembryonic antigen canonicalize to "CEA" while CEACAM1/CEACAM6 stay untouched; ERBB2 → "HER2" while ERBB2IP stays untouched; MAGE-A10 / MAGEA12 keep their exact paralog numbers rather than collapsing into MAGE-A1.
  • Disambiguates shared viral protein names (Nucleoprotein, Nucleocapsid, NS3, Spike, IE1) using species (or an inline [organism] suffix), and never maps host self proteins such as human Small nuclear ribonucleoprotein G (SNRPG) onto viral labels.
Source code in tcrsift/annotate.py
def canonicalize_antigen(
    antigen: str | None, species: str | None = None
) -> str | None:
    """Map a raw antigen/protein string to its canonical protein/antigen label.

    Strictly word-bounded and organism-aware:

    - Distinguishes proteins/proteoforms from encoding genes: both ``CTAG1A`` and
      ``CTAG1B`` canonicalize to ``"NY-ESO-1"``, whereas ``CTAG2`` canonicalizes to
      ``"LAGE-1"``; ``CEACAM5`` and ``Carcinoembryonic antigen`` canonicalize to
      ``"CEA"`` while ``CEACAM1``/``CEACAM6`` stay untouched; ``ERBB2`` → ``"HER2"``
      while ``ERBB2IP`` stays untouched; ``MAGE-A10`` / ``MAGEA12`` keep their
      exact paralog numbers rather than collapsing into ``MAGE-A1``.
    - Disambiguates shared viral protein names (``Nucleoprotein``,
      ``Nucleocapsid``, ``NS3``, ``Spike``, ``IE1``) using ``species`` (or an
      inline ``[organism]`` suffix), and never maps host self proteins such as
      human ``Small nuclear ribonucleoprotein G`` (``SNRPG``) onto viral labels.
    """
    if pd.isna(antigen):
        return None
    raw = str(antigen).strip()
    if not raw:
        return ""
    org = _extract_org_hint(raw, species)
    is_host_org = org in _HOST_SPECIES_SET

    # Strip trailing [organism] before matching so organism names inside brackets
    # don't accidentally match protein patterns.
    clean = _INLINE_BRACKET_ORG_RE.sub("", raw).strip() or raw

    # 1. Dynamic numbered MAGE family (MAGE-A1..A12, MAGE-B*, MAGE-C*).
    m_mage = _MAGE_NUMBERED_RE.search(clean)
    if m_mage:
        return f"MAGE-{m_mage.group(1).upper()}{int(m_mage.group(2))}"
    if _MAGE_A_BARE_RE.search(clean):
        return "MAGE-A"

    # 2. CEA / CEACAM5 (excluding other CEACAM paralogs like CEACAM1/CEACAM6).
    if _CEA_MATCH_RE.search(clean) and not _CEA_OTHER_PARALOG_RE.search(clean):
        return "CEA"

    # 3. Curated tumor/self/model proteins.
    for rx, canonical in _SELF_TUMOR_PROTEIN_RULES:
        if rx.search(clean):
            return canonical

    # Host proteins that didn't hit a curated self/tumor alias stay verbatim
    # (never fall through to viral protein heuristics).
    if is_host_org:
        return raw

    lowered = clean.lower()

    # 4. Murine viral antigens (LCMV, MCMV, MuLV, Sendai, VSV).
    if org == "Mouse CMV" or re.search(r"\bmcmv\b", lowered):
        if re.search(r"\bm45\b", lowered):
            return "MCMV M45"
        if re.search(r"\bm38\b", lowered):
            return "MCMV M38"
        if re.search(r"\bm139\b", lowered):
            return "MCMV m139"
        if re.search(r"\bm57\b", lowered):
            return "MCMV M57"
        if re.search(r"\bie1\b|immediate[- ]early", lowered):
            return "MCMV IE1"

    if org == "LCMV" or re.search(r"\blcmv\b", lowered):
        if re.search(r"glycoprotein|\bgpc?\b|\bgp(?:33|61|276)\b", lowered):
            return "LCMV GP"
        if re.search(r"\bnucleoprotein\b|\bnucleocapsid\b|\bnp\b", lowered):
            return "LCMV NP"

    if org == "MuLV" or re.search(r"\bmulv\b|murine leukemia", lowered):
        if re.search(r"\bp15e\b", lowered):
            return "MuLV p15E"
        if re.search(r"\bgp70\b|\bah1\b", lowered):
            return "MuLV gp70"
        if re.search(r"\benv(?:elope)?\b", lowered):
            return "MuLV Env"
    elif re.search(r"\bp15e\b", lowered):
        return "MuLV p15E"

    # 5. Human & shared viral / bacterial antigens (word-bounded + species-aware).
    if re.search(r"65 kda phosphoprotein|phosphoprotein 65|\bcmv pp65\b|\bpp65\b|\bul83\b", lowered):
        return "CMV pp65"
    if re.search(
        r"55 kda immediate-early|regulatory protein ie1|immediate[- ]early (?:protein )?1\b|\bcmv ie1\b|\bul123\b",
        lowered,
    ):
        if org == "Mouse CMV":
            return "MCMV IE1"
        if org in (None, "", "CMV") or "cmv" in lowered or "ul123" in lowered:
            return "CMV IE1"
        return f"{org} IE1"

    if re.search(r"nuclear antigen ebna-?3|\bebna-?3[abc]?\b", lowered):
        return "EBV EBNA-3"
    if re.search(r"nuclear antigen ebna-?1|\bebna-?1\b", lowered):
        return "EBV EBNA-1"
    if re.search(r"\bbzlf1\b", lowered):
        return "EBV BZLF1"
    if re.search(r"\bbmlf1\b", lowered):
        return "EBV BMLF1"
    if re.search(r"\bbrlf1\b", lowered):
        return "EBV BRLF1"
    if re.search(r"\blmp1\b", lowered):
        return "EBV LMP1"
    if re.search(r"\blmp2a?\b", lowered):
        return "EBV LMP2"

    if re.search(r"matrix protein 1\b|matrix protein m1\b|\bm1 protein\b|influenza a virus matrix", lowered):
        return "Flu M1"
    if re.search(r"\bhemagglutinin\b", lowered):
        if (
            org in (None, "", "Influenza", "Influenza A", "Influenza B")
            or "influenza" in lowered
            or re.search(r"\bflu\b", lowered)
        ):
            return "Flu HA"
        return f"{org} HA"

    if re.search(r"\bnucleoprotein\b|\bnp protein\b", lowered):
        if org in (None, "", "Influenza", "Influenza A", "Influenza B"):
            return "Flu NP"
        if org == "Sendai virus":
            return "Sendai NP"
        if org == "VSV":
            return "VSV N"
        if org == "SARS-CoV-2":
            return "SARS-CoV-2 N"
        if org == "SARS-CoV-1":
            return "SARS-CoV-1 N"
        return f"{org} NP"

    if re.search(r"replicase polyprotein 1ab?\b|orf1ab(?: polyprotein)?\b", lowered):
        if org == "SARS-CoV-1":
            return "SARS-CoV-1 ORF1ab"
        if org in (None, "", "SARS-CoV-2") or "sars" in lowered:
            return "SARS-CoV-2 ORF1ab"
        return f"{org} ORF1ab"

    if re.search(r"spike glycoprotein|surface glycoprotein|\bspike protein\b|sars-cov-2 spike", lowered):
        if org == "SARS-CoV-1":
            return "SARS-CoV-1 Spike"
        if org == "VSV":
            return "VSV G"
        if org in (None, "", "SARS-CoV-2") or (
            species is None and org in ("Pangolin coronavirus", "Bat coronavirus")
        ):
            return "SARS-CoV-2 Spike"
        return f"{org} Spike"

    if re.search(r"\bnucleocapsid\b", lowered):
        if org == "SARS-CoV-1":
            return "SARS-CoV-1 N"
        if org == "HBV":
            return "HBV Core"
        if org == "VSV":
            return "VSV N"
        if org in (None, "", "SARS-CoV-2"):
            return "SARS-CoV-2 N"
        return f"{org} N"

    if re.search(r"\bgag polyprotein\b|\bhiv[- ]?1? gag\b", lowered):
        return "HIV Gag"
    if re.search(r"\bnef protein\b|\bhiv[- ]?1? nef\b", lowered):
        return "HIV Nef"
    if re.search(r"protein tax-1\b|transcriptional activator tax\b|\btax-1\b", lowered):
        return "HTLV-1 Tax"

    if re.search(r"\bns3\b|non[- ]?structural protein (?:ns)?3\b", lowered):
        if org == "Dengue virus":
            return "Dengue NS3"
        if org == "Zika virus":
            return "Zika NS3"
        if org == "Yellow fever virus":
            return "YFV NS3"
        if org in (None, "", "HCV"):
            return "HCV NS3"
        return f"{org} NS3"
    if re.search(r"\bns5b\b", lowered):
        return "HCV NS5B"

    if re.search(r"\besat-?6\b|\besxa\b", lowered):
        return "ESAT-6"
    if re.search(r"\blisteriolysin\b|\bhly\b", lowered):
        return "LLO"

    return raw

resolve_antigen_gene

resolve_antigen_gene(antigen: str | None, canonical_protein: str | None = None, species: str | None = None) -> str | None

Resolve the official encoding gene symbol (HGNC/MGI) for an endogenous antigen.

Returns None for viral, bacterial, and foreign exogenous antigens (such as chicken OVA or CMV pp65) so db_antigen_gene strictly holds host or tumor gene symbols while db_protein_canonical holds the protein or antigen name.

Source code in tcrsift/annotate.py
def resolve_antigen_gene(
    antigen: str | None,
    canonical_protein: str | None = None,
    species: str | None = None,
) -> str | None:
    """Resolve the official encoding gene symbol (HGNC/MGI) for an endogenous antigen.

    Returns ``None`` for viral, bacterial, and foreign exogenous antigens (such as
    chicken ``OVA`` or ``CMV pp65``) so ``db_antigen_gene`` strictly holds host
    or tumor gene symbols while ``db_protein_canonical`` holds the protein or
    antigen name.
    """
    if pd.isna(antigen) and pd.isna(canonical_protein):
        return None
    raw = "" if pd.isna(antigen) else str(antigen).strip()
    clean = _INLINE_BRACKET_ORG_RE.sub("", raw).strip() if raw else ""
    org = _extract_org_hint(raw, species) if raw else canonicalize_species(species)

    # Foreign / pathogen species do not map to endogenous host gene symbols.
    if org is not None and org not in {"Homo sapiens", "Mus musculus"}:
        return None

    is_mouse = org == "Mus musculus"
    canon = (
        canonical_protein
        if (isinstance(canonical_protein, str) and canonical_protein)
        else canonicalize_antigen(raw, species=species)
    )
    if canon in _NON_GENE_CANONICAL_ANTIGENS:
        return None

    # Paralog-exact CTAG1A vs CTAG1B preservation before generic NY-ESO-1 lookup.
    if re.search(r"\bctag1a\b", clean, re.I):
        return None if is_mouse else "CTAG1A"
    if re.search(r"\bctag1b\b", clean, re.I):
        return None if is_mouse else "CTAG1B"

    # Dynamic MAGE paralogs (MAGE-A1 -> MAGEA1, MAGE-A10 -> MAGEA10, etc.).
    if isinstance(canon, str):
        m_mage = re.match(r"^MAGE-([ABC])(\d+)$", canon)
        if m_mage:
            sub, num = m_mage.group(1), m_mage.group(2)
            return f"Mage{sub.lower()}{num}" if is_mouse else f"MAGE{sub}{num}"

    if isinstance(canon, str):
        table = _CANONICAL_PROTEIN_TO_GENE_MGI if is_mouse else _CANONICAL_PROTEIN_TO_GENE_HGNC
        if canon in table:
            return table[canon]

    # When the source organism is explicitly human or mouse and the raw field is
    # already a clean bare HGNC/MGI gene symbol (e.g. SNRPG, ERBB2IP, TP53, Adpgk,
    # Trp53), preserve it verbatim.
    if org == "Homo sapiens" and clean and clean.upper() not in _NON_GENE_BARE_TOKENS:
        if _BARE_HGNC_SYMBOL_RE.match(clean):
            return clean
    if org == "Mus musculus" and clean and clean.upper() not in _NON_GENE_BARE_TOKENS:
        if _BARE_MGI_SYMBOL_RE.match(clean):
            return clean
        if _BARE_HGNC_SYMBOL_RE.match(clean):
            return clean[0].upper() + clean[1:].lower()
    return None

match_clonotypes

match_clonotypes(clonotypes: DataFrame, database: DataFrame, match_by: str = 'CDR3ab', match_strictness: str | None = None, match_mode: str = 'exact', max_distance: int = 1, verbose: bool = True, show_progress: bool = True, *, species: str = 'human', host_species_filter: str = 'all') -> pd.DataFrame

Match clonotypes against public database.

Parameters:

Name Type Description Default
clonotypes DataFrame

Clonotype DataFrame

required
database DataFrame

Combined database from load_databases

required
match_by str

Legacy matching strategy. "CDR3ab" (both chains, β-only fallback) or "CDR3b_only" (beta only). Kept for back-compat; prefer match_strictness for new code.

'CDR3ab'
match_strictness str

Explicit matching strictness. When set, takes precedence over match_by. One of:

  • "strict_ab" — αβ-only, no β-only fallback. Best when you want headline match counts you can trust.
  • "ab_with_partial" — αβ first, β-only fallback per clone (equivalent to legacy match_by="CDR3ab").
  • "b_only" — β-only across the board (equivalent to legacy match_by="CDR3b_only").
None
match_mode str

Distance regime for the β-only match (#57). When "exact", only exact-string β matches are recorded — pre-2.1 behaviour. When "levenshtein", clones that don't hit exactly fall through to a Levenshtein-≤max_distance neighbor search against the database's β CDR3s. αβ matching stays strict-exact in both modes — fuzzy αβ is too noisy biologically.

``"exact"``
max_distance int

Maximum edit distance for fuzzy β matching (only used when match_mode == "levenshtein"). Currently capped at 1 in the implementation; higher values fall back to 1 with a warning.

1
verbose bool

Print progress information

True
show_progress bool

Show progress bar

True

Returns:

Type Description
DataFrame

Clonotypes with match annotations: db_match, db_match_partial (β-only fallback flag — back-compat), db_match_strength ("ab" / "b_only" / "ab_cross" / "b_only_cross" / "b_only_near" / "b_only_near_cross" / None; _cross suffix indicates a non-human host-species match per #83; _near suffix indicates a Levenshtein-≤1 β-only fuzzy match per #57), db_match_distance (int — edit distance to the matched DB β CDR3; 0 for exact, 1 for Levenshtein-1, None when unmatched), db_epitope, db_protein, db_protein_canonical, db_species (canonical antigen source organism), db_host_species (canonical TCR donor organism, new in #83), db_mhc, db_category (viral / bacterial / self / tumor_self / other / unknown / contradictory — last when multiple matches disagree on an informative label per #83), db_category_dominant (most common informative label when unique), db_category_detail (e.g. viral / contradictory / contradictory_dominant_viral), and db_category_counts (label:count audit string), db_database, is_viral.

Source code in tcrsift/annotate.py
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
def match_clonotypes(
    clonotypes: pd.DataFrame,
    database: pd.DataFrame,
    match_by: str = "CDR3ab",
    match_strictness: str | None = None,
    match_mode: str = "exact",
    max_distance: int = 1,
    verbose: bool = True,
    show_progress: bool = True,
    *,
    species: str = "human",
    host_species_filter: str = "all",
) -> pd.DataFrame:
    """
    Match clonotypes against public database.

    Parameters
    ----------
    clonotypes : pd.DataFrame
        Clonotype DataFrame
    database : pd.DataFrame
        Combined database from load_databases
    match_by : str
        Legacy matching strategy. ``"CDR3ab"`` (both chains, β-only
        fallback) or ``"CDR3b_only"`` (beta only). Kept for back-compat;
        prefer ``match_strictness`` for new code.
    match_strictness : str, optional
        Explicit matching strictness. When set, takes precedence over
        ``match_by``. One of:

        - ``"strict_ab"`` — αβ-only, no β-only fallback. Best when you
          want headline match counts you can trust.
        - ``"ab_with_partial"`` — αβ first, β-only fallback per clone
          (equivalent to legacy ``match_by="CDR3ab"``).
        - ``"b_only"`` — β-only across the board (equivalent to legacy
          ``match_by="CDR3b_only"``).
    match_mode : str, default ``"exact"``
        Distance regime for the β-only match (#57). When ``"exact"``,
        only exact-string β matches are recorded — pre-2.1 behaviour.
        When ``"levenshtein"``, clones that don't hit exactly fall
        through to a Levenshtein-≤``max_distance`` neighbor search
        against the database's β CDR3s. αβ matching stays strict-exact
        in both modes — fuzzy αβ is too noisy biologically.
    max_distance : int, default 1
        Maximum edit distance for fuzzy β matching (only used when
        ``match_mode == "levenshtein"``). Currently capped at 1 in
        the implementation; higher values fall back to 1 with a
        warning.
    verbose : bool
        Print progress information
    show_progress : bool
        Show progress bar

    Returns
    -------
    pd.DataFrame
        Clonotypes with match annotations: ``db_match``,
        ``db_match_partial`` (β-only fallback flag — back-compat),
        ``db_match_strength`` (``"ab"`` / ``"b_only"`` / ``"ab_cross"``
        / ``"b_only_cross"`` / ``"b_only_near"`` /
        ``"b_only_near_cross"`` / None; ``_cross`` suffix indicates a
        non-human host-species match per #83; ``_near`` suffix
        indicates a Levenshtein-≤1 β-only fuzzy match per #57),
        ``db_match_distance`` (int — edit distance to the matched DB
        β CDR3; 0 for exact, 1 for Levenshtein-1, ``None`` when
        unmatched),
        ``db_epitope``, ``db_protein``, ``db_protein_canonical``,
        ``db_species`` (canonical antigen source organism),
        ``db_host_species`` (canonical TCR donor organism, new in #83),
        ``db_mhc``, ``db_category`` (``viral`` / ``bacterial`` /
        ``self`` / ``tumor_self`` / ``other`` / ``unknown`` /
        ``contradictory`` — last when multiple matches disagree on
        an informative label per #83), ``db_category_dominant`` (most
        common informative label when unique), ``db_category_detail``
        (e.g. ``viral`` / ``contradictory`` /
        ``contradictory_dominant_viral``), and
        ``db_category_counts`` (``label:count`` audit string),
        ``db_database``, ``is_viral``.
    """
    # Validate inputs
    clonotypes = validate_clonotype_df(clonotypes, for_annotation=True)
    database = validate_dataframe(database, "database", min_rows=1)

    if match_strictness is not None:
        if match_strictness not in MATCH_STRICTNESS_MODES:
            raise TCRsiftValidationError(
                f"Invalid match_strictness: '{match_strictness}'",
                hint=f"Valid options are: {list(MATCH_STRICTNESS_MODES)}",
            )
        strictness = match_strictness
    else:
        valid_match_by = ["CDR3ab", "CDR3b_only"]
        if match_by not in valid_match_by:
            raise TCRsiftValidationError(
                f"Invalid match_by: '{match_by}'",
                hint=f"Valid options are: {valid_match_by}",
            )
        strictness = "ab_with_partial" if match_by == "CDR3ab" else "b_only"

    # #57: validate fuzzy-match parameters before doing any DB work.
    if match_mode not in MATCH_MODES:
        raise TCRsiftValidationError(
            f"Invalid match_mode: {match_mode!r}",
            hint=f"Valid options are: {list(MATCH_MODES)}",
        )
    validate_numeric_param(max_distance, "max_distance", min_value=1)
    if match_mode == "levenshtein" and max_distance > 1:
        logger.warning(
            "match_mode='levenshtein' currently supports max_distance=1 "
            "only; clamping max_distance=%d → 1.", max_distance,
        )
        max_distance = 1

    from .species import resolve_species, species_to_binomial

    query_species = resolve_species(species, df=clonotypes, warn_mismatch=False)
    if host_species_filter not in ("all", "same"):
        raise TCRsiftValidationError(
            f"Invalid host_species_filter: {host_species_filter!r}",
            hint="Valid options are: ['all', 'same']",
        )

    df = clonotypes.copy()

    # Initialize annotation columns.
    df["db_match"] = False
    df["db_match_partial"] = False
    df["db_match_strength"] = None
    df["db_match_distance"] = None  # #57: edit distance to matched DB β
    df["db_match_score"] = None     # #56: composite confidence ∈ [0, 1]
    df["db_v_gene_agreement"] = None
    df["db_n_studies"] = None
    df["db_category_votes"] = None
    df["db_epitope"] = None
    df["db_protein"] = None
    df["db_protein_canonical"] = None
    df["db_antigen_gene"] = None
    df["db_species"] = None
    df["db_host_species"] = None
    df["db_mhc"] = None
    df["db_category"] = None
    df["db_category_dominant"] = None
    df["db_category_detail"] = None
    df["db_category_counts"] = None
    df["db_database"] = None
    df["is_viral"] = False

    required = {"cdr3_beta"} if strictness == "b_only" else {"cdr3_alpha", "cdr3_beta"}
    missing = required - set(database.columns)
    if missing:
        dbs = sorted(set(database.get("database", pd.Series(["unknown"]))))
        logger.warning(
            f"Skipping annotation: database(s) {dbs} are missing required "
            f"columns {sorted(missing)} after standardization. The source "
            "file format may have changed since the loader was written. "
            "Inspect the column list before reporting this as a tcrsift bug."
        )
        return df

    if host_species_filter == "same" and "host_species" in database.columns:
        target_host = species_to_binomial(query_species)
        canon_host = canonicalize_species_labels(database["host_species"])
        keep_host = canon_host.isna() | (canon_host == target_host)
        database = database.loc[keep_host].assign(host_species=canon_host.loc[keep_host])
        if database.empty:
            if verbose:
                logger.info(
                    "  No database entries remain after host_species_filter='same' (%s)",
                    target_host,
                )
            return df

    if verbose:
        logger.info(
            f"Matching {len(clonotypes):,} clonotypes against "
            f"{len(database):,} database entries "
            f"(strictness={strictness}, mode={match_mode})"
        )

    database = _canonicalize_database_species(database)

    species_col = (
        database["species"]
        if "species" in database.columns
        else pd.Series([""] * len(database), index=database.index)
    )
    antigen_col = (
        database["antigen_gene"]
        if "antigen_gene" in database.columns
        else pd.Series([""] * len(database), index=database.index)
    )
    new_columns: dict[str, pd.Series] = {}
    if "db_protein_canonical" not in database.columns:
        new_columns["db_protein_canonical"] = canonicalize_antigens(
            antigen_col, species=species_col
        )
    canon_col = new_columns.get("db_protein_canonical", database.get("db_protein_canonical"))
    if "db_category" not in database.columns:
        new_columns["db_category"] = classify_category(
            species_col,
            antigen_col,
            query_species=query_species,
            canonical_proteins=canon_col,
        )
    if "db_antigen_gene" not in database.columns:
        new_columns["db_antigen_gene"] = resolve_antigen_genes(
            antigen_col, canonical_proteins=canon_col, species=species_col
        )
    if new_columns:
        database = database.assign(**new_columns)

    # Normalize database CDR3 strings (strip whitespace + uppercase) once
    db_cdr3_updates: dict[str, pd.Series] = {}
    for col in ("cdr3_alpha", "cdr3_beta"):
        if col in database.columns:
            s = database[col]
            db_cdr3_updates[col] = s.where(
                s.isna(), s.astype(str).str.strip().str.upper()
            )
    if db_cdr3_updates:
        database = database.assign(**db_cdr3_updates)

    beta_neighbor_index: dict[str, set[str]] | None = (
        _build_cdr3_neighbor_index(database["cdr3_beta"])
        if match_mode == "levenshtein" and strictness != "strict_ab"
        else None
    )

    # Work on a clean 0..N-1 index internally so duplicate indices on the input
    # DataFrame never corrupt label-based _annotate_match writes; restore on return.
    orig_index = df.index
    df = df.reset_index(drop=True)

    # Pre-index positional row slices by CDR3β and paired (CDR3α, CDR3β) once
    # so per-clone lookups run in O(1) instead of scanning a 140k-row DataFrame.
    import numpy as np

    b_to_pos: dict[str, np.ndarray] = {}
    if strictness in ("ab_with_partial", "b_only"):
        valid_b = database["cdr3_beta"].notna() & (database["cdr3_beta"].astype(str) != "")
        if valid_b.any():
            b_sub = database.loc[valid_b, "cdr3_beta"].astype(str)
            b_positions = np.flatnonzero(valid_b.to_numpy())
            for beta_key, rel_idx in b_sub.groupby(b_sub, sort=False).indices.items():
                if len(rel_idx):
                    b_to_pos[str(beta_key)] = b_positions[rel_idx]

    if strictness in ("strict_ab", "ab_with_partial"):
        allow_b_fallback = strictness == "ab_with_partial"
        valid_ab = (
            database["cdr3_alpha"].notna()
            & (database["cdr3_alpha"].astype(str) != "")
            & database["cdr3_beta"].notna()
            & (database["cdr3_beta"].astype(str) != "")
        )
        ab_to_pos: dict[tuple[str, str], np.ndarray] = {}
        if valid_ab.any():
            ab_positions = np.flatnonzero(valid_ab.to_numpy())
            ab_sub = database.loc[valid_ab, ["cdr3_alpha", "cdr3_beta"]].astype(str)
            for (a_key, b_key), rel_idx in ab_sub.groupby(
                ["cdr3_alpha", "cdr3_beta"], sort=False
            ).indices.items():
                if len(rel_idx):
                    ab_to_pos[(str(a_key), str(b_key))] = ab_positions[rel_idx]

        row_iter = df.iterrows()
        if show_progress:
            row_iter = tqdm(
                list(df.iterrows()),
                desc="Matching clonotypes",
                unit="clone",
            )

        for idx, row in row_iter:
            raw_a = row.get("CDR3_alpha", "")
            raw_b = row.get("CDR3_beta", "")
            alpha = raw_a.strip().upper() if isinstance(raw_a, str) else ""
            beta = raw_b.strip().upper() if isinstance(raw_b, str) else ""

            if alpha and beta and (alpha, beta) in ab_to_pos:
                matches = database.iloc[ab_to_pos[(alpha, beta)]]
                _annotate_match(
                    df, idx, matches, strength="ab", distance=0, query_species=query_species
                )
            elif allow_b_fallback and beta and beta in b_to_pos:
                matches = database.iloc[b_to_pos[beta]]
                _annotate_match(
                    df, idx, matches, strength="b_only", partial=True, distance=0,
                    query_species=query_species,
                )
            elif allow_b_fallback and beta_neighbor_index is not None and beta:
                neighbors = _find_lev_neighbors(beta, beta_neighbor_index, max_distance)
                if neighbors:
                    best_d = neighbors[0][1]
                    pos_list = [b_to_pos[c] for c, d in neighbors if d == best_d and c in b_to_pos]
                    if pos_list:
                        pos = np.sort(np.concatenate(pos_list))
                        matches = database.iloc[pos]
                        _annotate_match(
                            df, idx, matches,
                            strength="b_only_near", partial=True, distance=best_d,
                            query_species=query_species,
                        )

    else:  # strictness == "b_only"
        row_iter = df.iterrows()
        if show_progress:
            row_iter = tqdm(
                list(df.iterrows()),
                desc="Matching clonotypes",
                unit="clone",
            )

        for idx, row in row_iter:
            raw_b = row.get("CDR3_beta", "")
            beta = raw_b.strip().upper() if isinstance(raw_b, str) else ""
            if beta and beta in b_to_pos:
                matches = database.iloc[b_to_pos[beta]]
                _annotate_match(
                    df, idx, matches, strength="b_only", distance=0,
                    query_species=query_species,
                )
            elif beta_neighbor_index is not None and beta:
                neighbors = _find_lev_neighbors(beta, beta_neighbor_index, max_distance)
                if neighbors:
                    best_d = neighbors[0][1]
                    pos_list = [b_to_pos[c] for c, d in neighbors if d == best_d and c in b_to_pos]
                    if pos_list:
                        pos = np.sort(np.concatenate(pos_list))
                        matches = database.iloc[pos]
                        _annotate_match(
                            df, idx, matches,
                            strength="b_only_near", distance=best_d,
                            query_species=query_species,
                        )

    df.index = orig_index
    n_matches = df["db_match"].sum()
    n_viral = df["is_viral"].sum()
    if verbose:
        logger.info(f"  Found {n_matches:,} matches ({n_viral:,} viral)")

    return df

annotate_clonotypes

annotate_clonotypes(clonotypes: DataFrame, vdjdb_path: str | Path | None = None, iedb_path: str | Path | None = None, cedar_path: str | Path | None = None, iedb_epitope_path: str | Path | None = None, match_by: str = 'CDR3ab', match_strictness: str | None = None, match_mode: str = 'exact', max_distance: int = 1, exclude_viral: bool = False, flag_only: bool = False, *, verbose: bool = True, show_progress: bool = True, add_publicness: bool = False, publicness_cdr3_col: str = 'CDR3_beta', publicness_v_gene_col: str = 'beta_v_gene', publicness_j_gene_col: str = 'beta_j_gene', species: str = 'human', host_species_filter: str = 'all') -> pd.DataFrame

Main annotation function.

Source code in tcrsift/annotate.py
def annotate_clonotypes(
    clonotypes: pd.DataFrame,
    vdjdb_path: str | Path | None = None,
    iedb_path: str | Path | None = None,
    cedar_path: str | Path | None = None,
    iedb_epitope_path: str | Path | None = None,
    match_by: str = "CDR3ab",
    match_strictness: str | None = None,
    match_mode: str = "exact",
    max_distance: int = 1,
    exclude_viral: bool = False,
    flag_only: bool = False,
    *,
    verbose: bool = True,
    show_progress: bool = True,
    add_publicness: bool = False,
    publicness_cdr3_col: str = "CDR3_beta",
    publicness_v_gene_col: str = "beta_v_gene",
    publicness_j_gene_col: str = "beta_j_gene",
    species: str = "human",
    host_species_filter: str = "all",
) -> pd.DataFrame:
    """Main annotation function."""
    from .species import resolve_species

    resolved_species = resolve_species(species, df=clonotypes, warn_mismatch=False)
    _DEFAULT_ANNOTATION_COLUMNS = {
        "db_match": False,
        "db_match_partial": False,
        "db_match_strength": None,
        "db_match_distance": None,
        "db_match_score": None,
        "db_v_gene_agreement": None,
        "db_n_studies": None,
        "db_category_votes": None,
        "db_epitope": None,
        "db_protein": None,
        "db_protein_canonical": None,
        "db_antigen_gene": None,
        "db_species": None,
        "db_host_species": None,
        "db_mhc": None,
        "db_category": None,
        "db_category_dominant": None,
        "db_category_detail": None,
        "db_category_counts": None,
        "db_database": None,
        "is_viral": False,
    }

    if not any([vdjdb_path, iedb_path, cedar_path]):
        if verbose:
            logger.info("No annotation database paths provided; returning input with empty annotations")
        df = clonotypes.copy()
        if "CDR3ab" not in df.columns and {"CDR3_alpha", "CDR3_beta"} <= set(df.columns):
            df["CDR3ab"] = df["CDR3_alpha"].fillna("") + "_" + df["CDR3_beta"].fillna("")
        for col, default in _DEFAULT_ANNOTATION_COLUMNS.items():
            if col not in df.columns:
                df[col] = default
        if add_publicness:
            df = _apply_publicness(
                df,
                cdr3_col=publicness_cdr3_col,
                v_gene_col=publicness_v_gene_col,
                j_gene_col=publicness_j_gene_col,
                log_summary=False,
                species=resolved_species,
            )
        return df

    database = load_databases(
        vdjdb_path=vdjdb_path,
        iedb_path=iedb_path,
        cedar_path=cedar_path,
        iedb_epitope_path=iedb_epitope_path,
        verbose=verbose,
    )

    df = match_clonotypes(
        clonotypes,
        database,
        match_by=match_by,
        match_strictness=match_strictness,
        match_mode=match_mode,
        max_distance=max_distance,
        verbose=verbose,
        show_progress=show_progress,
        species=resolved_species,
        host_species_filter=host_species_filter,
    )

    if exclude_viral and not flag_only:
        initial = len(df)
        df = df[~df["is_viral"]]
        if verbose:
            logger.info(f"Excluded {initial - len(df)} viral clones")

    if add_publicness:
        df = _apply_publicness(
            df,
            cdr3_col=publicness_cdr3_col,
            v_gene_col=publicness_v_gene_col,
            j_gene_col=publicness_j_gene_col,
            log_summary=verbose,
            species=resolved_species,
        )

    return df

get_annotation_summary

get_annotation_summary(clonotypes: DataFrame) -> dict

Get summary of annotation results.

Returns:

Type Description
dict

Summary statistics

Source code in tcrsift/annotate.py
def get_annotation_summary(clonotypes: pd.DataFrame) -> dict:
    """
    Get summary of annotation results.

    Returns
    -------
    dict
        Summary statistics
    """
    summary = {
        "total": len(clonotypes),
        "matched": clonotypes["db_match"].sum() if "db_match" in clonotypes.columns else 0,
        "viral": clonotypes["is_viral"].sum() if "is_viral" in clonotypes.columns else 0,
    }

    if "db_database" in clonotypes.columns:
        db_counts = {}
        for db in ["VDJdb", "IEDB", "CEDAR"]:
            db_counts[db] = clonotypes["db_database"].fillna("").str.contains(db).sum()
        summary["database_breakdown"] = db_counts

    if "db_species" in clonotypes.columns:
        species_counts = clonotypes["db_species"].value_counts().head(10).to_dict()
        summary["top_species"] = species_counts

    return summary