--- title: "Getting started with BamScaleR" author: "Chirag Parsania" output: BiocStyle::html_document: toc: true vignette: > %\VignetteIndexEntry{Getting started with BamScaleR} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include=FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` # Introduction `BamScaleR` provides multithreaded sequential BAM traversal for R/Bioconductor workflows. The package is designed for users who already rely on `Rsamtools`, `GenomicAlignments`, and `BiocParallel`, but need faster BAM parsing without moving to a separate non-Bioconductor workflow model. The package targets four common classes of BAM access: - metadata-oriented scans for filtering, fragment summaries, and quality control - generation of alignment objects for downstream `GenomicAlignments` workflows - sequence and quality extraction, including an optimized compact mode - summaries computed inside the multithreaded reader (fragment-size and mapping-quality distributions, per-base coverage, bigWig tracks), so that no per-read R objects are created at all The motivation for inclusion in Bioconductor is therefore straightforward: `BamScaleR` accelerates a core data-access bottleneck while preserving familiar Bioconductor inputs and output types. `BamScaleR` is built on the `ompBAM` C++ library, which supplies parallel BAM decompression. The section [BamScaleR and ompBAM](#bamscaler-and-ompbam) below explains what each package provides. # Installation ```r if (!requireNamespace("BiocManager", quietly = TRUE)) { install.packages("BiocManager") } BiocManager::install("BamScaleR") ``` ## Multithreading and OpenMP `BamScaleR` reads each BAM with several threads (the `threads` argument) using OpenMP. OpenMP is optional. Without it, every function works and returns the same results, but each BAM is read on a single thread. Processing several files in parallel through `BPPARAM` (see below) is unaffected. If `threads` greater than 1 is requested on a build without OpenMP, `BamScaleR` warns once per session. - **Linux and Windows.** The standard R toolchains (GCC, and Rtools on Windows) support OpenMP. Nothing extra is needed. - **macOS.** Apple's `clang` can compile OpenMP code, but Apple does not ship the OpenMP header (`omp.h`) or runtime library (`libomp`). CRAN's R for macOS ships a `libomp` in `R.home("lib")`, but no header. When `BamScaleR` is installed from source, its `configure` script tries several compiler and linker settings. For each one it builds a small OpenMP test library and loads it into R, and it uses the first setting that loads. With CRAN's R, the runtime that gets linked is always R's own `libomp`, so only one OpenMP runtime is loaded into the R session. The chosen flags are printed in the installation log. If no setting works, the package is built without OpenMP and the log says why. (If your own compiler flags switch OpenMP on for every package, for example `CPPFLAGS += -Xclang -fopenmp` in `~/.R/Makevars`, a build without OpenMP is not possible; `configure` then stops and says so.) To enable multithreading on macOS, install the OpenMP files that match your Xcode version from . Check the Apple clang version with `clang --version` in a terminal. For example, for Xcode 16.0 to 16.2 (Apple clang 1600): ```sh curl -O https://mac.r-project.org/openmp/openmp-17.0.6-darwin20-Release.tar.gz sudo tar fvxz openmp-17.0.6-darwin20-Release.tar.gz -C / ``` Use `openmp-16.0.4-darwin20-Release.tar.gz` for Xcode 15 (Apple clang 1500), or `openmp-19.1.5-darwin20-Release.tar.gz` for Xcode 16.3 or later (Apple clang 1700). The tarball installs `omp.h` under `/usr/local/include` and `libomp.dylib` under `/usr/local/lib`. A Homebrew installation (`brew install libomp`) is also detected. Then reinstall `BamScaleR` from source. A plain `BiocManager::install()` would skip a package that is already installed, or install the same binary again, so ask for a source build explicitly (this needs the Xcode Command Line Tools): ```r BiocManager::install("BamScaleR", type = "source", force = TRUE) ``` In a source checkout, rebuild with `R CMD INSTALL --preclean .` or `devtools::load_all(recompile = TRUE)`, so that objects compiled without OpenMP are not reused. Apple clang 1700 (Xcode 16.3 and later) needs an OpenMP runtime from LLVM 19 or later. If the `libomp` bundled with your R is older, `configure` rejects it, the package is built without OpenMP, and the installation log explains why. To bypass the detection, set both flags yourself before installing, for example: ```r Sys.setenv( BAMSCALER_OPENMP_CXXFLAGS = "-Xclang -fopenmp", BAMSCALER_OPENMP_LIBS = "-lomp" ) BiocManager::install("BamScaleR", type = "source", force = TRUE) ``` Setting both variables to `""` builds without OpenMP. # Basic usage ```{r load-example-bam} library(BamScaleR) bam <- ompBAM::example_BAM("Unsorted") ``` The example file shipped with `ompBAM` is a small paired-end RNA-seq BAM (10,000 alignments to the human genome, aligned with STAR). ## Metadata-oriented BAM access The most common BAM-access pattern is extraction of alignment metadata such as read name, flag, reference name, position, mapping quality, and CIGAR string. ```{r metadata-access} x <- bam_read( file = bam, what = c("qname", "flag", "rname", "pos", "mapq", "cigar"), as = "data.frame", threads = 2 ) head(x) ``` ## Filtering with `ScanBamParam` `BamScaleR` accepts `Rsamtools::ScanBamParam`, allowing existing filtering logic to be reused directly. ```{r scanbamparam-filtering} param <- Rsamtools::ScanBamParam( what = c("qname", "flag", "mapq"), mapqFilter = 20L, flag = Rsamtools::scanBamFlag(isUnmappedQuery = FALSE) ) filtered <- bam_read( file = bam, param = param, as = "data.frame", threads = 2 ) head(filtered) ``` ## Alignment-object output When downstream workflows expect `GenomicAlignments` objects, `bam_read()` can return those directly. ```{r galignments-output} ga <- bam_read( file = bam, what = c("qname", "flag", "rname", "pos", "cigar", "strand"), as = "GAlignments", threads = 2 ) ga ``` ## Sequence and quality extraction For `seq` and `qual`, `BamScaleR` supports both a compatibility-preserving mode and an optimized compact mode. The compatible mode (the default) returns the sequences and qualities as `Biostrings::DNAStringSet` and `Biostrings::PhredQuality` objects, identical to those from `Rsamtools::scanBam()`. A `DataFrame` holds such columns naturally; a base `data.frame` can carry them, but cannot print them. ```{r seqqual-compatible} seqqual_compatible <- bam_read( file = bam, what = c("qname", "seq", "qual"), as = "DataFrame", seqqual_mode = "compatible", threads = 2 ) seqqual_compatible ``` Compact mode returns lower-level raw vectors for throughput-oriented workflows. These values can be decoded back to ordinary strings explicitly when needed. ```{r seqqual-compact} seqqual_compact <- bam_read( file = bam, what = c("qname", "qwidth", "seq", "qual"), as = "data.frame", seqqual_mode = "compact", threads = 2 ) head(seqqual_compact) seqqual_decoded <- decode_seqqual_compact(seqqual_compact) head(seqqual_decoded) ``` ## Fast count summaries `bam_count()` provides chromosome-level count summaries using the same BAM filtering model. ```{r bam-count-example} counts <- bam_count(bam, threads = 2) counts ``` # Summaries computed inside the reader Many analyses do not need the alignments themselves, only a summary of them: a fragment-size distribution for ATAC-seq or ChIP-seq quality control, a mapping-quality profile, or per-base coverage for a genome-browser track. The usual route reads every alignment into R first and then summarises it. The four functions in this section instead compute the summary inside the multithreaded reader. Each thread keeps its own running totals while it decodes its share of the file, and only the finished summary is returned to R. The checks below compare each result with the standard Bioconductor route. All four functions accept a `ScanBamParam`, of which the `flag` and `mapqFilter` settings are applied to each read. (They cannot restrict the summary to regions, so setting `which` gives a warning.) The following filter (mapped, primary, passing QC) is the usual one for fragment-size QC: ```{r qc-param} qc_flag <- Rsamtools::scanBamFlag( isUnmappedQuery = FALSE, isSecondaryAlignment = FALSE, isNotPassingQualityControls = FALSE ) qc_param <- Rsamtools::ScanBamParam(flag = qc_flag) ``` ## Fragment-size distribution: `fragment_sizes()` `fragment_sizes()` tabulates the absolute template length (`abs(TLEN)`, the `isize` field in `Rsamtools`) of every read that passes the filter. It returns a `data.frame` with one row per observed fragment size, in increasing order, and the number of reads with that size. Reads that are unmapped, or whose mate is unmapped, have no defined fragment size and are excluded by default (`drop_mate_unmapped = TRUE`), just as `scanBam()` reports `NA` for them. ```{r fragment-sizes} fs <- fragment_sizes(bam, param = qc_param, threads = 2) str(fs) ## the most common fragment size fs[which.max(fs$count), ] ``` ```{r fragment-sizes-plot, fig.width = 6, fig.height = 3.5, fig.cap = "Fragment-size distribution of the example BAM (fragments up to 1 kb)."} short <- fs[fs$fragment_size <= 1000, ] plot(short$fragment_size, short$count, type = "h", xlab = "Fragment size (bp)", ylab = "Reads") ``` The same table computed the standard way, by reading every `isize` into R and tabulating it, is identical: ```{r fragment-sizes-check} isize <- Rsamtools::scanBam( bam, param = Rsamtools::ScanBamParam(what = "isize", flag = qc_flag) )[[1]]$isize tab <- table(abs(isize)) ref <- data.frame(fragment_size = as.integer(names(tab)), count = as.numeric(tab)) identical(fs, ref) ``` ## Mapping-quality distribution: `mapq_dist()` `mapq_dist()` returns the number of reads at each mapping quality (MAPQ, 0 to 255) as a `data.frame` with columns `mapq` and `count`. Unmapped reads have no mapping quality (`scanBam()` reports `NA` for them) and are not counted. ```{r mapq-dist} mq <- mapq_dist(bam, param = qc_param, threads = 2) mq ``` It is identical to tabulating the `mapq` values read with `scanBam()`: ```{r mapq-dist-check} mapq <- Rsamtools::scanBam( bam, param = Rsamtools::ScanBamParam(what = "mapq", flag = qc_flag) )[[1]]$mapq tab <- table(mapq) identical(mq, data.frame(mapq = as.integer(names(tab)), count = as.numeric(tab))) ``` The example BAM was aligned with STAR, which gives every uniquely mapped read a MAPQ of 255, so the distribution has a single value. On a BAM from an aligner such as Bowtie 2 or BWA, the table shows the full spread of MAPQ values, and setting `mapqFilter` in `param` removes reads below that value from the distribution. ## Per-base coverage: `bam_coverage()` `bam_coverage()` returns per-base read depth as an `RleList`: one run-length encoded integer vector per sequence in the BAM header, in header order, each as long as the sequence. Sequences with no reads are a single run of zeros. CIGAR operations are counted in the same way as `GenomicAlignments::coverage()`: `M`, `=`, `X` and `D` add depth, `N` (a splice junction) does not, and `I`, `S`, `H` and `P` are ignored. ```{r bam-coverage} cov <- bam_coverage(bam, threads = 2) cov[c("1", "MT")] ``` The result is an ordinary `RleList`, so the usual `IRanges` tools apply, for example per-chromosome summaries or the regions above a depth threshold: ```{r bam-coverage-use} head(data.frame( seqname = names(cov), covered_bp = sum(cov > 0), max_depth = max(cov) )) ## regions of the mitochondrial genome covered by at least 10 reads IRanges::slice(cov[["MT"]], lower = 10) ``` It is identical to the coverage computed from a `GAlignments` object: ```{r bam-coverage-check} ref_cov <- GenomicAlignments::coverage( GenomicAlignments::readGAlignments(bam) ) identical(cov, ref_cov) ``` ## Coverage straight to a bigWig file: `bam_coverage_bigwig()` To make a genome-browser track, `bam_coverage_bigwig()` computes the same coverage and writes it directly to a bigWig file, without creating the coverage `RleList` in R. It returns the path of the file it wrote (invisibly). Only non-zero runs are written, which is the bigWig convention; uncovered bases read back as zero. ```{r bigwig} bw <- tempfile(fileext = ".bw") bam_coverage_bigwig(bam, outfile = bw, threads = 2) file.size(bw) ``` The file can be loaded into a genome browser or read back into R with `rtracklayer`. The values match `bam_coverage()` on every sequence (a bigWig stores them as floating-point numbers, so they are compared as numbers): ```{r bigwig-check, eval = requireNamespace("rtracklayer", quietly = TRUE) && .Platform$OS.type != "windows"} imported <- rtracklayer::import(bw, as = "RleList") all(vapply(names(cov), function(chr) { isTRUE(all.equal(as.numeric(imported[[chr]]), as.numeric(cov[[chr]]))) }, logical(1))) ``` ## Several files at once Every function accepts several BAM files, as a character vector or an `Rsamtools::BamFileList`, and returns a named list with one result per file. Files are processed in parallel according to `BPPARAM`, and `threads` sets the number of threads used within each file. The `BPPARAM` object is used as supplied and is not modified, so it can be reused for other work afterwards. (On Linux, GCC's OpenMP runtime cannot start threads in a forked `MulticoreParam` worker once the R session has used OpenMP threads, and the worker would wait forever. `BamScaleR` releases the runtime's idle threads before each `fork()`, so forked workers use `threads` as requested. This needs libgomp 9 or later; with an older runtime, use `SnowParam()` instead.) ```{r multiple-files} two <- fragment_sizes( c(rep1 = bam, rep2 = bam), param = qc_param, threads = 1, BPPARAM = BiocParallel::SerialParam() ) vapply(two, function(x) sum(x$count), numeric(1)) ``` # Relationship to existing Bioconductor tools `BamScaleR` is intended to complement, not replace, existing Bioconductor packages. - `Rsamtools` remains the canonical low-level BAM access layer in R and defines the filtering idioms that `BamScaleR` reuses through `ScanBamParam`. - `GenomicAlignments` remains the standard package for alignment-centric downstream workflows, and `BamScaleR` supports direct generation of compatible alignment objects. - `BiocParallel` remains the standard mechanism for file-level parallelism, and `BamScaleR` adds a second axis of parallelism through per-file OpenMP threads. The main difference is therefore performance-oriented: `BamScaleR` accelerates the traversal step itself while staying close to existing Bioconductor usage patterns. ## BamScaleR and ompBAM {#bamscaler-and-ompbam} `ompBAM` and `BamScaleR` work at different levels. `ompBAM` is a header-only C++ library for package developers. It opens a BAM file, decompresses its compressed (BGZF) blocks on several OpenMP threads, and gives each thread a share of the raw alignment records, with C++ functions to read the fields of one record (flag, position, CIGAR, tags and so on). It has no R function that reads a BAM file into R; its R functions are helpers for developers, such as `use_ompBAM()` and `example_BAM()`. To do anything with the records, a package must write its own C++ loop over them. `BamScaleR` is that loop, together with what is needed to use its output in Bioconductor workflows: - **R functions with `Rsamtools` semantics.** `bam_read()` takes the `what` fields of `Rsamtools::scanBam()` (except `groupid` and `mate_status`), its `tag` fields and `ScanBamParam` settings (`flag`, `mapqFilter`, `which`), and applies them to each record in C++. (`which` selects the alignments that overlap a range, as in `Rsamtools`; `?bam_read` lists the remaining differences.) `bam_count()` and the summary functions apply the filters listed on their help pages, and warn about settings they cannot apply. - **Bioconductor output objects.** Results from all threads are merged in file order and converted into a `data.frame` or `DataFrame`, a `scanBam()`-style list (with `DNAStringSet` and `PhredQuality` for sequences and qualities), a `GAlignments` or a `GAlignmentPairs` object; the columns and the `GAlignments` slots are built in compiled code. The package tests compare fields, sequences and qualities with `Rsamtools::scanBam()`, and `GAlignments` objects with `readGAlignments()`, using `identical()`. They also check that, without `which`, `GAlignmentPairs` output contains the same pairs as `readGAlignmentPairs()`, including for secondary and supplementary alignments. - **Summaries inside the reader.** Per-chromosome counts, fragment-size and mapping-quality distributions, per-base coverage, and a bigWig writer (a bundled copy of libBigWig, extended to compress blocks in parallel). - **Two levels of parallelism.** OpenMP threads within a file and `BiocParallel` workers across files. With `auto_threads = TRUE` the two are balanced against the number of available cores. - **Portable builds.** The `configure` script described under [Installation](#installation) finds a working OpenMP setup on macOS. # Session information ```{r intro-session-info} sessionInfo() ```