Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ Suggests:
dplyr,
GenomicRanges,
IRanges,
Rsamtools,
BSgenome.Hsapiens.UCSC.hg19,
BSgenome.Hsapiens.UCSC.hg38
Config/testthat/edition: 3
Expand Down
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
149 changes: 148 additions & 1 deletion R/pseudobulk.R
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 `<dir>/fragments/`, `<dir>/rna/`,
#' and `<dir>/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
########################################################################
Expand Down
16 changes: 16 additions & 0 deletions _pkgdown.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -78,6 +80,7 @@ articles:
- marchr_hematopoiesis
- marchr_chrombpnet
- marchr_multiome
- marchr_scE2G
reference:
- title: All Functions
- subtitle: Package Overview
Expand Down Expand Up @@ -133,6 +136,7 @@ reference:
contents:
- DimReduction
- project
- project_bulk_atac
- PCA
- LSI
- IterativeLSI
Expand Down Expand Up @@ -217,6 +221,8 @@ reference:
- custom_enrichment
- get_matches
- get_positions
- get_motifs
- plot_motif_logo
- subtitle: Motif Deviations
contents:
- add_deviations_matrix
Expand All @@ -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
Expand Down
3 changes: 2 additions & 1 deletion man/pseudobulk_fragments.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion man/write_pseudobulk_bigwig.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion man/write_pseudobulk_chrom_sizes.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion man/write_pseudobulk_coverage.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion man/write_pseudobulk_fragments.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion man/write_pseudobulk_manifest.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion man/write_pseudobulk_peaks.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

70 changes: 70 additions & 0 deletions man/write_sce2g_inputs.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading