Integration with Seurat

Overview

MAGICR provides seamless integration with Seurat objects, supporting both Seurat v4 and v5. This vignette demonstrates how to use MAGIC within a typical Seurat workflow.

Prerequisites

# Install required packages
install.packages("Seurat")
install.packages("MAGICR", repos = "https://zaoqu-liu.r-universe.dev")

Basic Workflow

Loading Data

library(Seurat)
library(MAGICR)

# Create example Seurat object
# In practice, load your own data
data(magic_testdata)
seurat_obj <- CreateSeuratObject(counts = t(magic_testdata))

Standard Preprocessing

# Normalize data
seurat_obj <- NormalizeData(seurat_obj)

# Find variable features
seurat_obj <- FindVariableFeatures(seurat_obj, nfeatures = 2000)

# Scale data
seurat_obj <- ScaleData(seurat_obj)

# Run PCA
seurat_obj <- RunPCA(seurat_obj, npcs = 50)

Running MAGIC

# Run MAGIC on the Seurat object
seurat_obj <- magic(seurat_obj, 
                    assay = "RNA",
                    t = 3,
                    knn = 5)

# MAGIC results are stored in a new assay
Assays(seurat_obj)

Accessing MAGIC Results

# Switch to MAGIC assay for downstream analysis
DefaultAssay(seurat_obj) <- "MAGIC_RNA"

# Get imputed expression matrix
magic_data <- GetAssayData(seurat_obj, assay = "MAGIC_RNA", layer = "data")

Visualization Comparison

Gene Expression Before/After MAGIC

# Compare gene expression
gene <- "Gene1"

p1 <- FeaturePlot(seurat_obj, features = gene, 
                  reduction = "pca", slot = "data") +
      ggtitle("Original")

DefaultAssay(seurat_obj) <- "MAGIC_RNA"
p2 <- FeaturePlot(seurat_obj, features = gene,
                  reduction = "pca", slot = "data") +
      ggtitle("After MAGIC")

p1 | p2

Gene-Gene Scatter Plots

# Gene-gene relationships are clearer after MAGIC
DefaultAssay(seurat_obj) <- "RNA"
p1 <- FeatureScatter(seurat_obj, feature1 = "Gene1", feature2 = "Gene2") +
      ggtitle("Original")

DefaultAssay(seurat_obj) <- "MAGIC_RNA"
p2 <- FeatureScatter(seurat_obj, feature1 = "Gene1", feature2 = "Gene2") +
      ggtitle("After MAGIC")

p1 | p2

Advanced Usage

Imputing Specific Genes

# Only impute specific genes (faster)
seurat_obj <- magic(seurat_obj,
                    assay = "RNA",
                    genes = c("Gene1", "Gene2", "Gene3"),
                    t = 3)

Using Automatic t Selection

# Let MAGIC determine optimal diffusion time
seurat_obj <- magic(seurat_obj,
                    assay = "RNA",
                    t = "auto",
                    t_max = 20)

Custom Parameters

# Fine-tune parameters for your data
seurat_obj <- magic(seurat_obj,
                    assay = "RNA",
                    knn = 10,           # More neighbors
                    knn_max = 30,       # Larger neighborhood
                    decay = 2,          # Sharper kernel
                    t = 5,              # More diffusion
                    npca = 50,          # Fewer PCs
                    solver = "approximate")  # Faster

Seurat v4 vs v5 Compatibility

MAGICR automatically detects your Seurat version and uses the appropriate API:

# Check Seurat version
packageVersion("Seurat")

# MAGICR handles both versions automatically
seurat_obj <- magic(seurat_obj, assay = "RNA", t = 3)

Seurat v5 Layers

In Seurat v5, data is stored in layers. MAGICR works with the “data” layer by default:

# Seurat v5: Access specific layers
magic_data <- GetAssayData(seurat_obj, assay = "MAGIC_RNA", layer = "data")

Integration with Downstream Analysis

Trajectory Analysis

MAGIC-imputed data often improves trajectory inference:

# Use MAGIC data for trajectory analysis
DefaultAssay(seurat_obj) <- "MAGIC_RNA"

# Run UMAP on MAGIC data
seurat_obj <- RunUMAP(seurat_obj, dims = 1:30)

# Trajectory analysis with Monocle3 or slingshot
# ... (use imputed expression for pseudotime)

Gene Regulatory Networks

# MAGIC helps reveal gene-gene correlations
DefaultAssay(seurat_obj) <- "MAGIC_RNA"
magic_expr <- GetAssayData(seurat_obj, layer = "data")

# Compute correlation matrix
cor_matrix <- cor(t(as.matrix(magic_expr[1:100, ])))

Best Practices

When to Use MAGIC with Seurat

Recommended: - Visualizing gene expression patterns - Gene-gene correlation analysis - Trajectory/pseudotime analysis - Identifying gene regulatory relationships

Not Recommended: - Differential expression testing (use raw counts) - Cell type annotation (use normalized counts) - Integration with other datasets

Memory Considerations

For large datasets:

# Use approximate solver for large datasets
seurat_obj <- magic(seurat_obj,
                    solver = "approximate",
                    npca = 50)

# Or impute only genes of interest
seurat_obj <- magic(seurat_obj,
                    genes = VariableFeatures(seurat_obj)[1:500])

Troubleshooting

Common Issues

1. Memory errors:

# Reduce memory usage
seurat_obj <- magic(seurat_obj, 
                    solver = "approximate",
                    npca = 30)

2. Slow computation:

# Enable parallel processing
library(future)
plan(multisession, workers = 4)
seurat_obj <- magic(seurat_obj, t = 3)

3. Over-smoothing:

# Reduce diffusion time
seurat_obj <- magic(seurat_obj, t = 2)

Session Info

sessionInfo()
#> R version 4.6.1 (2026-06-24)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 26.04 LTS
#> 
#> Matrix products: default
#> BLAS:   /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3 
#> LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.32.so;  LAPACK version 3.12.0
#> 
#> locale:
#>  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
#>  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
#>  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
#>  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
#>  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
#> [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
#> 
#> time zone: Etc/UTC
#> tzcode source: system (glibc)
#> 
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> 
#> other attached packages:
#> [1] Matrix_1.7-5   MAGICR_1.0.0   rmarkdown_2.31
#> 
#> loaded via a namespace (and not attached):
#>  [1] cli_3.6.6         knitr_1.51        rlang_1.2.0       xfun_0.59        
#>  [5] otel_0.2.0        jsonlite_2.0.0    listenv_1.0.0     buildtools_1.0.0 
#>  [9] htmltools_0.5.9   maketools_1.3.2   sys_3.4.3         sass_0.4.10      
#> [13] grid_4.6.1        evaluate_1.0.5    jquerylib_0.1.4   fastmap_1.2.0    
#> [17] yaml_2.3.12       lifecycle_1.0.5   compiler_4.6.1    codetools_0.2-20 
#> [21] irlba_2.3.7       Rcpp_1.1.1-1.1    future_1.70.0     lattice_0.22-9   
#> [25] digest_0.6.39     R6_2.6.1          RANN_2.6.2        parallelly_1.48.0
#> [29] parallel_4.6.1    bslib_0.11.0      tools_4.6.1       globals_0.19.1   
#> [33] cachem_1.1.0