From 23c4d93599012ff8be34a8f6ff7824e04849df9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rayan=20Hassa=C3=AFne?= Date: Wed, 25 Nov 2026 13:04:49 +0100 Subject: [PATCH 1/2] fix(samtools): match samtools stats and flagstat 1.22.1 exactly Port the remaining details of samtools stats.c and bam_stat.c (1.22.1) so every data line of the stats output and the whole flagstat output match samtools, independent of --threads. samtools stats: - GCD: normalise bin GC with rint() in double precision (ties to even), compute percentiles and depth scaling in single precision as samtools does, compare GC groups like fabs(float - float) < 0.1, and give supplementary reads a GC of 0. Bins are put back in BAM order before output, because samtools leaves the last bin un-normalised; before, the "last" bin depended on how contigs were split across threads. - COV: simulate the samtools round buffer per contig. Its flush to the end visits only size - 1 slots, so one slot is carried into the next contig and dropped after the last one. The carry is resolved after all contigs are merged, so the result does not depend on --threads. - SN: error rate and the averages are float divisions in samtools; the insert-size summary halves each orientation separately and keeps insert size 0 for same-contig pairs; filtered sequences is 0; QC-failed, unmapped, properly paired, duplicated and different-chromosome counts use samtools' own conditions; mismatches and duplicates include supplementary reads; non-primary alignments counts secondary records. - First/last fragments follow samtools' read order (read1 only / read2 only); read lengths include hard clips; ID only lists indels up to 300 bases and skips leading deletions like count_indels; GCT skips empty cycles; FFQ/LFQ share one maximum quality and keep all 256 quality values (missing qualities are 255). samtools flagstat: count QC-passed and QC-failed records separately (port of flagstat_loop) and compute percentages in single precision. Library API: BamStatResult gains the samtools-only counters and a FlagstatCounts; ffq/lfq rows are [u64; 256]; the public BamStatAccum::flush_cov_buf_all is gone (coverage is finished per contig). Verified byte for byte (all non-comment lines of stats, full flagstat and idxstats) against samtools 1.22.1 (bioconda h96c455f_0) on the eight RustQC-benchmarks datasets and on synthetic BAMs with QC-fail, supplementary, secondary, hard-clipped, spliced and unmapped reads, at --threads 1, 2 and 6. Co-Authored-By: Claude Opus 5.5 --- docs/src/content/docs/rna/samtools.mdx | 19 +- src/rna/rseqc/accumulators.rs | 1118 +++++++++++------------- src/rna/rseqc/bam_stat.rs | 73 +- src/rna/rseqc/flagstat.rs | 333 ++++--- src/rna/rseqc/mod.rs | 1 + src/rna/rseqc/stats.rs | 731 +++++++++------- src/rna/rseqc/stats_coverage.rs | 375 ++++++++ 7 files changed, 1573 insertions(+), 1077 deletions(-) create mode 100644 src/rna/rseqc/stats_coverage.rs diff --git a/docs/src/content/docs/rna/samtools.mdx b/docs/src/content/docs/rna/samtools.mdx index 5d620d4b..f3d0ce29 100644 --- a/docs/src/content/docs/rna/samtools.mdx +++ b/docs/src/content/docs/rna/samtools.mdx @@ -40,7 +40,8 @@ written to a `samtools/` subdirectory under the output directory. Use **File:** `.flagstat` A text file matching the `samtools flagstat` output format. Each line reports a -count with the format ` + 0 `. The 16 standard metrics are: +count with the format ` + `. The 16 standard +metrics are: | Line | Description | | ---- | --------------------------------------------- | @@ -61,7 +62,8 @@ count with the format ` + 0 `. The 16 standard metrics are: | 15 | With mate mapped to a different chr | | 16 | With mate mapped to a different chr (mapQ>=5) | -The QC-failed column is always 0 (RustQC does not separate QC-pass/fail counts). +Records with the QC-fail flag (0x200) are counted in the second column, as in +samtools. Example: @@ -266,9 +268,16 @@ unmapped counts, plus the `*` row for unplaced reads. **Result: Near-identical** All SN (Summary Numbers) fields and 19 of 20 histogram sections match exactly -between `samtools stats` and RustQC on both datasets. The GCD (GC depth) section -shows minor differences (max absolute difference of 0.018) due to sampling -variation in the GC depth calculation. +between `samtools stats` and RustQC on both datasets. In this run the GCD (GC +depth) section showed small differences (max absolute difference of 0.018). They +came from rounding and floating-point precision details of the samtools +calculation, which RustQC now reproduces, so every data line of the GCD section +matches as well. + +RustQC reproduces `samtools stats` 1.22.1 run without options on a +coordinate-sorted BAM. One case is known to differ: the coverage distribution +(`COV`) when reads are 300 bases or longer, because samtools then resizes its +coverage buffer and drops part of the pending coverage.
Large dataset (GM12878) diff --git a/src/rna/rseqc/accumulators.rs b/src/rna/rseqc/accumulators.rs index ced01fb6..666b8886 100644 --- a/src/rna/rseqc/accumulators.rs +++ b/src/rna/rseqc/accumulators.rs @@ -12,9 +12,27 @@ use indexmap::IndexMap; use rust_htslib::bam; use super::bam_stat::{BamStatResult, GcDepthBin}; +use super::flagstat::FlagstatCounts; +use super::stats_coverage::{resolve_carries, ContigCovSummary, ContigCoverage}; /// Default GC-depth bin size in base pairs (matches upstream samtools default). const GCD_BIN_SIZE: u64 = 20_000; +/// samtools stats insert size cap (`-i`, default 8000). +const MAX_INSERT_SIZE: u64 = 8000; +/// Longest indel in samtools stats' ID section (`nindels`, fixed at 300). +const MAX_INDEL_LEN: i64 = 300; +/// samtools stats read order: first fragment (unpaired, or read1 only). +const READ_ORDER_FIRST: u8 = 1; +/// samtools stats read order: last fragment (read2 only). +const READ_ORDER_LAST: u8 = 2; + +/// samtools stats read order of a record: 1 = first, 2 = last, 0 or 3 = other. +fn read_order(flags: u16) -> u8 { + if flags & BAM_FPAIRED == 0 { + return READ_ORDER_FIRST; + } + u8::from(flags & BAM_FREAD1 != 0) + 2 * u8::from(flags & BAM_FREAD2 != 0) +} use super::common::{self, KnownJunctionSet, ReferenceJunctions}; use super::infer_experiment::{GeneModel, InferExperimentResult}; use super::inner_distance::{ @@ -172,9 +190,11 @@ pub struct BamStatAccum { pub read1_flagstat: u64, /// Read2 in pair (0x80), regardless of QC/dup — for flagstat. pub read2_flagstat: u64, - /// First fragments for samtools stats: primary reads that are not "last fragments". + /// samtools stats first fragments: primary reads with a sequence that are + /// unpaired, or paired with only the read1 flag. pub first_fragments: u64, - /// Last fragments for samtools stats: primary reads with 0x80 flag. + /// samtools stats last fragments: primary paired reads with a sequence and + /// only the read2 flag. pub last_fragments: u64, /// Properly paired reads (0x1 + 0x2), regardless of QC/dup. pub properly_paired: u64, @@ -196,30 +216,30 @@ pub struct BamStatAccum { // --- samtools stats SN additional fields --- /// Sum of query sequence lengths for all primary reads (non-secondary, non-supplementary). pub total_len: u64, - /// Sum of first fragment (read1 or unpaired) sequence lengths. + /// Sum of first fragment sequence lengths. pub total_first_fragment_len: u64, - /// Sum of last fragment (read2) sequence lengths. + /// Sum of last fragment sequence lengths. pub total_last_fragment_len: u64, /// Sum of query lengths for mapped primary reads. pub bases_mapped: u64, - /// Sum of M/=/X CIGAR operations for mapped primary reads. + /// Sum of M/I/=/X CIGAR operations for mapped non-secondary reads. pub bases_mapped_cigar: u64, /// Sum of query lengths for duplicate-flagged primary reads. pub bases_duplicated: u64, - /// Maximum query sequence length (among primary reads). + /// Maximum read length including hard clips (non-secondary reads). pub max_len: u64, - /// Maximum first-fragment sequence length. + /// Maximum first-fragment read length including hard clips. pub max_first_fragment_len: u64, - /// Maximum last-fragment sequence length. + /// Maximum last-fragment read length including hard clips. pub max_last_fragment_len: u64, - /// Sum of average per-read base qualities (for average-of-averages). + /// Sum of base qualities of primary first and last fragments. pub quality_sum: f64, - /// Number of reads contributing to quality_sum (primary, non-QC-fail). + /// Number of bases contributing to quality_sum. pub quality_count: u64, - /// Sum of NM tag values across mapped primary reads. + /// Sum of NM tag values across mapped non-secondary reads (wrapping). pub mismatches: u64, /// Insert size with orientation: abs_tlen → [total, inward, outward, other]. - /// Only one mate per pair contributes (upstream mate), capped at 8000. + /// Both mates contribute (halved at output), capped at 8000. pub is_hist: HashMap, /// Inward-oriented pairs (FR). pub inward_pairs: u64, @@ -235,11 +255,11 @@ pub struct BamStatAccum { pub primary_duplicates: u64, /// Primary mapped reads with MAPQ = 0 (matching upstream samtools stats). pub reads_mq0: u64, - /// Primary non-QC-fail mapped paired reads where mate is also mapped. + /// Primary mapped paired reads with a sequence whose mate is also mapped. pub reads_mapped_and_paired: u64, // --- samtools stats histogram/distribution fields --- - /// Read length histogram (all primary reads): length → count. + /// Read length histogram (primary reads, length including hard clips): length → count. pub rl_hist: HashMap, /// First fragment read length histogram: length → count. pub frl_hist: HashMap, @@ -247,11 +267,11 @@ pub struct BamStatAccum { pub lrl_hist: HashMap, /// MAPQ histogram: primary, mapped, !qcfail, !dup (quality 0-255). pub mapq_hist: [u64; 256], - /// Per-cycle quality for first fragments (primary, mapped, !qcfail, !dup). - /// Outer: cycle index. Inner: quality value → count (64 buckets covers Q0-Q63). - pub ffq: Vec<[u64; 64]>, - /// Per-cycle quality for last fragments. - pub lfq: Vec<[u64; 64]>, + /// Per-cycle quality for primary first fragments (read-oriented cycles). + /// Outer: cycle index. Inner: quality value (0-255) → count. + pub ffq: Vec<[u64; 256]>, + /// Per-cycle quality for primary last fragments. + pub lfq: Vec<[u64; 256]>, /// GC content step-function for first fragments, 200 bins (matching samtools ngc=200). /// Each bin i stores the number of reads with gc_count * 199 / seq_len <= i. pub gcf: [u64; 200], @@ -284,20 +304,38 @@ pub struct BamStatAccum { /// Coverage distribution: depth → number of reference positions at that depth. /// Populated from a round buffer pileup during sorted BAM processing. pub cov_hist: HashMap, - /// Circular buffer for coverage pileup, matching upstream samtools design. - /// `cov_buf[cov_buf_idx]` corresponds to reference position `cov_buf_pos`. - /// The buffer grows dynamically to accommodate `max_read_length * 5`. - cov_buf: Vec, - /// Index into `cov_buf` corresponding to `cov_buf_pos`. - cov_buf_idx: usize, - /// Reference position of the element at `cov_buf[cov_buf_idx]`. - cov_buf_pos: i64, - /// Current chromosome tid for round buffer tracking. - cov_buf_tid: i32, + /// Coverage round buffer of the contig being read. + cov_contig: Option, + /// Finished contigs, for the slot samtools carries between contigs. + cov_done: Vec, + + // --- samtools stats counters without a bam_stat/flagstat equivalent --- + /// Primary reads with a sequence that are neither first nor last fragments + /// (paired with both or neither of the read1/read2 flags). + pub other_fragments: u64, + /// Primary reads with a sequence and the QC-fail flag. + pub stats_qcfail: u64, + /// Primary unmapped reads with a sequence. + pub stats_unmapped: u64, + /// Primary reads with a sequence and the paired flag. + pub stats_paired_tech: u64, + /// Primary reads with a sequence, both mates mapped and the proper-pair flag. + pub stats_properly_paired: u64, + /// Primary reads with a sequence, both mates mapped, mate on another contig. + pub stats_anomalous: u64, + /// Duplicate-flagged non-secondary reads with a sequence. + pub stats_dup_reads: u64, + /// Sequence length of `stats_dup_reads`. + pub stats_dup_bases: u64, + + /// samtools flagstat counters, split by QC-fail. + pub flagstat: FlagstatCounts, // --- GC-depth (GCD section) fields --- - /// Accumulated GC-depth bins (one per `GCD_BIN_SIZE`-bp genomic window). - gcd_bins: Vec, + /// GC-depth bins (one per `GCD_BIN_SIZE`-bp window) with their contig and start. + gcd_bins: Vec<(i32, i64, GcDepthBin)>, + /// Index in `gcd_bins` of the bin being filled. + gcd_cur: Option, /// Start position of the current GCD bin. gcd_pos: i64, /// Chromosome tid of the current GCD bin. @@ -377,11 +415,19 @@ impl Default for BamStatAccum { ic: Vec::new(), chk: [0u32; 3], cov_hist: HashMap::new(), - cov_buf: vec![0u32; 1500], // matches upstream samtools: nbases * 5 = 300 * 5 - cov_buf_idx: 0, - cov_buf_pos: 0, - cov_buf_tid: -1, + cov_contig: None, + cov_done: Vec::new(), + other_fragments: 0, + stats_qcfail: 0, + stats_unmapped: 0, + stats_paired_tech: 0, + stats_properly_paired: 0, + stats_anomalous: 0, + stats_dup_reads: 0, + stats_dup_bases: 0, + flagstat: FlagstatCounts::default(), gcd_bins: Vec::new(), + gcd_cur: None, gcd_pos: -1, gcd_tid: -1, } @@ -412,7 +458,9 @@ impl BamStatAccum { let mapq = record.mapq(); // ================================================================= - // samtools flagstat counters (count ALL records, no early returns) + // samtools flagstat counters (count ALL records, no early returns). + // `flagstat` is what the flagstat output uses; the individual fields + // are kept for the library API. // ================================================================= if is_secondary { self.secondary += 1; @@ -423,16 +471,7 @@ impl BamStatAccum { if is_mapped { self.mapped += 1; } - // samtools stats: "1st fragments" / "last fragments" count primary reads only - // For paired reads: read2 flag -> last, everything else -> 1st - // For SE reads (no PAIRED flag): all counted as 1st fragments - if is_primary { - if flags & BAM_FREAD2 != 0 { - self.last_fragments += 1; - } else { - self.first_fragments += 1; - } - } + self.flagstat.add(flags, tid, record.mtid(), mapq); // samtools flagstat: paired-read metrics count PRIMARY reads only // (secondary/supplementary are excluded from paired/read1/read2/properly-paired counts) if is_paired && is_primary { @@ -512,521 +551,27 @@ impl BamStatAccum { } } - // Track gc_count from the primary-read per-cycle loop so the GCD - // section below can reuse it without re-scanning the sequence. - let mut primary_gc_count: u64 = 0; - - // ================================================================= - // samtools stats SN counters (primary reads only) - // ================================================================= + // Primary-read totals kept for the library API (`BamStatResult`). + let seq_len = record.seq_len(); if is_primary { self.primary_count += 1; - let seq_len = record.seq_len() as u64; - let mate_unmapped = flags & BAM_FMUNMAP != 0; - - self.total_len += seq_len; - let is_last_fragment = is_paired && flags & BAM_FREAD2 != 0; - if is_last_fragment { - self.total_last_fragment_len += seq_len; - if seq_len > self.max_last_fragment_len { - self.max_last_fragment_len = seq_len; - } - } else { - self.total_first_fragment_len += seq_len; - if seq_len > self.max_first_fragment_len { - self.max_first_fragment_len = seq_len; - } - } - if seq_len > self.max_len { - self.max_len = seq_len; - } - - // RL/FRL/LRL: read length histograms (all primary reads) - *self.rl_hist.entry(seq_len).or_insert(0) += 1; - if is_last_fragment { - *self.lrl_hist.entry(seq_len).or_insert(0) += 1; - } else { - *self.frl_hist.entry(seq_len).or_insert(0) += 1; - } - if is_dup { self.primary_duplicates += 1; - self.bases_duplicated += seq_len; - } - // "reads mapped and paired" for samtools stats: primary, non-QC-fail, - // mapped, paired, mate also mapped - if is_mapped && is_paired && !is_qcfail && !mate_unmapped { - self.reads_mapped_and_paired += 1; + self.bases_duplicated += seq_len as u64; } if is_mapped { self.primary_mapped += 1; - self.bases_mapped += seq_len; - - // samtools stats: reads MQ0 counts primary mapped reads with MAPQ=0 - // (upstream stats.c: MQ0 is counted inside collect_orig_read_stats, - // which is only called for IS_ORIGINAL reads = non-secondary, non-supplementary) - if record.mapq() == 0 { - self.reads_mq0 += 1; - } - - // NOTE: bases_mapped_cigar is now computed in the IC/ID CIGAR - // loop below (for all mapped non-secondary reads) to avoid a - // separate full CIGAR traversal here. - - // NM tag (edit distance) - if let Ok(rust_htslib::bam::record::Aux::U8(nm)) = record.aux(b"NM") { - self.mismatches += u64::from(nm); - } else if let Ok(rust_htslib::bam::record::Aux::U16(nm)) = record.aux(b"NM") { - self.mismatches += u64::from(nm); - } else if let Ok(rust_htslib::bam::record::Aux::U32(nm)) = record.aux(b"NM") { - self.mismatches += u64::from(nm); - } else if let Ok(rust_htslib::bam::record::Aux::I8(nm)) = record.aux(b"NM") { - if nm > 0 { - self.mismatches += nm as u64; - } - } else if let Ok(rust_htslib::bam::record::Aux::I16(nm)) = record.aux(b"NM") { - if nm > 0 { - self.mismatches += nm as u64; - } - } else if let Ok(rust_htslib::bam::record::Aux::I32(nm)) = record.aux(b"NM") { - if nm > 0 { - self.mismatches += nm as u64; - } - } - - // Insert size + orientation for paired primary reads where both - // mates are mapped. Matches samtools stats gate: - // IS_PAIRED_AND_MAPPED && IS_ORIGINAL - // if (isize > 0 || tid == mtid) - // Both mates contribute; samtools divides by 2 at output. - // We do the same in write_insert_size() and the SN section. - if is_paired && !mate_unmapped { - let tid = record.tid(); - let mtid = record.mtid(); - let tlen = record.insert_size(); - let abs_tlen = tlen.unsigned_abs(); - - if abs_tlen > 0 || tid == mtid { - let pos = record.pos(); - let mpos = record.mpos(); - - // Compute orientation (only meaningful for same-chromosome) - let pos_fst = mpos - pos; - let is_fst: i64 = if flags & BAM_FREAD1 != 0 { 1 } else { -1 }; - let is_fwd: i64 = if flags & BAM_FREVERSE != 0 { -1 } else { 1 }; - let is_mfwd: i64 = if flags & BAM_FMREVERSE != 0 { -1 } else { 1 }; - - // orientation_idx: 1=inward, 2=outward, 3=other - let orientation_idx = if is_fwd * is_mfwd > 0 { - self.other_orientation += 1; - 3usize - } else if is_fst * pos_fst > 0 { - if is_fst * is_fwd > 0 { - self.inward_pairs += 1; - 1usize - } else { - self.outward_pairs += 1; - 2usize - } - } else if is_fst * pos_fst < 0 { - if is_fst * is_fwd > 0 { - self.outward_pairs += 1; - 2usize - } else { - self.inward_pairs += 1; - 1usize - } - } else { - self.inward_pairs += 1; - 1usize - }; - - if abs_tlen > 0 { - // Cap at MAX_INSERT_SIZE (8000), matching - // samtools stats which accumulates overflow - // into the cap bucket. - let capped = abs_tlen.min(8000); - let entry = self.is_hist.entry(capped).or_insert([0; 4]); - entry[0] += 1; // total - entry[orientation_idx] += 1; - } - } - } - } - - // Average quality for primary non-QC-fail reads. - // Upstream samtools stats computes per-BASE quality average: - // sum of all individual base qualities / total bases. - // (Not a per-read average of averages.) - if !is_qcfail { - let quals = record.qual(); - if !quals.is_empty() { - let base_qual_sum: f64 = quals.iter().map(|&q| f64::from(q)).sum::(); - self.quality_sum += base_qual_sum; - self.quality_count += quals.len() as u64; - } - } - - // ============================================================= - // MAPQ histogram: primary + mapped + !qcfail + !dup - // (matches samtools stats.c:1239 five-flag exclusion) - // ============================================================= - if is_mapped && !is_qcfail && !is_dup { - self.mapq_hist[mapq as usize] += 1; } + } - // ============================================================= - // Per-cycle quality & base composition histograms: - // FFQ/LFQ, FBC/LBC, GCF/GCL, FTC/LTC, FBC_RO/LBC_RO - // - // Upstream samtools stats includes duplicates, unmapped, and - // qcfail reads in these histograms (collect_orig_read_stats - // has no such checks). Only secondary+supplementary are - // excluded (via IS_ORIGINAL), which is already handled by - // the outer is_primary guard. - // ============================================================= - { - let is_reverse = flags & BAM_FREVERSE != 0; - - let seq = record.seq(); - let quals = record.qual(); - let read_len = seq.len(); - - // Determine which arrays to use (first vs last fragment) - // If paired: read2 = last, read1 = first. If SE: all = first. - let (qual_arr, base_arr, base_ro_arr, gc_arr, tc_arr) = if is_last_fragment { - ( - &mut self.lfq, - &mut self.lbc, - &mut self.lbc_ro, - &mut self.gcl, - &mut self.ltc, - ) - } else { - ( - &mut self.ffq, - &mut self.fbc, - &mut self.fbc_ro, - &mut self.gcf, - &mut self.ftc, - ) - }; - - // Ensure per-cycle arrays are large enough - if read_len > qual_arr.len() { - qual_arr.resize(read_len, [0u64; 64]); - } - if read_len > base_arr.len() { - base_arr.resize(read_len, [0u64; 6]); - } - if read_len > base_ro_arr.len() { - base_ro_arr.resize(read_len, [0u64; 6]); - } - if read_len > self.gcc_rc.len() { - self.gcc_rc.resize(read_len, [0u64; 4]); - } - - let mut gc_count: u64 = 0; - - // Pre-built lookup tables for the per-cycle inner loop, - // avoiding branches and match overhead on every base. - // - // BAM 4-bit encoding: A=1, C=2, G=4, T=8, N=15, others=0,3,5..14 - // BASE_IDX[nibble] → 0=A, 1=C, 2=G, 3=T, 4=N, 5=Other - const BASE_IDX: [u8; 16] = [5, 0, 1, 5, 2, 5, 5, 5, 3, 5, 5, 5, 5, 5, 5, 4]; - // RC_IDX[base_idx] → reverse-complement base_idx (A↔T, C↔G) - // Only meaningful for base_idx 0-3 (ACGT). Index 4/5 not used. - const RC_IDX: [u8; 6] = [3, 2, 1, 0, 4, 5]; // A→T, C→G, G→C, T→A - - // Hoist the is_reverse branch outside the inner loop so the - // compiler can version the loop and potentially auto-vectorize - // each variant independently. - if !is_reverse { - for i in 0..read_len { - let q = quals[i] as usize; - qual_arr[i][q.min(63)] += 1; - - let base_idx = BASE_IDX[seq.encoded_base(i) as usize] as usize; - base_arr[i][base_idx] += 1; - base_ro_arr[i][base_idx] += 1; - if base_idx < 4 { - self.gcc_rc[i][base_idx] += 1; - } - if base_idx == 1 || base_idx == 2 { - gc_count += 1; - } - if base_idx < 5 { - tc_arr[base_idx] += 1; - } - } - } else { - for i in 0..read_len { - let ro_cycle = read_len - 1 - i; - let q = quals[i] as usize; - qual_arr[ro_cycle][q.min(63)] += 1; - - let base_idx = BASE_IDX[seq.encoded_base(i) as usize] as usize; - base_arr[i][base_idx] += 1; - base_ro_arr[ro_cycle][base_idx] += 1; - if base_idx < 4 { - self.gcc_rc[ro_cycle][RC_IDX[base_idx] as usize] += 1; - } - if base_idx == 1 || base_idx == 2 { - gc_count += 1; - } - if base_idx < 5 { - tc_arr[base_idx] += 1; - } - } - } - - // Save gc_count for GCD section below (avoids re-scanning the sequence). - primary_gc_count = gc_count; - - // GC content: cumulative step function with ngc=200 bins. - // Matches samtools stats.c:925-941. For a read with gc_count G/C - // bases out of read_len total, increment bins gc_idx_min..gc_idx_max. - let ngc: usize = 200; - if let (Some(gc_idx_min), Some(gc_idx_max)) = ( - (gc_count as usize * (ngc - 1)).checked_div(read_len), - ((gc_count as usize + 1) * (ngc - 1)).checked_div(read_len), - ) { - let gc_idx_max = gc_idx_max.min(ngc - 1); - for item in gc_arr.iter_mut().take(gc_idx_max).skip(gc_idx_min) { - *item += 1; - } - } - } - } // if is_primary - - // ============================================================= - // Indel distribution (ID) and indels per cycle (IC) from CIGAR. - // - // Upstream samtools stats calls count_indels() AFTER the - // secondary-read early return (line 1206-1210) and the - // IS_UNMAPPED return (line 1255), but OUTSIDE IS_ORIGINAL(). - // This means: all mapped, non-secondary reads are included - // (supplementary, duplicate, qcfail all contribute). - // - // IC uses first-fragment/last-fragment read order (not - // forward/reverse strand) and read-oriented cycle indices, - // matching upstream count_indels(). - // ============================================================= - // ============================================================= - // Combined single-CIGAR-pass block for IC/ID (indel distribution), - // bases_mapped_cigar, and COV (coverage ring-buffer pileup). - // - // Both IC/ID and COV apply to the same read set (mapped, - // non-secondary). Merging them into one CIGAR traversal - // eliminates two redundant record.cigar() calls per read. - // - // IC/ID: Upstream samtools stats calls count_indels() outside - // IS_ORIGINAL() — supplementary/dup/qcfail all contribute. - // IC uses first/last-fragment order and read-oriented cycles. - // - // COV: Circular-buffer pileup; buffer flushed up to read start - // before CIGAR walk; M/=/X blocks inserted as ranges. - // Buffer grown to max_read_len * 5 as needed. - // ============================================================= - if is_mapped && !is_secondary { - use rust_htslib::bam::record::Cigar as C; - let is_reverse = flags & BAM_FREVERSE != 0; - let read_len = record.seq_len(); - let tid = record.tid(); - let pos = record.pos(); // 0-based - - // Upstream order: paired ? (read1?FIRST:0)+(read2?LAST:0) : FIRST - let order: u32 = if is_paired { - (if flags & BAM_FREAD1 != 0 { 1 } else { 0 }) - + (if flags & BAM_FREAD2 != 0 { 2 } else { 0 }) - } else { - 1 // unpaired → FIRST - }; - - // COV buffer setup (must happen before CIGAR walk). - // Skip reads with no sequence (upstream samtools early-return). - let do_cov = read_len > 0; - let buf_size = if do_cov { - // Grow buffer to max_read_len * 5 if needed. - // When growing, linearise the circular data just like - // upstream samtools: copy [idx..old_size] then [0..idx] - // into a fresh buffer, and reset idx to 0. - let need = read_len * 5; - if need > self.cov_buf.len() { - let old_size = self.cov_buf.len(); - let mut new_buf = vec![0u32; need]; - let head = old_size - self.cov_buf_idx; - new_buf[..head].copy_from_slice(&self.cov_buf[self.cov_buf_idx..]); - new_buf[head..head + self.cov_buf_idx] - .copy_from_slice(&self.cov_buf[..self.cov_buf_idx]); - self.cov_buf = new_buf; - self.cov_buf_idx = 0; - } - let bs = self.cov_buf.len(); - // Flush entire buffer on chromosome change - if tid != self.cov_buf_tid { - self.flush_cov_buf_all(); - self.cov_buf_tid = tid; - self.cov_buf_pos = pos; - self.cov_buf_idx = 0; - } - // Flush positions from cov_buf_pos up to read start - self.cov_buf_flush_to(pos, bs); - bs - } else { - 0 - }; - - // Single CIGAR traversal serving IC/ID + bases_mapped_cigar + COV - let cigar = record.cigar(); - let mut icycle: usize = 0; - let mut cigar_mapped: u64 = 0; - let mut ref_pos = pos; - - for op in cigar.iter() { - match op { - C::Ins(n) => { - let ncig = *n as usize; - let len = *n as u64; - cigar_mapped += len; // I counts toward bases_mapped_cigar - - // ID: indel size distribution - let id_entry = self.id_hist.entry(len).or_insert([0; 2]); - id_entry[0] += 1; // insertions - - // IC: indels per cycle (read-oriented index) - let idx = if is_reverse { - read_len.saturating_sub(icycle + ncig) - } else { - icycle - }; - if idx >= self.ic.len() { - self.ic.resize(idx + 1, [0u64; 4]); - } - if order == 1 { - self.ic[idx][0] += 1; // ins_1st - } - if order == 2 { - self.ic[idx][1] += 1; // ins_2nd - } - - icycle += ncig; // I advances query cycle; ref unchanged - // COV: I consumes no reference positions - } - C::Del(n) => { - let len = *n as u64; - // ID: indel size distribution - let id_entry = self.id_hist.entry(len).or_insert([0; 2]); - id_entry[1] += 1; // deletions - - // IC: indels per cycle (read-oriented index) - let idx = if is_reverse { - if icycle == 0 { - // Discard meaningless deletions at cycle 0 - // (upstream: "if (idx<0) continue;") - ref_pos += *n as i64; // still advance ref for COV - continue; - } - read_len.saturating_sub(icycle + 1) - } else { - if icycle == 0 { - ref_pos += *n as i64; - continue; - } - icycle - 1 - }; - if idx >= self.ic.len() { - self.ic.resize(idx + 1, [0u64; 4]); - } - if order == 1 { - self.ic[idx][2] += 1; // del_1st - } - if order == 2 { - self.ic[idx][3] += 1; // del_2nd - } - // D does NOT advance query cycle; does advance ref - ref_pos += *n as i64; - } - C::Match(n) | C::Equal(n) | C::Diff(n) => { - let len = *n as u64; - cigar_mapped += len; // M/=/X count toward bases_mapped_cigar - icycle += *n as usize; - // COV: M/=/X consumes reference positions - if do_cov { - let end = ref_pos + *n as i64; - self.cov_buf_insert(ref_pos, end, buf_size); - ref_pos = end; - } else { - ref_pos += *n as i64; - } - } - C::RefSkip(n) => { - ref_pos += *n as i64; // N advances ref (COV skips it) - } - C::SoftClip(n) => { - icycle += *n as usize; // S advances query cycle - // COV: S consumes no reference positions - } - C::HardClip(_) | C::Pad(_) => {} - } - } - self.bases_mapped_cigar += cigar_mapped; - } // if is_mapped && !is_secondary (IC/ID + COV combined) - - // ============================================================= - // GCD: GC-depth accumulation (no-reference path). - // - // Matches upstream samtools stats without --ref-seq: bins of - // GCD_BIN_SIZE bp, depth incremented for each read, GC fraction - // accumulated from the read's sequence. - // - // Included reads: mapped, non-secondary (same as COV). - // - // NOTE: gc_count_for_gcd is set from the primary-read per-cycle - // loop above (when is_primary is true), or computed here only for - // non-primary mapped reads, avoiding a redundant full sequence scan. - // ============================================================= - if is_mapped && !is_secondary { - let tid = record.tid(); - let pos = record.pos(); - let seq_len = record.seq_len(); - - if seq_len > 0 { - // Start a new bin on: first read, chromosome change, or - // read beyond current bin boundary. - let new_bin = self.gcd_pos < 0 - || tid != self.gcd_tid - || pos - self.gcd_pos > GCD_BIN_SIZE as i64; - - if new_bin { - self.gcd_bins.push(GcDepthBin { gc: 0.0, depth: 0 }); - self.gcd_pos = pos; - self.gcd_tid = tid; - } - - // Increment depth and accumulate GC fraction from read seq. - if let Some(bin) = self.gcd_bins.last_mut() { - bin.depth += 1; - // For primary reads, gc_count was already computed in the - // per-cycle base loop above. For non-primary mapped reads - // (supplementary, etc.) compute it here from the sequence. - let gc_count: u32 = if is_primary { - primary_gc_count as u32 - } else { - let seq = record.seq(); - let mut count: u32 = 0; - for i in 0..seq_len { - let base = seq.encoded_base(i); - if base == 2 || base == 4 { - count += 1; - } - } - count - }; - bin.gc += gc_count as f32 / seq_len as f32; - } - } - } // if is_mapped && !is_secondary (GCD) + // ================================================================= + // samtools stats. Secondary records only count towards + // "non-primary alignments" and the CHK checksums above, and records + // without a sequence stop here, as in samtools `collect_stats`. + // ================================================================= + if !is_secondary && seq_len > 0 { + self.process_stats_read(record, flags, seq_len); + } // ================================================================= // RSeQC bam_stat cascade (original logic, with early returns) @@ -1097,86 +642,390 @@ impl BamStatAccum { } } - /// Flush all remaining positions in the coverage round buffer into cov_hist. - /// Must be called after processing all reads (or when switching chromosomes). - /// Flush the circular buffer from `cov_buf_pos` up to (but not including) `pos`. - /// Each slot's depth is recorded in `cov_hist` and the slot is zeroed. - /// Matches upstream `round_buffer_flush` logic from samtools stats.c. - fn cov_buf_flush_to(&mut self, pos: i64, buf_size: usize) { - if pos - self.cov_buf_pos >= buf_size as i64 { - // Gap exceeds buffer size. Match upstream samtools exactly: - // flush `size - 1` positions (from cov_buf_pos to - // cov_buf_pos + size - 2), leaving the LAST slot untouched. - // Then advance idx by `size - 1` and jump pos. - // - // Upstream (stats.c round_buffer_flush lines 334-366): - // pos = rbuf.pos + size - 1; // cap at last slot - // ito = lidx2ridx(start, size, rbuf.pos, pos-1); - // // flush from start to ito (size-1 slots) - // rbuf.start = lidx2ridx(start, size, rbuf.pos, pos); - // rbuf.pos = new_pos; - let flush_count = buf_size - 1; // flush all but the last slot - for _ in 0..flush_count { - let depth = self.cov_buf[self.cov_buf_idx]; - if depth > 0 { - *self.cov_hist.entry(depth).or_insert(0) += 1; - self.cov_buf[self.cov_buf_idx] = 0; + /// samtools stats counters for one non-secondary record with a sequence. + /// + /// Follows `collect_stats` in samtools `stats.c` (1.22.1) with default + /// options: no flag filters, no reference, coordinate-sorted input. + fn process_stats_read(&mut self, record: &bam::Record, flags: u16, seq_len: usize) { + use rust_htslib::bam::record::Cigar as C; + + let is_primary = flags & BAM_FSUPPLEMENTARY == 0; + let is_unmapped = flags & BAM_FUNMAP != 0; + let is_paired = flags & BAM_FPAIRED != 0; + let mate_unmapped = flags & BAM_FMUNMAP != 0; + let tid = record.tid(); + let pos = record.pos(); + let cigar = record.cigar(); + + if flags & BAM_FDUP != 0 { + self.stats_dup_reads += 1; + self.stats_dup_bases += seq_len as u64; + } + + let order = read_order(flags); + + // samtools `unclipped_length`: the sequence plus hard clips. + let read_len = seq_len as u64 + + cigar + .iter() + .map(|op| match op { + C::HardClip(n) => u64::from(*n), + _ => 0, + }) + .sum::(); + self.max_len = self.max_len.max(read_len); + if order == READ_ORDER_FIRST { + self.max_first_fragment_len = self.max_first_fragment_len.max(read_len); + } + if order == READ_ORDER_LAST { + self.max_last_fragment_len = self.max_last_fragment_len.max(read_len); + } + + // MAPQ histogram: !(UNMAP|SECOND|SUPPL|QCFAIL|DUP). + if is_primary && !is_unmapped && flags & (BAM_FQCFAIL | BAM_FDUP) == 0 { + self.mapq_hist[record.mapq() as usize] += 1; + } + + // GC of the read for the GC-depth bins: samtools only computes it for + // primary first/last fragments; other reads add depth with GC 0. + let mut gc_count: u32 = 0; + if is_primary { + *self.rl_hist.entry(read_len).or_insert(0) += 1; + if order == READ_ORDER_FIRST { + *self.frl_hist.entry(read_len).or_insert(0) += 1; + } + if order == READ_ORDER_LAST { + *self.lrl_hist.entry(read_len).or_insert(0) += 1; + } + gc_count = self.collect_orig_read_stats(record, flags, order, seq_len); + } + + if is_unmapped { + return; + } + + self.count_indels(&cigar, flags & BAM_FREVERSE != 0, order, seq_len); + + // Insert size and pair orientation: primary, paired, both mapped. + // Both mates are counted; output halves the counts. + if is_primary && is_paired && !mate_unmapped { + let mtid = record.mtid(); + let isize = record.insert_size().unsigned_abs().min(MAX_INSERT_SIZE); + if isize > 0 || tid == mtid { + let pos_fst = record.mpos() - pos; + let is_fst: i64 = if flags & BAM_FREAD1 != 0 { 1 } else { -1 }; + let is_fwd: i64 = if flags & BAM_FREVERSE != 0 { -1 } else { 1 }; + let is_mfwd: i64 = if flags & BAM_FMREVERSE != 0 { -1 } else { 1 }; + + // orientation index: 1 = inward, 2 = outward, 3 = other + let orientation_idx = if is_fwd * is_mfwd > 0 { + self.other_orientation += 1; + 3usize + } else if is_fst * pos_fst > 0 { + if is_fst * is_fwd > 0 { + self.inward_pairs += 1; + 1 + } else { + self.outward_pairs += 1; + 2 + } + } else if is_fst * pos_fst < 0 { + if is_fst * is_fwd > 0 { + self.outward_pairs += 1; + 2 + } else { + self.inward_pairs += 1; + 1 + } + } else { + // exactly overlapping reads count as inward + self.inward_pairs += 1; + 1 + }; + let entry = self.is_hist.entry(isize).or_insert([0; 4]); + entry[0] += 1; + entry[orientation_idx] += 1; + } + } + + // Mismatches from NM (`bam_aux2i`: signed, non-integer types count 0). + if let Some(nm) = get_aux_int(record, b"NM") { + self.mismatches = self.mismatches.wrapping_add(nm as u64); + } + + // Bases mapped (cigar): M, I, = and X operations. + self.bases_mapped_cigar += cigar + .iter() + .map(|op| match op { + C::Match(n) | C::Ins(n) | C::Equal(n) | C::Diff(n) => u64::from(*n), + _ => 0, + }) + .sum::(); + + // GC-depth bins (no reference): a new bin on the first read, a contig + // change, or a read starting more than GCD_BIN_SIZE past the bin start. + let new_bin = self.gcd_cur.is_none() + || tid != self.gcd_tid + || pos - self.gcd_pos > GCD_BIN_SIZE as i64; + if new_bin { + self.gcd_tid = tid; + self.gcd_pos = pos; + self.gcd_cur = Some(self.gcd_bins.len()); + self.gcd_bins + .push((tid, pos, GcDepthBin { gc: 0.0, depth: 0 })); + } + if let Some((_, _, bin)) = self.gcd_cur.and_then(|i| self.gcd_bins.get_mut(i)) { + bin.depth += 1; + bin.gc += gc_count as f32 / seq_len as f32; + } + + // Coverage distribution: one round buffer per contig (see stats_coverage). + if self.cov_contig.as_ref().is_none_or(|c| c.tid() != tid) { + self.finish_cov_contig(); + self.cov_contig = Some(ContigCoverage::new(tid)); + } + if let Some(cov) = self.cov_contig.as_mut() { + cov.ensure_read_len(read_len as usize); + cov.flush(pos, &mut self.cov_hist); + let mut p = pos; + for op in cigar.iter() { + match op { + C::Match(n) | C::Equal(n) | C::Diff(n) => { + cov.insert(p, p + i64::from(*n)); + p += i64::from(*n); + } + C::Del(n) | C::RefSkip(n) => p += i64::from(*n), + _ => {} + } + } + } + } + + /// samtools `collect_orig_read_stats`: per-read statistics of a primary + /// record with a sequence. Returns the read's G+C count (0 unless it is a + /// first or last fragment). + fn collect_orig_read_stats( + &mut self, + record: &bam::Record, + flags: u16, + order: u8, + seq_len: usize, + ) -> u32 { + self.total_len += seq_len as u64; + if flags & BAM_FQCFAIL != 0 { + self.stats_qcfail += 1; + } + if flags & BAM_FPAIRED != 0 { + self.stats_paired_tech += 1; + } + + let mut gc_count: u32 = 0; + if order == READ_ORDER_FIRST || order == READ_ORDER_LAST { + let is_reverse = flags & BAM_FREVERSE != 0; + let seq = record.seq(); + let quals = record.qual(); + + let (qual_arr, base_arr, base_ro_arr, gc_arr, tc_arr) = if order == READ_ORDER_LAST { + ( + &mut self.lfq, + &mut self.lbc, + &mut self.lbc_ro, + &mut self.gcl, + &mut self.ltc, + ) + } else { + ( + &mut self.ffq, + &mut self.fbc, + &mut self.fbc_ro, + &mut self.gcf, + &mut self.ftc, + ) + }; + + if seq_len > qual_arr.len() { + qual_arr.resize(seq_len, [0u64; 256]); + } + if seq_len > base_arr.len() { + base_arr.resize(seq_len, [0u64; 6]); + } + if seq_len > base_ro_arr.len() { + base_ro_arr.resize(seq_len, [0u64; 6]); + } + if seq_len > self.gcc_rc.len() { + self.gcc_rc.resize(seq_len, [0u64; 4]); + } + + // BAM 4-bit encoding: A=1, C=2, G=4, T=8, N=15, others=0,3,5..14 + // BASE_IDX[nibble] → 0=A, 1=C, 2=G, 3=T, 4=N, 5=Other + const BASE_IDX: [u8; 16] = [5, 0, 1, 5, 2, 5, 5, 5, 3, 5, 5, 5, 5, 5, 5, 4]; + // RC_IDX[base_idx] → reverse-complement base_idx (A↔T, C↔G) + const RC_IDX: [u8; 6] = [3, 2, 1, 0, 4, 5]; + + let mut qual_sum: u64 = 0; + // Hoist the strand branch out of the inner loop. + if !is_reverse { + for i in 0..seq_len { + let q = quals[i]; + qual_sum += u64::from(q); + qual_arr[i][usize::from(q)] += 1; + + let base_idx = BASE_IDX[seq.encoded_base(i) as usize] as usize; + base_arr[i][base_idx] += 1; + base_ro_arr[i][base_idx] += 1; + if base_idx < 4 { + self.gcc_rc[i][base_idx] += 1; + } + if base_idx == 1 || base_idx == 2 { + gc_count += 1; + } + if base_idx < 5 { + tc_arr[base_idx] += 1; + } } - self.cov_buf_idx += 1; - if self.cov_buf_idx >= buf_size { - self.cov_buf_idx = 0; + } else { + for i in 0..seq_len { + let ro_cycle = seq_len - 1 - i; + let q = quals[i]; + qual_sum += u64::from(q); + qual_arr[ro_cycle][usize::from(q)] += 1; + + let base_idx = BASE_IDX[seq.encoded_base(i) as usize] as usize; + base_arr[i][base_idx] += 1; + base_ro_arr[ro_cycle][base_idx] += 1; + if base_idx < 4 { + self.gcc_rc[ro_cycle][RC_IDX[base_idx] as usize] += 1; + } + if base_idx == 1 || base_idx == 2 { + gc_count += 1; + } + if base_idx < 5 { + tc_arr[base_idx] += 1; + } } } - // idx now points to the ONE unflushed slot (the last position - // in the old window). Jump pos to the new read position. - self.cov_buf_pos = pos; + self.quality_sum += qual_sum as f64; + self.quality_count += seq_len as u64; + + // GC content: cumulative step function with ngc = 200 bins. + let ngc: usize = 200; + let gc_idx_min = gc_count as usize * (ngc - 1) / seq_len; + let gc_idx_max = ((gc_count as usize + 1) * (ngc - 1) / seq_len).min(ngc - 1); + for item in gc_arr.iter_mut().take(gc_idx_max).skip(gc_idx_min) { + *item += 1; + } + } + + match order { + READ_ORDER_FIRST => { + self.first_fragments += 1; + self.total_first_fragment_len += seq_len as u64; + } + READ_ORDER_LAST => { + self.last_fragments += 1; + self.total_last_fragment_len += seq_len as u64; + } + _ => self.other_fragments += 1, + } + + if flags & BAM_FUNMAP != 0 { + self.stats_unmapped += 1; } else { - // Normal case: flush slot by slot. - while self.cov_buf_pos < pos { - let depth = self.cov_buf[self.cov_buf_idx]; - if depth > 0 { - *self.cov_hist.entry(depth).or_insert(0) += 1; - self.cov_buf[self.cov_buf_idx] = 0; + self.bases_mapped += seq_len as u64; + if record.mapq() == 0 { + self.reads_mq0 += 1; + } + if flags & BAM_FPAIRED != 0 && flags & BAM_FMUNMAP == 0 { + self.reads_mapped_and_paired += 1; + if flags & BAM_FPROPER_PAIR != 0 { + self.stats_properly_paired += 1; + } + if record.tid() != record.mtid() { + self.stats_anomalous += 1; + } + } + } + gc_count + } + + /// samtools `count_indels`: indel size distribution (ID) and indels per + /// read-oriented cycle (IC) of a mapped, non-secondary record. + fn count_indels( + &mut self, + cigar: &rust_htslib::bam::record::CigarStringView, + is_reverse: bool, + order: u8, + seq_len: usize, + ) { + use rust_htslib::bam::record::Cigar as C; + + let read_len = seq_len as i64; + let mut icycle: i64 = 0; + for op in cigar.iter() { + let ncig = i64::from(op.len()); + if ncig == 0 { + continue; // "curiously, this can happen: 0D" + } + match op { + C::Ins(_) => { + let idx = if is_reverse { + read_len - icycle - ncig + } else { + icycle + }; + if idx >= 0 { + self.add_indel_cycle(idx as usize, order, 0); + } + icycle += ncig; + if ncig <= MAX_INDEL_LEN { + self.id_hist.entry(ncig as u64).or_insert([0; 2])[0] += 1; + } } - self.cov_buf_idx += 1; - if self.cov_buf_idx >= buf_size { - self.cov_buf_idx = 0; + C::Del(_) => { + let idx = if is_reverse { + read_len - icycle - 1 + } else { + icycle - 1 + }; + if idx < 0 { + continue; // samtools discards these "meaningless deletions" + } + self.add_indel_cycle(idx as usize, order, 2); + if ncig <= MAX_INDEL_LEN { + self.id_hist.entry(ncig as u64).or_insert([0; 2])[1] += 1; + } } - self.cov_buf_pos += 1; + C::RefSkip(_) | C::HardClip(_) | C::Pad(_) => {} + _ => icycle += ncig, } } } - /// Insert a contiguous reference range `[from, to)` into the circular buffer, - /// incrementing depth for each position. The range must fit within `buf_size`. - fn cov_buf_insert(&mut self, from: i64, to: i64, buf_size: usize) { - for ref_pos in from..to { - // Map ref_pos to buffer index: offset from cov_buf_idx by (ref_pos - cov_buf_pos) - let offset = (ref_pos - self.cov_buf_pos) as usize; - let idx = (self.cov_buf_idx + offset) % buf_size; - self.cov_buf[idx] += 1; + /// Count an insertion (`kind` 0) or deletion (`kind` 2) at cycle `idx` + /// for first (`+0`) or last (`+1`) fragments. + fn add_indel_cycle(&mut self, idx: usize, order: u8, kind: usize) { + let col = match order { + READ_ORDER_FIRST => kind, + READ_ORDER_LAST => kind + 1, + _ => return, + }; + if idx >= self.ic.len() { + self.ic.resize(idx + 1, [0u64; 4]); } + self.ic[idx][col] += 1; } - /// Flush the entire circular buffer and reset tracking state. - pub fn flush_cov_buf_all(&mut self) { - for slot in self.cov_buf.iter_mut() { - if *slot > 0 { - *self.cov_hist.entry(*slot).or_insert(0) += 1; - *slot = 0; - } + /// End the coverage round buffer of the current contig, if any. + fn finish_cov_contig(&mut self) { + if let Some(cov) = self.cov_contig.take() { + self.cov_done.push(cov.finish(&mut self.cov_hist)); } - self.cov_buf_idx = 0; - self.cov_buf_pos = 0; - self.cov_buf_tid = -1; } /// Merge another accumulator into this one. pub fn merge(&mut self, mut other: BamStatAccum) { - // Flush any remaining positions in the other's round buffer into its - // cov_hist before merging. Without this, positions still in the - // round buffer would be silently lost during parallel merges. - other.flush_cov_buf_all(); + // End the other worker's open contig so its coverage is complete. + other.finish_cov_contig(); // RSeQC bam_stat fields self.total_records += other.total_records; @@ -1236,7 +1085,7 @@ impl BamStatAccum { } self.quality_sum += other.quality_sum; self.quality_count += other.quality_count; - self.mismatches += other.mismatches; + self.mismatches = self.mismatches.wrapping_add(other.mismatches); for (isize_val, counts) in other.is_hist { let entry = self.is_hist.entry(isize_val).or_insert([0; 4]); for i in 0..4 { @@ -1309,8 +1158,21 @@ impl BamStatAccum { *self.cov_hist.entry(depth).or_insert(0) += count; } - // GCD bins (concatenate — bins from different chromosome workers - // are independent and will be sorted during output). + // Finished contigs; the carried slots are resolved in into_result(). + self.cov_done.append(&mut other.cov_done); + + // samtools stats-only counters + self.other_fragments += other.other_fragments; + self.stats_qcfail += other.stats_qcfail; + self.stats_unmapped += other.stats_unmapped; + self.stats_paired_tech += other.stats_paired_tech; + self.stats_properly_paired += other.stats_properly_paired; + self.stats_anomalous += other.stats_anomalous; + self.stats_dup_reads += other.stats_dup_reads; + self.stats_dup_bases += other.stats_dup_bases; + self.flagstat.merge(&other.flagstat); + + // GCD bins (whole contigs per worker; put back in BAM order in into_result()). self.gcd_bins.append(&mut other.gcd_bins); } } @@ -2373,8 +2235,15 @@ fn merge_vec_arrays(target: &mut Vec<[u64; N]>, source: Vec<[u64 impl BamStatAccum { /// Convert accumulated counters into a `BamStatResult` for output. pub fn into_result(mut self) -> BamStatResult { - // Flush remaining positions in the coverage round buffer - self.flush_cov_buf_all(); + // End the last contig and resolve the slots carried between contigs. + self.finish_cov_contig(); + resolve_carries(std::mem::take(&mut self.cov_done), &mut self.cov_hist); + + // GC-depth bins in BAM order (contig, then position): samtools treats + // the last bin specially, so the order must not depend on threads. + self.gcd_bins.sort_by_key(|&(tid, pos, _)| (tid, pos)); + let gcd_bins = self.gcd_bins.into_iter().map(|(_, _, bin)| bin).collect(); + BamStatResult { // RSeQC bam_stat fields total_records: self.total_records, @@ -2451,7 +2320,16 @@ impl BamStatAccum { ic: self.ic, chk: self.chk, cov_hist: self.cov_hist, - gcd_bins: self.gcd_bins, + gcd_bins, + other_fragments: self.other_fragments, + stats_qcfail: self.stats_qcfail, + stats_unmapped: self.stats_unmapped, + stats_paired_tech: self.stats_paired_tech, + stats_properly_paired: self.stats_properly_paired, + stats_anomalous: self.stats_anomalous, + stats_dup_reads: self.stats_dup_reads, + stats_dup_bases: self.stats_dup_bases, + flagstat: self.flagstat, } } } diff --git a/src/rna/rseqc/bam_stat.rs b/src/rna/rseqc/bam_stat.rs index 2cd06acb..6ef012b4 100644 --- a/src/rna/rseqc/bam_stat.rs +++ b/src/rna/rseqc/bam_stat.rs @@ -10,6 +10,8 @@ use std::collections::HashMap; use std::io::Write; use std::path::Path; +use super::flagstat::FlagstatCounts; + // ============================================================================ // Result struct // ============================================================================ @@ -67,9 +69,11 @@ pub struct BamStatResult { pub read1_flagstat: u64, /// Read2 in pair (0x80). pub read2_flagstat: u64, - /// First fragments for samtools stats (read1 or unpaired). + /// samtools stats first fragments: primary reads with a sequence that are + /// unpaired, or paired with only the read1 flag. pub first_fragments: u64, - /// Last fragments for samtools stats (read2). + /// samtools stats last fragments: primary paired reads with a sequence and + /// only the read2 flag. pub last_fragments: u64, /// Properly paired reads (0x1 + 0x2). pub properly_paired: u64, @@ -91,27 +95,28 @@ pub struct BamStatResult { // --- samtools stats SN fields --- /// Sum of query sequence lengths for all primary reads. pub total_len: u64, - /// Sum of first fragment (read1 or unpaired) sequence lengths. + /// Sum of first fragment sequence lengths. pub total_first_fragment_len: u64, - /// Sum of last fragment (read2) sequence lengths. + /// Sum of last fragment sequence lengths. pub total_last_fragment_len: u64, /// Sum of query lengths for mapped primary reads. pub bases_mapped: u64, - /// Sum of M/I/=/X CIGAR operations for mapped primary reads. + /// Sum of M/I/=/X CIGAR operations for mapped non-secondary reads. pub bases_mapped_cigar: u64, /// Sum of query lengths for duplicate-flagged primary reads. pub bases_duplicated: u64, - /// Maximum query sequence length (among primary reads). + /// Maximum read length including hard clips (non-secondary reads). pub max_len: u64, - /// Maximum first-fragment sequence length. + /// Maximum first-fragment read length including hard clips. pub max_first_fragment_len: u64, - /// Maximum last-fragment sequence length. + /// Maximum last-fragment read length including hard clips. pub max_last_fragment_len: u64, - /// Sum of individual base qualities across all primary non-QC-fail reads. + /// Sum of base qualities of primary first and last fragments. pub quality_sum: f64, /// Total number of bases contributing to quality_sum. pub quality_count: u64, - /// Sum of NM tag values across mapped primary reads. + /// Sum of NM tag values across mapped non-secondary reads (two's + /// complement, as samtools adds signed values to an unsigned counter). pub mismatches: u64, /// Insert size with orientation breakdown: abs(TLEN) → [total, inward, outward, other]. /// Both mates contribute; divide by 2 at output to match samtools stats. @@ -130,11 +135,11 @@ pub struct BamStatResult { pub primary_duplicates: u64, /// Number of primary mapped reads with mapping quality 0. pub reads_mq0: u64, - /// Number of primary, non-QC-fail, mapped, paired reads whose mate is also mapped. + /// Number of primary mapped, paired reads whose mate is also mapped. pub reads_mapped_and_paired: u64, // --- samtools stats histogram/distribution fields --- - /// Read length histogram (all primary reads): length → count. + /// Read length histogram (primary reads, length including hard clips): length → count. pub rl_hist: HashMap, /// First fragment read length histogram: length → count. pub frl_hist: HashMap, @@ -142,10 +147,10 @@ pub struct BamStatResult { pub lrl_hist: HashMap, /// MAPQ histogram (primary, mapped, !qcfail, !dup): quality 0-255. pub mapq_hist: [u64; 256], - /// Per-cycle quality for first fragments: outer = cycle, inner = quality bucket counts. - pub ffq: Vec<[u64; 64]>, - /// Per-cycle quality for last fragments: outer = cycle, inner = quality bucket counts. - pub lfq: Vec<[u64; 64]>, + /// Per-cycle quality for first fragments: outer = cycle, inner = count per quality 0-255. + pub ffq: Vec<[u64; 256]>, + /// Per-cycle quality for last fragments: outer = cycle, inner = count per quality 0-255. + pub lfq: Vec<[u64; 256]>, /// GC content step-function for first fragments, 200 bins (samtools ngc=200). pub gcf: [u64; 200], /// GC content step-function for last fragments, 200 bins (samtools ngc=200). @@ -175,8 +180,31 @@ pub struct BamStatResult { pub chk: [u32; 3], /// Coverage distribution: depth → number of reference positions at that depth. pub cov_hist: HashMap, - /// GC-depth bins for the GCD section of samtools stats. + /// GC-depth bins for the GCD section of samtools stats, in BAM order + /// (contig, then position). samtools treats the last bin specially. pub gcd_bins: Vec, + + // --- samtools stats counters without a bam_stat/flagstat equivalent --- + /// Primary reads with a sequence that are neither first nor last fragments. + pub other_fragments: u64, + /// Primary reads with a sequence and the QC-fail flag. + pub stats_qcfail: u64, + /// Primary unmapped reads with a sequence. + pub stats_unmapped: u64, + /// Primary reads with a sequence and the paired flag. + pub stats_paired_tech: u64, + /// Primary reads with a sequence, both mates mapped and the proper-pair flag. + pub stats_properly_paired: u64, + /// Primary reads with a sequence, both mates mapped, mate on another contig. + pub stats_anomalous: u64, + /// Duplicate-flagged non-secondary reads with a sequence. + pub stats_dup_reads: u64, + /// Sequence length of `stats_dup_reads`. + pub stats_dup_bases: u64, + + // --- samtools flagstat --- + /// samtools flagstat counters, split by QC-fail. + pub flagstat: FlagstatCounts, } /// A single GC-depth bin, representing a `gcd_bin_size`-bp window of the genome. @@ -185,7 +213,7 @@ pub struct GcDepthBin { /// Accumulated GC fraction sum (sum of per-read `gc_count / seq_len`). /// Divided by `depth` during output to get the mean GC fraction. pub gc: f32, - /// Number of reads whose start position falls in this bin. + /// Number of mapped, non-secondary reads assigned to this bin. pub depth: u32, } @@ -263,6 +291,15 @@ impl Default for BamStatResult { chk: [0u32; 3], cov_hist: HashMap::new(), gcd_bins: Vec::new(), + other_fragments: 0, + stats_qcfail: 0, + stats_unmapped: 0, + stats_paired_tech: 0, + stats_properly_paired: 0, + stats_anomalous: 0, + stats_dup_reads: 0, + stats_dup_bases: 0, + flagstat: FlagstatCounts::default(), } } } diff --git a/src/rna/rseqc/flagstat.rs b/src/rna/rseqc/flagstat.rs index cb1e370d..8e3c6461 100644 --- a/src/rna/rseqc/flagstat.rs +++ b/src/rna/rseqc/flagstat.rs @@ -10,32 +10,149 @@ use log::debug; use super::bam_stat::BamStatResult; +use crate::rna::bam_flags::*; + // ============================================================================ -// Output formatting +// Counters // ============================================================================ -/// Format a flagstat count line with the standard ` + 0 ` format. -fn fmt_line(count: u64, description: &str) -> String { - format!("{count} + 0 {description}") +/// samtools flagstat counters, each indexed `[QC-passed, QC-failed]`. +/// +/// A direct port of `flagstat_loop` in samtools `bam_stat.c`: every record is +/// counted, split by its QC-fail flag (0x200). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct FlagstatCounts { + /// All records. + pub n_reads: [u64; 2], + /// Primary records (neither secondary nor supplementary). + pub n_primary: [u64; 2], + /// Secondary records (0x100). + pub n_secondary: [u64; 2], + /// Supplementary records (0x800, not secondary). + pub n_supp: [u64; 2], + /// Duplicate records (0x400). + pub n_dup: [u64; 2], + /// Primary duplicate records. + pub n_pdup: [u64; 2], + /// Mapped records. + pub n_mapped: [u64; 2], + /// Primary mapped records. + pub n_pmapped: [u64; 2], + /// Primary records paired in sequencing (0x1). + pub n_pair_all: [u64; 2], + /// Primary paired records that are read1 (0x40). + pub n_read1: [u64; 2], + /// Primary paired records that are read2 (0x80). + pub n_read2: [u64; 2], + /// Primary paired, mapped records with the proper-pair flag (0x2). + pub n_pair_good: [u64; 2], + /// Primary paired records with itself and mate mapped. + pub n_pair_map: [u64; 2], + /// Primary paired records mapped with the mate unmapped. + pub n_sgltn: [u64; 2], + /// `n_pair_map` records whose mate is on a different reference. + pub n_diffchr: [u64; 2], + /// `n_diffchr` records with MAPQ >= 5. + pub n_diffhigh: [u64; 2], +} + +impl FlagstatCounts { + /// Count one record (samtools `flagstat_loop`). + pub fn add(&mut self, flags: u16, tid: i32, mtid: i32, mapq: u8) { + let w = usize::from(flags & BAM_FQCFAIL != 0); + let unmapped = flags & BAM_FUNMAP != 0; + self.n_reads[w] += 1; + if flags & BAM_FSECONDARY != 0 { + self.n_secondary[w] += 1; + } else if flags & BAM_FSUPPLEMENTARY != 0 { + self.n_supp[w] += 1; + } else { + self.n_primary[w] += 1; + if flags & BAM_FPAIRED != 0 { + self.n_pair_all[w] += 1; + if flags & BAM_FPROPER_PAIR != 0 && !unmapped { + self.n_pair_good[w] += 1; + } + if flags & BAM_FREAD1 != 0 { + self.n_read1[w] += 1; + } + if flags & BAM_FREAD2 != 0 { + self.n_read2[w] += 1; + } + let mate_unmapped = flags & BAM_FMUNMAP != 0; + if mate_unmapped && !unmapped { + self.n_sgltn[w] += 1; + } + if !unmapped && !mate_unmapped { + self.n_pair_map[w] += 1; + if mtid != tid { + self.n_diffchr[w] += 1; + if mapq >= 5 { + self.n_diffhigh[w] += 1; + } + } + } + } + if !unmapped { + self.n_pmapped[w] += 1; + } + if flags & BAM_FDUP != 0 { + self.n_pdup[w] += 1; + } + } + if !unmapped { + self.n_mapped[w] += 1; + } + if flags & BAM_FDUP != 0 { + self.n_dup[w] += 1; + } + } + + /// Add another set of counters into this one. + pub fn merge(&mut self, other: &FlagstatCounts) { + let pairs: [(&mut [u64; 2], &[u64; 2]); 16] = [ + (&mut self.n_reads, &other.n_reads), + (&mut self.n_primary, &other.n_primary), + (&mut self.n_secondary, &other.n_secondary), + (&mut self.n_supp, &other.n_supp), + (&mut self.n_dup, &other.n_dup), + (&mut self.n_pdup, &other.n_pdup), + (&mut self.n_mapped, &other.n_mapped), + (&mut self.n_pmapped, &other.n_pmapped), + (&mut self.n_pair_all, &other.n_pair_all), + (&mut self.n_read1, &other.n_read1), + (&mut self.n_read2, &other.n_read2), + (&mut self.n_pair_good, &other.n_pair_good), + (&mut self.n_pair_map, &other.n_pair_map), + (&mut self.n_sgltn, &other.n_sgltn), + (&mut self.n_diffchr, &other.n_diffchr), + (&mut self.n_diffhigh, &other.n_diffhigh), + ]; + for (a, b) in pairs { + a[0] += b[0]; + a[1] += b[1]; + } + } } -/// Format a flagstat percentage as `(XX.XX% : N/A)`. +// ============================================================================ +// Output formatting +// ============================================================================ + +/// samtools `percent()`: `"%.2f%%"` of `(float)n / total * 100.0`, or `N/A`. /// -/// samtools uses `:` separated `passed : failed` percentages. Since we do not -/// separate QC-pass/fail, the failed side is always `N/A`. -fn fmt_pct(numerator: u64, denominator: u64) -> String { - if denominator == 0 { - "(N/A : N/A)".to_string() +/// The division is done in single precision, as in samtools. +fn percent(n: u64, total: u64) -> String { + if total == 0 { + "N/A".to_string() } else { - let pct = 100.0 * numerator as f64 / denominator as f64; - format!("({pct:.2}% : N/A)") + let pct = f64::from(n as f32 / total as f32) * 100.0; + format!("{pct:.2}%") } } -/// Write samtools flagstat-compatible output. -/// -/// The output format matches `samtools flagstat` exactly, with one line per -/// statistic. Each line has the form ` + 0 `. +/// Write samtools flagstat-compatible output (samtools `print_flagstat` text +/// format: ` + ` per line). /// /// # Arguments /// * `result` - The computed BAM statistics @@ -45,112 +162,47 @@ pub fn write_flagstat(result: &BamStatResult, output_path: &Path) -> Result<()> let mut out = std::fs::File::create(output_path) .with_context(|| format!("Failed to create flagstat file: {}", output_path.display()))?; - - // Total = primary + secondary + supplementary (all QC states) - let total = result.total_records; - - // Primary count for percentage denominators - let primary = result.primary_count; - - // Line 1: total (QC-passed + QC-failed) - writeln!( - out, - "{}", - fmt_line(total, "in total (QC-passed reads + QC-failed reads)") - )?; - - // Line 2: primary - writeln!(out, "{}", fmt_line(primary, "primary"))?; - - // Line 3: secondary - writeln!(out, "{}", fmt_line(result.secondary, "secondary"))?; - - // Line 4: supplementary - writeln!(out, "{}", fmt_line(result.supplementary, "supplementary"))?; - - // Line 5: duplicates - writeln!(out, "{}", fmt_line(result.duplicates, "duplicates"))?; - - // Line 6: primary duplicates - writeln!( - out, - "{}", - fmt_line(result.primary_duplicates, "primary duplicates") - )?; - - // Line 7: mapped - writeln!( - out, - "{} {}", - fmt_line(result.mapped, "mapped"), - fmt_pct(result.mapped, total) - )?; - - // Line 8: primary mapped - writeln!( - out, - "{} {}", - fmt_line(result.primary_mapped, "primary mapped"), - fmt_pct(result.primary_mapped, primary) - )?; - - // Line 9: paired in sequencing - writeln!( - out, - "{}", - fmt_line(result.paired_flagstat, "paired in sequencing") - )?; - - // Line 10: read1 - writeln!(out, "{}", fmt_line(result.read1_flagstat, "read1"))?; - - // Line 11: read2 - writeln!(out, "{}", fmt_line(result.read2_flagstat, "read2"))?; - - // Line 12: properly paired (percentage of paired reads) - writeln!( - out, - "{} {}", - fmt_line(result.properly_paired, "properly paired"), - fmt_pct(result.properly_paired, result.paired_flagstat) - )?; - - // Line 13: with itself and mate mapped - writeln!( - out, - "{}", - fmt_line(result.both_mapped, "with itself and mate mapped") - )?; - - // Line 14: singletons (percentage of paired reads) - writeln!( - out, - "{} {}", - fmt_line(result.singletons, "singletons"), - fmt_pct(result.singletons, result.paired_flagstat) - )?; - - // Line 15: with mate mapped to a different chr - writeln!( - out, - "{}", - fmt_line(result.mate_diff_chr, "with mate mapped to a different chr") - )?; - - // Line 16: with mate mapped to a different chr (mapQ>=5) - writeln!( - out, - "{}", - fmt_line( - result.mate_diff_chr_mapq5, - "with mate mapped to a different chr (mapQ>=5)" - ) - )?; + out.write_all(format_flagstat(&result.flagstat).as_bytes())?; debug!("Wrote flagstat output to {}", output_path.display()); Ok(()) } +/// Render flagstat counters in samtools' default text format. +fn format_flagstat(s: &FlagstatCounts) -> String { + let line = |v: &[u64; 2], desc: &str| format!("{} + {} {desc}\n", v[0], v[1]); + let line_pct = |v: &[u64; 2], total: &[u64; 2], desc: &str| { + format!( + "{} + {} {desc} ({} : {})\n", + v[0], + v[1], + percent(v[0], total[0]), + percent(v[1], total[1]) + ) + }; + let mut o = String::new(); + o += &line(&s.n_reads, "in total (QC-passed reads + QC-failed reads)"); + o += &line(&s.n_primary, "primary"); + o += &line(&s.n_secondary, "secondary"); + o += &line(&s.n_supp, "supplementary"); + o += &line(&s.n_dup, "duplicates"); + o += &line(&s.n_pdup, "primary duplicates"); + o += &line_pct(&s.n_mapped, &s.n_reads, "mapped"); + o += &line_pct(&s.n_pmapped, &s.n_primary, "primary mapped"); + o += &line(&s.n_pair_all, "paired in sequencing"); + o += &line(&s.n_read1, "read1"); + o += &line(&s.n_read2, "read2"); + o += &line_pct(&s.n_pair_good, &s.n_pair_all, "properly paired"); + o += &line(&s.n_pair_map, "with itself and mate mapped"); + o += &line_pct(&s.n_sgltn, &s.n_pair_all, "singletons"); + o += &line(&s.n_diffchr, "with mate mapped to a different chr"); + o += &line( + &s.n_diffhigh, + "with mate mapped to a different chr (mapQ>=5)", + ); + o +} + // ============================================================================ // Tests // ============================================================================ @@ -195,4 +247,51 @@ mod tests { "Missing mapped line in flagstat output" ); } + + #[test] + fn percent_divides_in_single_precision() { + // samtools: (float)n / total * 100.0. In double 1/160 prints 0.62%. + assert_eq!(percent(1, 160), "0.63%"); + assert_eq!(percent(7, 160), "4.37%"); + assert_eq!(percent(0, 0), "N/A"); + assert_eq!(percent(5, 5), "100.00%"); + } + + #[test] + fn counts_are_split_by_qc_fail() { + let mut c = FlagstatCounts::default(); + let pe = BAM_FPAIRED | BAM_FREAD1; + c.add(pe | BAM_FPROPER_PAIR, 0, 0, 60); // passed, proper pair + c.add(pe | BAM_FQCFAIL | BAM_FPROPER_PAIR, 0, 1, 60); // failed, mate elsewhere + c.add(pe | BAM_FUNMAP | BAM_FPROPER_PAIR, 0, 0, 0); // unmapped: not proper + c.add(pe | BAM_FMUNMAP | BAM_FDUP, 0, 0, 3); // singleton duplicate + c.add(BAM_FSECONDARY | BAM_FDUP, 0, 0, 0); + c.add(BAM_FSUPPLEMENTARY | BAM_FQCFAIL, 0, 0, 0); + let text = format_flagstat(&c); + let expected = "\ +4 + 2 in total (QC-passed reads + QC-failed reads) +3 + 1 primary +1 + 0 secondary +0 + 1 supplementary +2 + 0 duplicates +1 + 0 primary duplicates +3 + 2 mapped (75.00% : 100.00%) +2 + 1 primary mapped (66.67% : 100.00%) +3 + 1 paired in sequencing +3 + 1 read1 +0 + 0 read2 +1 + 1 properly paired (33.33% : 100.00%) +1 + 1 with itself and mate mapped +1 + 0 singletons (33.33% : 0.00%) +0 + 1 with mate mapped to a different chr +0 + 1 with mate mapped to a different chr (mapQ>=5) +"; + assert_eq!(text, expected); + + let mut merged = FlagstatCounts::default(); + merged.merge(&c); + merged.merge(&c); + assert_eq!(merged.n_reads, [8, 4]); + assert_eq!(merged.n_diffhigh, [0, 2]); + } } diff --git a/src/rna/rseqc/mod.rs b/src/rna/rseqc/mod.rs index 967a2809..c325571d 100644 --- a/src/rna/rseqc/mod.rs +++ b/src/rna/rseqc/mod.rs @@ -18,4 +18,5 @@ pub mod read_distribution; pub mod read_duplication; pub mod split_bam; pub mod stats; +mod stats_coverage; pub mod tin; diff --git a/src/rna/rseqc/stats.rs b/src/rna/rseqc/stats.rs index 20abf8c0..406d892c 100644 --- a/src/rna/rseqc/stats.rs +++ b/src/rna/rseqc/stats.rs @@ -46,17 +46,102 @@ fn fmt_sci(v: f64) -> String { } } -/// Write samtools stats SN-section compatible output. +/// Insert size summary computed like samtools `output_stats`. +struct InsertSizeStats { + /// Per insert size `[inward, outward, other]`, each halved (both mates + /// were counted) and truncated, for insert sizes `0..ibulk`. + rows: Vec<[u64; 3]>, + /// Totals of the halved counts over all insert sizes. + inward: u64, + outward: u64, + other: u64, + avg: f64, + sd: f64, +} + +/// samtools `isize_main_bulk` default, a `float` in samtools. +const ISIZE_MAIN_BULK: f32 = 0.99; +/// samtools insert size cap (`-i`, default 8000). +const MAX_INSERT_SIZE: usize = 8000; + +/// Port of the insert size part of samtools `output_stats`: halve each +/// orientation count, keep the main bulk (99%) of pairs, then compute the +/// mean and the population standard deviation over insert sizes `1..ibulk`. +fn insert_size_stats(is_hist: &HashMap) -> InsertSizeStats { + let mut halved = vec![[0u64; 3]; MAX_INSERT_SIZE + 1]; + for (&isize, counts) in is_hist { + if let Some(row) = halved.get_mut(isize as usize) { + for (half, &count) in row.iter_mut().zip(&counts[1..]) { + *half = (count as f64 * 0.5) as u64; + } + } + } + let (mut inward, mut outward, mut other) = (0u64, 0u64, 0u64); + for row in &halved { + inward += row[0]; + outward += row[1]; + other += row[2]; + } + let mut nisize = inward + outward + other; + + let main_bulk = f64::from(ISIZE_MAIN_BULK); + let mut ibulk = 0usize; + let mut bulk = 0.0f64; + let mut avg = 0.0f64; + for (isize, row) in halved.iter().enumerate() { + let num = row[0] + row[1] + row[2]; + if num > 0 { + ibulk = isize + 1; + } + bulk += num as f64; + avg += (isize as u64 * num) as f64; + if bulk / nisize as f64 > main_bulk { + ibulk = isize + 1; + nisize = bulk as u64; + break; + } + } + let denom = if nisize > 0 { nisize } else { 1 } as f64; + avg /= denom; + let mut sd = 0.0f64; + for (isize, row) in halved.iter().enumerate().take(ibulk).skip(1) { + let num = (row[0] + row[1] + row[2]) as f64; + let diff = isize as f64 - avg; + sd += num * diff * diff / denom; + } + halved.truncate(ibulk); + InsertSizeStats { + rows: halved, + inward, + outward, + other, + avg, + sd: sd.sqrt(), + } +} + +/// `a / b` in single precision, as samtools computes its `float` averages. +fn ratio_f32(a: u64, b: u64) -> f64 { + if b == 0 { + 0.0 + } else { + f64::from(a as f32 / b as f32) + } +} + +/// Write samtools stats compatible output. /// -/// The output starts with a samtools-compatible comment header (important for -/// MultiQC detection) and then emits `SN\t:\t\t# ` lines. +/// The data lines match `samtools stats` (1.22.1) run without options on a +/// coordinate-sorted BAM. The output starts with a samtools-style comment +/// header (MultiQC detects "This file was produced by samtools stats"). /// /// # Arguments /// * `result` - The computed BAM statistics /// * `output_path` - Path to write the stats file pub fn write_stats(result: &BamStatResult, output_path: &Path) -> Result<()> { - let mut out = std::fs::File::create(output_path) + let file = std::fs::File::create(output_path) .with_context(|| format!("Failed to create stats file: {}", output_path.display()))?; + let mut out = std::io::BufWriter::new(file); // Header comment — MultiQC detects "This file was produced by samtools stats" writeln!(out, "# This file was produced by samtools stats and RustQC")?; @@ -65,101 +150,16 @@ pub fn write_stats(result: &BamStatResult, output_path: &Path) -> Result<()> { "# The command line was: rustqc rna (samtools stats compatible output)" )?; - // Derived values - let raw_total = result.primary_count; // primary = non-secondary, non-supplementary - let filtered = result.qc_failed; - - // "sequences" = primary reads that passed QC - let sequences = raw_total.saturating_sub(filtered); + // Reads counted by samtools stats: primary reads with a sequence. + let sequences = result.first_fragments + result.last_fragments + result.other_fragments; + let is = insert_size_stats(&result.is_hist); - // Average lengths — use round() to match samtools' printf("%.0f") behavior - let avg_len = if raw_total > 0 { - (result.total_len as f64 / raw_total as f64).round() - } else { - 0.0 - }; - let avg_first = if result.first_fragments > 0 { - (result.total_first_fragment_len as f64 / result.first_fragments as f64).round() - } else { - 0.0 - }; - let avg_last = if result.last_fragments > 0 { - (result.total_last_fragment_len as f64 / result.last_fragments as f64).round() - } else { - 0.0 - }; - - // Average quality - let avg_quality = if result.quality_count > 0 { - result.quality_sum / result.quality_count as f64 - } else { - 0.0 - }; - - // Insert size stats — 99th percentile truncation matching samtools stats.c. - // Each pair is counted once (upstream mate only), capped at 8000. - // - // Upstream samtools stats.c logic (report_stats, lines 1492-1522): - // 1. nisize = total count across ALL bins (including isize=0) - // 2. Iterate bins: accumulate bulk count and weighted sum. - // Stop (including current bin) when bulk/nisize > 0.99. - // Then nisize = bulk (truncated count). - // 3. mean = weighted_sum / nisize - // 4. SD loop runs from isize=1 to ibulk-1 (skips isize=0): - // sd = sqrt( sum(count[i] * (i - mean)^2) / nisize ) [population SD] - let (avg_insert, insert_sd) = { - let total_count: u64 = result.is_hist.values().map(|v| v[0]).sum(); - if total_count > 0 { - let mut sorted_isizes: Vec<(u64, u64)> = - result.is_hist.iter().map(|(&k, v)| (k, v[0])).collect(); - sorted_isizes.sort_by_key(|&(k, _)| k); - - // Phase 1: Find 99th percentile cutoff and compute mean. - // Include entire bins; stop when cumulative/total > 0.99. - let mut bulk_count = 0u64; - let mut weighted_sum = 0.0f64; - let mut ibulk: u64 = 0; // exclusive upper bound for SD loop - - for &(isize_val, count) in &sorted_isizes { - if count > 0 { - ibulk = isize_val + 1; - } - bulk_count += count; - weighted_sum += isize_val as f64 * count as f64; - - if bulk_count as f64 / total_count as f64 > 0.99 { - break; - } - } - - if bulk_count > 0 { - let mean = weighted_sum / bulk_count as f64; - - // Phase 2: SD — population SD, loop from isize=1 (skip 0). - let mut sd_sum = 0.0f64; - for &(isize_val, count) in &sorted_isizes { - if isize_val == 0 { - continue; // upstream SD loop starts at isize=1 - } - if isize_val >= ibulk { - break; - } - let diff = isize_val as f64 - mean; - sd_sum += count as f64 * diff * diff; - } - let sd = (sd_sum / bulk_count as f64).sqrt(); - (mean, sd) - } else { - (0.0, 0.0) - } - } else { - (0.0, 0.0) - } - }; - - // Error rate = mismatches / bases_mapped_cigar - let error_rate = if result.bases_mapped_cigar > 0 { - result.mismatches as f64 / result.bases_mapped_cigar as f64 + // samtools: (float)nmismatches / nbases_mapped_cigar + let error_rate = ratio_f32(result.mismatches, result.bases_mapped_cigar); + // samtools: float avg_read_length = (float)total_len / sequences + let avg_read_len = ratio_f32(result.total_len, sequences); + let avg_quality = if result.total_len > 0 { + result.quality_sum / result.total_len as f64 } else { 0.0 }; @@ -179,51 +179,43 @@ pub fn write_stats(result: &BamStatResult, output_path: &Path) -> Result<()> { sn( &mut out, "raw total sequences:", - raw_total, + sequences, "excluding supplementary and secondary reads", )?; - sn_no_comment(&mut out, "filtered sequences:", filtered)?; + sn_no_comment(&mut out, "filtered sequences:", 0_u64)?; sn_no_comment(&mut out, "sequences:", sequences)?; sn(&mut out, "is sorted:", 1_u64, "sorted by coordinate")?; sn_no_comment(&mut out, "1st fragments:", result.first_fragments)?; sn_no_comment(&mut out, "last fragments:", result.last_fragments)?; - - // Reads mapped - sn_no_comment(&mut out, "reads mapped:", result.primary_mapped)?; + sn_no_comment(&mut out, "reads mapped:", sequences - result.stats_unmapped)?; sn( &mut out, "reads mapped and paired:", result.reads_mapped_and_paired, "paired-end technology bit set + both mates mapped", )?; - sn_no_comment(&mut out, "reads unmapped:", result.unmapped)?; + sn_no_comment(&mut out, "reads unmapped:", result.stats_unmapped)?; sn( &mut out, "reads properly paired:", - result.properly_paired, + result.stats_properly_paired, "proper-pair bit set", )?; sn( &mut out, "reads paired:", - result.paired_flagstat, + result.stats_paired_tech, "paired-end technology bit set", )?; sn( &mut out, "reads duplicated:", - result.primary_duplicates, + result.stats_dup_reads, "PCR or optical duplicate bit set", )?; sn(&mut out, "reads MQ0:", result.reads_mq0, "mapped and MQ=0")?; - - // Quality and length stats - sn_no_comment(&mut out, "reads QC failed:", filtered)?; - sn_no_comment( - &mut out, - "non-primary alignments:", - result.secondary + result.supplementary, - )?; + sn_no_comment(&mut out, "reads QC failed:", result.stats_qcfail)?; + sn_no_comment(&mut out, "non-primary alignments:", result.secondary)?; sn_no_comment(&mut out, "supplementary alignments:", result.supplementary)?; sn( &mut out, @@ -256,73 +248,92 @@ pub fn write_stats(result: &BamStatResult, output_path: &Path) -> Result<()> { "more accurate", )?; sn_no_comment(&mut out, "bases trimmed:", 0_u64)?; - sn_no_comment(&mut out, "bases duplicated:", result.bases_duplicated)?; - sn(&mut out, "mismatches:", result.mismatches, "from NM fields")?; + sn_no_comment(&mut out, "bases duplicated:", result.stats_dup_bases)?; + // samtools prints the unsigned counter through a (long) cast. + sn( + &mut out, + "mismatches:", + result.mismatches as i64, + "from NM fields", + )?; sn( &mut out, "error rate:", fmt_sci(error_rate), "mismatches / bases mapped (cigar)", )?; - sn_no_comment(&mut out, "average length:", avg_len as u64)?; - sn_no_comment(&mut out, "average first fragment length:", avg_first as u64)?; - sn_no_comment(&mut out, "average last fragment length:", avg_last as u64)?; - sn_no_comment(&mut out, "maximum length:", result.max_len)?; + sn_no_comment(&mut out, "average length:", format!("{avg_read_len:.0}"))?; sn_no_comment( &mut out, - "maximum first fragment length:", - result.max_first_fragment_len, + "average first fragment length:", + format!( + "{:.0}", + ratio_f32(result.total_first_fragment_len, result.first_fragments) + ), )?; sn_no_comment( &mut out, - "maximum last fragment length:", - result.max_last_fragment_len, + "average last fragment length:", + format!( + "{:.0}", + ratio_f32(result.total_last_fragment_len, result.last_fragments) + ), )?; - sn_no_comment(&mut out, "average quality:", fmt_1dp(avg_quality))?; - sn_no_comment(&mut out, "insert size average:", fmt_1dp(avg_insert))?; - sn_no_comment( - &mut out, - "insert size standard deviation:", - fmt_1dp(insert_sd), - )?; - // Orientation counts: both mates are counted, so halve to match samtools. - sn_no_comment(&mut out, "inward oriented pairs:", result.inward_pairs / 2)?; + sn_no_comment(&mut out, "maximum length:", result.max_len)?; sn_no_comment( &mut out, - "outward oriented pairs:", - result.outward_pairs / 2, + "maximum first fragment length:", + result.max_first_fragment_len, )?; sn_no_comment( &mut out, - "pairs with other orientation:", - result.other_orientation / 2, + "maximum last fragment length:", + result.max_last_fragment_len, )?; + sn_no_comment(&mut out, "average quality:", fmt_1dp(avg_quality))?; + sn_no_comment(&mut out, "insert size average:", fmt_1dp(is.avg))?; + sn_no_comment(&mut out, "insert size standard deviation:", fmt_1dp(is.sd))?; + sn_no_comment(&mut out, "inward oriented pairs:", is.inward)?; + sn_no_comment(&mut out, "outward oriented pairs:", is.outward)?; + sn_no_comment(&mut out, "pairs with other orientation:", is.other)?; sn_no_comment( &mut out, "pairs on different chromosomes:", - result.mate_diff_chr_mapq5, + result.stats_anomalous / 2, )?; - - // Percentage stats + // samtools: (float)(100 * nreads_properly_paired) / sequences sn_no_comment( &mut out, "percentage of properly paired reads (%):", - fmt_1dp(if raw_total > 0 { - 100.0 * result.properly_paired as f64 / raw_total as f64 - } else { - 0.0 - }), + fmt_1dp(ratio_f32(100 * result.stats_properly_paired, sequences)), )?; // ================================================================= // Histogram/distribution sections // ================================================================= + // samtools uses one maximum quality for both FFQ and LFQ. + let max_qual = max_quality(&result.ffq).max(max_quality(&result.lfq)); + // FFQ — first fragment quality per cycle - write_ffq_lfq(&mut out, "FFQ", "first fragment", &result.ffq)?; + write_ffq_lfq( + &mut out, + "FFQ", + "first fragment", + &result.ffq, + result.max_first_fragment_len as usize, + max_qual, + )?; // LFQ — last fragment quality per cycle - write_ffq_lfq(&mut out, "LFQ", "last fragment", &result.lfq)?; + write_ffq_lfq( + &mut out, + "LFQ", + "last fragment", + &result.lfq, + result.max_last_fragment_len as usize, + max_qual, + )?; // GCF — GC content of first fragments write_gc_content(&mut out, "GCF", "first fragments", &result.gcf)?; @@ -360,7 +371,7 @@ pub fn write_stats(result: &BamStatResult, output_path: &Path) -> Result<()> { write_total_base_counts(&mut out, "LTC", &result.ltc)?; // IS — insert size with orientation breakdown - write_insert_size(&mut out, &result.is_hist)?; + write_insert_size(&mut out, &is)?; // RL — read length histogram write_length_hist(&mut out, "RL", &result.rl_hist)?; @@ -384,8 +395,9 @@ pub fn write_stats(result: &BamStatResult, output_path: &Path) -> Result<()> { write_coverage_dist(&mut out, &result.cov_hist)?; // GCD — GC-depth - write_gc_depth(&mut out, &result.gcd_bins, result)?; + write_gc_depth(&mut out, &result.gcd_bins, avg_read_len as f32)?; + out.flush()?; debug!("Wrote samtools stats output to {}", output_path.display()); Ok(()) } @@ -415,35 +427,34 @@ fn sn_no_comment( // Histogram/distribution output helpers // ============================================================================ +/// Highest quality with a non-zero count in a per-cycle quality table. +fn max_quality(data: &[[u64; 256]]) -> usize { + data.iter() + .flat_map(|row| row.iter().rposition(|&c| c > 0)) + .max() + .unwrap_or(0) +} + /// Write FFQ or LFQ section (per-cycle quality distribution). /// -/// Each row is a cycle, columns are quality values 0..max_q. +/// Each row is a cycle, columns are qualities `0..=max_qual + 1` (samtools +/// prints one column past the highest quality seen in either fragment). +/// samtools prints a row for every cycle up to the longest read of that +/// fragment, hard clips included; cycles past the stored ones are zero. /// `tag` is "FFQ" or "LFQ", `desc` is "first fragment" or "last fragment". fn write_ffq_lfq( out: &mut W, tag: &str, desc: &str, - data: &[[u64; 64]], + data: &[[u64; 256]], + n_cycles: usize, + max_qual: usize, ) -> Result<()> { - // Determine max quality observed across all cycles. - // Upstream samtools stats bumps max_qual by 1 (stats.c:1616: - // `if (max_qual+1 < nquals) max_qual++`) to include one extra - // trailing zero column beyond the highest observed quality. - let max_q_observed = data - .iter() - .flat_map(|row| { - row.iter() - .enumerate() - .rev() - .find(|(_, &c)| c > 0) - .map(|(i, _)| i) - }) - .max() - .unwrap_or(0); - let max_q = if max_q_observed + 1 < 64 { - max_q_observed + 1 + // stats.c: `if (max_qual+1 < nquals) max_qual++` with nquals = 256 + let max_q = if max_qual + 1 < 256 { + max_qual + 1 } else { - max_q_observed + max_qual }; writeln!( @@ -458,7 +469,9 @@ fn write_ffq_lfq( out, "# Use `plot-bamstats -p ` to generate plots" )?; - for (cycle, row) in data.iter().enumerate() { + const EMPTY: [u64; 256] = [0; 256]; + for cycle in 0..n_cycles { + let row = data.get(cycle).unwrap_or(&EMPTY); write!(out, "{tag}\t{}", cycle + 1)?; // 1-based cycle numbering for &count in row.iter().take(max_q + 1) { write!(out, "\t{count}")?; @@ -588,9 +601,8 @@ fn write_gct( pcts[2], pcts[3] )?; - } else { - writeln!(out, "{tag}\t{}\t0.00\t0.00\t0.00\t0.00", cycle + 1)?; } + // Cycles without A/C/G/T are skipped (samtools `if (!acgt_sum) continue`). } Ok(()) } @@ -657,56 +669,18 @@ fn write_total_base_counts( Ok(()) } -/// Write IS section (insert size with orientation breakdown). -fn write_insert_size( - out: &mut W, - is_hist: &std::collections::HashMap, -) -> Result<()> { +/// Write IS section (insert size with orientation breakdown), for the insert +/// sizes in the main bulk (see [`insert_size_stats`]). +fn write_insert_size(out: &mut W, is: &InsertSizeStats) -> Result<()> { writeln!( out, "# IS, insert size. Use `plot-bamstats -p ` to generate plots" )?; - - if is_hist.is_empty() { - return Ok(()); - } - - // Compute the "main bulk" cutoff matching samtools stats' isize_main_bulk. - // Samtools halves counts (each pair counted twice), then accumulates into - // nisize, then finds the isize where cumulative/nisize > 0.99. - // We compute on the raw (double-counted) histogram using f64 to match - // samtools' 0.5 multiplication (which preserves fractional halves). - const MAX_INSERT_SIZE: u64 = 8000; - - // Halved total (nisize), matching samtools: sum of (count * 0.5) - // across ALL buckets including the overflow cap. - let nisize: f64 = is_hist.values().map(|v| v[0] as f64 * 0.5).sum(); - - let mut bulk: f64 = 0.0; - let mut bulk_limit: u64 = 0; - for isize_val in 0..=MAX_INSERT_SIZE { - let count = is_hist.get(&isize_val).map(|v| v[0]).unwrap_or(0); - if count > 0 { - bulk_limit = isize_val + 1; - } - bulk += count as f64 * 0.5; - if nisize > 0.0 && bulk / nisize > 0.99 { - bulk_limit = isize_val + 1; - break; - } - } - - // Output halved counts (each pair was counted twice). - // Use f64 * 0.5 and round to match samtools' integer truncation. - for isize_val in 0..bulk_limit { - let counts = is_hist.get(&isize_val).copied().unwrap_or([0; 4]); + for (isize, &[inward, outward, other]) in is.rows.iter().enumerate() { writeln!( out, - "IS\t{isize_val}\t{}\t{}\t{}\t{}", - (counts[0] as f64 * 0.5) as u64, - (counts[1] as f64 * 0.5) as u64, - (counts[2] as f64 * 0.5) as u64, - (counts[3] as f64 * 0.5) as u64 + "IS\t{isize}\t{}\t{inward}\t{outward}\t{other}", + inward + outward + other )?; } Ok(()) @@ -869,131 +843,99 @@ fn write_coverage_dist(out: &mut W, cov_hist: &HashMap f64 { - let pos = p as f64 * (n as f64 + 1.0) / 100.0; - let k = pos as usize; - if k == 0 { - return depths[0] as f64; +/// samtools `gcd_percentile`: the `p`-th percentile of the sorted `depths` +/// by linear interpolation, in single precision. +/// +/// The depth difference is an unsigned 32-bit subtraction in samtools; it is +/// kept as such (it can only wrap if a group mixes the raw last bin with a +/// normalised one). +fn gcd_percentile(depths: &[u32], p: u32) -> f32 { + let n_bins = depths.len() as i32; + let n = p as f32 * (n_bins + 1) as f32 / 100.0; + let k = n as i32; + if k <= 0 { + return depths[0] as f32; } - if k >= n { - return depths[n - 1] as f64; + if k >= n_bins { + return depths[(n_bins - 1) as usize] as f32; } - let d = pos - k as f64; - depths[k - 1] as f64 + d * (depths[k] as f64 - depths[k - 1] as f64) + let d = n - k as f32; + let (lo, hi) = (depths[(k - 1) as usize], depths[k as usize]); + lo as f32 + d * hi.wrapping_sub(lo) as f32 +} + +/// samtools `rint(100. * gc / depth)`: mean GC of a bin as a whole percentage, +/// computed in double precision and rounded half to even. +fn gcd_bin_gc_percent(gc: f32, depth: u32) -> f32 { + (100.0 * f64::from(gc) / f64::from(depth)).round_ties_even() as f32 } /// Write the GCD (GC-depth) section. /// -/// Matches upstream `samtools stats` without `--ref-seq`: -/// - Normalise per-bin GC to a percentage (sum of per-read GC fractions / depth) -/// - Sort bins by (gc%, depth) -/// - Group by GC% and compute depth percentiles (10, 25, 50, 75, 90) -/// - Scale depth by avg_read_length / gcd_bin_size +/// Port of samtools `output_stats` without `--ref-seq` (gc_depth_t holds a +/// `float` GC and a `uint32_t` depth; all depth arithmetic is `float`): +/// - The bins are `gcd[1..=igcd]`, with an unused zero bin `gcd[0]` in front. +/// - Every bin except the last (`gcd[igcd]`) gets its GC normalised to a +/// whole percentage; the last keeps its raw sum of per-read GC fractions. +/// - All `igcd + 1` entries are sorted by (GC, depth) and the first `igcd` are +/// printed, grouped by GC (within 0.1), with depth percentiles scaled by +/// `avg_read_len / GCD_BIN_SIZE`. +/// +/// `gcd_bins` must be in BAM order (contig, then position). fn write_gc_depth( out: &mut impl Write, gcd_bins: &[GcDepthBin], - result: &BamStatResult, + avg_read_len: f32, ) -> std::io::Result<()> { - if gcd_bins.is_empty() { - return Ok(()); - } - writeln!( out, "# GC-depth. Use `grep ^GCD | cut -f 2-` to extract this part. \ The columns are: GC%, unique sequence percentiles, 10th, 25th, \ 50th, 75th and 90th depth percentile" )?; + if gcd_bins.is_empty() { + return Ok(()); + } - // Normalise GC: divide accumulated GC sum by depth, then scale to % - // and round to nearest integer. Matches upstream no-reference path. - // Note: samtools normalises only bins 0..igcd-1 (all but the last real bin). - // The last bin keeps its raw accumulated gc fraction completely untouched - // (no rint, no /depth, no *100). This means it sorts as a raw fraction - // (typically < 1.0) and prints as %.1f showing e.g. "0.6". - let last = gcd_bins.len().saturating_sub(1); - let mut bins: Vec<(f32, u32)> = gcd_bins - .iter() - .enumerate() - .map(|(idx, b)| { - let gc_pct = if idx == last { - // Last bin: keep raw gc_sum (not normalised at all, matching upstream) - b.gc - } else if b.depth > 0 { - (100.0 * b.gc / b.depth as f32).round() - } else { - 0.0 - }; - (gc_pct, b.depth) - }) - .collect(); - - // Sort by (gc%, depth) — matches upstream qsort with gcd_cmp. - bins.sort_by(|a, b| { - a.0.partial_cmp(&b.0) - .unwrap_or(std::cmp::Ordering::Equal) - .then(a.1.cmp(&b.1)) - }); - - // Samtools allocates gcd[0] as a zero-depth ghost element that is never - // written to (indices start at 1), so after qsort the ghost sorts to the - // front of the array and is included in the percentile calculations but - // the last real bin is excluded from output. We replicate this by - // prepending a (0.0, 0) ghost element and limiting output to the - // original real bin count. - let real_bins = bins.len(); - bins.insert(0, (0.0f32, 0u32)); - // total for denominator = real_bins + 1 (the ghost) - let total_for_denom = real_bins + 1; - // only output `real_bins` elements (loop over the first `real_bins` of - // the now real_bins+1 sorted entries) - let output_len = real_bins; - - // Average read length for depth scaling (matches samtools: total_len / n_reads). - let avg_read_len = if result.primary_count > 0 { - result.total_len as f64 / result.primary_count as f64 - } else { - 0.0 - }; - let gcd_bin_size = 20_000.0_f64; - let scale = avg_read_len / gcd_bin_size; + let igcd = gcd_bins.len(); + let mut bins: Vec<(f32, u32)> = Vec::with_capacity(igcd + 1); + bins.push((0.0, 0)); // gcd[0] + for (idx, b) in gcd_bins.iter().enumerate() { + let gc = if idx + 1 < igcd && b.depth > 0 { + gcd_bin_gc_percent(b.gc, b.depth) + } else { + b.gc + }; + bins.push((gc, b.depth)); + } + // gcd_cmp: by GC, then depth. Equal entries are identical, so the + // (unstable) qsort order cannot show. + bins.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); + + const GCD_BIN_SIZE: f32 = 20_000.0; + let scale = |depth: f32| f64::from(depth * avg_read_len / GCD_BIN_SIZE); - // Group consecutive bins with the same GC% (within 0.1 tolerance) - // and emit one GCD line per group. let mut i = 0; - while i < output_len { + while i < igcd { let gc = bins[i].0; - let group_start = i; - - // Count bins in this GC% group (only within output_len, not the ghost - // at the end if it happens to sort there). - while i < output_len && (bins[i].0 - gc).abs() < 0.1 { - i += 1; + let mut end = i; + // fabs(float - float) < 0.1 (double) + while end < igcd && f64::from((bins[end].0 - gc).abs()) < 0.1 { + end += 1; } - let nbins = i - group_start; - - // Extract sorted depths for this group (already sorted by the - // secondary sort key above). - let depths: Vec = bins[group_start..i].iter().map(|b| b.1).collect(); - - // Cumulative percentile matches samtools: (igcd_start + nbins + 1) * 100 / (igcd + 1) - // where igcd_start = group_start (0-based), igcd = real_bins (total output bins), - // and total_for_denom = real_bins + 1. - let cum_pct = (group_start + nbins + 1) as f64 * 100.0 / total_for_denom as f64; - + let depths: Vec = bins[i..end].iter().map(|b| b.1).collect(); writeln!( out, "GCD\t{:.1}\t{:.3}\t{:.3}\t{:.3}\t{:.3}\t{:.3}\t{:.3}", - gc, - cum_pct, - gcd_percentile(&depths, nbins, 10) * scale, - gcd_percentile(&depths, nbins, 25) * scale, - gcd_percentile(&depths, nbins, 50) * scale, - gcd_percentile(&depths, nbins, 75) * scale, - gcd_percentile(&depths, nbins, 90) * scale, + f64::from(gc), + (end + 1) as f64 * 100.0 / (igcd + 1) as f64, + scale(gcd_percentile(&depths, 10)), + scale(gcd_percentile(&depths, 25)), + scale(gcd_percentile(&depths, 50)), + scale(gcd_percentile(&depths, 75)), + scale(gcd_percentile(&depths, 90)), )?; + i = end; } Ok(()) @@ -1062,4 +1004,159 @@ mod tests { } } } + + // --- Number formatting: Rust must print like C printf --- + + use std::ffi::{c_char, c_int, CStr, CString}; + + extern "C" { + fn snprintf(buf: *mut c_char, size: usize, fmt: *const c_char, ...) -> c_int; + } + + /// Format one double with the C library's printf. + fn c_fmt(fmt: &str, v: f64) -> String { + let fmt = CString::new(fmt).unwrap(); + let mut buf = vec![0 as c_char; 128]; + // SAFETY: `buf` is writable for its full length, `fmt` is a valid + // C string with exactly one double conversion, and `v` is a double. + let n = unsafe { snprintf(buf.as_mut_ptr(), buf.len(), fmt.as_ptr(), v) }; + assert!(n >= 0 && (n as usize) < buf.len()); + // SAFETY: snprintf NUL-terminated the buffer. + unsafe { CStr::from_ptr(buf.as_ptr()) } + .to_string_lossy() + .into_owned() + } + + /// Deterministic pseudo-random sample of f32-derived values. + fn sample_values() -> Vec { + let mut v = vec![ + 0.0, 0.5, 1.5, 2.5, 74.5, 98.5, 0.25, 0.35, 0.05, 37.25, 0.125, 0.375, 0.0625, 0.0225, + 1e-10, 1.0, 9.9999995, 99.995, 123456.5, + ]; + let mut state = 0x2545F4914F6CDD1Du64; + for _ in 0..20_000 { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + let a = (state >> 40) as u32; + let b = 1 + (state & 0xFFFF) as u32; + v.push(f64::from(a as f32 / b as f32)); + v.push(f64::from((a % 4096) as f32 * 75.0 / 20_000.0)); + v.push(f64::from(a % 1000) / 8.0); + } + v + } + + #[test] + fn fixed_point_formatting_matches_printf() { + for v in sample_values() { + assert_eq!(format!("{v:.0}"), c_fmt("%.0f", v), "%.0f of {v:e}"); + assert_eq!(format!("{v:.1}"), c_fmt("%.1f", v), "%.1f of {v:e}"); + assert_eq!(format!("{v:.2}"), c_fmt("%.2f", v), "%.2f of {v:e}"); + assert_eq!(format!("{v:.3}"), c_fmt("%.3f", v), "%.3f of {v:e}"); + } + } + + #[test] + fn scientific_formatting_matches_printf() { + for v in sample_values() { + assert_eq!(fmt_sci(v), c_fmt("%e", v), "%e of {v:e}"); + } + } + + #[test] + fn error_rate_is_single_precision() { + // sc_pe_rev: samtools prints 8.805891e-03; the double ratio prints ...892. + assert_eq!(fmt_sci(ratio_f32(1558, 176_927)), "8.805891e-03"); + assert_eq!(fmt_sci(1558.0 / 176_927.0), "8.805892e-03"); + assert_eq!(fmt_sci(ratio_f32(0, 0)), "0.000000e+00"); + } + + #[test] + fn gcd_gc_percent_rounds_half_to_even_in_double() { + // rint(): exact halves go to the even neighbour. + assert_eq!(gcd_bin_gc_percent(0.5, 4), 12.0); // 12.5 exactly + assert_eq!(gcd_bin_gc_percent(1.5, 4), 38.0); // 37.5 exactly + assert_eq!(gcd_bin_gc_percent(0.0, 3), 0.0); + // Computed in double from the float sum: 100 * 1.01f / 2 is + // 50.49999952..., while in float 100 * 1.01f rounds to 101.0 and + // the mean would be exactly 50.5. + assert_eq!((100.0f32 * 1.01f32 / 2.0).round(), 51.0); + assert_eq!(gcd_bin_gc_percent(1.01, 2), 50.0); + } + + #[test] + fn gcd_percentile_matches_samtools() { + let d = [1u32, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + // n = p * (N + 1) / 100 = 1.1 → k = 1, d = 0.1 + assert_eq!(gcd_percentile(&d, 10), 1.0 + (1.1f32 - 1.0)); + assert_eq!(gcd_percentile(&d, 50), 5.5); + assert_eq!(gcd_percentile(&d, 90), 9.0 + (9.9f32 - 9.0)); + // k <= 0 → first; k >= N → last + assert_eq!(gcd_percentile(&[7, 9], 10), 7.0); + assert_eq!(gcd_percentile(&[7, 9], 90), 9.0); + assert_eq!(gcd_percentile(&[3], 50), 3.0); + // Unsigned difference wraps like uint32_t in C. + let d = 1.6f32 - 1.0; + assert_eq!( + gcd_percentile(&[5, 3, 1], 40), + 5.0 + d * 3u32.wrapping_sub(5) as f32 + ); + } + + #[test] + fn gcd_last_bin_keeps_raw_gc_and_is_not_printed_alone() { + // Two bins: the first is normalised to 50%, the last keeps its raw + // GC sum (0.9). Sorted with the empty gcd[0] in front, only the first + // igcd = 2 entries are printed, so the 50% bin is left out. + let bins = vec![ + GcDepthBin { gc: 1.0, depth: 2 }, + GcDepthBin { gc: 0.9, depth: 3 }, + ]; + let mut out = Vec::new(); + write_gc_depth(&mut out, &bins, 100.0).unwrap(); + let text = String::from_utf8(out).unwrap(); + let lines: Vec<&str> = text.lines().filter(|l| l.starts_with("GCD")).collect(); + assert_eq!( + lines, + vec![ + "GCD\t0.0\t66.667\t0.000\t0.000\t0.000\t0.000\t0.000", + "GCD\t0.9\t100.000\t0.015\t0.015\t0.015\t0.015\t0.015", + ] + ); + } + + #[test] + fn insert_size_halves_each_orientation() { + let mut h = HashMap::new(); + // isize 0 on the same contig is kept; odd counts truncate per orientation. + h.insert(0u64, [2, 2, 0, 0]); + h.insert(100u64, [6, 3, 3, 0]); + h.insert(101u64, [4, 4, 0, 0]); + let is = insert_size_stats(&h); + assert_eq!(is.inward, 1 + 1 + 2); + assert_eq!(is.outward, 1); + assert_eq!(is.other, 0); + assert_eq!(is.rows.len(), 102); + assert_eq!(is.rows[0], [1, 0, 0]); + assert_eq!(is.rows[100], [1, 1, 0]); + assert_eq!(is.rows[101], [2, 0, 0]); + // mean over all 5 halved pairs: (0 + 2 * 100 + 2 * 101) / 5 + assert!((is.avg - 80.4).abs() < 1e-12); + } + + #[test] + fn insert_size_main_bulk_cut() { + let mut h = HashMap::new(); + h.insert(200u64, [198, 198, 0, 0]); + h.insert(8000u64, [2, 2, 0, 0]); + let is = insert_size_stats(&h); + // 99 of 100 pairs is not > 0.99, so the cap bin is included. + assert_eq!(is.rows.len(), 8001); + h.insert(200u64, [398, 398, 0, 0]); + let is = insert_size_stats(&h); + assert_eq!(is.rows.len(), 201); + assert_eq!(is.avg, 200.0); + assert_eq!(is.sd, 0.0); + } } diff --git a/src/rna/rseqc/stats_coverage.rs b/src/rna/rseqc/stats_coverage.rs new file mode 100644 index 00000000..c64bc011 --- /dev/null +++ b/src/rna/rseqc/stats_coverage.rs @@ -0,0 +1,375 @@ +//! Coverage distribution (`COV` section) for samtools stats output. +//! +//! `samtools stats` builds the coverage histogram with a round buffer that is +//! flushed as reads stream past in coordinate order (`round_buffer_flush` and +//! `round_buffer_insert_read` in samtools `stats.c`). Two quirks of that buffer +//! show up in the output, so they are reproduced here: +//! +//! - A flush to "the end" (`round_buffer_flush(stats, -1)`, called on every +//! contig change and once at end of input) only visits `size - 1` slots. One +//! slot keeps its depth: it is carried into the next contig, where it is +//! counted on that contig's first visit of the slot (on its own, or added to +//! the depth already there), and it is never counted after the last contig. +//! - Reference positions more than `size` bases past the read start (long +//! introns) wrap around and add to the depth of an earlier slot. +//! +//! RustQC splits the BAM by contig across threads, so each contig is simulated +//! on its own from the state samtools starts it with (`start = 0`, `pos = -1`, +//! empty buffer). The slot carried in from the previous contig is resolved in +//! [`resolve_carries`] once all contigs are known: only its first visit in the +//! next contig depends on it. This keeps the result independent of `--threads`. + +use std::collections::HashMap; + +/// Initial round buffer size in samtools: `nbases * 5` with `nbases = 300`. +pub(crate) const INITIAL_BUFFER_SIZE: usize = 1500; + +/// Sentinel for a slot that no flush has visited yet. +const UNVISITED: u32 = u32::MAX; + +/// `round_buffer_lidx2ridx`: buffer slot holding reference position `pos`. +fn lidx2ridx(offset: usize, size: usize, refpos: i64, pos: i64) -> usize { + let size = size as i64; + (offset as i64 + (pos - refpos) % size).rem_euclid(size) as usize +} + +/// Round buffer for one contig, mirroring samtools' `round_buffer_t`. +#[derive(Debug)] +pub(crate) struct ContigCoverage { + tid: i32, + buffer: Vec, + start: usize, + pos: i64, + /// Depth of each slot when a flush first visited it (`UNVISITED` if not yet). + /// Dropped once every slot has been visited. + first_visit: Option>, + /// Non-zero first-visit depths, `(slot, depth)`, filled from `first_visit`. + first_nonzero: Vec<(u32, u32)>, + unvisited: usize, + /// The buffer was enlarged for a long read (slot numbers no longer line up + /// with the contig's initial layout). + grown: bool, +} + +impl ContigCoverage { + /// Start a contig in the state samtools leaves after `round_buffer_flush(-1)`. + pub(crate) fn new(tid: i32) -> Self { + Self { + tid, + buffer: vec![0; INITIAL_BUFFER_SIZE], + start: 0, + pos: -1, + first_visit: Some(vec![UNVISITED; INITIAL_BUFFER_SIZE]), + first_nonzero: Vec::new(), + unvisited: INITIAL_BUFFER_SIZE, + grown: false, + } + } + + pub(crate) fn tid(&self) -> i32 { + self.tid + } + + /// Make room for a read of `read_len` bases (samtools sizes the buffer at + /// five read lengths). Keeps pending depths, linearised from `start`. + pub(crate) fn ensure_read_len(&mut self, read_len: usize) { + let need = read_len * 5; + if need <= self.buffer.len() { + return; + } + let mut new_buf = vec![0u32; need]; + let head = self.buffer.len() - self.start; + new_buf[..head].copy_from_slice(&self.buffer[self.start..]); + new_buf[head..head + self.start].copy_from_slice(&self.buffer[..self.start]); + self.buffer = new_buf; + self.start = 0; + // Slot numbers changed; stop tracking first visits for the carry. + self.take_first_visits(); + self.grown = true; + } + + /// Record the first visit of `slot`, then count and clear its depth. + #[inline] + fn visit(&mut self, slot: usize, hist: &mut HashMap) { + let depth = self.buffer[slot]; + if let Some(first) = self.first_visit.as_mut() { + if first[slot] == UNVISITED { + first[slot] = depth; + self.unvisited -= 1; + if self.unvisited == 0 { + self.take_first_visits(); + } + } + } + if depth != 0 { + *hist.entry(depth).or_insert(0) += 1; + self.buffer[slot] = 0; + } + } + + /// Move the non-zero first visits into `first_nonzero` and stop tracking. + fn take_first_visits(&mut self) { + if let Some(first) = self.first_visit.take() { + self.first_nonzero.extend( + first + .iter() + .enumerate() + .filter(|&(_, &d)| d != UNVISITED && d != 0) + .map(|(slot, &d)| (slot as u32, d)), + ); + } + } + + /// `round_buffer_flush`: count every position before `pos` (`-1` = flush + /// the whole buffer, which visits only `size - 1` slots). + pub(crate) fn flush(&mut self, pos: i64, hist: &mut HashMap) { + if pos == self.pos { + return; + } + let size = self.buffer.len(); + let new_pos = pos; + let mut pos = pos; + if pos == -1 || pos - self.pos >= size as i64 { + pos = self.pos + size as i64 - 1; + } + let mut ifrom = self.start; + let ito = lidx2ridx(self.start, size, self.pos, pos - 1); + if ifrom > ito { + for slot in ifrom..size { + self.visit(slot, hist); + } + ifrom = 0; + } + for slot in ifrom..=ito { + self.visit(slot, hist); + } + self.start = if new_pos == -1 { + 0 + } else { + lidx2ridx(self.start, size, self.pos, pos) + }; + self.pos = new_pos; + } + + /// `round_buffer_insert_read`: add one to the depth of `[from, to)`. + /// + /// Like samtools, a block exactly `size` long adds nothing and positions + /// past the end of the buffer wrap around onto earlier slots. + pub(crate) fn insert(&mut self, from: i64, to: i64) { + let size = self.buffer.len(); + let mut ifrom = lidx2ridx(self.start, size, self.pos, from); + let ito = lidx2ridx(self.start, size, self.pos, to); + if ifrom > ito { + for d in &mut self.buffer[ifrom..] { + *d += 1; + } + ifrom = 0; + } + for d in &mut self.buffer[ifrom..ito] { + *d += 1; + } + } + + /// End the contig the way samtools does on a contig change or at end of + /// input: `round_buffer_flush(-1)`, which leaves one slot unflushed. + pub(crate) fn finish(mut self, hist: &mut HashMap) -> ContigCovSummary { + let size = self.buffer.len(); + let end_slot = (self.start + size - 1) % size; + let end_slot_visited = match &self.first_visit { + Some(first) => first[end_slot] != UNVISITED, + None => true, + }; + self.flush(-1, hist); + let end_depth = self.buffer[end_slot]; + self.take_first_visits(); + self.first_nonzero.sort_unstable(); + ContigCovSummary { + tid: self.tid, + first_nonzero: self.first_nonzero, + end_slot: end_slot as u32, + end_depth, + end_slot_visited, + grown: self.grown, + } + } +} + +/// What the next contig needs from a finished contig to resolve the slot +/// samtools carries across the contig change. +#[derive(Debug, Clone)] +pub(crate) struct ContigCovSummary { + tid: i32, + /// Slots whose first visit saw a non-zero depth, sorted by slot. + first_nonzero: Vec<(u32, u32)>, + /// The slot left unflushed at the end of the contig, and its depth. + end_slot: u32, + end_depth: u32, + /// Whether `end_slot` was visited before the final flush. + end_slot_visited: bool, + grown: bool, +} + +/// Apply the carried slots between consecutive contigs (in BAM order, i.e. +/// ascending tid for a coordinate-sorted BAM) to `hist`. The depth left in the +/// buffer after the last contig is dropped, as in samtools. +pub(crate) fn resolve_carries(mut contigs: Vec, hist: &mut HashMap) { + contigs.sort_by_key(|c| c.tid); + let mut carry: Option<(u32, u32, bool)> = None; // (slot, depth, grown) + for contig in &mut contigs { + if let Some((slot, depth, prev_grown)) = carry { + // A grown buffer has a different slot layout; the carry cannot be + // mapped (and samtools' own buffer resize loses pending depths). + if depth > 0 && !prev_grown && !contig.grown { + if slot == contig.end_slot && !contig.end_slot_visited { + contig.end_depth += depth; + } else { + match contig + .first_nonzero + .binary_search_by_key(&slot, |&(s, _)| s) + { + Ok(i) => { + let first = contig.first_nonzero[i].1; + if let Some(n) = hist.get_mut(&first) { + *n -= 1; + if *n == 0 { + hist.remove(&first); + } + } + *hist.entry(first + depth).or_insert(0) += 1; + } + Err(_) => *hist.entry(depth).or_insert(0) += 1, + } + } + } + } + carry = Some((contig.end_slot, contig.end_depth, contig.grown)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Straight port of samtools' round buffer over a whole BAM (one global + /// buffer, contig changes flush with -1). Reads are `(tid, [(from, to)])`. + fn reference_hist(reads: &[(i32, Vec<(i64, i64)>)]) -> HashMap { + let mut hist = HashMap::new(); + let mut buf = ContigCoverage::new(-1); + buf.first_visit = None; + buf.pos = 0; // calloc'd stats struct + let mut tid = -1; + for (t, blocks) in reads { + if tid == -1 || tid != *t { + buf.flush(-1, &mut hist); + tid = *t; + } + buf.flush(blocks[0].0, &mut hist); + for &(from, to) in blocks { + buf.insert(from, to); + } + } + buf.flush(-1, &mut hist); + hist + } + + /// The per-contig simulation plus carry resolution, as the accumulator uses it. + fn split_hist(reads: &[(i32, Vec<(i64, i64)>)]) -> HashMap { + let mut hist = HashMap::new(); + let mut done = Vec::new(); + let mut cur: Option = None; + for (t, blocks) in reads { + if cur.as_ref().is_some_and(|c| c.tid() != *t) { + done.push(cur.take().unwrap().finish(&mut hist)); + } + let c = cur.get_or_insert_with(|| ContigCoverage::new(*t)); + c.flush(blocks[0].0, &mut hist); + for &(from, to) in blocks { + c.insert(from, to); + } + } + if let Some(c) = cur { + done.push(c.finish(&mut hist)); + } + resolve_carries(done, &mut hist); + hist + } + + #[test] + fn last_slot_is_not_counted_at_end_of_input() { + // A spliced read whose second block ends exactly on the last buffer + // slot: samtools never counts that slot's position. + let reads = vec![(0, vec![(100, 150), (100 + 1499, 100 + 1500)])]; + let hist = reference_hist(&reads); + assert_eq!(hist.get(&1), Some(&50)); + assert_eq!(split_hist(&reads), hist); + } + + #[test] + fn carried_slot_is_counted_in_next_contig() { + // Same read, then a second contig: the unflushed slot is carried and + // counted while flushing the next contig. + let reads = vec![ + (0, vec![(100, 150), (1599, 1600)]), + (1, vec![(10, 60)]), + (1, vec![(2000, 2050)]), + ]; + let hist = reference_hist(&reads); + assert_eq!(split_hist(&reads), hist); + // 50 + 1 (carried) + 50 + 50 positions at depth 1. + assert_eq!(hist.get(&1), Some(&151)); + assert_eq!(hist.len(), 1); + } + + #[test] + fn carry_adds_to_depth_in_next_contig() { + // The carried slot lands on a position the next contig also covers. + for shift in [0i64, 1, 5, 700, 1497, 1498, 1499, 1500, 3000] { + let reads = vec![ + (0, vec![(0, 10), (1499, 1500)]), + (2, vec![(shift, shift + 75)]), + (2, vec![(shift + 3, shift + 78)]), + ]; + assert_eq!(split_hist(&reads), reference_hist(&reads), "shift {shift}"); + } + } + + #[test] + fn wrapped_blocks_and_gaps_match_reference() { + // Pseudo-random spliced reads on three contigs, including intron + // lengths that wrap the buffer and gaps larger than the buffer. + let mut state = 12345u64; + let mut next = |m: u64| { + state = state + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (state >> 33) % m + }; + let mut reads = Vec::new(); + for tid in 0..3 { + let mut pos = next(3000) as i64; + for _ in 0..2000 { + let max_gap = if next(10) == 0 { 5000 } else { 40 }; + pos += next(max_gap) as i64; + let len = 1 + next(75) as i64; + let mut blocks = vec![(pos, pos + len)]; + if next(3) == 0 { + let intron = next(4000) as i64; + let s = pos + len + intron; + blocks.push((s, s + 1 + next(75) as i64)); + } + reads.push((tid, blocks)); + } + } + assert_eq!(split_hist(&reads), reference_hist(&reads)); + } + + #[test] + fn block_of_exactly_buffer_size_adds_nothing() { + let mut c = ContigCoverage::new(0); + let mut hist = HashMap::new(); + c.flush(0, &mut hist); + c.insert(0, INITIAL_BUFFER_SIZE as i64); + c.finish(&mut hist); + assert!(hist.is_empty()); + } +} From 5b47fd93d66c15e20515b8abdc7c066f44d7e814 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rayan=20Hassa=C3=AFne?= Date: Thu, 26 Nov 2026 16:12:04 +0100 Subject: [PATCH 2/2] fix(samtools): secondary beats supplementary in stats; pin flagstat and stats on every flag samtools gives SECONDARY priority over SUPPLEMENTARY in `flagstat_loop` (bam_stat.c) and in `stats.c`: a record carrying both flags is secondary only. The flagstat writer already did this through `FlagstatCounts`, but the per-field counters behind `samtools stats` still counted such a record as secondary and as supplementary, so `SN supplementary alignments` was too high (3072 against samtools' 6144 on the all-flags input below). Use `else if`, so primary + secondary + supplementary == total. Add the regression tests that expose it, all checked against samtools 1.22.1 (bioconda build h96c455f_0): - all 4096 flag values in three mate placements: flagstat and the `SN` section of stats against samtools-generated golden files, on the serial and the per-contig parallel path (integration test); - one flagged record between two plain reads for QC-failed, QC-failed duplicate, secondary+supplementary, QC-failed 0xf00 and the "properly paired needs a mapped read" case (0x4f); - unit tests against a transcription of samtools' flagstat_loop for every flag and placement, merged and partitioned counters, dual flags with QC-fail and duplicate, and large-count percentage rounding (expected strings produced by compiling samtools' percent() unchanged). The test cases and the semantics they pin come from seqeralabs/RustQC#175 (Nico DeVeaux) and #131 (Benjamin Demaille). Co-authored-by: Nico DeVeaux <105398+NicoDeVeaux@users.noreply.github.com> Co-authored-by: Benjamin Demaille <41732816+BenjaminDEMAILLE@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- src/rna/rseqc/accumulators.rs | 9 +- src/rna/rseqc/bam_stat.rs | 2 +- src/rna/rseqc/flagstat.rs | 306 +++++++++++++++++++++ tests/expected/samtools/README.md | 16 ++ tests/expected/samtools/all_flags.flagstat | 16 ++ tests/expected/samtools/all_flags.stats.sn | 39 +++ tests/integration_test.rs | 281 +++++++++++++++++++ 7 files changed, 665 insertions(+), 4 deletions(-) create mode 100644 tests/expected/samtools/README.md create mode 100644 tests/expected/samtools/all_flags.flagstat create mode 100644 tests/expected/samtools/all_flags.stats.sn diff --git a/src/rna/rseqc/accumulators.rs b/src/rna/rseqc/accumulators.rs index 666b8886..776e0498 100644 --- a/src/rna/rseqc/accumulators.rs +++ b/src/rna/rseqc/accumulators.rs @@ -180,7 +180,8 @@ pub struct BamStatAccum { // --- samtools flagstat additional fields --- /// Secondary alignments (0x100) — counted independently of QC/dup. pub secondary: u64, - /// Supplementary alignments (0x800) — counted independently of QC/dup. + /// Supplementary alignments (0x800) that are not also secondary, as in + /// samtools (SECONDARY takes priority) — independent of QC/dup. pub supplementary: u64, /// All mapped records (not 0x4), regardless of QC/dup. pub mapped: u64, @@ -462,10 +463,12 @@ impl BamStatAccum { // `flagstat` is what the flagstat output uses; the individual fields // are kept for the library API. // ================================================================= + // SECONDARY takes priority over SUPPLEMENTARY, as in samtools + // `flagstat_loop` and `stats.c`: a record with both flags is secondary + // only, so `primary + secondary + supplementary == total`. if is_secondary { self.secondary += 1; - } - if is_supplementary { + } else if is_supplementary { self.supplementary += 1; } if is_mapped { diff --git a/src/rna/rseqc/bam_stat.rs b/src/rna/rseqc/bam_stat.rs index 6ef012b4..c72b7505 100644 --- a/src/rna/rseqc/bam_stat.rs +++ b/src/rna/rseqc/bam_stat.rs @@ -59,7 +59,7 @@ pub struct BamStatResult { // --- samtools flagstat fields --- /// Secondary alignments (0x100). pub secondary: u64, - /// Supplementary alignments (0x800). + /// Supplementary alignments (0x800) that are not also secondary (0x100). pub supplementary: u64, /// All mapped records (not 0x4). pub mapped: u64, diff --git a/src/rna/rseqc/flagstat.rs b/src/rna/rseqc/flagstat.rs index 8e3c6461..750b2fbb 100644 --- a/src/rna/rseqc/flagstat.rs +++ b/src/rna/rseqc/flagstat.rs @@ -294,4 +294,310 @@ mod tests { assert_eq!(merged.n_reads, [8, 4]); assert_eq!(merged.n_diffhigh, [0, 2]); } + + // ------------------------------------------------------------------------ + // Oracle: samtools 1.22.1 `flagstat_loop` and `out_fmt_default` + // (bam_stat.c), transcribed independently of `FlagstatCounts`. + // Test cases adapted from seqeralabs/RustQC#175 (Nico DeVeaux). + // ------------------------------------------------------------------------ + + /// samtools' `bam_flagstat_t`; index 0 is QC-passed, 1 is QC-failed. + #[derive(Debug, Default)] + struct SamtoolsFlagstat { + n_reads: [u64; 2], + n_mapped: [u64; 2], + n_pair_all: [u64; 2], + n_pair_map: [u64; 2], + n_pair_good: [u64; 2], + n_sgltn: [u64; 2], + n_read1: [u64; 2], + n_read2: [u64; 2], + n_dup: [u64; 2], + n_diffchr: [u64; 2], + n_diffhigh: [u64; 2], + n_secondary: [u64; 2], + n_supp: [u64; 2], + n_primary: [u64; 2], + n_pmapped: [u64; 2], + n_pdup: [u64; 2], + } + + impl SamtoolsFlagstat { + fn add(&mut self, flag: u16, tid: i32, mtid: i32, qual: u8) { + let w = usize::from(flag & BAM_FQCFAIL != 0); + self.n_reads[w] += 1; + if flag & BAM_FSECONDARY != 0 { + self.n_secondary[w] += 1; + } else if flag & BAM_FSUPPLEMENTARY != 0 { + self.n_supp[w] += 1; + } else { + self.n_primary[w] += 1; + if flag & BAM_FPAIRED != 0 { + self.n_pair_all[w] += 1; + if flag & BAM_FPROPER_PAIR != 0 && flag & BAM_FUNMAP == 0 { + self.n_pair_good[w] += 1; + } + if flag & BAM_FREAD1 != 0 { + self.n_read1[w] += 1; + } + if flag & BAM_FREAD2 != 0 { + self.n_read2[w] += 1; + } + if flag & BAM_FMUNMAP != 0 && flag & BAM_FUNMAP == 0 { + self.n_sgltn[w] += 1; + } + if flag & BAM_FUNMAP == 0 && flag & BAM_FMUNMAP == 0 { + self.n_pair_map[w] += 1; + if mtid != tid { + self.n_diffchr[w] += 1; + if qual >= 5 { + self.n_diffhigh[w] += 1; + } + } + } + } + if flag & BAM_FUNMAP == 0 { + self.n_pmapped[w] += 1; + } + if flag & BAM_FDUP != 0 { + self.n_pdup[w] += 1; + } + } + if flag & BAM_FUNMAP == 0 { + self.n_mapped[w] += 1; + } + if flag & BAM_FDUP != 0 { + self.n_dup[w] += 1; + } + } + + fn render(&self) -> String { + // samtools computes `(float)n / total * 100.0`. + fn percent(n: u64, total: u64) -> String { + if total == 0 { + "N/A".to_string() + } else { + format!("{:.2}%", f64::from(n as f32 / total as f32) * 100.0) + } + } + let line = |c: [u64; 2], d: &str| format!("{} + {} {d}\n", c[0], c[1]); + let pct = |c: [u64; 2], t: [u64; 2], d: &str| { + format!( + "{} + {} {d} ({} : {})\n", + c[0], + c[1], + percent(c[0], t[0]), + percent(c[1], t[1]) + ) + }; + [ + line(self.n_reads, "in total (QC-passed reads + QC-failed reads)"), + line(self.n_primary, "primary"), + line(self.n_secondary, "secondary"), + line(self.n_supp, "supplementary"), + line(self.n_dup, "duplicates"), + line(self.n_pdup, "primary duplicates"), + pct(self.n_mapped, self.n_reads, "mapped"), + pct(self.n_pmapped, self.n_primary, "primary mapped"), + line(self.n_pair_all, "paired in sequencing"), + line(self.n_read1, "read1"), + line(self.n_read2, "read2"), + pct(self.n_pair_good, self.n_pair_all, "properly paired"), + line(self.n_pair_map, "with itself and mate mapped"), + pct(self.n_sgltn, self.n_pair_all, "singletons"), + line(self.n_diffchr, "with mate mapped to a different chr"), + line( + self.n_diffhigh, + "with mate mapped to a different chr (mapQ>=5)", + ), + ] + .concat() + } + } + + /// (tid, mtid, mapq) placements: mate on the same contig, mate on another + /// contig, mate on another contig with MAPQ below 5. + const PLACEMENTS: [(i32, i32, u8); 3] = [(0, 0, 60), (0, 1, 60), (1, 0, 3)]; + + fn record(flag: u16, (tid, mtid, mapq): (i32, i32, u8)) -> bam::Record { + use rust_htslib::bam::record::{Cigar, CigarString}; + let mut rec = bam::Record::new(); + rec.set( + b"r", + Some(&CigarString(vec![Cigar::Match(4)])), + b"ACGT", + &[30; 4], + ); + rec.set_flags(flag); + rec.set_tid(tid); + rec.set_pos(9); + rec.set_mtid(mtid); + rec.set_mpos(9); + rec.set_mapq(mapq); + rec + } + + fn render_flagstat(accum: BamStatAccum, name: &str) -> String { + let path = std::env::temp_dir().join(format!( + "rustqc_test_flagstat_{name}_{}.txt", + std::process::id() + )); + write_flagstat(&accum.into_result(), &path).expect("Failed to write flagstat"); + let contents = std::fs::read_to_string(&path).unwrap(); + let _ = std::fs::remove_file(&path); + contents + } + + /// Each of the 4,096 flags alone, in every placement, against the oracle. + #[test] + fn flagstat_matches_samtools_flagstat_loop_per_flag() { + let mut mismatches = Vec::new(); + for placement in PLACEMENTS { + for flag in 0..4096u16 { + let mut accum = BamStatAccum::default(); + accum.process_read(&record(flag, placement), 30); + let mut oracle = SamtoolsFlagstat::default(); + oracle.add(flag, placement.0, placement.1, placement.2); + + let got = render_flagstat(accum, "per_flag"); + let want = oracle.render(); + if got != want { + let diff: Vec = want + .lines() + .zip(got.lines()) + .filter(|(w, g)| w != g) + .map(|(w, g)| format!("want `{w}`, got `{g}`")) + .collect(); + mismatches.push(format!("{flag:#06x} {placement:?}: {}", diff.join("; "))); + } + } + } + assert!( + mismatches.is_empty(), + "{} of {} (flag, placement) cases differ from samtools' flagstat_loop; first:\n{}", + mismatches.len(), + 4096 * PLACEMENTS.len(), + mismatches[..mismatches.len().min(8)].join("\n") + ); + } + + /// All flags and placements in one file, split across two merged + /// accumulators as the per-contig parallel path does. + #[test] + fn flagstat_matches_samtools_flagstat_loop_merged() { + let mut parts = [BamStatAccum::default(), BamStatAccum::default()]; + let mut oracle = SamtoolsFlagstat::default(); + for placement in PLACEMENTS { + for flag in 0..4096u16 { + parts[placement.0 as usize].process_read(&record(flag, placement), 30); + oracle.add(flag, placement.0, placement.1, placement.2); + } + } + let [mut accum, other] = parts; + accum.merge(other); + assert_eq!(render_flagstat(accum, "merged"), oracle.render()); + } + + /// Dual-flagged records (secondary + supplementary), QC-failed and + /// duplicated: counted once, as secondary, in the right column, in both the + /// flagstat counters and the legacy per-field counters used by `stats`. + #[test] + fn flagstat_dual_flags_with_qcfail_and_duplicate() { + let mut accum = BamStatAccum::default(); + let mut direct = FlagstatCounts::default(); + let flags = [ + 0, + BAM_FDUP, + BAM_FSECONDARY, + BAM_FSUPPLEMENTARY, + BAM_FSECONDARY | BAM_FSUPPLEMENTARY, + BAM_FSECONDARY | BAM_FSUPPLEMENTARY | BAM_FDUP, + ]; + for qc in [0, BAM_FQCFAIL] { + for flag in flags { + let flag = flag | qc; + accum.process_read(&record(flag, PLACEMENTS[0]), 30); + direct.add(flag, 0, 0, 60); + } + } + for fs in [&accum.flagstat, &direct] { + assert_eq!(fs.n_reads, [6, 6]); + assert_eq!(fs.n_primary, [2, 2]); + assert_eq!(fs.n_secondary, [3, 3]); + assert_eq!(fs.n_supp, [1, 1]); + assert_eq!(fs.n_dup, [2, 2]); + assert_eq!(fs.n_pdup, [1, 1]); + assert_eq!(fs.n_mapped, [6, 6]); + assert_eq!(fs.n_pmapped, [2, 2]); + for w in 0..2 { + assert_eq!( + fs.n_primary[w] + fs.n_secondary[w] + fs.n_supp[w], + fs.n_reads[w] + ); + } + } + let result = accum.into_result(); + assert_eq!(result.total_records, 12); + assert_eq!(result.primary_count, 4); + assert_eq!(result.secondary, 6); + assert_eq!(result.supplementary, 2); + assert_eq!( + result.primary_count + result.secondary + result.supplementary, + result.total_records + ); + } + + #[test] + fn flagstat_partitioned_counts_match_serial() { + for partitions in [1, 2, 7, 31] { + let mut parts = vec![FlagstatCounts::default(); partitions]; + let mut oracle = SamtoolsFlagstat::default(); + for (i, (flag, placement)) in (0..4096u16) + .flat_map(|flag| PLACEMENTS.map(|placement| (flag, placement))) + .enumerate() + { + parts[i % partitions].add(flag, placement.0, placement.1, placement.2); + oracle.add(flag, placement.0, placement.1, placement.2); + } + let mut merged = FlagstatCounts::default(); + for part in parts.into_iter().rev() { + merged.merge(&part); + } + for w in 0..2 { + assert_eq!( + merged.n_primary[w] + merged.n_secondary[w] + merged.n_supp[w], + merged.n_reads[w] + ); + } + let mut accum = BamStatAccum::default(); + accum.flagstat.merge(&merged); + assert_eq!( + render_flagstat(accum, "partitioned"), + oracle.render(), + "{partitions} partitions" + ); + } + } + + #[test] + fn large_counter_percentages_match_samtools_c() { + // samtools 1.22.1 bam_stat.c percent(): + // sprintf(buffer, "%.2f%%", (float)n / total * 100.0). + // Expected strings were checked by compiling that C function unchanged. + let cases = [ + (0, 0, "N/A"), + (0, 1_000_000_000, "0.00%"), + (1, 32, "3.12%"), + (1, 6, "16.67%"), + (16_777_217, 16_777_218, "100.00%"), + (500_049_999, 1_000_000_000, "50.01%"), + (999_950_000, 1_000_000_000, "99.99%"), + (499_050_000, 1_000_000_000, "49.90%"), + (499_150_000, 1_000_000_000, "49.92%"), + (i64::MAX as u64 - 1, i64::MAX as u64, "100.00%"), + ]; + for (n, d, expected) in cases { + assert_eq!(percent(n, d), expected, "{n}/{d}"); + } + } } diff --git a/tests/expected/samtools/README.md b/tests/expected/samtools/README.md new file mode 100644 index 00000000..6f95968c --- /dev/null +++ b/tests/expected/samtools/README.md @@ -0,0 +1,16 @@ +# samtools reference outputs + +`all_flags.flagstat` and `all_flags.stats.sn` are `samtools flagstat` and the `SN` lines of +`samtools stats` from samtools 1.22.1 (bioconda build `h96c455f_0`) for the records +`all_flags_sam_lines()` in `tests/integration_test.rs` writes: all 4096 flag values in three +mate placements. To regenerate: + +```bash +{ printf '@HD\tVN:1.6\tSO:coordinate\n@SQ\tSN:chr1\tLN:1000\n@SQ\tSN:chr2\tLN:1000\n' + awk 'BEGIN{for(f=0;f<4096;f++){printf "f%da\t%d\tchr1\t10\t60\t4M\t=\t10\t0\tACGT\tIIII\n",f,f; printf "f%db\t%d\tchr1\t10\t60\t4M\tchr2\t10\t0\tACGT\tIIII\n",f,f}; for(f=0;f<4096;f++) printf "f%dc\t%d\tchr2\t10\t3\t4M\tchr1\t10\t0\tACGT\tIIII\n",f,f}' +} > all_flags.sam +samtools flagstat all_flags.sam > tests/expected/samtools/all_flags.flagstat +samtools stats all_flags.sam | grep '^SN' > tests/expected/samtools/all_flags.stats.sn +``` + +Do not edit these files by hand. diff --git a/tests/expected/samtools/all_flags.flagstat b/tests/expected/samtools/all_flags.flagstat new file mode 100644 index 00000000..7ddfb9b7 --- /dev/null +++ b/tests/expected/samtools/all_flags.flagstat @@ -0,0 +1,16 @@ +6144 + 6144 in total (QC-passed reads + QC-failed reads) +1536 + 1536 primary +3072 + 3072 secondary +1536 + 1536 supplementary +3072 + 3072 duplicates +768 + 768 primary duplicates +3072 + 3072 mapped (50.00% : 50.00%) +768 + 768 primary mapped (50.00% : 50.00%) +768 + 768 paired in sequencing +384 + 384 read1 +384 + 384 read2 +192 + 192 properly paired (25.00% : 25.00%) +192 + 192 with itself and mate mapped +192 + 192 singletons (25.00% : 25.00%) +128 + 128 with mate mapped to a different chr +64 + 64 with mate mapped to a different chr (mapQ>=5) diff --git a/tests/expected/samtools/all_flags.stats.sn b/tests/expected/samtools/all_flags.stats.sn new file mode 100644 index 00000000..29b7a369 --- /dev/null +++ b/tests/expected/samtools/all_flags.stats.sn @@ -0,0 +1,39 @@ +SN raw total sequences: 3072 # excluding supplementary and secondary reads +SN filtered sequences: 0 +SN sequences: 3072 +SN is sorted: 1 # sorted by coordinate +SN 1st fragments: 1920 +SN last fragments: 384 +SN reads mapped: 1536 +SN reads mapped and paired: 384 # paired-end technology bit set + both mates mapped +SN reads unmapped: 1536 +SN reads properly paired: 192 # proper-pair bit set +SN reads paired: 1536 # paired-end technology bit set +SN reads duplicated: 3072 # PCR or optical duplicate bit set +SN reads MQ0: 0 # mapped and MQ=0 +SN reads QC failed: 1536 +SN non-primary alignments: 6144 +SN supplementary alignments: 3072 +SN total length: 12288 # ignores clipping +SN total first fragment length: 7680 # ignores clipping +SN total last fragment length: 1536 # ignores clipping +SN bases mapped: 6144 # ignores clipping +SN bases mapped (cigar): 12288 # more accurate +SN bases trimmed: 0 +SN bases duplicated: 12288 +SN mismatches: 0 # from NM fields +SN error rate: 0.000000e+00 # mismatches / bases mapped (cigar) +SN average length: 4 +SN average first fragment length: 4 +SN average last fragment length: 4 +SN maximum length: 4 +SN maximum first fragment length: 4 +SN maximum last fragment length: 4 +SN average quality: 30.0 +SN insert size average: 0.0 +SN insert size standard deviation: 0.0 +SN inward oriented pairs: 32 +SN outward oriented pairs: 0 +SN pairs with other orientation: 32 +SN pairs on different chromosomes: 128 +SN percentage of properly paired reads (%): 6.2 diff --git a/tests/integration_test.rs b/tests/integration_test.rs index 699b7afa..466e5865 100644 --- a/tests/integration_test.rs +++ b/tests/integration_test.rs @@ -1178,3 +1178,284 @@ fn test_split_bam_off_without_bed() { ); let _ = fs::remove_dir_all(root); } + +// =================================================================== +// samtools flagstat / stats parity for QC-failed and dual-flagged records +// +// Cases adapted from seqeralabs/RustQC#175 (Nico DeVeaux) and #131 +// (Benjamin Demaille). Expected text is samtools 1.22.1 output. +// =================================================================== + +/// The two plain mapped reads every flagstat case sits between, so that some +/// read lands in a gene and `rustqc rna` produces its outputs. +const FLAGSTAT_BACKGROUND: [&str; 2] = [ + "r0\t0\tchr1\t1001\t60\t50M\t*\t0\t0\tACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTAC\t??????????????????????????????????????????????????", + "r1\t0\tchr1\t1201\t60\t50M\t*\t0\t0\tACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTAC\t??????????????????????????????????????????????????", +]; + +/// Run `rustqc rna` on the background reads plus one record with `flag` (and +/// mate field `rnext`) and return its flagstat and stats outputs. +fn samtools_for_one_record(label: &str, flag: u16, rnext: &str) -> (String, String) { + let root = unique_test_dir(label); + let bam_path = root.join("s.bam"); + let gtf_path = root.join("a.gtf"); + let outdir = root.join("out"); + fs::create_dir_all(&outdir).unwrap(); + fs::write( + >f_path, + "chr1\tt\tgene\t900\t3000\t.\t+\t.\tgene_id \"g1\"; gene_name \"g1\";\n\ + chr1\tt\texon\t900\t3000\t.\t+\t.\tgene_id \"g1\"; transcript_id \"t1\"; exon_number \"1\";\n", + ) + .unwrap(); + let pnext = if rnext == "*" { 0 } else { 1001 }; + let case = format!( + "r2\t{flag}\tchr1\t1001\t60\t50M\t{rnext}\t{pnext}\t0\tACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTAC\t??????????????????????????????????????????????????" + ); + write_bam_fixture( + &bam_path, + &[("chr1", 100_000), ("chr2", 100_000)], + &[FLAGSTAT_BACKGROUND[0], &case, FLAGSTAT_BACKGROUND[1]], + ); + + let output = run_rustqc_custom(&outdir, &bam_path, >f_path, 1, true, &[]); + assert!( + output.status.success(), + "rustqc failed on flag {flag:#06x}:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + let flagstat = fs::read_to_string(outdir.join("samtools/s.flagstat")).unwrap(); + let stats = fs::read_to_string(outdir.join("samtools/s.stats")).unwrap(); + let _ = fs::remove_dir_all(root); + (flagstat, stats) +} + +fn flagstat_for_one_record(label: &str, flag: u16, rnext: &str) -> String { + samtools_for_one_record(label, flag, rnext).0 +} + +/// A QC-failed read (0x200) belongs in samtools' second column. +#[test] +fn test_flagstat_qc_failed_column() { + let expected = "\ +2 + 1 in total (QC-passed reads + QC-failed reads) +2 + 1 primary +0 + 0 secondary +0 + 0 supplementary +0 + 0 duplicates +0 + 0 primary duplicates +2 + 1 mapped (100.00% : 100.00%) +2 + 1 primary mapped (100.00% : 100.00%) +0 + 0 paired in sequencing +0 + 0 read1 +0 + 0 read2 +0 + 0 properly paired (N/A : N/A) +0 + 0 with itself and mate mapped +0 + 0 singletons (N/A : N/A) +0 + 0 with mate mapped to a different chr +0 + 0 with mate mapped to a different chr (mapQ>=5) +"; + assert_eq!(flagstat_for_one_record("fs-qcfail", 0x200, "*"), expected); +} + +/// "properly paired" needs the read itself mapped (samtools bam_stat.c), +/// so PAIRED|PROPER_PAIR|UNMAP|MUNMAP|READ1 (0x4f) does not count. +#[test] +fn test_flagstat_properly_paired_requires_mapped_read() { + let expected = "\ +3 + 0 in total (QC-passed reads + QC-failed reads) +3 + 0 primary +0 + 0 secondary +0 + 0 supplementary +0 + 0 duplicates +0 + 0 primary duplicates +2 + 0 mapped (66.67% : N/A) +2 + 0 primary mapped (66.67% : N/A) +1 + 0 paired in sequencing +1 + 0 read1 +0 + 0 read2 +0 + 0 properly paired (0.00% : N/A) +0 + 0 with itself and mate mapped +0 + 0 singletons (0.00% : N/A) +0 + 0 with mate mapped to a different chr +0 + 0 with mate mapped to a different chr (mapQ>=5) +"; + assert_eq!( + flagstat_for_one_record("fs-proper-unmapped", 0x4f, "="), + expected + ); +} + +/// A QC-failed duplicate (0x600) is a duplicate in the QC-failed column, so +/// "primary duplicates" never exceeds "duplicates". +#[test] +fn test_flagstat_qc_failed_duplicate_counts_as_duplicate() { + let expected = "\ +2 + 1 in total (QC-passed reads + QC-failed reads) +2 + 1 primary +0 + 0 secondary +0 + 0 supplementary +0 + 1 duplicates +0 + 1 primary duplicates +2 + 1 mapped (100.00% : 100.00%) +2 + 1 primary mapped (100.00% : 100.00%) +0 + 0 paired in sequencing +0 + 0 read1 +0 + 0 read2 +0 + 0 properly paired (N/A : N/A) +0 + 0 with itself and mate mapped +0 + 0 singletons (N/A : N/A) +0 + 0 with mate mapped to a different chr +0 + 0 with mate mapped to a different chr (mapQ>=5) +"; + assert_eq!( + flagstat_for_one_record("fs-qcfail-dup", 0x600, "*"), + expected + ); +} + +/// SECONDARY takes priority over SUPPLEMENTARY, in flagstat and in the +/// `stats` summary numbers alike (samtools 1.22.1 `flagstat_loop` and +/// `stats.c`): a record with both flags is secondary only. +#[test] +fn test_secondary_supplementary_overlap_counts_secondary_only() { + let (flagstat, stats) = samtools_for_one_record("fs-sec-supp", 0x900, "*"); + let expected = "\ +3 + 0 in total (QC-passed reads + QC-failed reads) +2 + 0 primary +1 + 0 secondary +0 + 0 supplementary +0 + 0 duplicates +0 + 0 primary duplicates +3 + 0 mapped (100.00% : N/A) +2 + 0 primary mapped (100.00% : N/A) +0 + 0 paired in sequencing +0 + 0 read1 +0 + 0 read2 +0 + 0 properly paired (N/A : N/A) +0 + 0 with itself and mate mapped +0 + 0 singletons (N/A : N/A) +0 + 0 with mate mapped to a different chr +0 + 0 with mate mapped to a different chr (mapQ>=5) +"; + assert_eq!(flagstat, expected); + assert!( + stats.contains("SN\tnon-primary alignments:\t1\n"), + "{stats}" + ); + assert!( + stats.contains("SN\tsupplementary alignments:\t0\n"), + "{stats}" + ); +} + +/// A supplementary-only record is not a "non-primary alignment" in `stats`. +#[test] +fn test_stats_supplementary_is_not_non_primary() { + let (_, stats) = samtools_for_one_record("stats-supp-only", 0x800, "*"); + assert!( + stats.contains("SN\tnon-primary alignments:\t0\n"), + "{stats}" + ); + assert!( + stats.contains("SN\tsupplementary alignments:\t1\n"), + "{stats}" + ); +} + +/// A dual-flagged QC-failed duplicate is secondary in the failed column, +/// stays a duplicate, and contributes to neither supplementary nor primary. +#[test] +fn test_flagstat_secondary_supplementary_qcfail_duplicate() { + let (flagstat, stats) = samtools_for_one_record("fs-sec-supp-qcfail-dup", 0xf00, "*"); + let expected = "\ +2 + 1 in total (QC-passed reads + QC-failed reads) +2 + 0 primary +0 + 1 secondary +0 + 0 supplementary +0 + 1 duplicates +0 + 0 primary duplicates +2 + 1 mapped (100.00% : 100.00%) +2 + 0 primary mapped (100.00% : N/A) +0 + 0 paired in sequencing +0 + 0 read1 +0 + 0 read2 +0 + 0 properly paired (N/A : N/A) +0 + 0 with itself and mate mapped +0 + 0 singletons (N/A : N/A) +0 + 0 with mate mapped to a different chr +0 + 0 with mate mapped to a different chr (mapQ>=5) +"; + assert_eq!(flagstat, expected); + assert!( + stats.contains("SN\tnon-primary alignments:\t1\n"), + "{stats}" + ); + assert!( + stats.contains("SN\tsupplementary alignments:\t0\n"), + "{stats}" + ); +} + +/// SAM lines for every 12-bit flag in three placements: mate on the same +/// contig, mate on the other contig (MAPQ 60), and mate on the other contig +/// with MAPQ 3. `tests/expected/samtools/all_flags.*` is samtools 1.22.1's +/// output for exactly these records (see the README there). +fn all_flags_sam_lines() -> Vec { + let mut chr1 = Vec::new(); + let mut chr2 = Vec::new(); + for flag in 0..4096u16 { + chr1.push(format!( + "f{flag}a\t{flag}\tchr1\t10\t60\t4M\t=\t10\t0\tACGT\tIIII" + )); + chr1.push(format!( + "f{flag}b\t{flag}\tchr1\t10\t60\t4M\tchr2\t10\t0\tACGT\tIIII" + )); + chr2.push(format!( + "f{flag}c\t{flag}\tchr2\t10\t3\t4M\tchr1\t10\t0\tACGT\tIIII" + )); + } + chr1.extend(chr2); + chr1 +} + +/// Every flag, against the unmodified samtools 1.22.1 golden output, on both +/// the serial and per-contig parallel paths: all of `flagstat` and the `SN` +/// section of `stats`. +#[test] +fn test_samtools_flagstat_and_stats_match_on_every_flag() { + let expected_flagstat = + fs::read_to_string("tests/expected/samtools/all_flags.flagstat").unwrap(); + let expected_sn = fs::read_to_string("tests/expected/samtools/all_flags.stats.sn").unwrap(); + + let lines = all_flags_sam_lines(); + let lines: Vec<&str> = lines.iter().map(String::as_str).collect(); + for threads in [1, 2] { + let root = unique_test_dir(&format!("fs-all-flags-t{threads}")); + let bam_path = root.join("all_flags.bam"); + let gtf_path = root.join("all_flags.gtf"); + let outdir = root.join("out"); + fs::create_dir_all(&outdir).unwrap(); + write_test_gtf(>f_path, &["chr1", "chr2"]); + write_bam_fixture(&bam_path, &[("chr1", 1000), ("chr2", 1000)], &lines); + + let output = run_rustqc_custom(&outdir, &bam_path, >f_path, threads, true, &[]); + assert!( + output.status.success(), + "rustqc failed with --threads {threads}:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + let flagstat = fs::read_to_string(outdir.join("samtools/all_flags.flagstat")).unwrap(); + assert_eq!( + flagstat, expected_flagstat, + "flagstat with --threads {threads}" + ); + let stats = fs::read_to_string(outdir.join("samtools/all_flags.stats")).unwrap(); + let sn: String = stats + .lines() + .filter(|l| l.starts_with("SN\t")) + .map(|l| format!("{l}\n")) + .collect(); + assert_eq!(sn, expected_sn, "stats SN section with --threads {threads}"); + let _ = fs::remove_dir_all(root); + } +}