Scirpy: Single-cell Adaptive Immune Receptor Repertoire Analysis

repository·main·Indexed 42 days ago

https://github.com/scverse/scirpy

A Python library for analyzing T cell receptor (TCR) and B cell receptor (BCR) repertoires from single-cell RNA sequencing (scRNA-seq) data. Integrated with the scverse ecosystem (Scanpy and MuData), it provides tools for quality control, clonotype definition, clonal diversity analysis, V(D)J gene usage, and sequence distance calculations via the ir_dist module.

Tokens
20.1K
Snippets
60
Records
96
Agent score
49%

What's inside Scirpy

  1. Overview of Scirpy

    main

    Scirpy is a Python package designed for analyzing T cell receptor (TCR) or B cell receptor (BCR) repertoires from single-cell RNA sequencing (scRNA-seq) data.

    It is built to integrate seamlessly with the scverse ecosystem, specifically supporting [scanpy] and [mudata]. It provides specialized modules for:

    • Data import
    • Analysis
    • Visualization
  2. Understand Scirpy's receptor and chain models

    main

    Scirpy models immune receptors (IR) using several key biological abstractions:

    Chain Types

    • VJ chains: Chains assembled from V and J loci only (e.g., TCR-$\alpha$, TCR-$\gamma$, IG-$\kappa$, IG-$\lambda$).
    • VDJ chains: Chains assembled from V, D, and J segments (e.g., TCR-$\beta$, TCR-$\delta$, IG-heavy).

    Receptor Configurations

    • Dual IR: Cells with more than one pair of VJ and VDJ sequences.
    • Multichain-cell: Cells with more than two pairs of VJ and VDJ sequences. These are often technical artifacts (cell-multiplets) rather than biological reality.
    • Orphan chain: A chain where the counterpart was not detected.

    Loci Support

    Scirpy supports all valid IMGT locus names, including:

    • VJ Loci: TRA, TRG, IGL, IGK.
    • VDJ Loci: TRB, TRD, IGH.
  3. Use Scirpy tools for immune receptor analysis

    main

    The scirpy.tl module contains tools that add interpretable annotations to an AnnData object. These annotations can often be visualized using corresponding functions in scirpy.pl.

    Tools are categorized by task:

    Quality Control

    • tl.chain_qc: Perform quality control on chains.

    Clonotype Definition and Visualization

    • tl.define_clonotypes: Define clonotypes.
    • tl.define_clonotype_clusters: Define clonotype clusters.
    • tl.clonotype_convergence: Analyze clonotype convergence.
    • tl.clonotype_network: Generate clonotype networks.
    • tl.clonotype_network_igraph: Generate clonotype networks as igraph objects.

    Clonal Diversity Analysis

    • tl.clonal_expansion: Analyze clonal expansion.
    • tl.summarize_clonal_expansion: Summarize clonal expansion.
    • tl.alpha_diversity: Calculate alpha diversity.
    • tl.repertoire_overlap: Analyze repertoire overlap.
    • tl.clonotype_modularity: Analyze clonotype modularity.
    • tl.clonotype_imbalance: Analyze clonotype imbalance.

    Reference Database Queries

    • tl.ir_query: Query reference databases.
    • tl.ir_query_annotate: Annotate with reference database.
    • tl.ir_query_annotate_df: Annotate with reference database (returning a DataFrame).

    Gene Usage and Mutations

    • tl.spectratype: Analyze V(D)J gene usage.
    • tl.mutational_load: Calculate mutational load.
  4. How Scirpy handles dual-IR and multichain cells

    main

    Scirpy supports the investigation of both single- and dual-IR (Immune Receptor) cells. Instead of discarding cells with multiple productive CDR3 sequences, Scirpy uses a primary/secondary model:

    • Primary pair: The VJ and VDJ chains with the highest read count.
    • Secondary pair: The VJ and VDJ chains with the second highest expression level.

    Multichain-cells: If a cell has more than two variants of a chain recovered, Scirpy ignores the excess chains and flags the cell as a Multichain-cell. Users can then decide whether to include or discard these flagged cells in their downstream analysis.

  5. Understand the Scirpy clonotype and clonotype cluster model

    main

    Scirpy uses a hierarchical approach to group immune cells based on their receptor sequences:

    1. Clonotypes: Defined by cells sharing identical CDR3 nucleotide sequences for both VJ and VDJ chains (e.g., both $\alpha$ and $\beta$ TCR chains).
      • Note: Scirpy can optionally require identical V-genes to enforce CDR1 and CDR2 similarity.
    2. Clonotype Clusters: Defined by grouping cells based on their CDR3 amino acid sequences. This includes:
      • Identical CDR3 amino acid sequences.
      • Similar CDR3 amino acid sequences determined via pairwise sequence alignment.

    This dual approach allows for both high-fidelity nucleotide-level tracking and broader epitope-focused similarity analysis using amino acid sequences.

  6. Visualize Scirpy analysis results

    main

    The scirpy.pl module provides plotting functions for visualizing the results of Scirpy tools.

    Note on Workflow: Many plotting functions have a corresponding tool in scirpy.tl. Depending on the computational load, you may need to call the tool first to precompute and store results in the AnnData object before calling the plotting function. Some functions may invoke the tool on-the-fly.

    Common Plotting Functions

    • pl.alpha_diversity: Plot alpha diversity.
    • pl.clonal_expansion: Plot clonal expansion.
    • pl.group_abundance: Plot group abundance.
    • pl.spectratype: Plot spectratype.
    • pl.vdj_usage: Plot V(D)J usage.
    • pl.repertoire_overlap: Plot repertoire overlap.
    • pl.clonotype_modularity: Plot clonotype modularity.
    • pl.clonotype_imbalance: Plot clonotype imbalance.
    • pl.logoplot_cdr3_motif: Plot CDR3 motifs.
    • pl.embedding: Plot embeddings (generic).

    Base and Styling

    • pl.base: Provides base plotting primitives like bar, line, barh, and curve.
    • pl.styling: Functions for axis styling like apply_style_to_axes and style_axes.
  7. Understand the Scirpy AIRR data structure in AnnData

    main

    Scirpy stores AIRR rearrangement data as an awkward array in adata.obsm["airr"]. This allows for a lossless representation of the AIRR standard where one cell can have multiple receptor chains of variable length.

    Structure of adata.obsm["airr"]:

    • 1st dimension: Cells (aligned to adata.obs).
    • 2nd dimension: Number of chains per cell (variable length).
    • 3rd dimension: Fields defined in the AIRR rearrangement standard (e.g., locus, junction_aa).

    Example structure:

    [
        # cell0: 2 chains
        [
            {"locus": "TRA", "junction_aa": "CADASGT..."},
            {"locus": "TRB", "junction_aa": "CTFDD..."},
        ],
        # cell1: 1 chain
        [{"locus": "IGH", "junction_aa": "CDGFFA..."}],
        # cell2: 0 chains
        [],
    ]
    # adata.obsm["airr"]
    [
        # cell0: 2 chains
        [
            {"locus": "TRA", "junction_aa": "CADASGT..."},
            {"locus": "TRB", "junction_aa": "CTFDD..."},
        ],
        # cell1: 1 chain
        [{"locus": "IGH", "junction_aa": "CDGFFA..."}],
        # cell2: 0 chains
        [],
    ]
  8. Build Scirpy documentation locally

    main

    You can build the Scirpy documentation locally using several different package managers. The documentation is built using Sphinx and supports Markdown via MyST, NumPy-style docstrings, and Jupyter notebooks via myst-nb.

    Using Hatch

    hatch run docs:build
    hatch run docs:open

    Using uv

    cd docs
    uv run sphinx-build -M html . _build -W
    (xdg-)open _build/html/index.html

    Using Pip

    source .venv/bin/activate
    cd docs
    sphinx-build -M html . _build -W
    (xdg-)open _build/html/index.html
    hatch run docs:build
  9. Import Scirpy and follow Scanpy workflow principles

    main

    Scirpy is a scverse core package that follows scanpy workflow principles. The API is organized into three main modules:

    • scirpy.pp (preprocessing)
    • scirpy.tl (tools)
    • scirpy.pl (plotting)

    All functions operate on anndata.AnnData or mudata.MuData objects. By default, functions modify the object inplace unless inplace=False is specified.

    Note that Scirpy plotting functions (e.g., scirpy.pl.clonal_expansion) may call the corresponding tool (e.g., scirpy.tl.clonal_expansion) on-the-fly without storing the results in the object. Plotting functions return a matplotlib.axes.Axes object or a list of them.

    import scanpy as sc
    import scirpy as ir
  10. Convert custom formats to Scirpy data structure

    main

    To convert your own custom data formats into the Scirpy data structure, the recommended workflow is:

    1. Build a list of scirpy.io.AirrCell objects.
    2. Convert that list into an AnnData object using scirpy.io.from_airr_cells.
  11. Import Scirpy and Scanpy

    main

    Scirpy is designed to be used alongside Scanpy. For consistency, the Scirpy API follows the Scanpy API patterns closely.

    import scanpy as sc
    import scirpy as ir
    import scanpy as sc
    import scirpy as ir
  12. Use multiple GPUs for distance calculations

    main

    To utilize multiple GPUs, use the joblib Dask backend combined with dask-cuda.

    1. Install dependencies:

      pip install "dask[distributed]" dask-cuda
    2. Configuration:

      • Set CUDA_VISIBLE_DEVICES to a comma-separated list of GPU IDs (e.g., "0,1").
      • Set n_workers, n_jobs, and n_blocks to match the number of selected GPUs.
      • n_blocks controls the number of outer partitions distributed between workers.

    Example:

    import joblib
    from dask.distributed import Client
    from dask_cuda import LocalCUDACluster
    
    with LocalCUDACluster(
        CUDA_VISIBLE_DEVICES="0,1",
        n_workers=2,
        threads_per_worker=1,
    ) as cluster, Client(cluster):
        with joblib.parallel_config(backend="dask", n_jobs=2):
            ir.pp.ir_dist(
                mdata,
                metric="gpu_hamming",
                n_blocks=2,
            )