Skip to contents

Download data

The PBMC datasets are originally from SeuratData. We use one of them (10x Chromium (v3) from PBMC1 replicate). We filtered out some lowly epxressed genes to save computational time here.

data(pbmc, package = "ClusterDE")

Run the regular Seurat pipeline

We perform the default Seurat clustering. Note that in real data analysis, the cell type label is usually unknown.

RNGkind("L'Ecuyer-CMRG")
set.seed(123)
pbmc <- Seurat::UpdateSeuratObject(pbmc)
#> Validating object structure
#> Updating object slots
#> Ensuring keys are in the proper structure
#> Warning: Assay RNA changing from Assay to Assay
#> Ensuring keys are in the proper structure
#> Ensuring feature names don't have underscores or pipes
#> Updating slots in RNA
#> Validating object structure for Assay 'RNA'
#> Object representation is consistent with the most current Seurat version
pbmc <- Seurat::NormalizeData(pbmc)
#> Warning: The `slot` argument of `SetAssayData()` is deprecated as of SeuratObject 5.0.0.
#> ℹ Please use the `layer` argument instead.
#> ℹ The deprecated feature was likely used in the Seurat package.
#>   Please report the issue at <https://github.com/satijalab/seurat/issues>.
#> This warning is displayed once every 8 hours.
#> Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
#> generated.
#> Warning: The `slot` argument of `GetAssayData()` is deprecated as of SeuratObject 5.0.0.
#> ℹ Please use the `layer` argument instead.
#> ℹ The deprecated feature was likely used in the Seurat package.
#>   Please report the issue at <https://github.com/satijalab/seurat/issues>.
#> This warning is displayed once every 8 hours.
#> Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
#> generated.
pbmc <- Seurat::FindVariableFeatures(pbmc)
pbmc <- Seurat::ScaleData(pbmc)
#> Centering and scaling data matrix
pbmc <- Seurat::RunPCA(pbmc)
#> PC_ 1 
#> Positive:  IL32, CCL5, TRBC2, TRAC, CD69, CST7, RORA, CTSW, SPOCK2, ITM2A 
#>     GZMM, CD247, TRBC1, C12orf75, IL7R, CD8A, CD2, LDHB, GZMA, CD7 
#>     NKG7, CD6, GZMH, CD8B, BCL11B, PRF1, LYAR, LTB, FGFBP2, TCF7 
#> Negative:  LYZ, FCN1, CLEC7A, CPVL, SERPINA1, SPI1, S100A9, AIF1, NAMPT, CSTA 
#>     CTSS, MAFB, MPEG1, NCF2, VCAN, FGL2, S100A8, TYMP, CST3, LST1 
#>     CYBB, CFD, FCER1G, SLC11A1, TGFBI, GRN, CD14, PSAP, SLC7A7, MS4A6A 
#> PC_ 2 
#> Positive:  RPL10, EEF1A1, TMSB10, RPS2, RPS12, RPL13, RPS18, RPS23, RPLP1, TPT1 
#>     RPS8, IL32, S100A4, PFN1, RPLP0, NKG7, ARL4C, HSPA8, CST7, ZFP36L2 
#>     ANXA1, CTSW, S100A6, LDHA, CORO1A, CD247, GZMA, CALR, S100A10, GZMM 
#> Negative:  NRGN, PF4, SDPR, HIST1H2AC, MAP3K7CL, PPBP, GNG11, GPX1, TUBB1, SPARC 
#>     CLU, PGRMC1, FTH1, RGS18, MARCH2, TREML1, HIST1H3H, AP003068.23, NCOA4, ACRBP 
#>     TAGLN2, PRKAR2B, CD9, CA2, CMTM5, CTTN, MTURN, TMSB4X, HIST1H2BJ, TSC22D1 
#> PC_ 3 
#> Positive:  CD79A, HLA-DQA1, MS4A1, LINC00926, IGHM, BANK1, IGHD, TNFRSF13C, HLA-DQB1, CD74 
#>     IGKC, HLA-DRA, BLK, CD83, CD37, CD22, ADAM28, JUND, NFKBID, HLA-DRB1 
#>     P2RX5, CD79B, VPREB3, IGLC2, FCER2, RPS8, LTB, RPS23, TCOF1, GNG7 
#> Negative:  CCL5, TMSB4X, SRGN, NKG7, ACTB, CST7, GZMH, FGFBP2, CTSW, PRF1 
#>     GZMA, GZMB, C12orf75, S100A4, ANXA1, KLRD1, NRGN, GNLY, GZMM, IL32 
#>     PF4, SDPR, PPBP, MYO1F, CD247, GAPDH, MAP3K7CL, HIST1H2AC, GNG11, TUBB1 
#> PC_ 4 
#> Positive:  FCGR3A, GZMB, FGFBP2, GZMH, NKG7, HLA-DPA1, PRF1, HLA-DPB1, CST7, GNLY 
#>     KLRD1, HLA-DRB1, GZMA, CCL5, SPON2, ADGRG1, CTSW, ZEB2, PRSS23, IFITM2 
#>     CCL4, CD74, KLRF1, RHOC, MTSS1, CDKN1C, CD79B, CEP78, HLA-DQA1, CLIC3 
#> Negative:  IL7R, LEPROTL1, LTB, RCAN3, MAL, LEF1, TCF7, ZFP36L2, CAMK4, VIM 
#>     LDHB, NOSIP, JUNB, SLC2A3, TRABD2A, RGCC, SATB1, TNFAIP3, TMEM123, SOCS3 
#>     AQP3, BCL11B, NELL2, TNFRSF25, CD28, PABPC1, DNAJB1, TRAT1, OXNAD1, TRAC 
#> PC_ 5 
#> Positive:  CDKN1C, HES4, CSF1R, CKB, ZNF703, TCF7L2, CTSL, MS4A7, PAG1, FAM110A 
#>     SIGLEC10, LRRC25, FCGR3A, LTB, RNASET2, CDH23, IL7R, RRAS, LINC01272, IFITM3 
#>     LST1, LILRB2, PILRA, RHOC, SLC2A6, PECAM1, CAMK1, TAGLN, IFI30, BID 
#> Negative:  VCAN, S100A12, S100A8, CD14, CSF3R, ITGAM, CST7, GZMB, MT-CO1, GNLY 
#>     KLRD1, PRF1, MS4A6A, GZMH, FGFBP2, CD93, EGR1, NKG7, S100A9, MT-CO3 
#>     IER3, THBS1, RNASE6, CLEC4E, MGST1, CTSW, SGK1, GZMA, RP11-1143G9.4, CH17-373J23.1
pbmc <- Seurat::FindNeighbors(pbmc)
#> Computing nearest neighbor graph
#> Computing SNN
pbmc <- Seurat::FindClusters(pbmc, resolution = 0.3)
#> Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
#> 
#> Number of nodes: 3222
#> Number of edges: 108633
#> 
#> Running Louvain algorithm...
#> Maximum modularity in 10 random starts: 0.9372
#> Number of communities: 10
#> Elapsed time: 0 seconds
pbmc <- Seurat::RunUMAP(pbmc, dims = 1:10)
#> Warning: The default method for RunUMAP has changed from calling Python UMAP via reticulate to the R-native UWOT using the cosine metric
#> To use Python UMAP via reticulate, set umap.method to 'umap-learn' and metric to 'correlation'
#> This message will be shown once per session
#> 23:34:08 UMAP embedding parameters a = 0.9922 b = 1.112
#> 23:34:08 Read 3222 rows and found 10 numeric columns
#> 23:34:08 Using Annoy for neighbor search, n_neighbors = 30
#> 23:34:08 Building Annoy index with metric = cosine, n_trees = 50
#> 0%   10   20   30   40   50   60   70   80   90   100%
#> [----|----|----|----|----|----|----|----|----|----|
#> **************************************************|
#> 23:34:08 Writing NN index file to temp file /tmp/Rtmpk198cJ/file15e7e41d6bca09
#> 23:34:08 Searching Annoy index using 1 thread, search_k = 3000
#> 23:34:08 Annoy recall = 100%
#> 23:34:09 Commencing smooth kNN distance calibration using 1 thread with target n_neighbors = 30
#> 23:34:09 Initializing from normalized Laplacian + noise (using RSpectra)
#> 23:34:09 Commencing optimization for 500 epochs, with 126438 positive edges
#> 23:34:09 Using rng type: pcg
#> 23:34:12 Optimization finished
p1 <- Seurat::DimPlot(pbmc, reduction = "umap", label = T) +
  ggplot2::ggtitle("Clustering result") +
  Seurat::NoLegend()
p2 <- Seurat::DimPlot(pbmc, reduction = "umap", group.by = "CellType", label = T) +
  Seurat::NoLegend()
p1 + p2

In this vignette, we are interested in clusters 3 and 8, which approximately represent CD14+ and CD16+ monocytes.

We perform the DE test between cluster 3 and 8. We subset the cluster 3 and 8 (pbmc_sub).

pbmc_sub <- subset(x = pbmc, idents = c(3, 8))
# Remove genes with zero variance
non_zero_genes <- apply(Seurat::GetAssayData(pbmc_sub, layer = "counts"), 1, var) != 0
pbmc_sub <- pbmc_sub[non_zero_genes,]

original_markers <- Seurat::FindMarkers(
  pbmc_sub,
  ident.1 = 8,
  ident.2 = 3,
  min.pct = 0,
  logfc.threshold = 0
)
#> Warning: `PackageCheck()` was deprecated in SeuratObject 5.0.0.
#> ℹ Please use `rlang::check_installed()` instead.
#> ℹ The deprecated feature was likely used in the Seurat package.
#>   Please report the issue at <https://github.com/satijalab/seurat/issues>.
#> This warning is displayed once every 8 hours.
#> Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
#> generated.

PCA approximation for faster null data generation

Generating many null data replicates can be time-consuming. ClusterDE-Fast is a PCA-based approximation that generates continuous log-normalized expression while preserving the genes in the target data with much less time. Here we generate 40 null replicates.

null_data <- ClusterDE::constructNull(
  obj = pbmc_sub,
  approximation = "pca",
  n_rep = 40,
  n_pcs = 200
)
#> Contruct PCA
#> Construct scDesign3 data
#> Registered S3 method overwritten by 'scDesign3':
#>   method         from  
#>   predict.gamlss gamlss
#> Fit marginal
#> Fit copula
#> Generate null data of 40 replicates

The returned null_data contains all replicates. Because PCA-generated null data are continuous log-normalized expression rather than counts, we skip normalization and reuse the highly variable genes from the real reference data. Each replicate is independently processed, clustered into two groups, and tested for differential expression.

target_hvg <- Seurat::VariableFeatures(pbmc_sub)

null_pval_list <- lapply(
  seq_along(null_data),
  function(i) {
    set.seed(123)
    null_matrix <- null_data[[i]]

    zero_matrix <- Matrix::Matrix(
      0,
      nrow(null_matrix),
      ncol(null_matrix),
      sparse = TRUE
    )
    rownames(zero_matrix) <- rownames(null_matrix)
    colnames(zero_matrix) <- colnames(null_matrix)

    null_object <- Seurat::CreateSeuratObject(zero_matrix)
    null_object <- Seurat::SetAssayData(
      null_object,
      layer = "data",
      new.data = null_matrix
    )
    Seurat::VariableFeatures(null_object) <- target_hvg

    null_object <- Seurat::ScaleData(null_object)
    null_object <- Seurat::RunPCA(
      null_object,
      npcs = min(50, ncol(null_object) - 1, nrow(null_object) - 1)
    )
    null_object <- Seurat::FindNeighbors(null_object)

    right <- 0.3
    null_object <- Seurat::FindClusters(null_object, resolution = right)
    number_of_clusters <- length(unique(null_object$seurat_clusters))

    while (number_of_clusters < 2) {
      right <- right * 2
      null_object <- Seurat::FindClusters(null_object, resolution = right)
      number_of_clusters <- length(unique(null_object$seurat_clusters))
    }

    left <- 0
    while (number_of_clusters != 2) {
      mid <- (left + right) / 2
      null_object <- Seurat::FindClusters(null_object, resolution = mid)
      number_of_clusters <- length(unique(null_object$seurat_clusters))
      if (number_of_clusters < 2) {
        left <- mid
      } else {
        right <- mid
      }
    }
    Seurat::Idents(null_object) <- paste0(
      Seurat::DefaultAssay(null_object),
      "_snn_res.",
      right
    )

    null_clusters <- unique(Seurat::Idents(null_object))
    null_markers <- Seurat::FindMarkers(
      null_object,
      ident.1 = null_clusters[[1]],
      ident.2 = null_clusters[[2]],
      min.pct = 0,
      logfc.threshold = 0
    )
    null_scores <- null_markers$p_val
    names(null_scores) <- rownames(null_markers)

    list(data = null_object, p = null_scores)
  }
)

null_pval <- list(
  data = lapply(null_pval_list, `[[`, "data"),
  p = lapply(null_pval_list, `[[`, "p")
)

We pass the target and null p-values to callDE(). Marker calling uses the default target FDR of 0.05 in each replicate. The record column is the fraction of the 40 null replicates in which a gene is selected. We retain genes with record >= 0.5, corresponding to selection in at least 20 of 40 runs.

original_pval <- original_markers$p_val
names(original_pval) <- rownames(original_markers)

res <- ClusterDE::callDE(original_pval, null_pval$p)
stable_res <- res[res$record >= 0.5, ]

nrow(stable_res)
#> [1] 41
head(stable_res)
#> # A tibble: 6 × 3
#>   gene      cs record
#>   <chr>  <dbl>  <dbl>
#> 1 FCGR3A  35.1  0.825
#> 2 CDKN1C  33.1  0.9  
#> 3 CD79B   29.2  0.725
#> 4 RHOC    28.7  0.9  
#> 5 LYZ     25.7  0.95 
#> 6 CKB     25.6  0.7

We visualize the top genes selected across the PCA-generated null replicates.

Seurat::FeaturePlot(
  pbmc[, pbmc$seurat_clusters %in% c(3, 8)],
  features = stable_res$gene[1:6],
  ncol = 3
)
#> Warning: The `slot` argument of `FetchData()` is deprecated as of SeuratObject 5.0.0.
#> ℹ Please use the `layer` argument instead.
#> ℹ The deprecated feature was likely used in the Seurat package.
#>   Please report the issue at <https://github.com/satijalab/seurat/issues>.
#> This warning is displayed once every 8 hours.
#> Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
#> generated.

Finally, we randomly select one null replicate, concatenate its log-normalized expression with the target data, and embed all cells in the same PCA and UMAP space to demonstrate the similarity between the reference data and synthetic data.

set.seed(123)
plot_rep <- sample(seq_along(null_data), 1)

target_normalized <- Seurat::GetAssayData(pbmc_sub, layer = "data")
null_normalized <- null_data[[plot_rep]]
common_genes <- intersect(
  rownames(target_normalized),
  rownames(null_normalized)
)

target_normalized <- as.matrix(
  target_normalized[common_genes, , drop = FALSE]
)
null_normalized <- as.matrix(
  null_normalized[common_genes, , drop = FALSE]
)

mat <- t(cbind(target_normalized, null_normalized))
pcs <- irlba::prcomp_irlba(
  mat,
  center = TRUE,
  scale. = TRUE,
  n = 30
)$x
embedding <- umap::umap(pcs)$layout
#> Found more than one class "dist" in cache; using the first, from namespace 'spam'
#> Also defined by 'BiocGenerics'
colnames(embedding) <- c("UMAP1", "UMAP2")

umap_data <- data.frame(
  embedding,
  Dataset = factor(
    c(
      rep("Reference data", ncol(target_normalized)),
      rep("Synthetic data", ncol(null_normalized))
    ),
    levels = c("Reference data", "Synthetic data")
  )
)

ggplot2::ggplot(
  umap_data,
  ggplot2::aes(x = UMAP1, y = UMAP2, color = Dataset)
) +
  ggplot2::geom_point(size = 0.8, alpha = 0.8) +
  ggplot2::facet_wrap(~Dataset, nrow = 1) +
  ggplot2::coord_equal() +
  ggplot2::theme_classic() +
  ggplot2::theme(legend.position = "none")

Session information

sessionInfo()
#> R version 4.5.1 (2025-06-13)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 24.04.5 LTS
#> 
#> Matrix products: default
#> BLAS/LAPACK: FlexiBLAS OPENBLAS;  LAPACK version 3.12.0
#> 
#> Random number generation:
#>  RNG:     L'Ecuyer-CMRG 
#>  Normal:  Inversion 
#>  Sample:  Rejection 
#>  
#> locale:
#>  [1] LC_CTYPE=C.UTF-8       LC_NUMERIC=C           LC_TIME=C.UTF-8       
#>  [4] LC_COLLATE=C.UTF-8     LC_MONETARY=C.UTF-8    LC_MESSAGES=C.UTF-8   
#>  [7] LC_PAPER=C.UTF-8       LC_NAME=C              LC_ADDRESS=C          
#> [10] LC_TELEPHONE=C         LC_MEASUREMENT=C.UTF-8 LC_IDENTIFICATION=C   
#> 
#> time zone: America/Los_Angeles
#> tzcode source: system (glibc)
#> 
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> 
#> other attached packages:
#> [1] future_1.58.0      ClusterDE_0.99.4   Seurat_5.3.0       SeuratObject_5.1.0
#> [5] sp_2.2-0           BiocStyle_2.36.0  
#> 
#> loaded via a namespace (and not attached):
#>   [1] RcppAnnoy_0.0.22            splines_4.5.1              
#>   [3] later_1.4.2                 tibble_3.3.0               
#>   [5] polyclip_1.10-7             gamlss.data_6.0-6          
#>   [7] fastDummies_1.7.5           lifecycle_1.0.4            
#>   [9] globals_0.18.0              lattice_0.22-9             
#>  [11] MASS_7.3-65                 backports_1.5.0            
#>  [13] magrittr_2.0.3              limma_3.64.1               
#>  [15] plotly_4.10.4               sass_0.4.10                
#>  [17] rmarkdown_2.29              jquerylib_0.1.4            
#>  [19] yaml_2.3.10                 httpuv_1.6.16              
#>  [21] sctransform_0.4.2           askpass_1.2.1              
#>  [23] spam_2.11-1                 spatstat.sparse_3.1-0      
#>  [25] reticulate_1.42.0           cowplot_1.1.3              
#>  [27] pbapply_1.7-2               RColorBrewer_1.1-3         
#>  [29] abind_1.4-8                 Rtsne_0.17                 
#>  [31] GenomicRanges_1.60.0        purrr_1.0.4                
#>  [33] presto_1.0.0                BiocGenerics_0.54.0        
#>  [35] GenomeInfoDbData_1.2.14     IRanges_2.42.0             
#>  [37] S4Vectors_0.46.0            ggrepel_0.9.6              
#>  [39] irlba_2.3.5.1               listenv_0.9.1              
#>  [41] spatstat.utils_3.1-4        umap_0.2.10.0              
#>  [43] goftest_1.2-3               RSpectra_0.16-2            
#>  [45] spatstat.random_3.4-1       fitdistrplus_1.2-2         
#>  [47] parallelly_1.45.0           pkgdown_2.0.9              
#>  [49] codetools_0.2-20            DelayedArray_0.34.1        
#>  [51] tidyselect_1.2.1            UCSC.utils_1.4.0           
#>  [53] farver_2.1.2                matrixStats_1.5.0          
#>  [55] stats4_4.5.1                spatstat.explore_3.4-3     
#>  [57] jsonlite_2.0.0              progressr_0.15.1           
#>  [59] ggridges_0.5.6              survival_3.8-3             
#>  [61] systemfonts_1.2.3           bettermc_1.2.2.9000        
#>  [63] tools_4.5.1                 ragg_1.4.0                 
#>  [65] ica_1.0-3                   Rcpp_1.0.14                
#>  [67] glue_1.8.0                  gridExtra_2.3              
#>  [69] SparseArray_1.8.0           xfun_0.52                  
#>  [71] mgcv_1.9-3                  MatrixGenerics_1.20.0      
#>  [73] scDesign3_1.7.6             GenomeInfoDb_1.44.0        
#>  [75] dplyr_1.1.4                 withr_3.0.2                
#>  [77] BiocManager_1.30.27         fastmap_1.2.0              
#>  [79] openssl_2.3.3               digest_0.6.37              
#>  [81] gamlss_5.4-22               R6_2.6.1                   
#>  [83] mime_0.13                   textshaping_1.0.1          
#>  [85] scattermore_1.2             tensor_1.5                 
#>  [87] dichromat_2.0-0.1           spatstat.data_3.1-6        
#>  [89] utf8_1.2.6                  tidyr_1.3.1                
#>  [91] generics_0.1.4              data.table_1.17.4          
#>  [93] httr_1.4.7                  htmlwidgets_1.6.4          
#>  [95] S4Arrays_1.8.1              uwot_0.2.3                 
#>  [97] pkgconfig_2.0.3             gtable_0.3.6               
#>  [99] lmtest_0.9-40               SingleCellExperiment_1.30.1
#> [101] XVector_0.48.0              htmltools_0.5.8.1          
#> [103] dotCall64_1.2               bookdown_0.43              
#> [105] scales_1.4.0                Biobase_2.68.0             
#> [107] png_0.1-8                   spatstat.univar_3.1-3      
#> [109] knitr_1.50                  reshape2_1.4.4             
#> [111] checkmate_2.3.2             nlme_3.1-168               
#> [113] cachem_1.1.0                zoo_1.8-14                 
#> [115] stringr_1.5.1               KernSmooth_2.23-26         
#> [117] parallel_4.5.1              miniUI_0.1.2               
#> [119] desc_1.4.3                  pillar_1.10.2              
#> [121] grid_4.5.1                  vctrs_0.6.5                
#> [123] RANN_2.6.2                  promises_1.3.3             
#> [125] xtable_1.8-4                cluster_2.1.8.1            
#> [127] gamlss.dist_6.1-1           evaluate_1.0.3             
#> [129] cli_3.6.5                   compiler_4.5.1             
#> [131] rlang_1.1.6                 crayon_1.5.3               
#> [133] future.apply_1.20.0         labeling_0.4.3             
#> [135] mclust_6.1.1                plyr_1.8.9                 
#> [137] fs_1.6.6                    stringi_1.8.7              
#> [139] viridisLite_0.4.2           deldir_2.0-4               
#> [141] lazyeval_0.2.2              spatstat.geom_3.4-1        
#> [143] Matrix_1.7-5                RcppHNSW_0.6.0             
#> [145] patchwork_1.3.0             ggplot2_3.5.2              
#> [147] statmod_1.5.0               shiny_1.10.0               
#> [149] SummarizedExperiment_1.38.1 ROCR_1.0-11                
#> [151] igraph_2.1.4                memoise_2.0.1              
#> [153] bslib_0.9.0