This tutorial shows how to use CellSpectra 0.2.0 and what changed compared with 0.1.1. The method and the original tutorials are by Klötzer, Zhang and Susztak; please cite their manuscript (Klötzer et al., Nature Genetics 2025, doi:10.1038/s41588-025-02285-0). If you are new to CellSpectra, read the original on-the-fly and advanced tutorials first; they explain the method and its parameters in detail.

We use the data of the advanced tutorial: proximal tubule (PT) cells of one patient with acute kidney injury (sample 32-2, the query) and three healthy kidney samples (the reference), together with the KEGG gene sets shipped with that tutorial.

1. Installation

# install.packages("remotes")
remotes::install_github("jarxunlai/CellSpectra@v0.2.0")
# or download CellSpectra_0.2.0.tar.gz from
# https://github.com/jarxunlai/CellSpectra/releases and run
# install.packages("CellSpectra_0.2.0.tar.gz", repos = NULL, type = "source")

CellSpectra 0.2.0 needs R >= 4.1, SeuratObject >= 5.0 and BiocParallel (Bioconductor). The repository also contains a pixi.toml that sets up a complete environment (pixi install, then pixi run tutorial renders this file).

library(CellSpectra)
library(SeuratObject)
library(BiocParallel)
packageVersion("CellSpectra")
## [1] '0.2.0'

2. A Seurat v5 object, used as is

CellSpectra 0.1.1 read counts from object@assays$RNA@counts and therefore needed a Seurat v4 style assay. Version 0.2.0 reads the raw counts with SeuratObject::LayerData(), so Seurat v5 objects (Assay5) work directly; split counts layers (for example after split() for integration) are joined automatically.

The tutorial object was saved with a v4 assay. We convert it to a v5 assay to show that no conversion back is needed:

seurat_object <- readRDS("../CellSpectra_advanced/Human_PT_subset.rds")
seurat_object <- suppressWarnings({
  seurat_object[["RNA"]] <- as(seurat_object[["RNA"]], "Assay5")
  seurat_object
})
class(seurat_object[["RNA"]])
## [1] "Assay5"
## attr(,"package")
## [1] "SeuratObject"
Layers(seurat_object[["RNA"]])
## [1] "counts" "data"
table(seurat_object$orig_ident, seurat_object$disease_grouped_qr)
##         
##          query_samples reference_samples sample_of_interest
##   18-162             0               629                  0
##   18-312             0              1531                  0
##   32-2               0                 0                377
##   3499               0                74                  0

prepare_seurat_object() adds the three metadata columns CellSpectra uses (cell type, sample, query or control), exactly as in 0.1.1:

seurat_object <- prepare_seurat_object(
  seurat_obj = seurat_object,
  celltype_col = "C_scANVI_modified1",
  sample_id_col = "orig_ident",
  condition_col = "disease_grouped_qr",
  query_list = c("sample_of_interest"),
  control_list = c("reference_samples")
)

3. Reference pseudobulks: seeds and parallel backends

create_references() builds, for every query sample, count-matched pseudobulks of the reference samples by drawing cells with replacement until the query’s total count is reached. Two arguments are new or changed in 0.2.0:

  • seed: each combination of cell type, query sample and reference sample gets its own independent random stream derived from seed and the cell type name. Results for a cell type depend only on the seed and that cell type’s data (and cell_number_threshold), not on which other cell types are run, their order, or the parallel backend. Your own random number state is left unchanged. In 0.1.1 all reference samples reused the same random index sequence, so with the same seed 0.2.0 draws different (but statistically equivalent) reference pseudobulks.
  • BPPARAM: a BiocParallel backend, one task per query sample. The default is SerialParam(progressbar = TRUE).
output_folder_base <- "output/"

create_references(
  seurat_object = seurat_object,
  output_folder_base = output_folder_base,
  num_replicates = 1,
  cell_types = c("PT"),
  cell_number_threshold = 10,
  seed = 123,
  BPPARAM = SerialParam()
)
list.files(output_folder_base, recursive = TRUE)
##  [1] "go_sets_modified.rds"                   
##  [2] "Padj/Padj_PT.csv"                       
##  [3] "PT/samples_of_interest.rds"             
##  [4] "PT/subfolder_sample_32-2/datD.rds"      
##  [5] "PT/subfolder_sample_32-2/datH.rds"      
##  [6] "PT/subfolder_sample_32-2/pathway_QC.csv"
##  [7] "PT/valid_samples.rds"                   
##  [8] "Pval/Pval_PT.csv"                       
##  [9] "R2/R2_PT.csv"                           
## [10] "samples_of_interest.rds"

Besides the per-sample datH.rds (reference) and datD.rds (query) files, the query samples are now saved per cell type (PT/samples_of_interest.rds); in 0.1.1 a single top-level file was overwritten for every cell type.

4. Running CellSpectra

We use the KEGG gene sets of the advanced tutorial. run_spectra() expects them as go_sets_modified.rds in the output folder.

invisible(file.copy("../CellSpectra_advanced/output/go_sets_modified.rds",
                    output_folder_base, overwrite = TRUE))

run_spectra(
  output_folder_base = output_folder_base,
  cell_types = c("PT"),
  CHISQ.MAX = 4,
  expression_threshold = -1,
  gene_number_threshold = 10,
  QC_report = TRUE,
  BPPARAM = SerialParam()
)

run_spectra() warns once for every gene set that has fewer than gene_number_threshold genes after filtering (hidden above); those gene sets are NA in the results. The results are written as before:

r2 <- read.csv("output/R2/R2_PT.csv", row.names = 1, check.names = FALSE)
padj <- read.csv("output/Padj/Padj_PT.csv", row.names = 1, check.names = FALSE)

results <- data.frame(
  gene_set = colnames(r2),
  R2 = unlist(r2[1, ]),
  Padj = unlist(padj[1, ]),
  row.names = NULL
)
results <- results[!is.na(results$Padj), ]
c(gene_sets = ncol(r2), tested = nrow(results), significant = sum(results$Padj < 0.05))
##   gene_sets      tested significant 
##         350         334         255
head(results[order(results$Padj), ], 10)
##                                                                              gene_set
## 291                    hsa05171 Coronavirus disease - COVID-19 - Homo sapiens (human)
## 330 hsa05022 Pathways of neurodegeneration - multiple diseases - Homo sapiens (human)
## 259                                hsa05200 Pathways in cancer - Homo sapiens (human)
## 324                                 hsa05010 Alzheimer disease - Homo sapiens (human)
## 298                    hsa05165 Human papillomavirus infection - Homo sapiens (human)
## 151                                         hsa04145 Phagosome - Homo sapiens (human)
## 329                                     hsa05020 Prion disease - Homo sapiens (human)
## 149                           hsa04514 Cell adhesion molecules - Homo sapiens (human)
## 326                     hsa05014 Amyotrophic lateral sclerosis - Homo sapiens (human)
## 325                                 hsa05012 Parkinson disease - Homo sapiens (human)
##            R2         Padj
## 291 0.6819264 6.964458e-33
## 330 0.7981796 6.964458e-33
## 259 0.8781555 3.661674e-31
## 324 0.8329400 3.732713e-28
## 298 0.8342250 1.169984e-26
## 151 0.6750254 7.686397e-25
## 329 0.8004165 4.654156e-24
## 149 0.8021086 2.438303e-23
## 326 0.7342780 1.280550e-22
## 325 0.7853369 8.040665e-22

The QC report summarizes, for every gene set, how consistent the reference samples are among themselves (leave-one-out R²). A large R2sd means the reference itself is heterogeneous for that gene set, so a low query R² is less informative.

qc <- read.csv("output/PT/subfolder_sample_32-2/pathway_QC.csv", check.names = FALSE)
head(qc[order(-qc$R2sd), ], 5)
##                                                                Pathway
## 51  hsa00515 Mannose type O-glycan biosynthesis - Homo sapiens (human)
## 291    hsa05150 Staphylococcus aureus infection - Homo sapiens (human)
## 78                            hsa03010 Ribosome - Homo sapiens (human)
## 42            hsa00360 Phenylalanine metabolism - Homo sapiens (human)
## 328           hsa04940 Type I diabetes mellitus - Homo sapiens (human)
##        R2mean  R2median      R2sd      V1VE
## 51  0.7426069 0.9190538 0.3193947 0.9348073
## 291 0.6040787 0.6969785 0.3157457 0.9041215
## 78  0.5989295 0.7522449 0.3111851 0.9427769
## 42  0.7218055 0.8436318 0.2337883 0.9074227
## 328 0.5185208 0.4296488 0.2295335 0.8184663

Two further notes on the statistics:

  • The chi-square test uses (number of genes - 1) degrees of freedom, as in the manuscript. The new argument chisq_df_offset = 2 subtracts both fitted regression parameters (intercept and slope); the default is unchanged.
  • If the reference fits a gene set exactly (for example a gene set with only two genes, or with at most one expressed gene), the p-value is undefined. 0.2.0 then reports NA with a warning instead of a number; R² is still reported.

5. Same computation as 0.1.1

0.2.0 replaces lm() by the closed-form solution of the simple linear regression and runs the gene sets in parallel. For the same datH/datD files the results are the same as in 0.1.1 up to floating-point rounding. You can check this with the files that were computed by 0.1.1 for the advanced tutorial:

old <- file.path(tempdir(), "advanced_0.1.1")
dir.create(old, showWarnings = FALSE)
invisible(file.copy("../CellSpectra_advanced/output", old, recursive = TRUE))
old <- file.path(old, "output/")
unlink(file.path(old, c("R2", "Pval", "Padj")), recursive = TRUE)

suppressWarnings(run_spectra(old, cell_types = "PT", expression_threshold = -1,
                             BPPARAM = SerialParam()))

read_table <- function(path) as.matrix(read.csv(path, row.names = 1, check.names = FALSE))
r2_new <- read_table(file.path(old, "R2/R2_PT.csv"))
r2_011 <- read_table("../CellSpectra_advanced/output/R2/R2_PT.csv")
p_new <- read_table(file.path(old, "Pval/Pval_PT.csv"))
p_011 <- read_table("../CellSpectra_advanced/output/Pval/Pval_PT.csv")

c(same_NA_pattern = identical(is.na(r2_new), is.na(r2_011)),
  max_abs_diff_R2 = max(abs(r2_new - r2_011), na.rm = TRUE),
  max_abs_diff_log10_p = max(abs(log10(p_new) - log10(p_011)), na.rm = TRUE))
##      same_NA_pattern      max_abs_diff_R2 max_abs_diff_log10_p 
##         1.000000e+00         9.992007e-16         5.151435e-13

The package’s test suite makes the same comparison against a verbatim copy of the 0.1.1 code on many synthetic and real data sets.

6. How stable are the results under reference sampling?

The reference pseudobulks are random draws, so every seed gives a slightly different reference and slightly different R² and p-values. This was already the case in 0.1.1; it matters most when there are few reference samples, as here (three). A simple way to see which conclusions depend on the draw is to repeat the analysis with several seeds:

run_with_seed <- function(seed) {
  out <- paste0(tempfile(paste0("seed", seed, "_")), "/")
  create_references(seurat_object, out, num_replicates = 1, cell_types = "PT",
                    cell_number_threshold = 10, seed = seed, BPPARAM = SerialParam())
  invisible(file.copy("../CellSpectra_advanced/output/go_sets_modified.rds", out))
  suppressWarnings(run_spectra(out, cell_types = "PT", expression_threshold = -1,
                               BPPARAM = SerialParam()))
  list(R2 = unlist(read.csv(paste0(out, "R2/R2_PT.csv"), row.names = 1, check.names = FALSE)),
       Padj = unlist(read.csv(paste0(out, "Padj/Padj_PT.csv"), row.names = 1, check.names = FALSE)))
}

seeds <- 1:5
runs <- lapply(seeds, run_with_seed)
R2_runs <- sapply(runs, `[[`, "R2")
Padj_runs <- sapply(runs, `[[`, "Padj")
tested <- !is.na(Padj_runs[, 1])

times_significant <- rowSums(Padj_runs[tested, ] < 0.05)
table(times_significant)
## times_significant
##   0   1   2   3   4   5 
##  51  14   9  20  24 216

Most gene sets are significant under every seed or under none. The gene sets in between are borderline: their call depends on which cells were drawn for the reference.

stability <- data.frame(
  gene_set = rownames(Padj_runs)[tested],
  times_significant = times_significant,
  R2_min = apply(R2_runs[tested, ], 1, min),
  R2_max = apply(R2_runs[tested, ], 1, max),
  row.names = NULL
)
borderline <- stability[stability$times_significant %in% 1:4, ]
head(borderline[order(borderline$times_significant), ], 10)
##                                                                            gene_set
## 8                     hsa00500 Starch and sucrose metabolism - Homo sapiens (human)
## 11          hsa00630 Glyoxylate and dicarboxylate metabolism - Homo sapiens (human)
## 29                  hsa00592 alpha-Linolenic acid metabolism - Homo sapiens (human)
## 52             hsa00514 Other types of O-glycan biosynthesis - Homo sapiens (human)
## 60  hsa00604 Glycosphingolipid biosynthesis - ganglio series - Homo sapiens (human)
## 91                       hsa03420 Nucleotide excision repair - Homo sapiens (human)
## 119                          hsa04068 FoxO signaling pathway - Homo sapiens (human)
## 159             hsa04610 Complement and coagulation cascades - Homo sapiens (human)
## 177    hsa04672 Intestinal immune network for IgA production - Homo sapiens (human)
## 220         hsa04964 Proximal tubule bicarbonate reclamation - Homo sapiens (human)
##     times_significant    R2_min    R2_max
## 8                   1 0.7549607 0.8202740
## 11                  1 0.9086808 0.9237032
## 29                  1 0.9674184 0.9934007
## 52                  1 0.8373059 0.8575854
## 60                  1 0.8128763 0.8937486
## 91                  1 0.8449274 0.8698175
## 119                 1 0.9177095 0.9227037
## 159                 1 0.5977765 0.6511870
## 177                 1 0.5669781 0.6997501
## 220                 1 0.8134670 0.8284752
r2_mean <- rowMeans(R2_runs[tested, ])
r2_range <- stability$R2_max - stability$R2_min
group <- cut(times_significant, c(-1, 0, 4, 5),
             labels = c("never significant", "borderline (1-4 of 5)", "always significant"))
cols <- c("grey60", "#D55E00", "#0072B2")
plot(r2_mean, r2_range, pch = 19, cex = 0.8, col = cols[group],
     xlab = "mean R² over 5 seeds", ylab = "R² range over 5 seeds",
     main = "Query PT sample 32-2: stability of 334 KEGG gene sets")
legend("topright", legend = levels(group), col = cols, pch = 19, bty = "n")

Recommendations:

  • Report gene sets that are significant for (almost) every seed with confidence; treat borderline gene sets as uncertain.
  • More reference samples make the reference more stable. The three healthy samples here are the minimum for a meaningful leave-one-out estimate; the manuscript used about 50 for the human kidney.
  • Pseudoreplicates (num_replicates > 1) do not add independent information; see the advanced tutorial for when they help.

7. Underlying genes

report_genes() returns, for one gene set, each gene’s residual from the fit to the reference pattern, divided by that gene’s normal variation in the reference. The sign is relative to the fitted line, not a direct up- or down-regulation, so always look at the expression values as well:

gene_set <- "hsa04024 cAMP signaling pathway - Homo sapiens (human)"
genes <- report_genes(output_folder_base, gene_set, cell_type = "PT",
                      sample_of_interest = "32-2", expression_threshold = 0)
## Warning in report_genes(output_folder_base, gene_set, cell_type = "PT", : Genes
## below the threshold were removed for hsa04024 cAMP signaling pathway - Homo
## sapiens (human) - proceeding with 132 genes
genes <- genes[order(-abs(genes$Normalized_Residual)), ]

datH <- readRDS("output/PT/subfolder_sample_32-2/datH.rds")
datD <- readRDS("output/PT/subfolder_sample_32-2/datD.rds")
top <- head(genes, 8)
top$reference_mean <- colMeans(datH[, top$Gene])
top$query <- datD[1, top$Gene]
top
##       Gene Normalized_Residual reference_mean       query
## 33  POPDC2          -10.087967    0.013174196 0.009972996
## 129  MAPK1            9.953971    0.997025785 1.174061379
## 65   VIPR2           -7.571543    0.003304994 0.009972996
## 83   GPHA2           -7.571543    0.003304994 0.009972996
## 72  GRIN3A           -5.632106    0.006577540 0.009972996
## 75  CAMK2G            5.387339    0.612056762 0.816640295
## 21   ROCK2           -5.339447    1.307866409 0.968401640
## 41   CNGA1           -5.231629    0.009901650 0.019847513

Values are log1p(counts per 10,000). The largest residuals belong to two kinds of genes:

  • Genes whose expression clearly changed, for example MAPK1 and CAMK2G (higher in the patient) and ROCK2 (lower).
  • Genes that are barely expressed in both, such as POPDC2 or VIPR2. Their normal variation in the reference is tiny, so a very small difference gives a large residual. They contribute to the chi-square statistic (each gene at most CHISQ.MAX), but they are not convincing drivers on their own. A higher expression_threshold in report_genes() removes them.

8. When does parallel computing help?

Both create_references() and run_spectra() accept any BiocParallel backend. Results do not depend on the backend or on the number of workers:

serial_folder <- paste0(tempfile("serial_"), "/")
parallel_folder <- paste0(tempfile("parallel_"), "/")
for (folder in c(serial_folder, parallel_folder)) {
  dir.create(folder)
  invisible(file.copy(list.files(output_folder_base, full.names = TRUE), folder,
                      recursive = TRUE))
}
suppressWarnings(run_spectra(serial_folder, cell_types = "PT", expression_threshold = -1,
                             BPPARAM = SerialParam()))
suppressWarnings(run_spectra(parallel_folder, cell_types = "PT", expression_threshold = -1,
                             BPPARAM = MulticoreParam(workers = 2)))
identical(readLines(paste0(serial_folder, "Padj/Padj_PT.csv")),
          readLines(paste0(parallel_folder, "Padj/Padj_PT.csv")))
## [1] TRUE

Starting workers costs about a second, so parallel runs only pay off when there is enough work: many query samples (one task per query in create_references()) or many gene sets and samples in run_spectra(). Timings from bench/benchmark.R (32-core Linux machine, R 4.5.3):

Step Data 0.1.1 0.2.0, 1 core 0.2.0, 8 workers
run_spectra ifnb tutorial, 3 cell types × 2659 GO sets 66.4 s 7.2 s 4.2 s
run_spectra this tutorial, 350 KEGG sets 2.2 s 0.5 s 0.7 s
create_references ifnb tutorial, 10 replicates 25.1 s 0.34 s 1.3 s
create_references this tutorial 2.6 s 0.17 s 1.4 s

For one patient, as here, the serial backend is fastest. For an atlas with dozens of query samples, use for example

bp <- MulticoreParam(workers = 8, progressbar = TRUE)   # Windows: SnowParam()
create_references(seurat_object, output_folder_base, num_replicates = 3,
                  cell_types = c("PT", "TAL", "Podo"), seed = 123, BPPARAM = bp)
run_spectra(output_folder_base, cell_types = c("PT", "TAL", "Podo"), BPPARAM = bp)

With forked workers (MulticoreParam), set OPENBLAS_NUM_THREADS=1 (or the equivalent for your BLAS) before starting R, so that workers do not compete for threads; the repository’s pixi environment does this.

Session information

sessionInfo()
## R version 4.5.3 (2026-03-11)
## Platform: x86_64-conda-linux-gnu
## Running under: Ubuntu 24.04.1 LTS
## 
## Matrix products: default
## BLAS/LAPACK: /home/ljx/Github/CellSpectra/.claude/worktrees/project-script-algorithm-analysis-4105dd/.pixi/envs/default/lib/libopenblasp-r0.3.34.so;  LAPACK version 3.12.0
## 
## 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] BiocParallel_1.46.0 SeuratObject_5.4.0  sp_2.2-3           
## [4] CellSpectra_0.2.0  
## 
## loaded via a namespace (and not attached):
##  [1] sass_0.4.10         future_1.80.0       generics_0.1.4     
##  [4] tidyr_1.3.2         lattice_0.23-1      listenv_1.1.0      
##  [7] digest_0.6.39       magrittr_2.0.5      evaluate_1.0.5     
## [10] grid_4.5.3          fastmap_1.2.0       jsonlite_2.0.0     
## [13] Matrix_1.7-6        httr_1.4.9          spam_2.11-4        
## [16] purrr_1.2.2         Biostrings_2.80.2   codetools_0.2-20   
## [19] jquerylib_0.1.4     cli_3.6.6           rlang_1.3.0        
## [22] crayon_1.5.3        XVector_0.52.0      future.apply_1.21.0
## [25] parallelly_1.48.0   cachem_1.1.0        yaml_2.3.12        
## [28] otel_0.2.0          tools_4.5.3         parallel_4.5.3     
## [31] dplyr_1.2.1         globals_0.20.0      BiocGenerics_0.58.1
## [34] vctrs_0.7.3         R6_2.6.1            png_0.1-9          
## [37] stats4_4.5.3        lifecycle_1.0.5     KEGGREST_1.52.2    
## [40] Seqinfo_1.2.0       S4Vectors_0.50.3    IRanges_2.46.0     
## [43] pkgconfig_2.0.3     progressr_1.1.0     pillar_1.11.1      
## [46] bslib_0.12.0        glue_1.8.1          Rcpp_1.1.2         
## [49] xfun_0.61           tibble_3.3.1        tidyselect_1.2.1   
## [52] knitr_1.52          htmltools_0.5.9     rmarkdown_2.32     
## [55] dotCall64_1.2       compiler_4.5.3