bam_read() is a multithreaded sequential BAM reader built on top of
ompBAM. The interface is designed to be familiar to users of
Rsamtools::scanBam(), GenomicAlignments::readGAlignments(), and
GenomicAlignments::readGAlignmentPairs().
Usage
bam_read(
file,
param = NULL,
what = NULL,
tag = NULL,
as = c("DataFrame", "data.frame", "GAlignments", "GAlignmentPairs", "scanBam"),
seqqual_mode = c("compatible", "compact"),
threads = 1L,
BPPARAM = BiocParallel::bpparam(),
auto_threads = FALSE,
use.names = FALSE,
with.which_label = FALSE,
include_unmapped = TRUE
)Arguments
- file
A BAM input. Supported values are:
a single BAM path (
character(1)) or multiple BAM paths,
- param
Optional
Rsamtools::ScanBamParam(or a compatible list for lightweight use). The following fields are honored:mapqFilter,flag,which,what, andtag.tagFilter,simpleCigarandreverseComplementare not supported; setting them gives a warning and they are ignored.- what
Character vector of fields to return, similar to
scanBam(what=...). Supported fields areqname,flag,rname,strand,pos,qwidth,mapq,cigar,mrnm,mpos,isize,seq,qual.- tag
Character vector of 2-letter tag names to extract.
- as
Output format:
"DataFrame": returnsS4Vectors::DataFrame(default),"data.frame": returns basedata.frame,"GAlignments": returnsGenomicAlignments::GAlignments,"GAlignmentPairs": returnsGenomicAlignments::GAlignmentPairs,"scanBam": returns ascanBam()-shaped list-of-lists.
- seqqual_mode
Controls representation of
seq/qualwhen those fields are requested:"compatible"(default): returnseqandqualasBiostrings::DNAStringSetandBiostrings::PhredQualityobjects, identical to those fromRsamtools::scanBam(). These are best held in aDataFrame(as = "DataFrame"); a basedata.framecan carry them but cannot print them,"compact": return lower-level raw list-columns for faster/lower-overhead extraction. In compact mode,seqis returned as onerawvector per read containing BAM-native packed sequence bytes (two bases per byte), andqualis returned as onerawvector per read containing per-base Phred bytes. These are not plain character strings.qwidthis needed to decode compactseqback to base letters, andqualvalues of255correspond to missing quality values. This mode is currently supported foras = "data.frame"oras = "DataFrame".
- threads
Requested number of OpenMP threads used for reading/decompression. May be capped when
auto_threads = TRUE. Values above 1 require a build with OpenMP (see the Installation section ofvignette("BamScaleR-intro")); without it a warning is issued once per session and each file is read on one thread.- BPPARAM
BiocParallelparameter used whenfilecontains more than one BAM. Defaults toBiocParallel::bpparam(). Set toNULLto force serial file processing. The object is used as supplied and is never modified, so it can be reused afterwards; an already-started cluster stays running with its configured number of workers.- auto_threads
Logical; when
TRUEandBPPARAMhas multiple workers, BamScaleR adaptively avoids oversubscription by preserving higher per-file OpenMP thread counts when possible and reducing the number of concurrently active file workers before shrinking per-file threads.- use.names
Passed to alignment object conversion. When
TRUE, read names (qname) are used as object names (they are read for this even whenwhatdoes not include"qname").- with.which_label
Logical; if
TRUEandparamincludeswhich, an extrawhich_labelcolumn is returned. It is a character column (or mcol), wherereadGAlignments()returns a factorRle.- include_unmapped
Logical; whether unmapped records are retained (subject to
param$flagconstraints).
Value
If file is length 1: one object in the format specified by as.
If file has length > 1 (or is a BamFileList): a named list of outputs,
one per BAM file.
Details
bam_read() is intentionally column-compatible with common BAM fields used by
Bioconductor workflows and can be used in place of Rsamtools::scanBam()
for the supported fields and settings; the differences are listed below.
Parallelism model:
BPPARAMparallelizes across files (one file per BiocParallel worker).threadsparallelizes within each file via OpenMP.Effective total concurrency is approximately
min(length(file), BiocParallel::bpnworkers(BPPARAM)) * threads.If
auto_threads = TRUEandBPPARAMhas multiple workers, BamScaleR first limits the number of concurrently active workers to preserve the requested per-file thread count within the detected core budget, then caps per-file OpenMP threads only if a single file would still oversubscribe the machine.BPPARAMitself is never changed. AMulticoreParamthat is not running is replaced by a copy with fewer workers; aSnowParamthat is not running is started with only the workers needed (also when there are fewer files than workers) and stopped again afterwards. For a running cluster, or another kind ofBPPARAM, the files are grouped into that manybplapply()tasks; an error then stops its whole group, andBiocParallel::bptry()returns one result per group rather than per file.GCC's OpenMP runtime (the usual one on Linux) cannot start threads in a process created by
fork()once its parent has used OpenMP threads, and such a forked worker (BiocParallel::MulticoreParam) would wait forever. BamScaleR therefore releases the runtime's idle threads just before eachfork()in the session, so forked workers can usethreadsas requested, whichever package used OpenMP first. (This may also discard other libraries' OpenMP thread-private data.) With an OpenMP runtime too old to support this (GCC's libgomp before version 9), a worker forked after BamScaleR has used several threads reads on one thread, and a worker forked after another package used OpenMP threads can still hang; useBiocParallel::SnowParam()(type"SOCK") there.
Compatibility notes:
rname,mrnm, andstrandare returned asfactorcolumns, matchingRsamtools::scanBam().rname/mrnmlevels are the BAM header reference names; unmapped or unset references areNA(not"*").strandhas levelsc("+", "-", "*").Region filtering via
param$whichis a sequential filter (the whole file is read; the BAM index is not used). As inRsamtools, a record is kept when its alignment overlaps a range. UnlikeRsamtools, a record that overlaps several ranges is returned once, labelled with the first of them; records come in file order rather than grouped by range; and unmapped records are not returned whenwhichis set. As inRsamtools, a zero-width range selects nothing, and a range on a sequence that is not in the BAM header is an error. Repeated range labels are made unique withmake.unique(), one batch per range; a range given twice therefore gets an empty second batch, wherescanBam()repeats the records.Flag filtering uses
ScanBamFlagsemantics by converting logical flag requirements into required-set and required-unset bit masks.Tag values are returned with their native BAM-derived type, matching
scanBam(): integer-valued tags (c,C,s,S,i,I) become integer columns (or double when a value exceeds the R integer range), floating-point (f) tags become double columns, andA/Z/H/Btags become character columns.Btags are comma-separated character values. Absent tag values areNA.seqqual_mode = "compact"is optimized for throughput-oriented benchmarking and returns raw list-columns forseq/qual, not ordinary sequence or quality strings. In this representation,seqcontains BAM-packed nucleotide bytes andqualcontains raw Phred bytes. Compact output is intended for users who want to defer or avoid full string-materialization costs; usedecode_compact_seq(),decode_compact_qual(), ordecode_seqqual_compact()to decode compact output back to standard string form when needed."GAlignments"and"GAlignmentPairs"output exclude unmapped records.For plain
as = "GAlignments"requests (nowhich, tags,seqorqual), the object is assembled from slots built in C++. Every invariant checked by theGAlignmentsvalidity method holds by construction, except for two kinds of record that the reader counts: a CIGAR with an op code above 8 or a zero-length op (which the validity method may reject), and an alignment that extends outside its sequence. If either occurs,methods::validObject()is run on the result, so an invalid object is never returned and out-of-bound alignments give the same warning asGenomicAlignments::readGAlignments(). Setoptions(BamScaleR.ga_fastpath = FALSE)to always use the validatingGAlignmentsconstructor instead.For
as = "GAlignmentPairs", mates are matched byGenomicAlignments::makeGAlignmentPairs(), on the read name, each record's position against its mate'smrnm/mpos, the strand, first/last, proper-pair and secondary flags. Withoutwhich, the result contains the same pairs asGenomicAlignments::readGAlignmentPairs(), ordered by the position of the first mate (pairs whose first mates start at the same position may come in a different order). Withwhich, records are filtered before pairing, so only pairs with both mates in the ranges are returned, each once, whereasreadGAlignmentPairs()returns every pair with at least one mate in a range. Ambiguous mates are dropped, andBamFileread-name options (qnamePrefixEnd,qnameSuffixStart) are not used. The mates' mcols hold the requestedwhatfields and tags that are not alignment slots, as foras = "GAlignments".as = "scanBam"returns a strict scan-like list-of-lists: withoutparam$which, it returns one unnamed batch; withparam$which, it returns one batch per range label (including empty ranges), with requestedwhatfields andtagvalues under$tag. In this output mode,seqandqualare returned asBiostrings::DNAStringSetandBiostrings::PhredQualityfor closerscanBam()compatibility.
Examples
bam <- ompBAM::example_BAM("Unsorted")
# Familiar scanBam-like field selection
x <- bam_read(bam, what = c("qname", "flag", "rname", "pos", "cigar"))
# Include sequence + quality
y <- bam_read(bam, what = c("qname", "seq", "qual"), threads = 2)
# scanBam-shaped output
z <- bam_read(bam, what = c("qname", "flag"), tag = "NM", as = "scanBam")
