### Install Tangram Package Source: https://github.com/broadinstitute/tangram/blob/master/README.md Instructions for installing the Tangram Python package using conda and pip. Requires PyTorch and scanpy to be pre-installed. Assumes the existence of an environment.yml file for conda environment setup. ```bash conda env create -f environment.yml conda activate tangram-env pip install tangram-sc ``` -------------------------------- ### Install Tangram via pip Source: https://github.com/broadinstitute/tangram/blob/master/docs/source/getting_started.rst Installs the tangram-sc package using pip. Ensure PyTorch and scanpy are installed beforehand. Refer to environment.yml for detailed dependencies. ```shell pip install tangram-sc ``` -------------------------------- ### Install and Import Tangram and Dependencies (Python) Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_without_squidpy.ipynb This code block installs the necessary Python packages for the Tangram tutorial, including scanpy, torch, and tangram-sc. It also imports these libraries and sets up the plotting environment. Ensure 'tangram-sc' is installed via pip or by uncommenting the sys.path modification for local imports. ```python import os, sys import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import scanpy as sc import torch sys.path.append('./') # uncomment for local import import tangram as tg %load_ext autoreload %autoreload 2 %matplotlib inline tg.__version__ ``` -------------------------------- ### Setup Tangram Environment and Imports (Python) Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_with_squidpy.ipynb Sets up the Python environment for Tangram by importing necessary libraries such as scanpy, squidpy, numpy, pandas, anndata, and matplotlib. It also prints the versions of scanpy and squidpy to ensure compatibility. The %load_ext, %autoreload, and %matplotlib inline magic commands are used for interactive development. ```python import scanpy as sc import squidpy as sq import numpy as np import pandas as pd from anndata import AnnData import pathlib import matplotlib.pyplot as plt import matplotlib as mpl import skimage import seaborn as sns import tangram as tg sc.logging.print_header() print(f"squidpy=={sq.__version__}") %load_ext autoreload %autoreload 2 %matplotlib inline ``` -------------------------------- ### Tangram Mapping Training Output Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_with_squidpy.ipynb Displays the training progress and output messages from the Tangram mapping process. This includes information about tensor allocation, training start, and periodic score printing. ```log INFO:root:Allocate tensors for mapping. INFO:root:Begin training with 1280 genes and rna_count_based density_prior in cells mode... INFO:root:Printing scores every 100 epochs. ``` -------------------------------- ### Create and Activate Tangram Conda Environment Source: https://github.com/broadinstitute/tangram/blob/master/docs/source/getting_started.rst Creates a new conda environment from the provided environment.yml file and activates it. This ensures all necessary dependencies are correctly installed for Tangram. ```shell conda env create --file environment.yml conda activate tangram-env ``` -------------------------------- ### Initialize Tangram Mapping Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_with_squidpy.ipynb Initializes the Tangram mapping process with specified parameters. It sets up the training configuration including cluster labels, density prior, number of epochs, and the device to be used for computation. ```python import tangram as tg import anndata import scanpy as sc import pandas as pd import matplotlib.pyplot as plt ad_map = tg.map_cells_to_space( adata_sc, adata_st, cluster_label='cell_subclass', # .obs field w cell types density_prior='rna_count_based', num_epochs=500, # device="cuda:0", device='cpu', ) ``` -------------------------------- ### Download and Unzip Spatial and Single-Cell Data (Shell) Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_without_squidpy.ipynb This code snippet downloads the necessary datasets for the Tangram tutorial using wget. It fetches the single-cell RNA-seq data (mop_sn_tutorial.h5ad.gz), spatial data (slideseq_MOp_1217.h5ad.gz), and marker genes (MOp_markers.csv). It then unzips the .gz files. If wget is not available, manual download instructions are provided. ```shell # Skip this cells if data are already downloaded !wget https://storage.googleapis.com/tommaso-brain-data/tangram_demo/mop_sn_tutorial.h5ad.gz -O data/mop_sn_tutorial.h5ad.gz !wget https://storage.googleapis.com/tommaso-brain-data/tangram_demo/slideseq_MOp_1217.h5ad.gz -O data/slideseq_MOp_1217.h5ad.gz !wget https://storage.googleapis.com/tommaso-brain-data/tangram_demo/MOp_markers.csv -O data/MOp_markers.csv !gunzip -f data/mop_sn_tutorial.h5ad.gz !gunzip -f data/slideseq_MOp_1217.h5ad.gz ``` -------------------------------- ### Cross-Validation for Hyperparameter Tuning Source: https://context7.com/broadinstitute/tangram/llms.txt Demonstrates the initial steps for setting up cross-validation in Tangram, such as loading and preprocessing single-cell (adata_sc) and spatial (adata_sp) data. This is a prerequisite for evaluating mapping quality and optimizing hyperparameters using techniques like leave-one-out or k-fold cross-validation. ```python import scanpy as sc import tangram as tg # Load and preprocess data adata_sc = sc.read_h5ad("single_cell_data.h5ad") adata_sp = sc.read_h5ad("spatial_data.h5ad") tg.pp_adatas(adata_sc, adata_sp, genes=None) ``` -------------------------------- ### Import Tangram Library Source: https://github.com/broadinstitute/tangram/blob/master/README.md Demonstrates how to import the Tangram library into a Python script or Jupyter notebook for use in subsequent analyses. ```python import tangram as tg ``` -------------------------------- ### Load and Prepare Spatial and Single-Cell Data Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_without_squidpy.ipynb Loads spatial and single-cell data from H5AD files and preprocesses the single-cell data by normalizing total counts. It also reads gene marker data from a CSV file and reshapes it for Tangram. ```python path = os.path.join('data', 'slideseq_MOp_1217.h5ad') ad_sp = sc.read_h5ad(path) path = os.path.join('data','mop_sn_tutorial.h5ad') ad_sc = sc.read_h5ad(path) sc.pp.normalize_total(ad_sc) df_genes = pd.read_csv('data/MOp_markers.csv', index_col=0) markers = np.reshape(df_genes.values, (-1, )) markers = list(markers) tg.pp_adatas(ad_sc, ad_sp, genes=markers) ``` -------------------------------- ### AnnData Object Representation Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_with_squidpy.ipynb Shows the summarized information of the `AnnData` object returned by the mapping process. This includes the dimensions and a list of keys for `obs`, `var`, and `uns`. ```python ad_map ``` -------------------------------- ### Prepare AnnData Objects for Tangram Mapping Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_without_squidpy.ipynb Prepares single-cell (ad_sc) and spatial (ad_sp) AnnData objects for Tangram mapping. It subsets genes to be shared between both datasets, ensures gene order consistency, and converts gene names to lowercase by default. The number of training genes and overlapped genes are reported. ```python tg.pp_adatas(ad_sc, ad_sp, genes=markers) ``` -------------------------------- ### Import Libraries for Tangram Analysis Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_without_squidpy.ipynb Imports essential Python libraries including numpy, pandas, matplotlib, scanpy, torch, and tangram for data manipulation, plotting, and spatial transcriptomics analysis. ```python import os, sys import numpy as np import pandas as pd import matplotlib.pyplot as plt import scanpy as sc import torch import tangram as tg ``` -------------------------------- ### Project Cell Annotations with Tangram Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_with_squidpy.ipynb Projects cell type annotations from a single-cell reference onto a spatial dataset using Tangram. It takes an annotation map, a spatial AnnData object, and the annotation key as input. ```python tg.project_cell_annotations(ad_map, adata_st, annotation="cell_subclass") ``` -------------------------------- ### AnnData Object Details Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_with_squidpy.ipynb Provides a detailed breakdown of the `AnnData` object's contents after mapping. It lists the number of observations and variables, along with the specific fields available in the `obs`, `var`, and `uns` attributes. ```text Result: AnnData object with n_obs × n_vars = 21697 × 324 obs: 'sample_name', 'organism', 'donor_sex', 'cell_class', 'cell_subclass', 'cell_cluster', 'n_genes_by_counts', 'log1p_n_genes_by_counts', 'total_counts', 'log1p_total_counts', 'pct_counts_in_top_50_genes', 'pct_counts_in_top_100_genes', 'pct_counts_in_top_200_genes', 'pct_counts_in_top_500_genes', 'total_counts_mt', 'log1p_total_counts_mt', 'pct_counts_mt', 'n_counts' var: 'in_tissue', 'array_row', 'array_col', 'n_genes_by_counts', 'log1p_n_genes_by_counts', 'total_counts', 'log1p_total_counts', 'pct_counts_in_top_50_genes', 'pct_counts_in_top_100_genes', 'pct_counts_in_top_200_genes', 'pct_counts_in_top_500_genes', 'total_counts_MT', 'log1p_total_counts_MT', 'pct_counts_MT', 'n_counts', 'leiden', 'cluster', 'uniform_density', 'rna_count_based_density' uns: 'train_genes_df', 'training_history' ``` -------------------------------- ### Visualize Cell Count with Scanpy Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_with_squidpy.ipynb Adds cell count data to the AnnData object's observation DataFrame and visualizes spatial data using Scanpy's plotting function. It allows coloring by cluster and cell count. ```python adata_st.obs["cell_count"] = adata_st.obsm["image_features"]["segmentation_label"] sc.pl.spatial(adata_st, color=["cluster", "cell_count"], frameon=False) ``` -------------------------------- ### Explanation of Training Scores Plot Panels Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_with_squidpy.ipynb Provides a detailed explanation of the four panels within the `plot_training_scores` output. It describes what each panel visualizes, including histograms of similarity scores, gene sparsity comparisons between single-cell and spatial data, and the relationship between training scores and sparsity differences. ```text - The first panel is a histogram of the simlarity scores for each training gene. - In the second panel, each dot is a training gene and we can observe the training score (y-axis) and the sparsity in the scRNA-seq data (x-axis) of each gene. - The third panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data are usually more sparse than single cell data, a discrepancy which is often responsible for low quality mapping. - The last panel is similar to the second one, but contains the gene sparsity of the spatial data. Spatial data ``` -------------------------------- ### Visualizing Segmentation Results with Matplotlib and Squidpy Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_with_squidpy.ipynb Visualizes cell segmentation masks alongside the original DAPI staining and cluster information. This helps in assessing the quality of the segmentation by comparing it with the histology. ```python inset_y = 1500 inset_x = 1700 inset_sy = 400 inset_sx = 500 fig, axs = plt.subplots(1, 3, figsize=(30, 10)) sc.pl.spatial( adata_st, color="cluster", alpha=0.7, frameon=False, show=False, ax=axs[0], title="" ) axs[0].set_title("Clusters", fontdict={"fontsize": 20}) sf = adata_st.uns["spatial"]["V1_Adult_Mouse_Brain_Coronal_Section_2"]["scalefactors"][ "tissue_hires_scalef" ] rect = mpl.patches.Rectangle( (inset_y * sf, inset_x * sf), width=inset_sx * sf, height=inset_sy * sf, ec="yellow", lw=4, fill=False, ) axs[0].add_patch(rect) axs[0].axes.xaxis.label.set_visible(False) axs[0].axes.yaxis.label.set_visible(False) axs[1].imshow( img["image"][inset_y : inset_y + inset_sy, inset_x : inset_x + inset_sx, 0, 0] / 65536, interpolation="none", ) axs[1].grid(False) axs[1].set_xticks([]) axs[1].set_yticks([]) axs[1].set_title("DAPI", fontdict={"fontsize": 20}) crop = img["segmented_watershed"]( inset_y : inset_y + inset_sy, inset_x : inset_x + inset_sx ).values.squeeze(-1) crop = skimage.segmentation.relabel_sequential(crop)[0] cmap = plt.cm.plasma cmap.set_under(color="black") axs[2].imshow(crop, interpolation="none", cmap=cmap, vmin=0.001) axs[2].grid(False) axs[2].set_xticks([]) axs[2].set_yticks([]) axs[2].set_title("Nucleous segmentation", fontdict={"fontsize": 20}); ``` -------------------------------- ### Load Spatial and Single-Cell Datasets with Squidpy Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_with_squidpy.ipynb Loads spatial and single-cell datasets from Squidpy. It includes subsetting spatial data to specific cortex clusters and cropping the associated image. The single-cell data is sourced from Tasic et al. (2018) and pre-processed using scanpy. ```python adata_st = sq.datasets.visium_fluo_adata_crop() adata_st = adata_st[ adata_st.obs.cluster.isin([f"Cortex_{i}" for i in np.arange(1, 5)]) ].copy() img = sq.datasets.visium_fluo_image_crop() adata_sc = sq.datasets.sc_mouse_cortex() ``` -------------------------------- ### Image Pre-processing and Segmentation with Squidpy Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_with_squidpy.ipynb Applies smoothing to an image as a pre-processing step and then computes segmentation masks using the watershed algorithm. This is crucial for identifying individual cells within spatial voxels. ```python sq.im.process(img=img, layer="image", method="smooth") sq.im.segment( img=img, layer="image_smooth", method="watershed", channel=0, ) ``` -------------------------------- ### Project Cell Annotations and Plot Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_with_squidpy.ipynb Projects cell annotations from the single-cell data onto the spatial data using Tangram and then plots the cell annotations in space. This involves transferring the 'cell_subclass' annotation and visualizing it using `plot_cell_annotation_sc`. ```python tg.project_cell_annotations(ad_map, adata_st, annotation="cell_subclass") annotation_list = list(pd.unique(adata_sc.obs['cell_subclass'])) tg.plot_cell_annotation_sc(adata_st, annotation_list,perc=0.02) ``` -------------------------------- ### Load Marker Genes for Tangram Mapping Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_without_squidpy.ipynb Loads marker genes from a CSV file into a pandas DataFrame and extracts them as a list. This list will be used as training genes for Tangram. ```python df_genes = pd.read_csv('data/MOp_markers.csv', index_col=0) markers = np.reshape(df_genes.values, (-1, )) markers = list(markers) len(markers) ``` -------------------------------- ### Display Spatial Dataset Metadata Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_with_squidpy.ipynb Displays the observation (metadata) of the spatial dataset (`adata_st`). This output shows various metrics associated with each spatial coordinate, such as tissue status, gene counts, and mitochondrial content. ```python adata_st.obs ``` -------------------------------- ### Select and Display Gene Data Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_without_squidpy.ipynb Selects specific genes from the `df_all_genes` DataFrame and displays their associated data, including score, training status, and sparsity metrics. This is useful for inspecting individual gene performance. ```python genes = ['snap25', 'atp1b1', 'atp1a3', 'ctgf', 'nefh', 'aak1', 'fa2h', ] df_all_genes.loc[genes] ``` -------------------------------- ### Create Segmentation Cell Dataframe with Tangram Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_with_squidpy.ipynb Creates a dataframe mapping segmentation objects (cells) to spots in the spatial data. It extracts spatial coordinates and generates unique centroid IDs, storing the result in the AnnData object's 'uns' attribute. ```python tg.create_segment_cell_df(adata_st) adata_st.uns["tangram_cell_segmentation"].head() ``` -------------------------------- ### Mapper.train Method Source: https://github.com/broadinstitute/tangram/blob/master/docs/source/classes/tangram.mapping_optimizer.Mapper.train.rst This method is used for training a mapper object. It likely takes data and configuration as input to optimize the mapping process. ```APIDOC ## Mapper.train ### Description Trains the mapper object using the provided data and configuration. ### Method *This is a method call within a class, not a direct HTTP endpoint.* ### Endpoint *N/A - Class method* ### Parameters *Detailed parameters for this method would typically be found in the Python docstring or source code.* ### Request Example *N/A - Python method call* ### Response *N/A - Python method return value would be the trained mapper object.* #### Success Response (200) *N/A* #### Response Example *N/A* ``` -------------------------------- ### Tangram Training Scores Output Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_with_squidpy.ipynb Shows the iterative training scores and KL regularization values during the Tangram mapping process. These scores are printed every 100 epochs, providing insight into the training convergence. ```log Score: 0.613, KL reg: 0.001 Score: 0.733, KL reg: 0.000 Score: 0.736, KL reg: 0.000 Score: 0.737, KL reg: 0.000 Score: 0.737, KL reg: 0.000 ``` -------------------------------- ### Load Single Cell Data with Scanpy Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_without_squidpy.ipynb Loads single-cell RNA sequencing (scRNAseq) or single-nuclei RNA sequencing (snRNAseq) data from an h5ad file into an AnnData object. This snippet requires the scanpy library. ```python import scanpy as sc import os path = os.path.join('data','mop_sn_tutorial.h5ad') ad_sc = sc.read_h5ad(path) ad_sc ``` -------------------------------- ### Constrained Deconvolution with Tangram Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_with_squidpy.ipynb Performs cell deconvolution to map single-cell profiles to spatial locations using Tangram. This method uses a 'constrained' mode to match the number of segmented cells and requires a density prior. ```python ad_map = tg.map_cells_to_space( adata_sc, adata_st, mode="constrained", target_count=adata_st.obs.cell_count.sum(), density_prior=np.array(adata_st.obs.cell_count) / adata_st.obs.cell_count.sum(), num_epochs=1000, ) ``` -------------------------------- ### Visualize Gene Patterns with Tangram Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_without_squidpy.ipynb Uses the `plot_genes_sc` function from the Tangram library to visualize gene expression patterns. It compares spatial measurements (`ad_sp`) with predicted gene expression (`ad_ge`) for a given list of genes. Parameters like `spot_size`, `scale_factor`, and `perc` control the visualization's appearance and data filtering. ```python tg.plot_genes_sc(genes, adata_measured=ad_sp, adata_predicted=ad_ge, spot_size=50, scale_factor=0.1, perc=0.001, return_figure=False) ``` -------------------------------- ### Project Cell Annotations onto Spatial Data Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_without_squidpy.ipynb This function projects cell type annotations from single-cell data onto the spatial data using the Tangram mapping results. It helps visualize the spatial distribution of cell types. Dependencies include pandas for unique value extraction. ```python tg.project_cell_annotations(ad_map, ad_sp, annotation='subclass_label') annotation_list = list(pd.unique(ad_sc.obs['subclass_label'])) tg.plot_cell_annotation_sc(ad_sp, annotation_list,x='x', y='y',spot_size= 60, scale_factor=0.1, perc=0.001) ``` -------------------------------- ### AnnData Structure of Mapping Results Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_with_squidpy.ipynb Describes the structure of the AnnData object (`ad_map`) that stores the mapping results. It details the contents of the `X` matrix, `obs` dataframe, `var` dataframe, and `uns` dictionary, explaining what each component represents. ```text The mapping results are stored in the returned `AnnData` structure, saved as `ad_map`, structured as following: - The cell-by-spot matrix `X` contains the probability of cell `i` to be in spot `j`. - The `obs` dataframe contains the metadata of the single cells. - The `var` dataframe contains the metadata of the spatial data. - The `uns` dictionary contains a dataframe with various information about the training genes (saved as `train_genes_df`). ``` -------------------------------- ### Load Spatial Data with Scanpy Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_without_squidpy.ipynb Loads spatial data from an h5ad file into an AnnData object. The data is expected to be in a voxel-by-gene matrix format. This snippet requires the scanpy library. ```python import scanpy as sc import os path = os.path.join('./data', 'slideseq_MOp_1217.h5ad') ad_sp = sc.read_h5ad(path) ad_sp ``` -------------------------------- ### Feature Extraction for Deconvolution with Tangram Source: https://github.com/broadinstitute/tangram/blob/master/tutorial_tangram_with_squidpy.ipynb Defines keyword arguments for extracting image features essential for deconvolution. It specifies the segmentation layer to use and the properties to extract, such as 'label' and 'centroid'. ```python # define image layer to use for segmentation features_kwargs = { "segmentation": { "label_layer": "segmented_watershed", "props": ["label", "centroid"], "channels": [1, 2], } } ```