diff --git a/DESCRIPTION b/DESCRIPTION index 0146bcb..8174cbb 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -67,6 +67,7 @@ Suggests: dplyr, GenomicRanges, IRanges, + Rsamtools, BSgenome.Hsapiens.UCSC.hg19, BSgenome.Hsapiens.UCSC.hg38 Config/testthat/edition: 3 diff --git a/NAMESPACE b/NAMESPACE index b57f3fc..b1b10d1 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -360,6 +360,7 @@ export(write_pseudobulk_coverage) export(write_pseudobulk_fragments) export(write_pseudobulk_manifest) export(write_pseudobulk_peaks) +export(write_sce2g_inputs) exportPattern("^[[:alpha:]]+") import(BPCells) importFrom(Matrix,t) diff --git a/R/pseudobulk.R b/R/pseudobulk.R index 0f18f89..57f95ae 100644 --- a/R/pseudobulk.R +++ b/R/pseudobulk.R @@ -212,7 +212,7 @@ pseudobulk_fragments.MarchRProject <- function( group_by = if (is.null(names(group_by))) group_by else "custom_groups", dataset_names = dataset_names, frags_name = frags_name, - blacklist = isTRUE(blacklist), + blacklist = !isFALSE(blacklist) && !is.null(blacklist), exclude_chr = exclude_chr, min_fragments = min_fragments, on_low_depth = on_low_depth, @@ -708,6 +708,153 @@ write_pseudobulk_manifest <- function(pb, dir) { } +######################################################################## +# write_sce2g_inputs() +######################################################################## + +#' Write pseudobulk inputs for the scE2G enhancer-gene pipeline +#' +#' Writes the per-cluster fragment files, optional RNA matrices, and cluster table that +#' the scE2G Snakemake pipeline (\url{https://github.com/EngreitzLab/scE2G}) takes as +#' input. Each group in `pb` becomes one scE2G cell cluster. +#' +#' @param pb (MarchRPseudobulk) Output of \code{pseudobulk_fragments()}, built with +#' `blacklist = FALSE` (see Details). +#' @param dir (character) Output directory. Files land in `/fragments/`, `/rna/`, +#' and `/config_cell_clusters.tsv`. +#' @param rna (IterableMatrix or NULL) Raw-count gene x cell matrix for multiome data, e.g. +#' \code{proj[["RNA", by_dataset = FALSE]]}. `NULL` for ATAC-only. Default `NULL`. +#' @param model (character) scE2G model folder names under its `models/` directory. Default +#' `"multiome_powerlaw_v3"` when `rna` is given, else `"scATAC_powerlaw_v3"`. +#' @param verbose (logical) Print progress. Default `TRUE`. +#' +#' @return `pb` with `fragments_path` (and `rna_path` when `rna` is given) added to its +#' manifest, and `params$sce2g_config_path` set to the cluster table. +#' +#' @details Requires the optional `Rsamtools` package. +#' +#' Build `pb` with `blacklist = FALSE`; this warns otherwise. scE2G removes blocklisted +#' candidate regions itself and then adds gene promoters back, so fragments already +#' filtered by MarchR leave any promoter inside a blocklisted region with no signal. +#' +#' scE2G's models are trained on human data. Its default references are hg38; hg19 data +#' runs by pointing its config at the hg19 reference files in its ABC submodule. +#' +#' @references Sheth MU, Qiu W-L, Ma XR, et al. (2026). Mapping enhancer-gene regulatory +#' interactions from single-cell data. \emph{Nature Genetics} 58(8), 1941-1952. +#' \doi{10.1038/s41588-026-02695-8} +#' +#' @family pseudobulk +#' @seealso \code{\link{pseudobulk_fragments}} +#' +#' @examples +#' \dontrun{ +#' pb <- pseudobulk_fragments(proj, group_by = "clusters", blacklist = FALSE) +#' pb <- write_sce2g_inputs(pb, "sce2g_inputs") +#' +#' # Multiome +#' pb <- write_sce2g_inputs(pb, "sce2g_inputs", rna = proj[["RNA", by_dataset = FALSE]]) +#' } +#' +#' @export +write_sce2g_inputs <- function(pb, dir, rna = NULL, model = NULL, verbose = TRUE) { + assert_for(pb, "MarchRPseudobulk") + if (!requireNamespace("Rsamtools", quietly = TRUE)) { + rlang::abort( + "Rsamtools is required to index fragments for scE2G. Install: BiocManager::install('Rsamtools')" + ) + } + model <- model %||% if (is.null(rna)) "scATAC_powerlaw_v3" else "multiome_powerlaw_v3" + assert_is_character(model) + if (is.null(rna) && any(startsWith(model, "multiome"))) { + rlang::abort( + "Multiome scE2G models need an RNA matrix. Pass `rna`, or use model = \"scATAC_powerlaw_v3\"." + ) + } + + if (pb$params$blacklist) { + rlang::warn(paste0( + "Fragments were blacklist-filtered. scE2G applies its own blocklist and then restores ", + "promoters, so rebuild with pseudobulk_fragments(..., blacklist = FALSE)." + )) + } + + groups <- names(pb$fragments) + chrs <- chrNames(pb$fragments_all) + if (!any(startsWith(chrs, "chr"))) { + rlang::abort(sprintf( + "scE2G references use UCSC chromosome names (chr1, chr2, ...), but these fragments use %s.", + pretty_print_vector(chrs) + )) + } + + if (!is.null(rna)) { + assert_for(rna, "IterableMatrix") + if (anyDuplicated(rownames(rna)) > 0) { + rlang::abort("scE2G requires unique gene names, but `rna` has duplicated rownames.") + } + missing <- setdiff(names(pb$cell_groups)[pb$cell_groups %in% groups], colnames(rna)) + if (length(missing) > 0) { + rlang::abort(sprintf( + "%d exported cell(s) are missing from the columns of `rna`, e.g. %s", + length(missing), pretty_print_vector(missing) + )) + } + large <- with(pb$manifest, group[group %in% groups & n_cells > 20000]) + if (length(large) > 0) { + rlang::warn(sprintf( + "scE2G computes RNA-ATAC correlation on a random 20,000-cell subsample of: %s", + pretty_print_vector(large) + )) + } + } + + pb <- write_pseudobulk_fragments(pb, dir, append_5th_column = TRUE, verbose = verbose) + frag_paths <- stats::setNames(pb$manifest$fragments_path, pb$manifest$group)[groups] + + # BPCells writes plain gzip, and tabix can only index BGZF-compressed files. + purrr::walk(frag_paths, function(path) { + tmp <- paste0(path, ".bgz") + Rsamtools::bgzip(path, dest = tmp, overwrite = TRUE) + file.rename(tmp, path) + Rsamtools::indexTabix(path, format = "bed") + }) + + if (!is.null(rna)) { + rna_dir <- .pseudobulk_subdir(dir, "rna") + rna_paths <- stats::setNames( + file.path(rna_dir, paste0(.sanitize_group_name(groups), ".h5ad")), groups + ) + purrr::iwalk(rna_paths, function(path, grp) { + if (verbose) message(sprintf(" Writing RNA counts for group '%s'", grp)) + unlink(path) + write_matrix_anndata_hdf5(rna[, names(pb$cell_groups)[pb$cell_groups == grp]], path) + }) + pb <- .pseudobulk_record(pb, "rna_path", rna_paths) + } + + # scE2G resolves relative paths against its own repository, not this directory. + config <- data.frame( + cluster = .sanitize_group_name(groups), + rna_matrix_file = if (is.null(rna)) "" else normalizePath(rna_paths), + atac_frag_file = normalizePath(frag_paths), + HiC_file = "", + HiC_type = "", + HiC_resolution = "", + alt_TSS = "", + alt_genes = "", + model_dir = paste0("models/", model, collapse = ",") + ) + config_path <- file.path(.pseudobulk_subdir(dir), "config_cell_clusters.tsv") + utils::write.table(config, config_path, sep = "\t", quote = FALSE, row.names = FALSE) + config_path <- normalizePath(config_path) + + if (verbose) message("Run scE2G with --config cell_clusters=", config_path) + pb$params$sce2g_config_path <- config_path + pb +} + + ######################################################################## # Internal: writer helpers ######################################################################## diff --git a/_pkgdown.yml b/_pkgdown.yml index d8b4e5d..e56a617 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -67,6 +67,8 @@ navbar: href: articles/marchr_chrombpnet.html - text: Multiome href: articles/marchr_multiome.html + - text: scE2G Export + href: articles/marchr_scE2G.html repo: url: home: https://github.com/GreenleafLab/MarchR @@ -78,6 +80,7 @@ articles: - marchr_hematopoiesis - marchr_chrombpnet - marchr_multiome + - marchr_scE2G reference: - title: All Functions - subtitle: Package Overview @@ -133,6 +136,7 @@ reference: contents: - DimReduction - project + - project_bulk_atac - PCA - LSI - IterativeLSI @@ -217,6 +221,8 @@ reference: - custom_enrichment - get_matches - get_positions + - get_motifs + - plot_motif_logo - subtitle: Motif Deviations contents: - add_deviations_matrix @@ -233,6 +239,16 @@ reference: - add_peak2gene_links - get_peak2gene_links - make_knn_pseudobulks +- subtitle: Pseudobulk Export + contents: + - pseudobulk_fragments + - write_pseudobulk_fragments + - write_pseudobulk_coverage + - write_pseudobulk_bigwig + - write_pseudobulk_chrom_sizes + - write_pseudobulk_peaks + - write_pseudobulk_manifest + - write_sce2g_inputs - subtitle: Doublet Detection contents: - add_doublet_scores diff --git a/man/pseudobulk_fragments.Rd b/man/pseudobulk_fragments.Rd index 68ebd43..52f9422 100644 --- a/man/pseudobulk_fragments.Rd +++ b/man/pseudobulk_fragments.Rd @@ -102,6 +102,7 @@ Other pseudobulk: \code{\link{write_pseudobulk_coverage}()}, \code{\link{write_pseudobulk_fragments}()}, \code{\link{write_pseudobulk_manifest}()}, -\code{\link{write_pseudobulk_peaks}()} +\code{\link{write_pseudobulk_peaks}()}, +\code{\link{write_sce2g_inputs}()} } \concept{pseudobulk} diff --git a/man/write_pseudobulk_bigwig.Rd b/man/write_pseudobulk_bigwig.Rd index 6dd320e..cc2ba1e 100644 --- a/man/write_pseudobulk_bigwig.Rd +++ b/man/write_pseudobulk_bigwig.Rd @@ -48,6 +48,7 @@ Other pseudobulk: \code{\link{write_pseudobulk_coverage}()}, \code{\link{write_pseudobulk_fragments}()}, \code{\link{write_pseudobulk_manifest}()}, -\code{\link{write_pseudobulk_peaks}()} +\code{\link{write_pseudobulk_peaks}()}, +\code{\link{write_sce2g_inputs}()} } \concept{pseudobulk} diff --git a/man/write_pseudobulk_chrom_sizes.Rd b/man/write_pseudobulk_chrom_sizes.Rd index ac68401..e17cbe5 100644 --- a/man/write_pseudobulk_chrom_sizes.Rd +++ b/man/write_pseudobulk_chrom_sizes.Rd @@ -33,6 +33,7 @@ Other pseudobulk: \code{\link{write_pseudobulk_coverage}()}, \code{\link{write_pseudobulk_fragments}()}, \code{\link{write_pseudobulk_manifest}()}, -\code{\link{write_pseudobulk_peaks}()} +\code{\link{write_pseudobulk_peaks}()}, +\code{\link{write_sce2g_inputs}()} } \concept{pseudobulk} diff --git a/man/write_pseudobulk_coverage.Rd b/man/write_pseudobulk_coverage.Rd index 1a58474..23067b2 100644 --- a/man/write_pseudobulk_coverage.Rd +++ b/man/write_pseudobulk_coverage.Rd @@ -62,6 +62,7 @@ Other pseudobulk: \code{\link{write_pseudobulk_chrom_sizes}()}, \code{\link{write_pseudobulk_fragments}()}, \code{\link{write_pseudobulk_manifest}()}, -\code{\link{write_pseudobulk_peaks}()} +\code{\link{write_pseudobulk_peaks}()}, +\code{\link{write_sce2g_inputs}()} } \concept{pseudobulk} diff --git a/man/write_pseudobulk_fragments.Rd b/man/write_pseudobulk_fragments.Rd index 3353c52..d147d2c 100644 --- a/man/write_pseudobulk_fragments.Rd +++ b/man/write_pseudobulk_fragments.Rd @@ -36,6 +36,7 @@ Other pseudobulk: \code{\link{write_pseudobulk_chrom_sizes}()}, \code{\link{write_pseudobulk_coverage}()}, \code{\link{write_pseudobulk_manifest}()}, -\code{\link{write_pseudobulk_peaks}()} +\code{\link{write_pseudobulk_peaks}()}, +\code{\link{write_sce2g_inputs}()} } \concept{pseudobulk} diff --git a/man/write_pseudobulk_manifest.Rd b/man/write_pseudobulk_manifest.Rd index 6399129..9b2e01d 100644 --- a/man/write_pseudobulk_manifest.Rd +++ b/man/write_pseudobulk_manifest.Rd @@ -29,6 +29,7 @@ Other pseudobulk: \code{\link{write_pseudobulk_chrom_sizes}()}, \code{\link{write_pseudobulk_coverage}()}, \code{\link{write_pseudobulk_fragments}()}, -\code{\link{write_pseudobulk_peaks}()} +\code{\link{write_pseudobulk_peaks}()}, +\code{\link{write_sce2g_inputs}()} } \concept{pseudobulk} diff --git a/man/write_pseudobulk_peaks.Rd b/man/write_pseudobulk_peaks.Rd index 027c9d5..49f8ca5 100644 --- a/man/write_pseudobulk_peaks.Rd +++ b/man/write_pseudobulk_peaks.Rd @@ -39,6 +39,7 @@ Other pseudobulk: \code{\link{write_pseudobulk_chrom_sizes}()}, \code{\link{write_pseudobulk_coverage}()}, \code{\link{write_pseudobulk_fragments}()}, -\code{\link{write_pseudobulk_manifest}()} +\code{\link{write_pseudobulk_manifest}()}, +\code{\link{write_sce2g_inputs}()} } \concept{pseudobulk} diff --git a/man/write_sce2g_inputs.Rd b/man/write_sce2g_inputs.Rd new file mode 100644 index 0000000..b029c81 --- /dev/null +++ b/man/write_sce2g_inputs.Rd @@ -0,0 +1,70 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pseudobulk.R +\name{write_sce2g_inputs} +\alias{write_sce2g_inputs} +\title{Write pseudobulk inputs for the scE2G enhancer-gene pipeline} +\usage{ +write_sce2g_inputs(pb, dir, rna = NULL, model = NULL, verbose = TRUE) +} +\arguments{ +\item{pb}{(MarchRPseudobulk) Output of \code{pseudobulk_fragments()}, built with +\code{blacklist = FALSE} (see Details).} + +\item{dir}{(character) Output directory. Files land in \verb{/fragments/}, \verb{/rna/}, +and \verb{/config_cell_clusters.tsv}.} + +\item{rna}{(IterableMatrix or NULL) Raw-count gene x cell matrix for multiome data, e.g. +\code{proj[["RNA", by_dataset = FALSE]]}. \code{NULL} for ATAC-only. Default \code{NULL}.} + +\item{model}{(character) scE2G model folder names under its \verb{models/} directory. Default +\code{"multiome_powerlaw_v3"} when \code{rna} is given, else \code{"scATAC_powerlaw_v3"}.} + +\item{verbose}{(logical) Print progress. Default \code{TRUE}.} +} +\value{ +\code{pb} with \code{fragments_path} (and \code{rna_path} when \code{rna} is given) added to its +manifest, and \code{params$sce2g_config_path} set to the cluster table. +} +\description{ +Writes the per-cluster fragment files, optional RNA matrices, and cluster table that +the scE2G Snakemake pipeline (\url{https://github.com/EngreitzLab/scE2G}) takes as +input. Each group in \code{pb} becomes one scE2G cell cluster. +} +\details{ +Requires the optional \code{Rsamtools} package. + +Build \code{pb} with \code{blacklist = FALSE}; this warns otherwise. scE2G removes blocklisted +candidate regions itself and then adds gene promoters back, so fragments already +filtered by MarchR leave any promoter inside a blocklisted region with no signal. + +scE2G's models are trained on human data. Its default references are hg38; hg19 data +runs by pointing its config at the hg19 reference files in its ABC submodule. +} +\examples{ +\dontrun{ +pb <- pseudobulk_fragments(proj, group_by = "clusters", blacklist = FALSE) +pb <- write_sce2g_inputs(pb, "sce2g_inputs") + +# Multiome +pb <- write_sce2g_inputs(pb, "sce2g_inputs", rna = proj[["RNA", by_dataset = FALSE]]) +} + +} +\references{ +Sheth MU, Qiu W-L, Ma XR, et al. (2026). Mapping enhancer-gene regulatory +interactions from single-cell data. \emph{Nature Genetics} 58(8), 1941-1952. +\doi{10.1038/s41588-026-02695-8} +} +\seealso{ +\code{\link{pseudobulk_fragments}} + +Other pseudobulk: +\code{\link{pseudobulk_fragments}()}, +\code{\link{write_pseudobulk_bigwig}()}, +\code{\link{write_pseudobulk_chrom_sizes}()}, +\code{\link{write_pseudobulk_coverage}()}, +\code{\link{write_pseudobulk_fragments}()}, +\code{\link{write_pseudobulk_manifest}()}, +\code{\link{write_pseudobulk_peaks}()} +} +\concept{pseudobulk} diff --git a/tests/testthat/test-pseudobulk.R b/tests/testthat/test-pseudobulk.R index 5b35090..ae34fe4 100644 --- a/tests/testthat/test-pseudobulk.R +++ b/tests/testthat/test-pseudobulk.R @@ -449,3 +449,108 @@ test_that("print.MarchRPseudobulk summarizes groups and depths", { expect_output(print(pb), "MarchRPseudobulk") expect_output(print(pb), "2 groups") }) + + +######################################################################## +# write_sce2g_inputs() +######################################################################## + +sce2g_test_pb <- function(proj) { + pseudobulk_fragments( + proj, group_by = pseudobulk_test_groups(proj), blacklist = FALSE, verbose = FALSE + ) +} + +test_that("write_sce2g_inputs writes indexed 5-column fragments, h5ad RNA, and the cluster table", { + skip_if_not_installed("Rsamtools") + proj <- create_test_project(include_fragments = TRUE) + pb <- sce2g_test_pb(proj) + rna <- proj[["RNA", by_dataset = FALSE]] + out <- withr::local_tempdir() + + pb <- write_sce2g_inputs(pb, out, rna = rna, verbose = FALSE) + + frag <- pb$manifest$fragments_path[pb$manifest$group == "A"] + expect_true("chr1" %in% Rsamtools::headerTabix(frag)$seqnames) + expect_length(strsplit(readLines(gzfile(frag), n = 1L), "\t")[[1]], 5L) + sorted_key <- function(d) sort(paste(d$chr, d$start, d$end, d$cell_id)) + written <- as.data.frame(open_fragments_10x(frag, comment = "")) + expect_equal(sorted_key(written), sorted_key(as.data.frame(pb$fragments$A))) + + h5ad <- open_matrix_anndata_hdf5(pb$manifest$rna_path[pb$manifest$group == "A"]) + expect_setequal(colnames(h5ad), cellNames(pb$fragments$A)) + expect_equal( + as.matrix(as(h5ad, "dgCMatrix")), + as.matrix(as(rna[, colnames(h5ad)], "dgCMatrix")) + ) + + config <- utils::read.delim(pb$params$sce2g_config_path, colClasses = "character") + expect_named(config, c( + "cluster", "rna_matrix_file", "atac_frag_file", "HiC_file", "HiC_type", + "HiC_resolution", "alt_TSS", "alt_genes", "model_dir" + )) + expect_setequal(config$cluster, c("A", "B")) + expect_equal(config$model_dir, rep("models/multiome_powerlaw_v3", 2)) + expect_equal(config$atac_frag_file[config$cluster == "A"], normalizePath(frag)) +}) + +test_that("write_sce2g_inputs defaults to the ATAC-only model without RNA", { + skip_if_not_installed("Rsamtools") + proj <- create_test_project(include_fragments = TRUE) + out <- withr::local_tempdir() + + pb <- write_sce2g_inputs(sce2g_test_pb(proj), out, verbose = FALSE) + + config <- utils::read.delim(pb$params$sce2g_config_path, colClasses = "character") + expect_equal(config$model_dir, rep("models/scATAC_powerlaw_v3", 2)) + expect_equal(config$rna_matrix_file, rep("", 2)) + expect_false("rna_path" %in% names(pb$manifest)) +}) + +test_that("write_sce2g_inputs rejects inputs scE2G cannot use", { + skip_if_not_installed("Rsamtools") + proj <- create_test_project(include_fragments = TRUE) + pb <- sce2g_test_pb(proj) + rna <- proj[["RNA", by_dataset = FALSE]] + out <- withr::local_tempdir() + + expect_error( + write_sce2g_inputs(pb, out, model = "multiome_powerlaw_v3", verbose = FALSE), + "need an RNA matrix" + ) + expect_error( + write_sce2g_inputs(pb, out, rna = rna[, colnames(rna)[-1]], verbose = FALSE), + "missing from the columns of `rna`" + ) + dup <- rna + rownames(dup) <- rep(rownames(rna)[1], nrow(rna)) + expect_error(write_sce2g_inputs(pb, out, rna = dup, verbose = FALSE), "unique gene names") + + ensembl_style <- pb + chrNames(ensembl_style$fragments_all) <- sub("^chr", "", chrNames(pb$fragments_all)) + expect_error(write_sce2g_inputs(ensembl_style, out, verbose = FALSE), "UCSC chromosome names") +}) + +test_that("write_sce2g_inputs warns only for multiome clusters scE2G will subsample", { + skip_if_not_installed("Rsamtools") + proj <- create_test_project(include_fragments = TRUE) + pb <- sce2g_test_pb(proj) + pb$manifest$n_cells[pb$manifest$group == "A"] <- 20001 + rna <- proj[["RNA", by_dataset = FALSE]] + out <- withr::local_tempdir() + + expect_warning(write_sce2g_inputs(pb, out, rna = rna, verbose = FALSE), "20,000-cell") + expect_no_warning(write_sce2g_inputs(pb, out, verbose = FALSE)) +}) + +test_that("write_sce2g_inputs warns when fragments were blacklist-filtered", { + skip_if_not_installed("Rsamtools") + proj <- create_test_project(include_fragments = TRUE) + bl <- data.frame(chr = "chr1", start = 0L, end = 10L) + pb <- pseudobulk_fragments( + proj, group_by = pseudobulk_test_groups(proj), blacklist = bl, verbose = FALSE + ) + out <- withr::local_tempdir() + + expect_warning(write_sce2g_inputs(pb, out, verbose = FALSE), "blacklist = FALSE") +}) diff --git a/vignettes/marchr_scE2G.Rmd b/vignettes/marchr_scE2G.Rmd new file mode 100644 index 0000000..bfa822e --- /dev/null +++ b/vignettes/marchr_scE2G.Rmd @@ -0,0 +1,237 @@ +--- +title: "MarchR scE2G tutorial (WIP)" +author: "Eric Liu" +output: + html_document: + toc: true + toc_float: true + toc_depth: 2 +vignette: > + %\VignetteIndexEntry{MarchR scE2G tutorial} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +```{r setup, include=FALSE} +knitr::opts_chunk$set(collapse = FALSE, eval = FALSE) +``` + +## Introduction + +[scE2G](https://github.com/EngreitzLab/scE2G) predicts which enhancers regulate which genes in +each cell cluster, from scATAC-seq alone or from multiome (paired ATAC and RNA) data. Its models +are trained on CRISPR perturbations of more than 10,000 element-gene pairs, and benchmarked against +CRISPR data, fine-mapped eQTLs, and GWAS variant-gene associations +([Sheth, Qiu et al.](https://doi.org/10.1038/s41588-026-02695-8)). + +`add_peak2gene_links()` correlates accessibility with gene expression and needs an RNA assay. +scE2G instead scores links within each cluster, and its ATAC-only model needs no RNA at all. + +scE2G runs as its own Snakemake pipeline. MarchR writes the inputs with `write_sce2g_inputs()`; +you then run scE2G and read its predictions back into R for plotting. +**This tutorial continues from the hematopoiesis tutorial** (`vignette("marchr_hematopoiesis")`): +an hg19 scATAC-seq project with clusters stored in `atac_clusters`. + +## Requirements + +- **Human data.** scE2G's models are trained on human cells. Its default reference files are + hg38; hg19 is covered under [Run scE2G](#run-sce2g). +- **Linux with conda.** Singularity or Apptainer is needed for scE2G's recommended container + route. scE2G recommends at least 32 GB of RAM. +- **Rsamtools**, which `write_sce2g_inputs()` uses to compress and index fragment files: + +```{r} +BiocManager::install("Rsamtools") +``` + +## Setup + +Load MarchR and the project saved at the end of the hematopoiesis tutorial. + +```{r} +library(MarchR) +cache_dir <- path.expand("~/.cache/marchr_hematopoiesis") +proj <- load_project(file.path(cache_dir, "saved_project")) +``` + +## Group Fragments by Cluster + +```{r} +pb <- pseudobulk_fragments( + proj, + group_by = "atac_clusters", + # Keep blacklisted regions. scE2G removes blacklisted candidate regions itself and then adds + # gene promoters back, so fragments filtered out here would leave any promoter inside a + # blacklisted region with no signal. + blacklist = FALSE +) +pb +``` + +Each group becomes one scE2G cell cluster. For multiome data, scE2G computes its RNA-accessibility +correlation on a random sample of 20,000 cells from any larger cluster, and `write_sce2g_inputs()` +warns when that applies. + +## Write scE2G Inputs + +```{r} +input_dir <- file.path(cache_dir, "scE2G_inputs") +pb <- write_sce2g_inputs(pb, dir = input_dir) +``` + +This writes: + +- `fragments/.tsv.gz`: one fragment file per cluster, compressed with bgzip and indexed + with tabix (a `.tbi` file alongside). +- `config_cell_clusters.tsv`: the cluster table scE2G reads. It holds absolute file paths and the + model to apply, `scATAC_powerlaw_v3` for ATAC-only data. + +`write_sce2g_inputs()` stops with an error if the fragments use chromosome names without the +`chr` prefix, because scE2G would discard every fragment. + +### Fragment Files from Outside MarchR + +scE2G needs bgzip-compressed fragment files with a tabix index; a plain gzip file cannot be +indexed. `write_sce2g_inputs()` handles this for you. To prepare a fragment file yourself: + +```{r} +Rsamtools::bgzip("fragments.tsv.gz", dest = "fragments.bgz.tsv.gz") +Rsamtools::indexTabix("fragments.bgz.tsv.gz", format = "bed") +``` + +`bgzip()` reads plain gzip input directly. The file also needs 5 columns (`chr`, `start`, `end`, +cell barcode, count). scE2G's multiome step reads fragments through Signac, which rejects files +with 4 columns but never uses the count value. + +### Multiome Data + +For paired ATAC and RNA data, also pass the raw RNA counts. scE2G then applies its multiome +model, which adds RNA-accessibility correlation features. + +```{r} +pb <- write_sce2g_inputs( + pb, + dir = input_dir, + rna = proj[["RNA", by_dataset = FALSE]] # raw RNA counts assay +) +``` + +RNA is written per cluster as `rna/.h5ad`: + +- **Use `.h5ad`, not a 10x `.h5` file.** scE2G reads both extensions with `read_h5ad()`, so a + 10x HDF5 file fails. +- **Counts must be unnormalized.** scE2G normalizes them itself. +- **Gene names must be unique, and every exported cell must be in the matrix.** + `write_sce2g_inputs()` checks both. +- **Gene names must match the `gene_name` field of the GTF** set as `gene_annotations` in + scE2G's `config/config.yaml`. The default is GENCODE v43; for CellRanger output, use the + GENCODE version CellRanger was built with. + +## Install scE2G + +```bash +git clone --recurse-submodules --shallow-submodules --depth 1 https://github.com/EngreitzLab/scE2G.git +cd scE2G +git submodule update --init --recursive + +conda config --set channel_priority flexible +conda env create -f workflow/envs/run_snakemake.yml +conda activate run_snakemake +``` + +The first run also builds scE2G's software environments, which takes 30-40 minutes. The +[scE2G README](https://github.com/EngreitzLab/scE2G) has tips for HPC clusters. + +## Run scE2G + +Run Snakemake from inside the scE2G directory. The `--config` flags point scE2G at the MarchR +cluster table and an output directory without editing scE2G's own `config/config.yaml`. Use +absolute paths. + +For hg38 data: + +```bash +snakemake -j1 --use-conda --use-singularity \ + --configfile config/config.yaml \ + --config cell_clusters=/path/to/scE2G_inputs/config_cell_clusters.tsv \ + results_dir=/path/to/scE2G_results/ +``` + +Drop `--use-singularity` to build every environment with conda instead of using scE2G's +container. Raise `-j` to run steps in parallel. On a workstation, also cap memory with +`--resources mem_mb=`, for example `--resources mem_mb=12000` on a 16 GB machine. Otherwise +Snakemake can run memory-heavy steps for several clusters at once, and the operating system +kills one of them. + +### hg19 Data + +scE2G's default reference files are hg38, but the ABC pipeline bundled inside it ships hg19 +equivalents. Point the config at them; these paths are relative to the scE2G directory: + +```bash +snakemake -j1 --use-conda --use-singularity \ + --configfile config/config.yaml \ + --config cell_clusters=/path/to/scE2G_inputs/config_cell_clusters.tsv \ + results_dir=/path/to/scE2G_results/ \ + chr_sizes=ENCODE_rE2G/ABC/reference/hg19/chrom_sizes.tsv \ + regions_blocklist=ENCODE_rE2G/ABC/reference/hg19/wgEncodeHg19ConsensusSignalArtifactRegions.bed \ + gene_TSS500=ENCODE_rE2G/ABC/reference/hg19/CollapsedGeneBounds.hg19.TSS500bp.bed \ + genes=ENCODE_rE2G/ABC/reference/hg19/CollapsedGeneBounds.hg19.bed +``` + +The hematopoiesis project is hg19, so use this command for it. scE2G itself documents only hg38. +Its model features (distances, accessibility ranks, and gene annotations joined by gene symbol) +do not depend on the assembly, but the hg19 gene list differs slightly from the hg38 list the +models were calibrated on. + +## Plot scE2G Links + +For each cluster and model, scE2G writes every candidate pair to `scE2G_predictions.tsv.gz` and +the pairs that pass the model's threshold to `scE2G_predictions_threshold.tsv.gz`. The +score is in `E2G.Score.qnorm`. Cluster folders are named by the `cluster` column of +`config_cell_clusters.tsv`: the group label, with characters that are unsafe in file names +replaced by `_`. + +```{r} +results_dir <- "/path/to/scE2G_results" +cluster <- "C1" + +links <- read.delim(Sys.glob(file.path( + results_dir, cluster, "scATAC_powerlaw_v3", "scE2G_predictions_threshold*.tsv.gz" +))) + +# Self-promoter links overlap their own gene's TSS and would draw as zero-length arcs. +# scE2G writes Python-style True/False, which as.logical() reads but read.delim() does not. +links <- links[!as.logical(links$isSelfPromoter), ] + +element_mid <- (links$start + links$end) %/% 2 +loops <- data.frame( + chr = links$chr, + start = pmin(element_mid, links$TargetGeneTSS), + end = pmax(element_mid, links$TargetGeneTSS), + score = links$E2G.Score.qnorm +) + +# Center the window on scE2G's TSS for the gene. scE2G links end at TSSs from its own gene +# list, which can differ from the project's annotation, so a window from gene_region() can +# miss them. +gene <- "CD14" +hit <- links[links$TargetGene == gene, ][1, ] +region <- sprintf("%s:%d-%d", hit$chr, hit$TargetGeneTSS - 50000L, hit$TargetGeneTSS + 50000L) + +plot_browser_track( + proj, + region = region, + group_by = "atac_clusters", + frags_name = "ATAC", + tracks = c("coverage", "gene", "loop"), + loops = loops, + loop_color_by = "score", + loop_track_label = "scE2G", + title = gene +) +``` + +If you use scE2G, cite: Sheth MU, Qiu W-L, Ma XR, et al. (2026). Mapping enhancer-gene regulatory +interactions from single-cell data. *Nature Genetics* 58(8), 1941-1952. + diff --git a/vignettes/marchr_scE2G.html b/vignettes/marchr_scE2G.html new file mode 100644 index 0000000..7235b78 --- /dev/null +++ b/vignettes/marchr_scE2G.html @@ -0,0 +1,1728 @@ + + + + + + + + + + + + + + +MarchR scE2G tutorial (WIP) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +
+
+
+
+
+ +
+ + + + + + + +
+

Introduction

+

scE2G predicts which enhancers regulate which genes in each cell cluster, from scATAC-seq alone or from multiome (paired ATAC and RNA) data. Its models are trained on CRISPR perturbations of more than 10,000 element-gene pairs, and benchmarked against CRISPR data, fine-mapped eQTLs, and GWAS variant-gene associations (Sheth, Qiu et al.).

+

add_peak2gene_links() correlates accessibility with gene expression and needs an RNA assay. scE2G instead scores links within each cluster, and its ATAC-only model needs no RNA at all.

+

scE2G runs as its own Snakemake pipeline. MarchR writes the inputs with write_sce2g_inputs(); you then run scE2G and read its predictions back into R for plotting. This tutorial continues from the hematopoiesis tutorial (vignette("marchr_hematopoiesis")): an hg19 scATAC-seq project with clusters stored in atac_clusters.

+
+
+

Requirements

+
    +
  • Human data. scE2G’s models are trained on human cells. Its default reference files are hg38; hg19 is covered under Run scE2G.
  • +
  • Linux with conda. Singularity or Apptainer is needed for scE2G’s recommended container route. scE2G recommends at least 32 GB of RAM.
  • +
  • Rsamtools, which write_sce2g_inputs() uses to compress and index fragment files:
  • +
+
BiocManager::install("Rsamtools")
+
+
+

Setup

+

Load MarchR and the project saved at the end of the hematopoiesis tutorial.

+
library(MarchR)
+cache_dir <- path.expand("~/.cache/marchr_hematopoiesis")
+proj <- load_project(file.path(cache_dir, "saved_project"))
+
+
+

Group Fragments by Cluster

+
pb <- pseudobulk_fragments(
+  proj,
+  group_by = "atac_clusters",
+  # Keep blacklisted regions. scE2G removes blacklisted candidate regions itself and then adds
+  # gene promoters back, so fragments filtered out here would leave any promoter inside a
+  # blacklisted region with no signal.
+  blacklist = FALSE
+)
+pb
+

Each group becomes one scE2G cell cluster. For multiome data, scE2G computes its RNA-accessibility correlation on a random sample of 20,000 cells from any larger cluster, and write_sce2g_inputs() warns when that applies.

+
+
+

Write scE2G Inputs

+
input_dir <- file.path(cache_dir, "scE2G_inputs")
+pb <- write_sce2g_inputs(pb, dir = input_dir)
+

This writes:

+
    +
  • fragments/<cluster>.tsv.gz: one fragment file per cluster, compressed with bgzip and indexed with tabix (a .tbi file alongside).
  • +
  • config_cell_clusters.tsv: the cluster table scE2G reads. It holds absolute file paths and the model to apply, scATAC_powerlaw_v3 for ATAC-only data.
  • +
+

write_sce2g_inputs() stops with an error if the fragments use chromosome names without the chr prefix, because scE2G would discard every fragment.

+
+

Fragment Files from Outside MarchR

+

scE2G needs bgzip-compressed fragment files with a tabix index; a plain gzip file cannot be indexed. write_sce2g_inputs() handles this for you. To prepare a fragment file yourself:

+
Rsamtools::bgzip("fragments.tsv.gz", dest = "fragments.bgz.tsv.gz")
+Rsamtools::indexTabix("fragments.bgz.tsv.gz", format = "bed")
+

bgzip() reads plain gzip input directly. The file also needs 5 columns (chr, start, end, cell barcode, count). scE2G’s multiome step reads fragments through Signac, which rejects files with 4 columns but never uses the count value.

+
+
+

Multiome Data

+

For paired ATAC and RNA data, also pass the raw RNA counts. scE2G then applies its multiome model, which adds RNA-accessibility correlation features.

+
pb <- write_sce2g_inputs(
+  pb,
+  dir = input_dir,
+  rna = proj[["RNA", by_dataset = FALSE]]  # raw RNA counts assay
+)
+

RNA is written per cluster as rna/<cluster>.h5ad:

+
    +
  • Use .h5ad, not a 10x .h5 file. scE2G reads both extensions with read_h5ad(), so a 10x HDF5 file fails.
  • +
  • Counts must be unnormalized. scE2G normalizes them itself.
  • +
  • Gene names must be unique, and every exported cell must be in the matrix. write_sce2g_inputs() checks both.
  • +
  • Gene names must match the gene_name field of the GTF set as gene_annotations in scE2G’s config/config.yaml. The default is GENCODE v43; for CellRanger output, use the GENCODE version CellRanger was built with.
  • +
+
+
+
+

Install scE2G

+
git clone --recurse-submodules --shallow-submodules --depth 1 https://github.com/EngreitzLab/scE2G.git
+cd scE2G
+git submodule update --init --recursive
+
+conda config --set channel_priority flexible
+conda env create -f workflow/envs/run_snakemake.yml
+conda activate run_snakemake
+

The first run also builds scE2G’s software environments, which takes 30-40 minutes. The scE2G README has tips for HPC clusters.

+
+
+

Run scE2G

+

Run Snakemake from inside the scE2G directory. The --config flags point scE2G at the MarchR cluster table and an output directory without editing scE2G’s own config/config.yaml. Use absolute paths.

+

For hg38 data:

+
snakemake -j1 --use-conda --use-singularity \
+  --configfile config/config.yaml \
+  --config cell_clusters=/path/to/scE2G_inputs/config_cell_clusters.tsv \
+           results_dir=/path/to/scE2G_results/
+

Drop --use-singularity to build every environment with conda instead of using scE2G’s container. Raise -j to run steps in parallel. On a workstation, also cap memory with --resources mem_mb=<MB>, for example --resources mem_mb=12000 on a 16 GB machine. Otherwise Snakemake can run memory-heavy steps for several clusters at once, and the operating system kills one of them.

+
+

hg19 Data

+

scE2G’s default reference files are hg38, but the ABC pipeline bundled inside it ships hg19 equivalents. Point the config at them; these paths are relative to the scE2G directory:

+
snakemake -j1 --use-conda --use-singularity \
+  --configfile config/config.yaml \
+  --config cell_clusters=/path/to/scE2G_inputs/config_cell_clusters.tsv \
+           results_dir=/path/to/scE2G_results/ \
+           chr_sizes=ENCODE_rE2G/ABC/reference/hg19/chrom_sizes.tsv \
+           regions_blocklist=ENCODE_rE2G/ABC/reference/hg19/wgEncodeHg19ConsensusSignalArtifactRegions.bed \
+           gene_TSS500=ENCODE_rE2G/ABC/reference/hg19/CollapsedGeneBounds.hg19.TSS500bp.bed \
+           genes=ENCODE_rE2G/ABC/reference/hg19/CollapsedGeneBounds.hg19.bed
+

The hematopoiesis project is hg19, so use this command for it. scE2G itself documents only hg38. Its model features (distances, accessibility ranks, and gene annotations joined by gene symbol) do not depend on the assembly, but the hg19 gene list differs slightly from the hg38 list the models were calibrated on.

+
+
+ + + + +
+
+ +
+ + + + + + + + + + + + + + + +