Tangram

repository·master·Indexed 18 days ago

https://github.com/broadinstitute/tangram

A Python package for mapping single-cell or single-nucleus gene expression data onto spatial gene expression data. Using PyTorch, Tangram aligns single-cell data in space by fitting gene expression on shared genes. It supports mapping at both the cell and cluster levels and provides utilities for preprocessing AnnData objects, optimizing mappings via the Mapper and MapperConstrained classes, and visualizing results through plot_utils.

Tokens
7.6K
Snippets
35
Records
59
Agent score
62%

What's inside Tangram

  1. What is Tangram?

    master

    Tangram is a Python package built on PyTorch and scanpy designed for mapping single-cell (or single-nucleus) gene expression data onto spatial gene expression data.

    To use Tangram effectively, your datasets should meet the following criteria:

    • Biological Context: The single-cell dataset and the spatial dataset should be collected from the same anatomical region or tissue type (ideally from a biological replicate).
    • Gene Overlap: The datasets must share a set of genes.

    Tangram performs spatial alignment by fitting gene expression on these shared genes.

  2. Use the `tangram.mapping_optimizer` module for mapping optimization

    master

    The tangram.mapping_optimizer module provides classes to optimize the mapping between different data representations (e.g., cell types or gene sets) using optimization techniques. It primarily exposes two classes for this purpose:

    • Mapper: A standard mapper for finding optimal alignments or mappings.
    • MapperConstrained: A mapper that allows for constraints to be applied during the optimization process, ensuring that certain mapping rules or boundaries are respected.
  3. Use tangram.mapping_utils for cell and cluster mapping

    master

    The tangram.mapping_utils module provides utility functions for mapping cells to a spatial reference and processing AnnData objects for downstream analysis.

    Key functions include:

    • map_cells_to_space: Maps cells to a spatial reference.
    • adata_to_cluster_expression: Converts an AnnData object into cluster-level expression data.
    • pp_adatas: Performs preprocessing on multiple AnnData objects.
  4. How Tangram mapping works

    master

    Tangram finds a mapping matrix $M$ (shape: voxels-by-cells) by maximizing the similarity between the projected single-cell gene expression and the observed spatial gene expression.

    Specifically, it maximizes the cosine similarity between the single-cell matrix $S$ (cell-by-training-genes) and the spatial matrix $G$ (voxels-by-genes). The element $M_{ij}$ signifies the probability of cell $i$ being located in voxel $j$.

  5. Cell segmentation requirements for Visium and Slide-seq

    master

    Whether you need cell segmentation depends on your specific goal:

    • For Mapping: You do not need to segment cells in your histology for mapping on spatial transcriptomics data (such as Visium or Slide-seq).
    • For Deconvolution: You do need cell segmentation if you intend to deconvolve the data (i.e., deterministically assigning a single cell profile to each cell within a spatial voxel).
  6. How Tangram works under the hood

    master

    Tangram performs cell-type mapping by finding a mapping matrix $M$ (shape: voxels-by-cells) that minimizes a loss function. The goal is to ensure that the gene expression of the mapped single cells is as similar as possible to the spatial data $G$ using cosine similarity.

    To instantiate the process, Tangram uses a Mapper object with two primary inputs:

    • _S_: A single cell matrix with shape cell-by-gene. The number of genes must match the training genes.
    • _G_: A spatial data matrix with shape voxels-by-genes. A single voxel can contain multiple cells.

    The optimization seeks to minimize the loss between the reconstructed spatial expression and the observed spatial expression, where the mapping $M$ represents the probability of cell $i$ being in spot $j$.

  7. Run Tangram at the cluster level

    master

    To enable faster training and reduce memory consumption, you can perform mapping at the cell cluster level instead of individual cells.

    1. Map: Call tg.map_cells_to_space with mode='clusters' and provide a cluster_label. The cluster_label must be a column existing in ad_sc.obs.
    2. Project: When calling tg.project_genes, you must pass the same cluster_label used during the mapping step.
    import tangram as tg
    
    # Map at the cluster level
    ad_map = tg.map_cells_to_space(
        ad_sc, 
        ad_sp,         
        mode='clusters',
        cluster_label='subclass_label'
    )
    
    # Project gene expression using the same cluster label
    ad_ge = tg.project_genes(
        ad_map, 
        ad_sc,
        cluster_label='subclass_label'
    )
  8. Run Tangram at the cell level

    master

    Cell-level mapping involves pre-processing single-cell and spatial datasets, mapping cells to spatial voxels, and then projecting gene expression.

    1. Pre-process: Use tg.pp_adatas(ad_sc, ad_sp, genes=None) to find common genes. This function saves the intersected genes in adatas.uns for later use. If genes=None, it uses all shared genes. If a specific set of training genes is provided, it subsets to those.
    2. Map: Use tg.map_cells_to_space(ad_sc, ad_sp) to generate a cell-by-voxel probability matrix.
    3. Project: Use tg.project_genes(ad_map, ad_sc) to project gene expression from single cells to the spatial voxels, resulting in a voxel-by-gene AnnData object.
    import tangram as tg
    import scanpy as sc
    
    # 1. Load and pre-process
    ad_sp = sc.read_h5ad('spatial_data.h5ad')
    ad_sc = sc.read_h5ad('single_cell_data.h5ad')
    tg.pp_adatas(ad_sc, ad_sp, genes=None)
    
    # 2. Map cells to space
    ad_map = tg.map_cells_to_space(ad_sc, ad_sp)
    
    # 3. Project gene expression
    ad_ge = tg.project_genes(ad_map, ad_sc)
  9. Run Tangram at cluster level

    master

    To reduce memory consumption and speed up training, you can perform mapping at the cell cluster level. This requires providing a cluster_label that exists in ad_sc.obs.

    When projecting genes after cluster-level mapping, you must pass the same cluster_label to tg.project_genes.

    # Mapping at cluster level
    ad_map = tg.map_cells_to_space(
        ad_sc, 
        ad_sp,         
        mode='clusters',
        cluster_label='subclass_label'
    )
    
    # Projecting genes with cluster label
    ad_ge = tg.project_genes(
        ad_map, 
        ad_sc,
        cluster_label='subclass_label'
    )
  10. How to choose training genes for mapping

    master

    When selecting a list of training genes for mapping, consider the following strategies:

    1. Marker Gene Approach: Use the top 1,000 unique marker genes, stratified across different cell types.
    2. Whole Transcriptome: Map using the entire transcriptome.

    Best Practices: Ensure your training genes contain high-quality signals. Avoid sets where most genes are prone to dropouts or were obtained with low-quality RNA probes, as this will decrease mapping accuracy.

  11. Run Tangram with refinements for improved consistency

    master

    You can improve mapping consistency by using additional regularization parameters in tg.map_cells_to_space.

    Requirements for Refinement:

    • If lambda_neighborhood_g1, lambda_ct_islands, or lambda_getis_ord are non-zero, spatial information must be provided in ad_sc.obsm['spatial'].
    • If lambda_ct_islands is non-zero, a cluster_label must be provided.

    Regularization Parameters:

    • lambda_r: Regularization parameter.
    • lambda_l2: L2 regularization.
    • lambda_neighborhood_g1: Neighborhood regularization.
    • lambda_ct_islands: Cell type island regularization.
    • lambda_getis_ord: Getis-Ord spatial statistics regularization.

    When projecting genes after using these refinements, ensure you pass the same cluster_label to tg.project_genes.

    # Mapping with refinements
    ad_map = tg.map_cells_to_space(
        ad_sc, 
        ad_sp,         
        mode='cells',
        cluster_label='subclass_label',
        lambda_r = 2.95e-9, 
        lambda_l2 = 1.00e-18, 
        lambda_neighborhood_g1 = 0.96, 
        lambda_ct_islands = 0.17, 
        lambda_getis_ord = 0.71
    )
    
    # Projecting genes
    ad_ge = tg.project_genes(
        ad_map, 
        ad_sc,
        cluster_label='subclass_label'
    )