Repository navigation
bigWig coverage tracks - #114
Conversation
Code review: bigWig coverage tracks (# 114)Reviewed the full diff. This is a clean, well-documented addition that slots the coverage accumulation into the existing single-pass BAM loop and matches Below are the things worth addressing before merge, ordered by impact. 🔴 Memory: dense per-base arrays held for the whole genome
By contrast Options worth considering:
At minimum, please document the expected memory footprint. 🟠 Hot-loop allocation per readIn if settings.split {
let mut blocks_buf = Vec::new();
genomecov_blocks(record, &mut blocks_buf);
...
}A fresh 🟠 Hot-loop linear search by chromosome name
self.chroms.iter_mut().find(|(name, _)| name == chrom)This runs per read per track. The caller already has the 🟡 Minor
✅ Things I checked and are fine
❓ Worth confirmingThe if settings.deduplicate_strand
&& record.is_paired()
&& !record.is_mate_unmapped()
&& record.flags() & BAM_FREAD2 != 0bedtools' Test coverageGood: two integration tests cross-check combined and stranded-forward against the real bedtools + UCSC chain, plus unit tests for Overall: solid, faithful implementation with strong validation. The memory profile is the one item I'd want resolved (or at least explicitly documented) before this runs on real genomes; the two hot-loop items are straightforward wins given RustQC's performance focus. |
Review follow-upPushed three commits addressing the review ( 🔴 Memory — fixedThe dense whole-genome difference array is gone. The accumulator now does a streaming sweep: since each chromosome's reads arrive coordinate-sorted, it keeps only a sparse map of pending coverage deltas plus a cursor, emits finished bedGraph intervals as the cursor advances, and drops the deltas below it. Peak memory is bounded by the widest single-read span (introns included) — a few KB per track — instead of chromosome length × depth × thread count. The ~25 GB (combined) / ~75 GB (stranded) footprint on a human genome is eliminated and no longer scales with genome size or core count. Output is unchanged, validated bit-for-bit against native bedtools genomecov v2.30 + UCSC bedClip/bedGraphToBigWig/bigWigToBedGraph: 738/738 intervals identical for both the combined ( 🟠 Per-read allocation — fixedSplit-read blocks now use a single reusable scratch buffer instead of a fresh 🟠 Per-read linear chromosome scan — fixedEliminated entirely. The streaming design accumulates one active chromosome at a time, so there is no per-read name lookup at all. 🟡 Redundant BAM re-open — fixedChromosome sizes are carried through 🟡 Dead non-split branch — fixedRemoved; all nf-core/rnaseq tracks are 🟡
|
Test coverage updateClosed out the remaining test gaps from the review follow-up:
Commits |
Implement bedtools genomecov-equivalent coverage accumulation in the
existing BAM streaming pass and write bigWig files via bigtools.
Produces nf-core/rnaseq-compatible outputs:
- {sample}.bigWig (combined, -split -bg)
- {sample}.forward/reverse.bigWig for stranded libraries (-split -du -strand)
Validated against bedtools genomecov + UCSC bedClip/bedGraphToBigWig in
integration tests.
Co-authored-by: Phil Ewels <phil.ewels@seqera.io>
Add a dedicated bigWig docs page and update README, AGENTS.md, CONTRIBUTING.md, getting-started guides, credits, CLI/config references, benchmark details, and library doc comments to describe nf-core/rnaseq- compatible genome coverage track output. Co-authored-by: Phil Ewels <phil.ewels@seqera.io>
Co-authored-by: Phil Ewels <phil.ewels@seqera.io>
Address review feedback on the bigWig coverage tracks: - Reuse a single scratch buffer for split-read alignment blocks instead of allocating a Vec per record per track in the hot loop. - Index each track's chromosomes by name (HashMap) for O(1) lookup per read, replacing the previous linear name scan. - Carry BAM header-ordered chromosome sizes through GenomeCovResult so the output step no longer re-opens the BAM purely to read the header. - Drop the unreachable non-split code path (all nf-core/rnaseq tracks use -split) and document clip_bedgraph as defensive. - Tidy a clippy manual-find warning in the bigWig integration helper. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
… size The difference-array accumulator allocated one counter per genome base and kept every chromosome resident, costing ~25 GB (combined) to ~75 GB (stranded) on a human genome. Replace it with a streaming sweep that exploits the coordinate-sorted BAM: keep only a sparse map of pending coverage deltas plus a cursor, emit finished bedGraph intervals as the cursor advances, and drop deltas below it. Peak memory is now bounded by the widest single-read span (introns included), independent of chromosome length, sequencing depth, and thread count. Output is unchanged: validated bit-for-bit against bedtools genomecov v2.30 + UCSC bedClip/bedGraphToBigWig/bigWigToBedGraph (738/738 intervals identical for both combined `-split` and stranded `-split -du -strand +`), plus a randomised brute-force equivalence test covering overlaps, nesting, clamping, and net-zero interval merging. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The streaming accumulator already clamps interval ends to each chromosome's length and never emits a chromosome absent from chrom_sizes, so clip_bedgraph was a pure pass-through. Remove it and write the bedGraph intervals directly. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Builds a synthetic BAM exercising the full matrix of cases that affect genomecov coverage and strand assignment, and compares the combined, forward, and reverse tracks against bedtools genomecov + UCSC tools at both 1 and 4 threads (sequential and parallel paths): - read-1 vs read-2 strand flipping under -du - read-2 with an *unmapped* mate (not flipped — bedtools only flips when the mate is mapped; this pins down the previously-unverified guard) - read-1 mate-unmapped and single-end reads (no flip) - spliced (N) and deletion (D) CIGAR splitting - a read overhanging the chromosome end (clamping) - secondary, duplicate, QC-fail, supplementary (counted); unmapped (ignored) - a second chromosome (parallel per-chromosome merge) Verified end-to-end against bedtools v2.30 + UCSC bedClip/bedGraphToBigWig/ bigWigToBedGraph; skips cleanly when those tools are absent. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Tool-independent test using a forward-only BAM: an unstranded run produces only the combined track, and a --stranded forward run populates the forward track while skipping the empty reverse track (no stub file written). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
9a7485b to
44a6a89
Compare
|
Rebased this branch onto the corrected This branch had Force-pushed, so please re-pull if you have a local copy. The noodles work itself lives in #118. |
|
Corresponding PRs for testing / benchmarks:
No manual effort done here, so still a way to go with validation work. |
Brings the bigWig branch up to date with the noodles migration (#118) and everything else on main. The bigWig accumulator and its integration-test helper now use the rust-htslib-shaped shim at crate::rna::bam instead of rust_htslib. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Make the coverage tracks follow bedtools genomecov v2.31.1 (CoverageBam) and expose its options, while the defaults still give exactly nf-core/rnaseq's three files: - tracks: combined / forward / reverse (default: combined, plus the two stranded tracks for stranded libraries; forward/reverse swap their -strand for reverse-stranded libraries, as rnaseq does) - split (-split, default on), du (-du, default on), scale (-scale, applied in float and rounded to the six significant digits bedtools prints), bga (-bga), read_end (-5 / -3), fragment_size (-fs) All are settable under rna.bigwig in YAML and as --bigwig-* flags / RUSTQC_BIGWIG_* env vars; --skip-bigwig turns the tracks off. Finished coverage is now kept as per-chromosome (end, depth) runs keyed by tid, 8 bytes a run instead of a String per interval, and zero spans for -bga are synthesised at write time. -fs keeps a fragment_size window open behind the cursor so reverse reads can extend backwards. Input that is not coordinate-sorted (which the streaming sweep cannot handle) now drops the tracks with a warning instead of failing the run with an overlapping-interval error from bigtools; this fixes the same_reference_multi_slice CRAM test from main. bigtools and tokio are optional behind a default-on `bigwig` feature; without it the run warns that no bigWig tracks are written and everything else works. Empty tracks are skipped with a warning. Tests: the combined track is read back from the bigWig container and compared with a real `bedtools genomecov -split -bg` fixture for tests/data/test.bam (from #166; regenerate with tests/create_bigwig_test_data.sh) on 1 and 4 threads, plus -bga and -scale derived from it. A synthetic BAM pins the default tracks for forward and reverse libraries and every option against bedtools' source semantics. The live-bedtools tests, which always skipped without bedtools installed, are replaced. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ature - bigwig.mdx: exact bedtools genomecov + sort + bedClip + bedGraphToBigWig command for each output file, an options table with bedtools flags, read filters, a "Replacing bedtools in nf-core/rnaseq" section, unsupported options (-pc and why), the bigwig cargo feature, and how the tracks are validated - configuration and CLI reference: rna.bigwig keys, --bigwig-* flags and RUSTQC_BIGWIG_* env vars - The default build compiles libdeflate (via bigtools) with the C compiler Rust already links with; installation, CONTRIBUTING, AGENTS.md and the lib docs now say so, and that --no-default-features compiles no C code - Cite the bigWig format paper (Kent et al. 2010) and fix the bigtools reference; README, CHANGELOG and AGENTS.md updated Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Replace bigtools (which builds libdeflate in C) and tokio with a small bigWig writer that follows UCSC bedGraphToBigWig: chromosome B+ tree, zlib (flate2) bedGraph sections, R-tree indexes with blockSize 256 and 1024 items per slot, and zoom levels chosen and summarised as in bbiWriteZoomLevels, plus the total summary. bigWigInfo and bigWigSummary report the same zoom levels and values as for bedGraphToBigWig files. The `bigwig` cargo feature and its gates are gone; RustQC is pure Rust again. Tests now decode the bigWig in the test module and compare every track and option with real bedtools 2.31.1 genomecov output, for test.bam and a new edge-case BAM (bigwig_edge.sam), regenerated by tests/create_bigwig_test_data.sh. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Closes #112.
rustqc rnanow writes genome-wide bigWig coverage tracks in its single pass over the BAM. The tracks matchbedtools genomecov(v2.31.1) followed by UCSCbedClipandbedGraphToBigWig, and the defaults give exactly the three files that nf-core/rnaseq publishes in{aligner}/bigwig/. The aim is that nf-core/rnaseq can later drop itsBEDTOOLS_GENOMECOV_*andBEDGRAPH_BEDCLIP_BEDGRAPHTOBIGWIG_*tasks and use RustQC's output instead (that pipeline change is not part of this PR).Output
Files go in
bigwig/(or the output directory with--flat-output). With the default settings each file equals the output ofbedtools genomecov ... | LC_ALL=C sort -k1,1 -k2,2n, thenbedClipandbedGraphToBigWigwith the BAM's chromosome sizes:{sample}.bigWig-ibam {bam} -split -bg{sample}.forward.bigWig-split -du -strand + -bg(-strand -for a reverse-stranded library){sample}.reverse.bigWig-split -du -strand - -bg(-strand +for a reverse-stranded library)forward/reversename the transcript strand, so their-strandfilters swap for reverse-stranded libraries, as in nf-core/rnaseq'sconf/modules/bigwig.config. A track with no coverage is skipped with a warning (a bigWig cannot hold an empty track); a BAM that is not coordinate-sorted gets no tracks and a warning. Neither fails the run.Options
Each option is a key under
rna.bigwigin the YAML config, a CLI flag and aRUSTQC_*env var; CLI flags override the config. Options apply to all tracks of a run.enabled--skip-bigwigtruetracks--bigwig-tracks combined,forward,reversecombined, plusforward,reverseif stranded-strand +/-split--bigwig-split[=BOOL]true-splitdu--bigwig-du[=BOOL]true-duscale--bigwig-scale <FLOAT>1.0-scalebga--bigwig-bga[=BOOL]false-bga(else-bg)read_end--bigwig-read-end 5p|3p-5/-3fragment_size--bigwig-fragment-size <N>-fsCoverageBamsourceDalways splits a read into blocks (no-ignoreD);Nsplits only withsplit.-duflips read 2 only when the read is paired and its mate is mapped, and only affects the-strandfilter (so it is a no-op on the combined track).-5,-3and-fsuse the read's own strand;-fstakes priority over-5/-3, which take priority over-split, as in bedtools (which refuses-splittogether with-5/-3, soread_endsimply ignoressplit).-scalemultiplies infloatand rounds to the six significant digits bedtools prints (ties to even, like glibc), so values equal whatbedGraphToBigWigwould store; with scale 1 depths are exact integers.bgathe bigWig stores zero spans (and whole uncovered contigs) as 0 instead of leaving gaps.-pc(paired fragment coverage): its interval runs from read 1's mate position to read 1's end, so it is only known when read 1 arrives, which can be an arbitrary insert size (hundreds of kb for spliced RNA-seq pairs) behind the sweep cursor. Supporting it means holding a whole chromosome's coverage or fragile mate matching, so it does not fit the streaming design.-ignoreD,-max,-d/-dz/histogram output and-tracklinewere not requested and are left out.Replacing bedtools in nf-core/rnaseq
Run RustQC with defaults on the BAM that nf-core/rnaseq gives to
bedtools genomecov, with the sample's strandedness:This writes
results/bigwig/{sample}.bigWig, plus{sample}.forward.bigWigand{sample}.reverse.bigWigwhen--strandedisforwardorreverse, the same files as nf-core/rnaseq's three genomecov/bedClip/bedGraphToBigWig chains. The other bigWig options must stay at their defaults.Implementation
-fsfragment, which keeps that much open behind the cursor), not by genome size.(end, depth)runs keyed by reference id (8 bytes per depth change, no per-interval chromosomeString), and-bgazero spans are produced at write time.src/rna/bigwig/writer.rs, 508 lines)bigtools, notokio, no cargo feature: RustQC stays pure Rust after Make RustQC pure Rust: drop the C++ RNG shim and native font libraries #211 (cargo treehas nocc,cmakeor libdeflate). zlib comes fromflate2, which was already a dependency.bedGraphToBigWig: header, chromosome B+ tree (name-sorted, only chromosomes with data, multi-level past 256), zlib-compressed bedGraph sections of up to 1024 items, R-tree index with blockSize 256, and zoom levels plus the total summary.bbiWriteZoomLevels: candidate sizes start at the average interval size and grow 4x, the first level is the finest whose estimated size is at most half the data, and each further level merges the previous one until the record count stops falling. Summaries aref32, as in UCSC, so they round the same way.mainis merged in (no rebase); the accumulator now uses the noodles shim (crate::rna::bam).same_reference_multi_slice.cram) produced overlapping intervals. Out-of-order input is now detected and the tracks are dropped with a warning.Validation
tests/create_bigwig_test_data.shruns bedtools 2.31.1genomecov(via a bedtools + samtools container) ontests/data/test.bamand on a new hand-written edge-case BAM (tests/data/bigwig_edge.sam: reads 1/2 on each strand with mapped and unmapped mates, single-end reads,NandDCIGARs, a read past the contig end, secondary/duplicate/QC-fail/supplementary records, an unmapped read, a second contig).-split -bg),-du -strand +and-strand -,-bga,-scale 0.37,-5,-3,-fs 25, and on the edge BAM also no-splitand-strand -without-du. These replace the expectations that were only derived from the bedtools source; all of the old hand-derived values agreed with real bedtools.ucsc-bigwigtobedgraph:469,ucsc-bigwiginfo:469,ucsc-bigwigsummary:482, and nf-core'sucsc-bedgraphtobigwig:482)test.bam(default, forward, reverse,bga,scale,5p,3p,fs,split=false) and the 52.8K-read benchmark BAM (3 tracks), 17 files.bigWigToBedGraphdecodes all 17 new files to exactly the bigtools output.bigWigToBedGraphlists chromosomes in B+ tree order, which is now name-sorted as UCSC requires (bigtools wrote them in id order).bedClipsnapshots in RustQC-benchmarks refactor: remove BED input support, make --gtf required #28 (snapshots/rna/small/bigwig/, 54,615 / 24,961 / 29,656 lines), compared locally only.bigWigInfoandbigWigSummarywere compared withbedGraphToBigWigfiles built from the same bedGraphs: identical zoom levels (e.g. 352 to 92,274,688 bp, 10 levels on the benchmark track), identical total summary, and identicalbigWigSummarymean/max/min/coverage/std over whole chromosomes and sub-regions on the benchmark,-bgaand 300-contig files. bigtools' zoom summaries did not match UCSC's (region means were several-fold too low).bedGraphToBigWigoutput: zlib-rs compresses differently, and UCSC pads its last R-tree leaf with 24-byte rather than 32-byte empty slots.cargo fmt --check,cargo clippy -- -D warningsandcargo test --releasepass;cargo +1.89 check --all-targetspasses (MSRV unchanged).clippy --all-targetsadds no new warnings.Performance
Release build, Apple silicon, RustQC-benchmarks
small/test.bam(3.8 MB, 52.8K reads, chr6),-s reverseso all three tracks are written, median of 7 runs:The three tracks now add about 0.05 s. The writer is single-threaded and runs after the BAM pass.
🤖 Generated with Claude Code