Before using code patterns, verify installed versions match. If versions differ:
Python: pip show <package> then help(module.function) to check signatures
If code throws ImportError, AttributeError, or TypeError, introspect the installed
package and adapt the example to match the actual API rather than retrying.
Spatial Preprocessing
"Preprocess my spatial transcriptomics data" → Calculate spatial QC metrics (genes/spot, mitochondrial fraction), filter spots by expression and tissue coverage, normalize, and select variable genes.
Python: scanpy.pp.calculate_qc_metrics() → filter_cells() → normalize_total() on spatial AnnData
QC, filtering, normalization, and feature selection for spatial data.
Required Imports
import squidpy as sq
import scanpy as sc
import numpy as np
import matplotlib.pyplot as plt
Calculate QC Metrics
Goal: Compute per-spot and per-gene quality control statistics.
Approach: Use Scanpy's calculate_qc_metrics to generate total counts, gene counts, and other summary statistics.
Goal: Remove low-quality spots based on count, gene, and mitochondrial thresholds.
Approach: Apply sequential filters for minimum counts, minimum genes, and maximum mitochondrial percentage.
# Filter based on QC metrics
print(f'Before filtering: {adata.n_obs} spots')
# Minimum counts and genes
sc.pp.filter_cells(adata, min_counts=500)
sc.pp.filter_cells(adata, min_genes=200)
# Maximum mitochondrial content
adata = adata[adata.obs['pct_counts_mt'] < 20].copy()
print(f'After filtering: {adata.n_obs} spots')
Filter Genes
Goal: Remove lowly expressed genes detected in very few spots.
Approach: Apply a minimum cell count threshold to drop genes with negligible spatial coverage.
# Remove genes detected in few spots
print(f'Before filtering: {adata.n_vars} genes')
sc.pp.filter_genes(adata, min_cells=10)
print(f'After filtering: {adata.n_vars} genes')
Normalization
Goal: Normalize count data to remove library size effects and prepare for downstream analysis.
Approach: Store raw counts as a layer, normalize to median total counts, then log-transform.
# Store raw counts
adata.layers['counts'] = adata.X.copy()
# Normalize to median total counts
sc.pp.normalize_total(adata, target_sum=1e4)
# Log transform
sc.pp.log1p(adata)
SCTransform-like Normalization
Goal: Apply variance-stabilizing normalization analogous to Seurat's SCTransform.
Approach: Compute Pearson residuals from raw counts using Scanpy's experimental module.