---
title: "Integration with Seurat"
author: "Zaoqu Liu"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Integration with Seurat}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 5,
  fig.align = "center",
  message = FALSE,
  warning = FALSE,
  eval = FALSE
)
```

## 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

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

## Basic Workflow

### Loading Data

```{r}
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

```{r}
# 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

```{r}
# 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

```{r}
# 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

```{r fig.width=10, fig.height=5}
# 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

```{r fig.width=10, fig.height=5}
# 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

```{r}
# Only impute specific genes (faster)
seurat_obj <- magic(seurat_obj,
                    assay = "RNA",
                    genes = c("Gene1", "Gene2", "Gene3"),
                    t = 3)
```
### Using Automatic t Selection

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

### Custom Parameters

```{r}
# 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:

```{r}
# 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:

```{r}
# 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:
```{r}
# 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

```{r}
# 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:

```{r}
# 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:**
```{r}
# Reduce memory usage
seurat_obj <- magic(seurat_obj, 
                    solver = "approximate",
                    npca = 30)
```

**2. Slow computation:**
```{r}
# Enable parallel processing
library(future)
plan(multisession, workers = 4)
seurat_obj <- magic(seurat_obj, t = 3)
```

**3. Over-smoothing:**
```{r}
# Reduce diffusion time
seurat_obj <- magic(seurat_obj, t = 2)
```

## Session Info

```{r eval=TRUE}
sessionInfo()
```
