diff --git a/_pkgdown.yml b/_pkgdown.yml index 3438efc..d8b4e5d 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -63,6 +63,8 @@ navbar: menu: - text: Hematopoiesis href: articles/marchr_hematopoiesis.html + - text: ChromBPNet Export + href: articles/marchr_chrombpnet.html - text: Multiome href: articles/marchr_multiome.html repo: @@ -74,6 +76,7 @@ articles: - title: Tutorials contents: - marchr_hematopoiesis + - marchr_chrombpnet - marchr_multiome reference: - title: All Functions diff --git a/vignettes/marchr_chrombpnet.Rmd b/vignettes/marchr_chrombpnet.Rmd new file mode 100644 index 0000000..af49ea8 --- /dev/null +++ b/vignettes/marchr_chrombpnet.Rmd @@ -0,0 +1,432 @@ +--- +title: "Exporting Pseudobulks for ChromBPNet with MarchR (WIP)" +author: "Eric Liu" +output: + html_document: + toc: true + toc_float: true + toc_depth: 2 +vignette: > + %\VignetteIndexEntry{Exporting Pseudobulks for ChromBPNet with MarchR} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +```{r setup, include=FALSE} +knitr::opts_chunk$set(collapse = FALSE) + +# Collect each chunk's printed output, messages, and warnings into a single +# collapsible "Output" box rendered after the code, keeping code and logs +# visually separate. +local({ + buf <- new.env(parent = emptyenv()) + buf$txt <- character(0) + collect <- function(x, options) { + buf$txt <- c(buf$txt, x) + "" + } + esc <- function(x) { + x <- gsub("&", "&", x, fixed = TRUE) + x <- gsub("<", "<", x, fixed = TRUE) + gsub(">", ">", x, fixed = TRUE) + } + default_chunk <- knitr::knit_hooks$get("chunk") + knitr::knit_hooks$set( + output = collect, + message = collect, + warning = collect, + chunk = function(x, options) { + out <- default_chunk(x, options) + if (length(buf$txt)) { + body <- esc(paste(buf$txt, collapse = "")) + buf$txt <- character(0) + out <- paste0( + out, "\n\n```{=html}\n", + "
Output", + "
", body, "
\n", + "```\n\n" + ) + } + out + } + ) +}) +``` + +```{css, echo=FALSE} +details.marchr-log { + background-color: #eef4fb; + border: 1px solid #cfe0f3; + border-left: 4px solid #4f88c6; + border-radius: 4px; + margin: 0.5em 0 1em 0; + padding: 0.4em 0.8em; +} +details.marchr-log > summary { + cursor: pointer; + color: #2c5c8f; + font-weight: 600; + font-size: 0.85em; + list-style: none; +} +details.marchr-log > summary::-webkit-details-marker { display: none; } +details.marchr-log > summary::before { content: "\25B6 "; } +details.marchr-log[open] > summary::before { content: "\25BC "; } +details.marchr-log .marchr-log-body { + background: transparent; + border: none; + margin: 0.4em 0 0 0; + padding: 0; + font-size: 0.85em; + white-space: pre-wrap; +} +``` + +## Introduction + +[ChromBPNet](https://github.com/kundajelab/chrombpnet) learns base-resolution chromatin accessibility +from DNA sequence while factoring out Tn5 sequence bias. +It trains one model per pseudobulk, and for single-cell data it is suggested to aggregate the +fragments by cluster instead of sample to train cluster-specific ChromBPNet models. + +This tutorial provides instructions to setup your single-cell ATAC datasets from your MarchRProject +directly for ChromBPNet model training. +It continues from the end of the [MarchR Hematopoiesis tutorial](marchr_hematopoiesis.html) and +exports the files that the ChromBPNet pipeline reads. +**We highly recommend you read the [ChromBPNet Wiki](https://github.com/kundajelab/chrombpnet/wiki) +prior to starting this tutorial.** + +| ChromBPNet input | Flag | Source | +|---|---|---| +| Fragments per cluster | `-ifrag` | `write_pseudobulk_fragments()` | +| Peaks per cluster (10-column narrowPeak) | `-p` | `write_pseudobulk_peaks()` | +| Chromosome sizes | `-c` | `write_pseudobulk_chrom_sizes()` | +| Blacklist | `-br` (`prep nonpeaks`) | `get_blacklist()` | +| Reference genome FASTA | `-g` | Downloaded | +| Train / validation / test chromosome folds | `-fl` | `chrombpnet prep splits` | +| GC-matched background regions | `-n` | `chrombpnet prep nonpeaks` | +| Bias model | `-b` | Pre-trained, or `chrombpnet bias pipeline` | + +The last three come from ChromBPNet's own tools, so they always match the ChromBPNet release you +train with. +**Training needs a GPU and is not run in this tutorial**; the shell commands are shown for reference. + +## Setup + +Load MarchR and set the session thread count. + +```{r message=FALSE} +library(MarchR) +set_threads(4) +``` + +The Hematopoiesis tutorial saved its project to `cache_dir`. +The export is written next to it, in `export_dir`. + +```{r} +cache_dir <- path.expand("~/.cache/marchr_hematopoiesis") +export_dir <- file.path(cache_dir, "chrombpnet_tutorial") +proj <- load_project(file.path(cache_dir, "saved_project")) +proj +``` + +## Calling Peaks per Cluster + +ChromBPNet trains each cluster's model on that cluster's own peaks. +`add_group_coverages()` builds pseudobulk replicates for each cluster, and +`add_reproducible_peak_set()` calls peaks on them with [MACS3](https://github.com/macs3-project/MACS). +It stores the merged peak set in `proj$peak_set` and each cluster's reproducible peaks in +`proj$group_peak_sets`, which is what gets exported below. + +ChromBPNet +[recommends relaxed peak calls](https://github.com/kundajelab/chrombpnet/wiki/Preprocessing#peak-calling) +("MACS2 with p-value parameter threshold set to 0.01"), so `-p 0.01` is appended to the default MACS +arguments. + +```{r} +proj <- add_group_coverages(proj, group_by = "atac_clusters") +proj <- add_reproducible_peak_set( + proj, + group_by = "atac_clusters", + additional_params = paste( + "--call-summits --keep-dup all --shift -75 --extsize 150 --nomodel --nolambda", + "-p 0.01" + ) +) +``` + +## Grouping Fragments by Cluster + +Each of the `atac_clusters` from the Hematopoiesis tutorial becomes one pseudobulk, one fragment +file, and one ChromBPNet model. + +```{r fig.width=7, fig.height=6} +plot_embedding(proj, col_name = "atac_clusters", title = "UMAP - Clusters") +``` + +`pseudobulk_fragments()` groups cells by a metadata column and returns one lazy fragment set per group. +Fragments are pooled across the three datasets and pass through the same blacklist and chromosome +filters as peak calling, so the exported fragments and peaks cover the same regions. + +```{r} +pb <- pseudobulk_fragments(proj, group_by = "atac_clusters") +pb +``` + +The manifest reports cells, fragments, and median TSS enrichment for each cluster. +Each ChromBPNet model learns its own count scale, so clusters do not need matched depth. +To leave shallow clusters out of the export, set `min_fragments` with `on_low_depth = "drop"`. +ChromBPNet does not publish a minimum depth, so pick the floor for your own data. + +## Writing Fragment Files + +`write_pseudobulk_fragments()` writes one gzipped, 10x-style fragment file per cluster to +`export_dir/fragments/`. +These are the `-ifrag` inputs. + +```{r} +pb <- write_pseudobulk_fragments(pb, export_dir) +``` + +```{r} +read.delim(pb$manifest$fragments_path[[1]], header = FALSE, nrows = 5) +``` + +The columns are chromosome, start, end, and cell barcode. +ChromBPNet reads only the first three: its +[fragment reader](https://github.com/kundajelab/chrombpnet/blob/master/chrombpnet/helpers/preprocessing/auto_shift_detect.py) +expects "tsv with columns chr, start, end and optionally more columns", so Cell Ranger's fifth +duplicate-count column is not needed. +Coordinates are written unshifted, because ChromBPNet estimates and corrects the Tn5 shift itself; +its guide notes that "you do not need to worry about pre-shifting the fragments". + +ArchR's `getGroupFragments()` writes the same four columns. +One difference is that MarchR has already removed fragments in blacklisted regions and on chrM. + +## Writing Peaks + +`write_pseudobulk_peaks()` writes each cluster's peaks to `export_dir/peaks/`. +`scope = "group"` skips the merged peak set; the default, `"both"`, also writes it as +`union.narrowPeak`. + +```{r} +pb <- write_pseudobulk_peaks(pb, export_dir, scope = "group") +read.delim(pb$manifest$peaks_path[[1]], header = FALSE, nrows = 5) +``` + +ChromBPNet's `-p` takes a "10 column bed file of peaks" and centers each training window at start +(column 2) plus summit (column 10). +MarchR peaks are 501 bp wide around the MACS summit, and column 10 holds the stored summit offset. + +`plot_browser_track()` shows the signal each cluster's model will learn. +At the CD14 locus, nearby gene promoters are open in every cluster, while several distal peaks are +open mainly in C8, so each cluster's model trains on a different accessibility profile. +The peaks track shows the merged peak set. + +```{r fig.width=8, fig.height=6} +region <- gene_region( + get_gene_annotations(proj, "genes"), + gene_symbol = "CD14", + upstream = 50000L, + downstream = 50000L +) + +plot_browser_track( + proj, + region = region, + group_by = "atac_clusters", + frags_name = "ATAC", + tracks = c("coverage", "peaks", "gene"), + bins = 400L, + norm_method = "ReadsInTSS", + title = "CD14" +) +``` + +## Chromosome Sizes and Blacklist + +`chrombpnet prep splits` assigns every chromosome in the chromosome sizes file to a fold, so the file +should list only the chromosomes to train on. +This project's chromosome sizes already cover just chr1-22, chrX, and chrY, the same set the +ChromBPNet tutorial uses. + +```{r} +pb <- write_pseudobulk_chrom_sizes(pb, export_dir, get_chrom_sizes(proj)) +readLines(pb$params$chrom_sizes_path, n = 3) +``` + +ChromBPNet uses the blacklist twice: to filter peaks and to keep background regions out of +blacklisted sequence. +Writing the project's own blacklist keeps it consistent with the fragment filtering above. + +```{r} +blacklist <- get_blacklist(proj) +write.table( + blacklist[, c("chr", "start", "end")], + file.path(export_dir, "blacklist.bed"), + sep = "\t", quote = FALSE, row.names = FALSE, col.names = FALSE +) +``` + +## Writing the Manifest + +`write_pseudobulk_manifest()` writes `manifest.tsv`, which works as a samplesheet for workflow +managers, and `manifest.json`, which also records the export parameters and package versions. +Each writer above added its file paths to the manifest as a new column. + +```{r} +write_pseudobulk_manifest(pb, export_dir) +colnames(pb$manifest) +``` + +```{r} +list.files(export_dir, recursive = TRUE) +``` + +If you train your own bias model (below), use a deep cluster so the model sees as many background +reads as possible. +The deepest cluster here is: + +```{r} +pb$manifest$group[which.max(pb$manifest$n_fragments)] +``` + +## Preparing ChromBPNet Inputs + +The remaining steps run in a shell where ChromBPNet is +[installed](https://github.com/kundajelab/chrombpnet/wiki/Installation), and follow its +[Preprocessing](https://github.com/kundajelab/chrombpnet/wiki/Preprocessing), +[Bias model training](https://github.com/kundajelab/chrombpnet/wiki/Bias-model-training), and +[ChromBPNet training](https://github.com/kundajelab/chrombpnet/wiki/ChromBPNet-training) pages. +**The tutorial fragments are aligned to hg19, so every reference below is hg19**, whereas the +ChromBPNet tutorial uses hg38. + +```{bash eval=FALSE} +DATA=~/.cache/marchr_hematopoiesis/chrombpnet_tutorial +mkdir -p $DATA/downloads + +wget https://hgdownload.soe.ucsc.edu/goldenPath/hg19/bigZips/hg19.fa.gz -O $DATA/downloads/hg19.fa.gz +gunzip $DATA/downloads/hg19.fa.gz +``` + +ChromBPNet reads 2,114 bp of sequence around each summit, so peaks must also stay clear of the +blacklist "extended by 1057 bp on both sides": + +```{bash eval=FALSE} +bedtools slop -i $DATA/blacklist.bed -g $DATA/chrom.sizes -b 1057 > $DATA/blacklist_slop1057.bed + +mkdir -p $DATA/peaks_no_blacklist +for peaks in $DATA/peaks/*.narrowPeak; do + bedtools intersect -v -a $peaks -b $DATA/blacklist_slop1057.bed \ + > $DATA/peaks_no_blacklist/$(basename $peaks) +done +``` + +Split chromosomes into training, validation, and test sets. +This is fold 0 of the standard ENCODE folds used by the ChromBPNet tutorial: + +```{bash eval=FALSE} +mkdir -p $DATA/splits +chrombpnet prep splits -c $DATA/chrom.sizes -tcr chr1 chr3 chr6 -vcr chr8 chr20 \ + -op $DATA/splits/fold_0 +``` + +Generate GC-matched background regions for each cluster. +Each run writes `nonpeaks//output_negatives.bed`: + +```{bash eval=FALSE} +for peaks in $DATA/peaks_no_blacklist/*.narrowPeak; do + group=$(basename $peaks .narrowPeak) + mkdir -p $DATA/nonpeaks/$group + chrombpnet prep nonpeaks \ + -g $DATA/downloads/hg19.fa \ + -p $peaks \ + -c $DATA/chrom.sizes \ + -fl $DATA/splits/fold_0.json \ + -br $DATA/blacklist.bed \ + -o $DATA/nonpeaks/$group/output +done +``` + +## Choosing a Bias Model + +The bias model captures Tn5 sequence preference so the main model can learn TF activity apart from it. +There are two options. + +**Pre-trained.** +ChromBPNet's [FAQ](https://github.com/kundajelab/chrombpnet/wiki/FAQ) advises picking +"a pre-trained bias model that is similar in experimental setting to the current dataset". +The ChromBPNet tutorial's ATAC bias model is: + +```{bash eval=FALSE} +mkdir -p $DATA/bias_model +wget https://storage.googleapis.com/chrombpnet_data/input_files/bias_models/ATAC/ENCSR868FGK_bias_fold_0.h5 \ + -O $DATA/bias_model/ENCSR868FGK_bias_fold_0.h5 +BIAS=$DATA/bias_model/ENCSR868FGK_bias_fold_0.h5 +``` + +**Trained on one cluster.** +Train a single bias model on a deep cluster and reuse it for every cluster, as the +[HDMA atlas](https://github.com/GreenleafLab/HDMA/tree/main/code/03-chrombpnet) does. +`-b` is the bias threshold factor, for which ChromBPNet recommends starting at 0.5 for ATAC. + +```{bash eval=FALSE} +BIAS_GROUP=C8 +mkdir -p $DATA/bias_model/$BIAS_GROUP +chrombpnet bias pipeline \ + -ifrag $DATA/fragments/$BIAS_GROUP.tsv.gz \ + -d "ATAC" \ + -g $DATA/downloads/hg19.fa \ + -c $DATA/chrom.sizes \ + -p $DATA/peaks_no_blacklist/$BIAS_GROUP.narrowPeak \ + -n $DATA/nonpeaks/$BIAS_GROUP/output_negatives.bed \ + -fl $DATA/splits/fold_0.json \ + -b 0.5 \ + -o $DATA/bias_model/$BIAS_GROUP/ +BIAS=$DATA/bias_model/$BIAS_GROUP/models/bias.h5 +``` + +Read `evaluation/overall_report.html` before using a trained bias model. +It should learn the expected Tn5 bias motif and no TF motifs; the FAQ explains how to tune `-b` when +it does not. + +## Training ChromBPNet per Cluster + +Train one bias-factorized model per cluster. +Each run is a GPU job, so on a cluster submit one job per cluster instead of running the loop as +written. + +```{bash eval=FALSE} +for frag in $DATA/fragments/*.tsv.gz; do + group=$(basename $frag .tsv.gz) + mkdir -p $DATA/chrombpnet_model/$group + chrombpnet pipeline \ + -ifrag $frag \ + -d "ATAC" \ + -g $DATA/downloads/hg19.fa \ + -c $DATA/chrom.sizes \ + -p $DATA/peaks_no_blacklist/$group.narrowPeak \ + -n $DATA/nonpeaks/$group/output_negatives.bed \ + -fl $DATA/splits/fold_0.json \ + -b $BIAS \ + -o $DATA/chrombpnet_model/$group/ +done +``` + +Each model's `evaluation/overall_report.html` is its quality check. +The bias-corrected model, `models/chrombpnet_nobias.h5`, should learn the expected TF motifs and no +enzyme bias. +For production models, the FAQ recommends training all five folds and averaging the predictions and +contribution scores across them. + +## Optional: Coverage Tracks + +ChromBPNet builds its own signal tracks from the fragment files, so no coverage file is needed for +training. +To view observed signal next to model predictions in a genome browser, MarchR can write per-cluster +insertion coverage in a single pass over the fragments: + +```{r eval=FALSE} +pb <- write_pseudobulk_coverage(pb, export_dir) +pb <- write_pseudobulk_bigwig(pb, export_dir, get_chrom_sizes(proj)) +``` diff --git a/vignettes/marchr_chrombpnet.html b/vignettes/marchr_chrombpnet.html new file mode 100644 index 0000000..80fd080 --- /dev/null +++ b/vignettes/marchr_chrombpnet.html @@ -0,0 +1,2000 @@ + + + + + + + + + + + + + + +Exporting Pseudobulks for ChromBPNet with MarchR (WIP) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +
+
+
+
+
+ +
+ + + + + + + + +
+

Introduction

+

ChromBPNet learns base-resolution chromatin accessibility from DNA sequence while factoring out Tn5 sequence bias. It trains one model per pseudobulk, and for single-cell data it is suggested to aggregate the fragments by cluster instead of sample to train cluster-specific ChromBPNet models.

+

This tutorial provides instructions to setup your single-cell ATAC datasets from your MarchRProject directly for ChromBPNet model training. It continues from the end of the MarchR Hematopoiesis tutorial and exports the files that the ChromBPNet pipeline reads. We highly recommend you read the ChromBPNet Wiki prior to starting this tutorial.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ChromBPNet inputFlagSource
Fragments per cluster-ifragwrite_pseudobulk_fragments()
Peaks per cluster (10-column narrowPeak)-pwrite_pseudobulk_peaks()
Chromosome sizes-cwrite_pseudobulk_chrom_sizes()
Blacklist-br (prep nonpeaks)get_blacklist()
Reference genome FASTA-gDownloaded
Train / validation / test chromosome folds-flchrombpnet prep splits
GC-matched background regions-nchrombpnet prep nonpeaks
Bias model-bPre-trained, or chrombpnet bias pipeline
+

The last three come from ChromBPNet’s own tools, so they always match the ChromBPNet release you train with. Training needs a GPU and is not run in this tutorial; the shell commands are shown for reference.

+
+
+

Setup

+

Load MarchR and set the session thread count.

+
library(MarchR)
+set_threads(4)
+

The Hematopoiesis tutorial saved its project to cache_dir. The export is written next to it, in export_dir.

+
cache_dir <- path.expand("~/.cache/marchr_hematopoiesis")
+export_dir <- file.path(cache_dir, "chrombpnet_tutorial")
+proj <- load_project(file.path(cache_dir, "saved_project"))
+proj
+
Output
## MarchRProject Object
+## Directory: /home/eric1126/.cache/marchr_hematopoiesis/saved_project
+## 3 Datasets:
+##   scATAC_BMMC_R1:
+##     4696 cells: scATAC_BMMC_R1#TAGGAGGGTTAACCGT-1, scATAC_BMMC_R1#CCTTGGTAGTTCTCCC-1, scATAC_BMMC_R1#GCCAGCAGTTCTGAGT-1, scATAC_BMMC_R1#TAGCATGGTGACCAGA-1 ... scATAC_BMMC_R1#GTGGATTCATCACAGT-1
+##     Assays: TileMatrix, GeneScoreMatrix, IterativeLSI
+##     Fragments: ATAC
+##     Cell metadata: 3 features (atac_clusters, UMAP_1, UMAP_2)
+##   scATAC_CD34_BMMC_R1:
+##     3173 cells: scATAC_CD34_BMMC_R1#ATTTGTCTCAATCGTG-1, scATAC_CD34_BMMC_R1#CACATGAGTGATAAGT-1, scATAC_CD34_BMMC_R1#GCATTCCTCGTTGTTT-1, scATAC_CD34_BMMC_R1#TGCTTTAGTAACAATG-1 ... scATAC_CD34_BMMC_R1#AACGAGGTCTGAAAGA-1
+##     Assays: TileMatrix, GeneScoreMatrix, IterativeLSI
+##     Fragments: ATAC
+##     Cell metadata: 3 features (atac_clusters, UMAP_1, UMAP_2)
+##   scATAC_PBMC_R1:
+##     2402 cells: scATAC_PBMC_R1#CAGGGCTTCTTTCGAT-1, scATAC_PBMC_R1#GATGATCCACGTTACA-1, scATAC_PBMC_R1#TTTGCGCTCTATCTAC-1, scATAC_PBMC_R1#ATGTACGAGTATGCTC-1 ... scATAC_PBMC_R1#TTCGGTCTCATTCGGA-1
+##     Assays: TileMatrix, GeneScoreMatrix, IterativeLSI
+##     Fragments: ATAC
+##     Cell metadata: 3 features (atac_clusters, UMAP_1, UMAP_2)
+## All datasets aligned.
+## Assays:
+##   TileMatrix: 
+##     6072620 features
+##   GeneScoreMatrix: 
+##     20561 features
+##   IterativeLSI: 
+##     29 features
+## Genome object: 
+##   Chromosomes: 
+##     chr1, chr2 ... chr21
+##   Annotation names: 
+##     transcripts, genes ... blacklist
+##   Sequence: 
+##     BSgenome.Hsapiens.UCSC.hg19
+## DimReductions: IterativeLSI
+## Impute Weights: 2 blocks (embedding = IterativeLSI)
+
+
+
+

Calling Peaks per Cluster

+

ChromBPNet trains each cluster’s model on that cluster’s own peaks. add_group_coverages() builds pseudobulk replicates for each cluster, and add_reproducible_peak_set() calls peaks on them with MACS3. It stores the merged peak set in proj$peak_set and each cluster’s reproducible peaks in proj$group_peak_sets, which is what gets exported below.

+

ChromBPNet recommends relaxed peak calls (“MACS2 with p-value parameter threshold set to 0.01”), so -p 0.01 is appended to the default MACS arguments.

+
proj <- add_group_coverages(proj, group_by = "atac_clusters")
+
proj <- add_reproducible_peak_set(
+  proj,
+  group_by = "atac_clusters",
+  additional_params = paste(
+    "--call-summits --keep-dup all --shift -75 --extsize 150 --nomodel --nolambda",
+    "-p 0.01"
+  )
+)
+
Output
## Creating pseudobulk replicates for 11 groups
+##   Group 'C8': 2546 cells -> 2 replicates (500, 500 cells each)
+##   Group 'C4': 434 cells -> 2 replicates (255, 173 cells each)
+##   Group 'C2': 1352 cells -> 2 replicates (500, 67 cells each)
+##   Group 'C6': 378 cells -> 2 replicates (189, 189 cells each)
+##   Group 'C5': 322 cells -> 2 replicates (168, 145 cells each)
+##   Group 'C10': 1188 cells -> 2 replicates (500, 343 cells each)
+##   Group 'C1': 862 cells -> 2 replicates (500, 279 cells each)
+##   Group 'C9': 876 cells -> 2 replicates (500, 201 cells each)
+##   Group 'C3': 574 cells -> 2 replicates (500, 48 cells each)
+##   Group 'C7': 446 cells -> 2 replicates (358, 88 cells each)
+##   Group 'C11': 1293 cells -> 2 replicates (500, 143 cells each)
+## Calling peaks per replicate...
+##   C8_Rep1: 500 cells
+##   C8_Rep2: 500 cells
+##   C4_Rep1: 255 cells
+##   C4_Rep2: 173 cells
+##   C2_Rep1: 500 cells
+##   C2_Rep2: 67 cells
+##   C6_Rep1: 189 cells
+##   C6_Rep2: 189 cells
+##   C5_Rep1: 168 cells
+##   C5_Rep2: 145 cells
+##   C10_Rep1: 500 cells
+##   C10_Rep2: 343 cells
+##   C1_Rep1: 500 cells
+##   C1_Rep2: 279 cells
+##   C9_Rep1: 500 cells
+##   C9_Rep2: 201 cells
+##   C3_Rep1: 500 cells
+##   C3_Rep2: 48 cells
+##   C7_Rep1: 358 cells
+##   C7_Rep2: 88 cells
+##   C11_Rep1: 500 cells
+##   C11_Rep2: 143 cells
+## Filtering for reproducible peaks...
+##   Group 'C8': 72869 reproducible peaks (from 2 replicates)
+##   Group 'C4': 86125 reproducible peaks (from 2 replicates)
+##   Group 'C2': 57013 reproducible peaks (from 2 replicates)
+##   Group 'C6': 95956 reproducible peaks (from 2 replicates)
+##   Group 'C5': 95402 reproducible peaks (from 2 replicates)
+##   Group 'C10': 99365 reproducible peaks (from 2 replicates)
+##   Group 'C1': 77834 reproducible peaks (from 2 replicates)
+##   Group 'C9': 91391 reproducible peaks (from 2 replicates)
+##   Group 'C3': 38690 reproducible peaks (from 2 replicates)
+##   Group 'C7': 70884 reproducible peaks (from 2 replicates)
+##   Group 'C11': 70714 reproducible peaks (from 2 replicates)
+## Final peak set: 306316 peaks
+##   Distal: 114959
+##   Intronic: 164432
+##   Promoter: 26925
+
+
+
+

Grouping Fragments by Cluster

+

Each of the atac_clusters from the Hematopoiesis tutorial becomes one pseudobulk, one fragment file, and one ChromBPNet model.

+
plot_embedding(proj, col_name = "atac_clusters", title = "UMAP - Clusters")
+

+

pseudobulk_fragments() groups cells by a metadata column and returns one lazy fragment set per group. Fragments are pooled across the three datasets and pass through the same blacklist and chromosome filters as peak calling, so the exported fragments and peaks cover the same regions.

+
pb <- pseudobulk_fragments(proj, group_by = "atac_clusters")
+pb
+
Output
## MarchRPseudobulk: 11 groups (by atac_clusters)
+## # A tibble: 11 × 5
+##    group n_cells n_fragments median_tss_enrichment passed_depth_gate
+##    <chr>   <int>       <dbl>                 <dbl> <lgl>            
+##  1 C8       2546     8770439                  16.3 NA               
+##  2 C4        434     1379563                  19.2 NA               
+##  3 C2       1352     3081804                  19.5 NA               
+##  4 C6        378     1264174                  15.8 NA               
+##  5 C5        322     1213031                  14.5 NA               
+##  6 C10      1188     5179436                  14.5 NA               
+##  7 C1        862     4411933                  20.7 NA               
+##  8 C9        876     3102157                  16.7 NA               
+##  9 C3        574     2762631                  22.4 NA               
+## 10 C7        446     1508948                  16.9 NA               
+## 11 C11      1293     4509833                  17.7 NA
+
+

The manifest reports cells, fragments, and median TSS enrichment for each cluster. Each ChromBPNet model learns its own count scale, so clusters do not need matched depth. To leave shallow clusters out of the export, set min_fragments with on_low_depth = "drop". ChromBPNet does not publish a minimum depth, so pick the floor for your own data.

+
+
+

Writing Fragment Files

+

write_pseudobulk_fragments() writes one gzipped, 10x-style fragment file per cluster to export_dir/fragments/. These are the -ifrag inputs.

+
pb <- write_pseudobulk_fragments(pb, export_dir)
+
Output
##   Writing fragments for group 'C8'
+##   Writing fragments for group 'C4'
+##   Writing fragments for group 'C2'
+##   Writing fragments for group 'C6'
+##   Writing fragments for group 'C5'
+##   Writing fragments for group 'C10'
+##   Writing fragments for group 'C1'
+##   Writing fragments for group 'C9'
+##   Writing fragments for group 'C3'
+##   Writing fragments for group 'C7'
+##   Writing fragments for group 'C11'
+
+
read.delim(pb$manifest$fragments_path[[1]], header = FALSE, nrows = 5)
+
Output
##     V1     V2     V3                                V4
+## 1 chr1 750947 751028 scATAC_PBMC_R1#GCGCATGTCTCTCAAT-1
+## 2 chr1 750989 751069 scATAC_BMMC_R1#AATGGCTTCTTGTGCC-1
+## 3 chr1 751650 751736 scATAC_PBMC_R1#CAAGCTAAGTGCCCTG-1
+## 4 chr1 751658 751726 scATAC_BMMC_R1#TTCTGTAGTAATGTAG-1
+## 5 chr1 751663 751804 scATAC_PBMC_R1#CATAACGTCGAGCGCT-1
+
+

The columns are chromosome, start, end, and cell barcode. ChromBPNet reads only the first three: its fragment reader expects “tsv with columns chr, start, end and optionally more columns”, so Cell Ranger’s fifth duplicate-count column is not needed. Coordinates are written unshifted, because ChromBPNet estimates and corrects the Tn5 shift itself; its guide notes that “you do not need to worry about pre-shifting the fragments”.

+

ArchR’s getGroupFragments() writes the same four columns. One difference is that MarchR has already removed fragments in blacklisted regions and on chrM.

+
+
+

Writing Peaks

+

write_pseudobulk_peaks() writes each cluster’s peaks to export_dir/peaks/. scope = "group" skips the merged peak set; the default, "both", also writes it as union.narrowPeak.

+
pb <- write_pseudobulk_peaks(pb, export_dir, scope = "group")
+
read.delim(pb$manifest$peaks_path[[1]], header = FALSE, nrows = 5)
+
Output
##   Writing peaks for group 'C8'
+##   Writing peaks for group 'C4'
+##   Writing peaks for group 'C2'
+##   Writing peaks for group 'C6'
+##   Writing peaks for group 'C5'
+##   Writing peaks for group 'C10'
+##   Writing peaks for group 'C1'
+##   Writing peaks for group 'C9'
+##   Writing peaks for group 'C3'
+##   Writing peaks for group 'C7'
+##   Writing peaks for group 'C11'
+##      V1        V2        V3   V4   V5 V6      V7      V8 V9 V10
+## 1 chr14  77234591  77235092 C8_1 1000  . 314.012 314.012 -1 250
+## 2  chr2  64977998  64978499 C8_2 1000  . 211.867 211.867 -1 250
+## 3  chr7  36192419  36192920 C8_3 1000  . 211.867 211.867 -1 250
+## 4  chr8 103251243 103251744 C8_4 1000  . 293.821 293.821 -1 250
+## 5 chr19  42579873  42580374 C8_5 1000  . 285.221 285.221 -1 250
+
+

ChromBPNet’s -p takes a “10 column bed file of peaks” and centers each training window at start (column 2) plus summit (column 10). MarchR peaks are 501 bp wide around the MACS summit, and column 10 holds the stored summit offset.

+

plot_browser_track() shows the signal each cluster’s model will learn. At the CD14 locus, nearby gene promoters are open in every cluster, while several distal peaks are open mainly in C8, so each cluster’s model trains on a different accessibility profile. The peaks track shows the merged peak set.

+
region <- gene_region(
+  get_gene_annotations(proj, "genes"),
+  gene_symbol = "CD14",
+  upstream = 50000L,
+  downstream = 50000L
+)
+
+plot_browser_track(
+  proj,
+  region = region,
+  group_by = "atac_clusters",
+  frags_name = "ATAC",
+  tracks = c("coverage", "peaks", "gene"),
+  bins = 400L,
+  norm_method = "ReadsInTSS",
+  title = "CD14"
+)
+

+
+
+

Chromosome Sizes and Blacklist

+

chrombpnet prep splits assigns every chromosome in the chromosome sizes file to a fold, so the file should list only the chromosomes to train on. This project’s chromosome sizes already cover just chr1-22, chrX, and chrY, the same set the ChromBPNet tutorial uses.

+
pb <- write_pseudobulk_chrom_sizes(pb, export_dir, get_chrom_sizes(proj))
+readLines(pb$params$chrom_sizes_path, n = 3)
+
Output
## [1] "chr1\t249250621" "chr2\t243199373" "chr3\t198022430"
+
+

ChromBPNet uses the blacklist twice: to filter peaks and to keep background regions out of blacklisted sequence. Writing the project’s own blacklist keeps it consistent with the fragment filtering above.

+
blacklist <- get_blacklist(proj)
+write.table(
+  blacklist[, c("chr", "start", "end")],
+  file.path(export_dir, "blacklist.bed"),
+  sep = "\t", quote = FALSE, row.names = FALSE, col.names = FALSE
+)
+
+
+

Writing the Manifest

+

write_pseudobulk_manifest() writes manifest.tsv, which works as a samplesheet for workflow managers, and manifest.json, which also records the export parameters and package versions. Each writer above added its file paths to the manifest as a new column.

+
write_pseudobulk_manifest(pb, export_dir)
+colnames(pb$manifest)
+
Output
## [1] "group"                 "n_cells"               "n_fragments"          
+## [4] "median_tss_enrichment" "passed_depth_gate"     "fragments_path"       
+## [7] "peaks_path"
+
+
list.files(export_dir, recursive = TRUE)
+
Output
##  [1] "blacklist.bed"        "chrom.sizes"          "fragments/C1.tsv.gz" 
+##  [4] "fragments/C10.tsv.gz" "fragments/C11.tsv.gz" "fragments/C2.tsv.gz" 
+##  [7] "fragments/C3.tsv.gz"  "fragments/C4.tsv.gz"  "fragments/C5.tsv.gz" 
+## [10] "fragments/C6.tsv.gz"  "fragments/C7.tsv.gz"  "fragments/C8.tsv.gz" 
+## [13] "fragments/C9.tsv.gz"  "manifest.json"        "manifest.tsv"        
+## [16] "peaks/C1.narrowPeak"  "peaks/C10.narrowPeak" "peaks/C11.narrowPeak"
+## [19] "peaks/C2.narrowPeak"  "peaks/C3.narrowPeak"  "peaks/C4.narrowPeak" 
+## [22] "peaks/C5.narrowPeak"  "peaks/C6.narrowPeak"  "peaks/C7.narrowPeak" 
+## [25] "peaks/C8.narrowPeak"  "peaks/C9.narrowPeak"
+
+

If you train your own bias model (below), use a deep cluster so the model sees as many background reads as possible. The deepest cluster here is:

+
pb$manifest$group[which.max(pb$manifest$n_fragments)]
+
Output
## [1] "C8"
+
+
+
+

Preparing ChromBPNet Inputs

+

The remaining steps run in a shell where ChromBPNet is installed, and follow its Preprocessing, Bias model training, and ChromBPNet training pages. The tutorial fragments are aligned to hg19, so every reference below is hg19, whereas the ChromBPNet tutorial uses hg38.

+
DATA=~/.cache/marchr_hematopoiesis/chrombpnet_tutorial
+mkdir -p $DATA/downloads
+
+wget https://hgdownload.soe.ucsc.edu/goldenPath/hg19/bigZips/hg19.fa.gz -O $DATA/downloads/hg19.fa.gz
+gunzip $DATA/downloads/hg19.fa.gz
+

ChromBPNet reads 2,114 bp of sequence around each summit, so peaks must also stay clear of the blacklist “extended by 1057 bp on both sides”:

+
bedtools slop -i $DATA/blacklist.bed -g $DATA/chrom.sizes -b 1057 > $DATA/blacklist_slop1057.bed
+
+mkdir -p $DATA/peaks_no_blacklist
+for peaks in $DATA/peaks/*.narrowPeak; do
+  bedtools intersect -v -a $peaks -b $DATA/blacklist_slop1057.bed \
+    > $DATA/peaks_no_blacklist/$(basename $peaks)
+done
+

Split chromosomes into training, validation, and test sets. This is fold 0 of the standard ENCODE folds used by the ChromBPNet tutorial:

+
mkdir -p $DATA/splits
+chrombpnet prep splits -c $DATA/chrom.sizes -tcr chr1 chr3 chr6 -vcr chr8 chr20 \
+  -op $DATA/splits/fold_0
+

Generate GC-matched background regions for each cluster. Each run writes nonpeaks/<cluster>/output_negatives.bed:

+
for peaks in $DATA/peaks_no_blacklist/*.narrowPeak; do
+  group=$(basename $peaks .narrowPeak)
+  mkdir -p $DATA/nonpeaks/$group
+  chrombpnet prep nonpeaks \
+    -g $DATA/downloads/hg19.fa \
+    -p $peaks \
+    -c $DATA/chrom.sizes \
+    -fl $DATA/splits/fold_0.json \
+    -br $DATA/blacklist.bed \
+    -o $DATA/nonpeaks/$group/output
+done
+
+
+

Choosing a Bias Model

+

The bias model captures Tn5 sequence preference so the main model can learn TF activity apart from it. There are two options.

+

Pre-trained. ChromBPNet’s FAQ advises picking “a pre-trained bias model that is similar in experimental setting to the current dataset”. The ChromBPNet tutorial’s ATAC bias model is:

+
mkdir -p $DATA/bias_model
+wget https://storage.googleapis.com/chrombpnet_data/input_files/bias_models/ATAC/ENCSR868FGK_bias_fold_0.h5 \
+  -O $DATA/bias_model/ENCSR868FGK_bias_fold_0.h5
+BIAS=$DATA/bias_model/ENCSR868FGK_bias_fold_0.h5
+

Trained on one cluster. Train a single bias model on a deep cluster and reuse it for every cluster, as the HDMA atlas does. -b is the bias threshold factor, for which ChromBPNet recommends starting at 0.5 for ATAC.

+
BIAS_GROUP=C8
+mkdir -p $DATA/bias_model/$BIAS_GROUP
+chrombpnet bias pipeline \
+  -ifrag $DATA/fragments/$BIAS_GROUP.tsv.gz \
+  -d "ATAC" \
+  -g $DATA/downloads/hg19.fa \
+  -c $DATA/chrom.sizes \
+  -p $DATA/peaks_no_blacklist/$BIAS_GROUP.narrowPeak \
+  -n $DATA/nonpeaks/$BIAS_GROUP/output_negatives.bed \
+  -fl $DATA/splits/fold_0.json \
+  -b 0.5 \
+  -o $DATA/bias_model/$BIAS_GROUP/
+BIAS=$DATA/bias_model/$BIAS_GROUP/models/bias.h5
+

Read evaluation/overall_report.html before using a trained bias model. It should learn the expected Tn5 bias motif and no TF motifs; the FAQ explains how to tune -b when it does not.

+
+
+

Training ChromBPNet per Cluster

+

Train one bias-factorized model per cluster. Each run is a GPU job, so on a cluster submit one job per cluster instead of running the loop as written.

+
for frag in $DATA/fragments/*.tsv.gz; do
+  group=$(basename $frag .tsv.gz)
+  mkdir -p $DATA/chrombpnet_model/$group
+  chrombpnet pipeline \
+    -ifrag $frag \
+    -d "ATAC" \
+    -g $DATA/downloads/hg19.fa \
+    -c $DATA/chrom.sizes \
+    -p $DATA/peaks_no_blacklist/$group.narrowPeak \
+    -n $DATA/nonpeaks/$group/output_negatives.bed \
+    -fl $DATA/splits/fold_0.json \
+    -b $BIAS \
+    -o $DATA/chrombpnet_model/$group/
+done
+

Each model’s evaluation/overall_report.html is its quality check. The bias-corrected model, models/chrombpnet_nobias.h5, should learn the expected TF motifs and no enzyme bias. For production models, the FAQ recommends training all five folds and averaging the predictions and contribution scores across them.

+
+
+

Optional: Coverage Tracks

+

ChromBPNet builds its own signal tracks from the fragment files, so no coverage file is needed for training. To view observed signal next to model predictions in a genome browser, MarchR can write per-cluster insertion coverage in a single pass over the fragments:

+
pb <- write_pseudobulk_coverage(pb, export_dir)
+pb <- write_pseudobulk_bigwig(pb, export_dir, get_chrom_sizes(proj))
+
+ + + +
+
+ +
+ + + + + + + + + + + + + + + +