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 `
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.
write_sce2g_inputs() uses to compress and index fragment files:BiocManager::install("Rsamtools")
+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"))
+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.
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.
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.
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:
.h5ad, not a 10x .h5 file. scE2G reads both extensions with read_h5ad(), so a 10x HDF5 file fails.write_sce2g_inputs() checks both.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.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 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.
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.
+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<value>.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 _.
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. https://doi.org/10.1038/s41588-026-02695-8
+