5a. Perform dimensionality reduction with iterativeLSI

proj2 <- addIterativeLSI(proj2, useMatrix = "TileMatrix",
                         name = "IterativeLSI",                         
                         iterations = 5,
                         clusterParams = list(resolution = c(0.2, 0.8, 1.5, 2),
                            sampleCells = 10000,
                            maxClusters = 12,
                            n.start = 10),
                         varFeatures = 15000)

5b. Batch correct using Harmony

proj2 <- addHarmony(
    ArchRProj = proj2,
    reducedDims = "IterativeLSI",
    name = "LSI_Harmony",
    groupBy = "Sample"
)

5c. Add initial clusters

proj2 <- addClusters(
    input = proj2,
    reducedDims = "LSI_Harmony",
    method = "Seurat",
    name = "Clusters_LSI",
    resolution = 0.8
)

5d. Add UMAP visualization

proj2 <- addUMAP(
    ArchRProj = proj2, 
    reducedDims = "LSI_Harmony", 
    name = "UMAP_LSI_Harmony", 
    nNeighbors = 30, 
    minDist = 0.5, 
    metric = "cosine"
)

5e. Visualize clustering

cM <- confusionMatrix(paste0(proj2$Clusters_LSI), paste0(proj2$Sample))
cM
library(pheatmap)
cM <- cM / Matrix::rowSums(cM)
p <- pheatmap::pheatmap(
    mat = as.matrix(cM), 
    color = paletteContinuous("whiteBlue"), 
    border_color = "black"
)
pdf(paste0(sample_name,
           "_cluster-seurat_confusion_heatmap_",
           Sys.Date(), ".pdf")
    )
p
dev.off()

# Visualize sample embeddings

sample_embedding_plot <- plotEmbedding(ArchRProj = proj2,
    colorBy = "cellColData",
    name = "Sample",
    embedding = "UMAP_LSI_Harmony")
svglite(paste0(sample_name,
           "_cluster-seurat_UMAP-LSI-Harmony_sample-embedding_",
           Sys.Date(),
           ".svg")
    )
sample_embedding_plot
dev.off()

# Visualize sample embeddings colored by cluster

cluster_embedding_plot <- plotEmbedding(ArchRProj = proj2,
    colorBy = "cellColData",
    name = "Clusters_LSI",
    embedding = "UMAP_LSI_Harmony")
svglite(paste0(sample_name,
           "_cluster-seurat_UMAP-LSI-Harmony_cluster-embedding_",
           Sys.Date(),
           ".svg")
    )
cluster_embedding_plot
dev.off()

# Plot cluster embeddings by sample and cluster in single plot

svglite(paste0(sample_name,
           "_cluster-seurat_UMAP-LSI-Harmony_sample-cluster-embedding_",
           Sys.Date(),
           ".svg")
    )
ggAlignPlots(sample_embedding_plot, cluster_embedding_plot, type = "h")
dev.off()

proj2 <- saveArchRProject(ArchRProj = proj2)
save.image(paste0(sample_name, "_project2_", Sys.Date(), ".RData"))