diff --git a/docs/src/content/docs/rna/qualimap.mdx b/docs/src/content/docs/rna/qualimap.mdx index 92181d8..1ef5149 100644 --- a/docs/src/content/docs/rna/qualimap.mdx +++ b/docs/src/content/docs/rna/qualimap.mdx @@ -105,7 +105,7 @@ Alignment-level statistics for all primary reads: | Field | Description | | --------------------- | ---------------------------------------------------------------------- | -| reads aligned | Total primary alignments (excluding secondary, supplementary, QC-fail) | +| reads aligned | Primary alignments: mapped records not flagged secondary (SE) | | total alignments | All mapped reads (primary + secondary) | | secondary alignments | Alignments flagged as secondary (0x100) | | non-unique alignments | Multi-mappers (NH tag > 1) | @@ -125,7 +125,7 @@ against the annotation: exonic = 122,500,822 (76.45%) intronic = 29,504,572 (18.37%) intergenic = 8,344,022 (5.19%) - overlapping exon = 6,754,726 (4.20%) + overlapping exon = 6,754,726 (4.2%) ``` | Field | Description | @@ -146,11 +146,18 @@ Coverage bias metrics computed from the gene body coverage profile: 5'-3' bias = 1.11 ``` -| Metric | Description | -| ---------- | --------------------------------------------------------------------------------------- | -| 5' bias | Ratio of median coverage in the 5' region (first 100bp) to the median of the middle 80% | -| 3' bias | Ratio of median coverage in the 3' region (last 100bp) to the median of the middle 80% | -| 5'-3' bias | Ratio of 5' median to 3' median | +| Metric | Description | +| ---------- | ----------------------------------------------------------------------------------- | +| 5' bias | Median over transcripts of mean coverage of the first 100 bases / mean coverage | +| 3' bias | Median over transcripts of mean coverage of the last 100 bases / mean coverage | +| 5'-3' bias | Median over transcripts of mean coverage of the first 100 / of the last 100 bases | + +As in Qualimap, the transcripts are the best-covered transcript of each gene (at +least 500 bp long, mean coverage at least 1), limited to those at or above the +1001st highest mean coverage. The medians are Commons Math 2.0 percentiles: a +transcript with no coverage at either end gives a 5'/3' ratio of NaN, which is +kept and sorted last, so it raises the 5'-3' bias median rather than being +dropped. Bias values close to 1.0 indicate uniform coverage. Values significantly above 1.0 for 5' bias or below 1.0 for 3' bias suggest degradation or protocol issues. @@ -323,6 +330,27 @@ eliminating the separate name-sort and Qualimap run required by the original Jav +Every number is printed the way Qualimap prints it. Qualimap formats counts, +ratios and percentages with Java's `DecimalFormat` (at most two decimals, +trailing zeros dropped, half-even rounding), so a whole percentage is `60%`, +not `60.0%`, and a ratio of exactly one half is `0.5`. The coverage profile +files use Java's `Double.toString` (`0.0`, `1.0E-4`). Reads on a sequence with +no annotated exon are left out of the counts, as in Qualimap, and reported in +the HTML report as "Missing chromosome in annotation". + +Reads are selected as Qualimap selects them. Secondary, supplementary and +QC-fail records are not skipped: every mapped record with an NH tag of at most +1 (or none) is counted. Proper pairs are grouped by read name, as Qualimap does +with its name-sorted input. A group of exactly two records is one fragment, and +Qualimap skips any other group, for example a pair plus a supplementary record. + + +
Small dataset (~52K reads, chr6) @@ -345,11 +373,10 @@ Both tools were run on the same BAM file with matching parameters are from the AWS benchmark run (2026-03-09).
@@ -384,10 +411,10 @@ multiple transcripts of the same gene have identical mean coverage. | ---------- | --------------- | ------ | -------- | | 5' bias | 0.71 | 0.71 | Yes | | 3' bias | 0.57 | 0.57 | Yes | -| 5'-3' bias | 1.30 | 1.19 | Minor diff | +| 5'-3' bias | 1.3 | 1.3 | Yes | -The 5'-3' bias shows a minor difference (1.30 vs 1.19) on this small dataset. -All other values are identical. +All values are identical (`rnaseq_qc_results.txt` matches apart from the input +paths).
@@ -416,7 +443,7 @@ All other values are identical. | exonic fraction | 76.45% | 76.45% | Yes | | intronic fraction | 18.37% | 18.37% | Yes | | intergenic fraction | 5.19% | 5.19% | Yes | -| overlapping exon | 4.20% | 4.20% | Yes | +| overlapping exon | 4.2% | 4.2% | Yes | ##### Transcript coverage profile @@ -432,8 +459,9 @@ All other values are identical. | ------------------ | --------------- | ---------- | ------ | | reads at junctions | 56,119,719 | 56,119,719 | Yes | -Junction motif type percentages match with rounding differences less than 0.05 -percentage points. The underlying read counts are identical. +Junction motif counts and percentages are identical. Motifs with the same +count are listed alphabetically, which can differ from Qualimap's order (see the note on +junction motifs above).
diff --git a/src/rna/qualimap/accumulator.rs b/src/rna/qualimap/accumulator.rs index f8e82fd..e8b96eb 100644 --- a/src/rna/qualimap/accumulator.rs +++ b/src/rna/qualimap/accumulator.rs @@ -3,8 +3,12 @@ //! Processes BAM records using Qualimap's counting rules: //! - M-only CIGAR blocks (no insertion/deletion/softclip contribution) //! - Enclosure-based gene assignment (each M-block must be fully contained in exons of the same gene) -//! - PE reads: combine both mates' M-blocks, assign on combined set, count numReads=2 -//! - Multi-mappers excluded entirely (NH > 1) +//! - Read selection as in Qualimap 2.3 `ComputeCountsTask` (`checkRead`, +//! `computeReadWeight`): secondary, supplementary and QC-fail records are +//! processed like any other; reads with NH > 1 or on a sequence without +//! annotated exons are counted and dropped +//! - PE proper pairs: records are grouped by read name; a group of exactly two +//! is one fragment (numReads=2), other groups are skipped //! - Junction motif extraction from read sequence at N-operation boundaries use std::collections::{HashMap, HashSet}; @@ -41,11 +45,25 @@ struct CachedBlockHits { use crate::rna::bam_flags::*; // ============================================================ -// Mate buffer for PE reads +// Read-name groups for PE fragments // ============================================================ -/// Key for mate buffering: (qname_hash, r1_tid, r1_pos, r2_tid, r2_pos). -type MateKey = (u64, i32, i64, i32, i64); +/// The proper-pair records seen so far for one read name. +/// +/// Qualimap reads a name-sorted BAM in `-pe` mode and collects consecutive +/// proper-pair records with the same name into a fragment +/// (`ComputeCountsTask.run`). `processFragment` then counts a fragment of +/// exactly two records and skips any other size: a single record +/// (`numSingleReadOnly`) or more than two (e.g. a pair plus a supplementary or +/// secondary record that passed the NH check). +#[derive(Debug, Clone, Default)] +struct PendingFragment { + /// The records of this name that passed the read filters. + mates: Vec, + /// Whether more records of this name may still follow after two have been + /// seen, so the fragment has to wait for the end of the input. + hold: bool, +} /// A splice junction motif extracted from the read sequence at an N-operation. #[derive(Debug, Clone)] @@ -58,8 +76,8 @@ struct JunctionMotif { /// Per-mate data passed through the PE reconciliation pipeline. /// -/// Groups the per-read data needed for `reconcile_pair()` and -/// `classify_and_count()`, reducing parameter counts. +/// Groups the per-read data needed for `process_fragment()` and +/// `process_single()`, reducing parameter counts. #[derive(Debug, Clone)] struct MateData { /// M-only aligned blocks (0-based half-open). @@ -72,6 +90,14 @@ struct MateData { is_reverse: bool, /// Whether this mate is the first read in pair (flag 0x40). is_first_of_pair: bool, + /// Reference sequence id (resolved through `QualimapAccum::chrom_names`). + tid: i32, + /// Number of N operations (Qualimap `numReadsWithJunction` increments). + n_op_count: usize, + /// Junction motifs read from the sequence at N operations. + motifs: Vec, + /// `(posInRef1, posInRef2)` for each N operation. + junction_ref_positions: Vec<(i32, i32)>, } // ============================================================ @@ -84,9 +110,9 @@ struct MateData { /// in `rnaseq_qc_results.txt`. #[derive(Debug, Clone, Default)] pub struct QualimapCounters { - /// Total primary alignments processed. + /// Mapped records not flagged secondary (supplementary and QC-fail included). pub primary_alignments: u64, - /// Total secondary alignments seen (skipped). + /// Mapped records flagged secondary. pub secondary_alignments: u64, /// Unmapped reads (flag 0x4). pub not_aligned: u64, @@ -106,7 +132,7 @@ pub struct QualimapCounters { /// overlapping exon" in Qualimap terminology). Only counted once per /// read/fragment that has any M-block overlapping an exon. pub overlapping_exon: u64, - /// Total reads counted (numReads: for PE, 2 per fragment). + /// Mapped records on an annotated sequence (Qualimap `readCount`). pub read_count: u64, /// Left mates in proper pairs (flag 0x2 + 0x40). pub left_proper_in_pair: u64, @@ -126,8 +152,12 @@ pub struct QualimapCounters { /// /// Matches Qualimap Java's `partlyKnownJunctions` counter. pub partly_known_junction_events: u64, - /// Total supplementary alignments seen (skipped). + /// Supplementary records that passed the read filters (processed like + /// any other read, as Qualimap does). pub supplementary: u64, + /// Mapped reads on a sequence with no annotated exon (Qualimap + /// `seqNotFoundCount`, "Missing chromosome in annotation"). + pub seq_not_found: u64, /// SSP forward-strand estimation counter. pub ssp_fwd: u64, /// SSP reverse-strand estimation counter. @@ -155,6 +185,7 @@ impl QualimapCounters { self.known_junction_events += other.known_junction_events; self.partly_known_junction_events += other.partly_known_junction_events; self.supplementary += other.supplementary; + self.seq_not_found += other.seq_not_found; self.ssp_fwd += other.ssp_fwd; self.ssp_rev += other.ssp_rev; } @@ -201,8 +232,10 @@ pub struct QualimapAccum { pub coverage: TranscriptCoverage, /// Junction splice motif counts. pub junction_motifs: JunctionMotifCounts, - /// Mate buffer for PE reconciliation. - mate_buffer: HashMap, + /// Proper-pair records waiting for the rest of their read-name group. + fragments: HashMap, PendingFragment>, + /// Chromosome name for each reference id seen (for deferred fragments). + chrom_names: HashMap, /// Strandedness protocol. stranded: Strandedness, } @@ -214,19 +247,21 @@ impl QualimapAccum { counters: QualimapCounters::default(), coverage: TranscriptCoverage::new(), junction_motifs: JunctionMotifCounts::default(), - mate_buffer: HashMap::new(), + fragments: HashMap::new(), + chrom_names: HashMap::new(), stranded, } } /// Process a single BAM record. /// - /// Applies Qualimap's filtering and counting logic: - /// 1. Skip unmapped, secondary, QC-fail, supplementary reads - /// 2. Skip multi-mappers (NH > 1) + /// Applies Qualimap's filtering and counting logic (`ComputeCountsTask`): + /// 1. `checkRead`: count unmapped, secondary and primary records; drop + /// reads on a sequence without annotated exons + /// 2. `computeReadWeight`: drop multi-mappers (NH > 1) /// 3. Extract M-only CIGAR blocks - /// 4. For SE: assign immediately via enclosure check - /// 5. For PE: buffer mate, assign when pair is complete + /// 4. Single reads and non-proper pairs: assign immediately + /// 5. Proper pairs: group by read name, assign once the group is complete /// /// # Arguments /// * `record` - The BAM record to process. @@ -247,60 +282,51 @@ impl QualimapAccum { return; } - // Multi-mapper check on ALL mapped reads (including secondary). - // Qualimap increments alignmentNotUnique before the skipSecondary check, - // so secondary reads with NH>1 are counted in both secondary AND non-unique. - let is_multi_mapped = get_nh_tag(record).is_some_and(|nh| nh > 1); - if is_multi_mapped { - self.counters.alignment_not_unique += 1; - } - - // Track secondary vs primary + // Track secondary vs primary (Qualimap ComputeCountsTask.checkRead). let is_secondary = flags & BAM_FSECONDARY != 0; if is_secondary { self.counters.secondary_alignments += 1; - // Qualimap skipSecondary=true by default in RNA-Seq mode. - // Secondary reads are counted but excluded from all downstream - // gene assignment, SSP, and junction analysis. - return; - } - self.counters.primary_alignments += 1; - - // Count left/right reads for ALL primary paired reads (not just proper pair). - // Qualimap: leftProperInPair counts first-of-pair, rightProperInPair counts - // second-of-pair — despite the name, they don't check the proper-pair flag. - // bothProperInPair counts reads that ARE proper pair (used for numberOfMappedPairs). - if flags & BAM_FPAIRED != 0 { - if flags & BAM_FREAD1 != 0 { - self.counters.left_proper_in_pair += 1; - } - if flags & BAM_FREAD2 != 0 { - self.counters.right_proper_in_pair += 1; - } - if flags & BAM_FPROPER_PAIR != 0 { - self.counters.both_proper_in_pair += 1; + } else { + self.counters.primary_alignments += 1; + + // Count left/right reads for ALL primary paired reads (not just proper pair). + // Qualimap: leftProperInPair counts first-of-pair, rightProperInPair counts + // second-of-pair — despite the name, they don't check the proper-pair flag. + // bothProperInPair counts reads that ARE proper pair (used for numberOfMappedPairs). + if flags & BAM_FPAIRED != 0 { + if flags & BAM_FREAD1 != 0 { + self.counters.left_proper_in_pair += 1; + } + if flags & BAM_FREAD2 != 0 { + self.counters.right_proper_in_pair += 1; + } + if flags & BAM_FPROPER_PAIR != 0 { + self.counters.both_proper_in_pair += 1; + } } } - // Skip supplementary and QC-fail (these never contribute) - if flags & BAM_FSUPPLEMENTARY != 0 { - self.counters.supplementary += 1; - return; - } - if flags & BAM_FQCFAIL != 0 { + // checkRead then drops reads on a sequence with no annotated exon + // ("Missing chromosome in annotation"), before the NH check. + if index.exon_tree(chrom).is_none() { + self.counters.seq_not_found += 1; return; } - - // readCount: primary reads that pass initial filters - // (Qualimap: readCount counts all non-secondary, non-supplementary reads) + // readCount: reads that passed checkRead self.counters.read_count += 1; - // Skip multi-mappers from gene assignment, junction counting, and coverage. - // Coverage is added only for uniquely-mapped reads, restricted to fully-enclosed - // M-blocks, matching the correct Qualimap coverage model. - if is_multi_mapped { + // Multi-mapper check (computeReadWeight). Qualimap's + // skipSecondaryAlignments is false, so this applies to secondary + // alignments too, and a missing NH tag counts as NH = 1. + let nh = get_nh_tag(record); + if nh.is_some_and(|nh| nh > 1) { + self.counters.alignment_not_unique += 1; return; } + // Supplementary and QC-fail records are not filtered by Qualimap. + if flags & BAM_FSUPPLEMENTARY != 0 { + self.counters.supplementary += 1; + } // Extract M-only CIGAR blocks (replicating Qualimap's CIGAR bug where // offset += length for ALL operations, including I/S/H/P) AND junction @@ -308,37 +334,6 @@ impl QualimapAccum { let (m_blocks, n_op_count, motifs, junction_ref_positions) = extract_m_blocks_and_junctions(record); - if m_blocks.is_empty() { - return; - } - // Qualimap increments numReadsWithJunction for every N-operation, - // even when the motif extraction guard fails. Match that behavior. - self.counters.reads_at_junctions += n_op_count as u64; - - // Count junction motifs per-read, matching Qualimap which - // calls collectJunctionInfo independently for each SAMRecord. - for motif in &motifs { - *self - .junction_motifs - .counts - .entry((motif.donor, motif.acceptor)) - .or_insert(0) += 1; - } - - // Classify junction events as known/partly known/novel using the - // Qualimap junction location map (exon boundary positions ±1 tolerance). - for &(pos_ref1, pos_ref2) in &junction_ref_positions { - let j1 = index.has_junction_overlap(chrom, pos_ref1); - let j2 = index.has_junction_overlap(chrom, pos_ref2); - if j1 && j2 { - self.counters.known_junction_events += 1; - } else if j1 || j2 { - self.counters.partly_known_junction_events += 1; - } - // Novel junctions (neither matches) are computed as: - // reads_at_junctions - known - partly_known - } - // --- Cache tree query results for all M-blocks --- // Query the merged exon tree ONCE per block set and reuse the results // across enclosure check, coverage, overlapping-exon, and SSP. @@ -360,13 +355,10 @@ impl QualimapAccum { let enclosing_genes = find_enclosing_genes_cached(&cached_hits, self.stranded, is_reverse, is_first_of_pair); - // --- Coverage: per-block, strand-independent (Qualimap model) --- - // Qualimap adds coverage per M-block to each enclosing gene, without - // strand filtering. This is separate from gene assignment counting. - // For SE reads: add coverage now. For PE: deferred to reconcile_pair(). - if flags & BAM_FPAIRED == 0 || flags & BAM_FPROPER_PAIR == 0 { - self.add_per_block_coverage_cached(&m_blocks, &cached_hits, index); - } + let tid = record.tid(); + self.chrom_names + .entry(tid) + .or_insert_with(|| chrom.to_string()); // Bundle per-read data for downstream use let data = MateData { @@ -375,51 +367,112 @@ impl QualimapAccum { cached_hits, is_reverse, is_first_of_pair, + tid, + n_op_count, + motifs, + junction_ref_positions, }; // PE path: check BAM flags directly (no library-level paired flag needed) if flags & BAM_FPAIRED != 0 && flags & BAM_FPROPER_PAIR != 0 { - // PE proper pair: buffer and combine with mate (Qualimap name-sorts - // and processes both mates' intervals together as a fragment). - self.process_pe_read(record, data, chrom, index); + // A pair is complete with its two primary records unless the name + // may have more records that pass the filters: a supplementary + // record (announced by the SA tag on every part of a chimeric + // alignment), or secondary records, which are only kept when they + // lack an NH tag (with NH present they have NH > 1). + let extra_records_possible = flags & (BAM_FSECONDARY | BAM_FSUPPLEMENTARY) != 0 + || nh.is_none() + || record.aux(b"SA").is_ok(); + self.add_to_fragment(record.qname(), data, extra_records_possible, index); } else { - // SE mode or non-proper pair: assign immediately (numReads = 1) - self.classify_and_count(&data, chrom, index, 1); + // SE mode or non-proper pair: processRead (numReads = 1) + self.process_single(&data, index); } } - /// Process a PE read — buffer first mate, reconcile when second arrives. - fn process_pe_read( + /// Add a proper-pair record to its read-name group and count the group + /// as soon as it is known to be a complete two-record fragment. + fn add_to_fragment( &mut self, - record: &bam::Record, + qname: &[u8], data: MateData, - chrom: &str, + extra_records_possible: bool, index: &QualimapIndex, ) { - let key = make_mate_key(record); + let group = self.fragments.entry(qname.into()).or_default(); + group.mates.push(data); + group.hold |= extra_records_possible; + if group.mates.len() == 2 && !group.hold { + let group = self + .fragments + .remove(qname) + .expect("fragment group was just inserted"); + self.process_fragment(&group.mates[0], &group.mates[1], index); + } + } - if let Some(mate) = self.mate_buffer.remove(&key) { - // Found the mate — reconcile the pair. - // Current read is r1 (second-seen), buffered mate is r2 (first-seen). - self.reconcile_pair(&data, &mate, chrom, index); - } else { - // First mate seen — buffer it - self.mate_buffer.insert(key, data); + /// Chromosome name of a record's reference id. + fn chrom_of(&self, tid: i32) -> &str { + self.chrom_names.get(&tid).map(String::as_str).unwrap_or("") + } + + /// Junction statistics of one record (`collectJunctionInfo`), which + /// Qualimap gathers in `getReadIntervals` only for reads it counts. + fn count_junctions(&mut self, data: &MateData, index: &QualimapIndex) { + // Qualimap increments numReadsWithJunction for every N-operation, + // even when the motif extraction guard fails. Match that behavior. + self.counters.reads_at_junctions += data.n_op_count as u64; + + // Count junction motifs per-read, matching Qualimap which + // calls collectJunctionInfo independently for each SAMRecord. + for motif in &data.motifs { + *self + .junction_motifs + .counts + .entry((motif.donor, motif.acceptor)) + .or_insert(0) += 1; } + + // Classify junction events as known/partly known/novel using the + // Qualimap junction location map (exon boundary positions ±1 tolerance). + let chrom = self.chrom_of(data.tid); + let (mut known, mut partly_known) = (0, 0); + for &(pos_ref1, pos_ref2) in &data.junction_ref_positions { + let j1 = index.has_junction_overlap(chrom, pos_ref1); + let j2 = index.has_junction_overlap(chrom, pos_ref2); + if j1 && j2 { + known += 1; + } else if j1 || j2 { + partly_known += 1; + } + // Novel junctions (neither matches) are computed as: + // reads_at_junctions - known - partly_known + } + self.counters.known_junction_events += known; + self.counters.partly_known_junction_events += partly_known; } - /// Reconcile a PE pair: combine M-blocks and gene assignments. + /// Count a two-record PE fragment (`processFragment` with two reads). /// - /// Qualimap intersects the enclosing gene sets of both mates. + /// Qualimap keeps the genes that enclose every M-block of both records. /// If exactly one gene encloses ALL M-blocks of BOTH mates → assigned. /// If >1 gene → ambiguous. If 0 genes → check intronic/intergenic. - fn reconcile_pair(&mut self, r1: &MateData, r2: &MateData, chrom: &str, index: &QualimapIndex) { - // Intersect the enclosing gene sets from both mates (already computed). - let assigned_genes: HashSet = r1 - .enclosing_genes - .intersection(&r2.enclosing_genes) - .copied() - .collect(); + fn process_fragment(&mut self, r1: &MateData, r2: &MateData, index: &QualimapIndex) { + self.count_junctions(r1, index); + self.count_junctions(r2, index); + + // A record without M-blocks adds no interval, so it does not + // constrain the genes of the fragment. + let assigned_genes: HashSet = match (r1.m_blocks.is_empty(), r2.m_blocks.is_empty()) { + (false, false) => r1 + .enclosing_genes + .intersection(&r2.enclosing_genes) + .copied() + .collect(), + (false, true) => r1.enclosing_genes.clone(), + (true, false) => r2.enclosing_genes.clone(), + (true, true) => HashSet::new(), + }; // --- Coverage: per-block, strand-independent (Qualimap model) --- // Use cached hits from both mates to add coverage without re-querying the tree. @@ -427,22 +480,22 @@ impl QualimapAccum { self.add_per_block_coverage_cached(&r2.m_blocks, &r2.cached_hits, index); // Check for overlapping_exon using cached hits from both mates. - // At most one increment per fragment: check r2 only if r1 didn't trigger. - if !check_has_overlap_not_enclosed(&r1.cached_hits) { - self.check_overlapping_exon_cached(&r2.cached_hits); - } else { + // At most one increment per fragment. + if check_has_overlap_not_enclosed(&r1.cached_hits) + || check_has_overlap_not_enclosed(&r2.cached_hits) + { self.counters.overlapping_exon += 1; } - // Combine blocks for intronic/intergenic classification only when needed match assigned_genes.len() { 0 => { // No gene encloses all blocks — classify as intronic or intergenic - let mut combined_blocks: Vec<(i32, i32)> = - Vec::with_capacity(r1.m_blocks.len() + r2.m_blocks.len()); - combined_blocks.extend_from_slice(&r1.m_blocks); - combined_blocks.extend_from_slice(&r2.m_blocks); - self.classify_no_feature(&combined_blocks, chrom, index, 2); + let intronic = self.overlaps_intron(r1, index) || self.overlaps_intron(r2, index); + if intronic { + self.counters.intronic_reads += 2; + } else { + self.counters.intergenic_reads += 2; + } // Qualimap: noFeature += numReads (2 for PE fragment) self.counters.no_feature += 2; } @@ -460,35 +513,31 @@ impl QualimapAccum { // SSP estimation using cached hits — avoids re-querying the tree. self.count_ssp_for_blocks_cached(&r1.cached_hits, r1.is_reverse, r1.is_first_of_pair); - let r2_is_first = !r1.is_first_of_pair; - self.count_ssp_for_blocks_cached(&r2.cached_hits, r2.is_reverse, r2_is_first); + self.count_ssp_for_blocks_cached(&r2.cached_hits, r2.is_reverse, r2.is_first_of_pair); } - /// Classify and count a fragment (SE read or single-mate data). - /// - /// Shared logic for SE reads, non-proper pairs, and cross-chromosome - /// mate reconciliation. `num_reads` is 1 for SE / non-proper and 2 for - /// cross-chromosome PE fragments. - fn classify_and_count( - &mut self, - data: &MateData, - chrom: &str, - index: &QualimapIndex, - num_reads: u64, - ) { + /// Count a single read: SE reads and non-proper pairs (`processRead`). + fn process_single(&mut self, data: &MateData, index: &QualimapIndex) { + self.count_junctions(data, index); + self.add_per_block_coverage_cached(&data.m_blocks, &data.cached_hits, index); + // Check for overlapping_exon using cached results. self.check_overlapping_exon_cached(&data.cached_hits); match data.enclosing_genes.len() { 0 => { - self.classify_no_feature(&data.m_blocks, chrom, index, num_reads); - self.counters.no_feature += num_reads; + if self.overlaps_intron(data, index) { + self.counters.intronic_reads += 1; + } else { + self.counters.intergenic_reads += 1; + } + self.counters.no_feature += 1; } 1 => { - self.counters.exonic_reads += num_reads; + self.counters.exonic_reads += 1; } _ => { - self.counters.ambiguous += num_reads; + self.counters.ambiguous += 1; } } @@ -532,28 +581,20 @@ impl QualimapAccum { } } - /// Classify a read that wasn't assigned to any gene as intronic or intergenic. - fn classify_no_feature( - &mut self, - m_blocks: &[(i32, i32)], - chrom: &str, - index: &QualimapIndex, - num_reads: u64, - ) { - // Classify as intronic or intergenic - if let Some(intron_tree) = index.intron_tree(chrom) { - for &(start, end) in m_blocks { - let mut found_intron = false; - intron_tree.query(start, end, |_iv| { - found_intron = true; - }); - if found_intron { - self.counters.intronic_reads += num_reads; - return; - } - } - } - self.counters.intergenic_reads += num_reads; + /// Whether any M-block of a record overlaps an intron + /// (`collectNonFeatureMappedReadInfo`): a no-feature read is intronic if + /// so, intergenic otherwise. + fn overlaps_intron(&self, data: &MateData, index: &QualimapIndex) -> bool { + let Some(intron_tree) = index.intron_tree(self.chrom_of(data.tid)) else { + return false; + }; + data.m_blocks.iter().any(|&(start, end)| { + let mut found_intron = false; + intron_tree.query(start, end, |_iv| { + found_intron = true; + }); + found_intron + }) } /// Count SSP votes using pre-computed cached block hits. @@ -585,76 +626,40 @@ impl QualimapAccum { } } - /// Flush any remaining unpaired mates at the end of a chromosome batch. + /// Count the read-name groups still open at the end of the input. /// - /// PE mates that were never reconciled are treated as singletons and - /// Qualimap skips proper-pair fragments where only one mate survived - /// filters (numSingleReadOnly). We simply discard orphaned mates. - pub fn flush_unpaired(&mut self, _index: &QualimapIndex) { - // Qualimap behaviour: if a proper-pair read's mate was filtered out - // (by NH>1, unmapped, etc.), the fragment is skipped entirely — - // neither exonic nor noFeature is counted. We match this by simply - // draining the mate buffer without processing. - self.mate_buffer.clear(); + /// Groups of exactly two records are fragments; Qualimap skips the rest + /// (a single record whose mate was filtered out, or more than two + /// records). Call once, after all accumulators have been merged. + pub fn flush_unpaired(&mut self, index: &QualimapIndex) { + let groups: Vec = self.fragments.drain().map(|(_, g)| g).collect(); + for group in groups { + if let [r1, r2] = group.mates.as_slice() { + self.process_fragment(r1, r2, index); + } + } } /// Merge another `QualimapAccum` into this one. /// - /// Used when combining results from parallel chromosome batches. + /// Used when combining results from parallel chromosome batches. Open + /// read-name groups are combined and counted by `flush_unpaired`. pub fn merge(&mut self, other: QualimapAccum) { self.counters.merge(&other.counters); self.coverage.merge(other.coverage); self.junction_motifs.merge(&other.junction_motifs); - - // Merge mate buffers (cross-chromosome mates). - // When both mates were buffered in different per-chromosome batches, - // reconcile them here. These are PE fragments, so num_reads = 2. - for (key, info) in other.mate_buffer { - if let Some(existing) = self.mate_buffer.remove(&key) { - // We don't have the chrom handy for intronic classification, - // so treat no-feature conservatively as intergenic. - let common_genes: HashSet = existing - .enclosing_genes - .intersection(&info.enclosing_genes) - .copied() - .collect(); - - // Union fallback: if one mate has no enclosing genes, use - // the other mate's set (cross-chrom pairs often have one - // mate in an unannotated region). - let assigned = if existing.enclosing_genes.is_empty() - && !info.enclosing_genes.is_empty() - { - info.enclosing_genes.clone() - } else if info.enclosing_genes.is_empty() && !existing.enclosing_genes.is_empty() { - existing.enclosing_genes.clone() - } else { - common_genes - }; - - // PE fragment: count both reads (num_reads = 2) - match assigned.len() { - 0 => { - self.counters.no_feature += 2; - self.counters.intergenic_reads += 2; - } - 1 => { - self.counters.exonic_reads += 2; - } - _ => { - self.counters.ambiguous += 2; - } - } - } else { - self.mate_buffer.insert(key, info); - } + self.chrom_names.extend(other.chrom_names); + for (qname, group) in other.fragments { + let mine = self.fragments.entry(qname).or_default(); + mine.mates.extend(group.mates); + mine.hold |= group.hold; } } - /// Get the number of unmatched mates still in the buffer. + /// Get the number of read names with an open fragment group. #[allow(dead_code)] pub fn unmatched_count(&self) -> usize { - self.mate_buffer.len() + self.fragments.len() } /// Convert this accumulator into a `QualimapResult`. @@ -677,6 +682,7 @@ impl QualimapAccum { secondary_alignments: self.counters.secondary_alignments, not_aligned: self.counters.not_aligned, alignment_not_unique: self.counters.alignment_not_unique, + seq_not_found: self.counters.seq_not_found, exonic_reads: self.counters.exonic_reads, ambiguous_reads: self.counters.ambiguous, no_feature: self.counters.no_feature, @@ -837,7 +843,7 @@ fn decode_base(encoded: u8) -> u8 { /// Check whether any cached block hit has an overlap that is not fully enclosed. /// -/// Pure predicate — does not modify any counters. Used in `reconcile_pair` to +/// Pure predicate — does not modify any counters. Used in `process_fragment` to /// avoid double-incrementing `overlapping_exon` when checking both mates. fn check_has_overlap_not_enclosed(cached_hits: &[CachedBlockHits]) -> bool { cached_hits.iter().any(|h| h.has_overlap_not_enclosed) @@ -987,29 +993,6 @@ fn find_enclosing_genes( find_enclosing_genes_cached(&cached_hits, stranded, is_reverse, is_first_of_pair) } -/// Build a mate buffer key from a BAM record. -/// -/// Uses FNV-1a hash of qname + r1-centric ordering of positions. -fn make_mate_key(record: &bam::Record) -> MateKey { - let qname_hash = hash_qname(record.qname()); - let tid = record.tid(); - let pos = record.pos(); - let mate_tid = record.mtid(); - let mate_pos = record.mpos(); - - // Always store with read1 position first for consistent lookup - if tid < mate_tid || (tid == mate_tid && pos <= mate_pos) { - (qname_hash, tid, pos, mate_tid, mate_pos) - } else { - (qname_hash, mate_tid, mate_pos, tid, pos) - } -} - -/// FNV-1a hash of a byte slice (for qname hashing). -fn hash_qname(qname: &[u8]) -> u64 { - crate::io::fnv1a(qname) -} - // ============================================================ // Unit tests // ============================================================ @@ -1018,15 +1001,6 @@ fn hash_qname(qname: &[u8]) -> u64 { mod tests { use super::*; - #[test] - fn test_hash_qname_deterministic() { - let h1 = hash_qname(b"read1"); - let h2 = hash_qname(b"read1"); - let h3 = hash_qname(b"read2"); - assert_eq!(h1, h2); - assert_ne!(h1, h3); - } - #[test] fn test_decode_base() { assert_eq!(decode_base(1), b'A'); diff --git a/src/rna/qualimap/format.rs b/src/rna/qualimap/format.rs new file mode 100644 index 0000000..c3f3cf2 --- /dev/null +++ b/src/rna/qualimap/format.rs @@ -0,0 +1,270 @@ +//! Number formatting that reproduces Qualimap's Java output. +//! +//! Qualimap 2.3 formats every number in `rnaseq_qc_results.txt` and in the +//! summary tables of `qualimapReport.html` through `StringUtilsSwing` +//! (`org.bioinfo.ngs.qc.qualimap.gui.utils`), which calls +//! `org.bioinfo.commons.utils.StringUtils.decimalFormat(value, pattern)`, i.e. +//! `new java.text.DecimalFormat(pattern).format(value)`: +//! +//! | method | pattern | example | +//! |----------------------|-------------------------------------|--------------| +//! | `formatLong` | `###,###,####,###,…,###.##` | `1,234,567` | +//! | `formatDecimal` | `###,###,###,###,###,###,###.##` | `1,234.5` | +//! | `formatPercentage` | `###.##` followed by `%` | `60%` | +//! +//! `DecimalFormat` with these patterns prints at most two fraction digits, +//! drops trailing zeros (so whole numbers have no decimal point), always prints +//! at least one integer digit, groups the integer part by three (grouping size +//! is the last group in the pattern; `###.##` has no grouping) and rounds +//! with `RoundingMode.HALF_EVEN`. + +/// Doubles at or above 2^53 are whole numbers whose exact decimal expansion +/// can have more digits than Java prints. +const EXACT_INTEGER_LIMIT: f64 = 9_007_199_254_740_992.0; + +/// Java `DecimalFormat` output for NaN (CLDR locale data, Java 9+). +/// +/// The nf-core Qualimap image (`biocontainers/qualimap:2.3--hdfd78af_0`) +/// ships OpenJDK 21.0.1 with `LANG=C.UTF-8`, so this and [`JAVA_INFINITY`] +/// are what it prints; Java 18+ also writes files as UTF-8 by default. +const JAVA_NAN: &str = "NaN"; + +/// Java `DecimalFormat` output for infinity. +const JAVA_INFINITY: &str = "\u{221e}"; + +/// Qualimap `StringUtilsSwing.formatLong`: an integer with `,` every three digits. +/// +/// `formatLong` passes the `long` to `decimalFormat(double, String)`, so counts +/// above 2^53 lose precision exactly as a double does. +pub(crate) fn format_long(n: u64) -> String { + decimal_format(n as f64, true) +} + +/// Qualimap `StringUtilsSwing.formatDecimal`: up to two decimals, grouped by three. +pub(crate) fn format_decimal(v: f64) -> String { + decimal_format(v, true) +} + +/// Qualimap `StringUtilsSwing.formatPercentage`: up to two decimals and a `%` sign. +pub(crate) fn format_percentage(v: f64) -> String { + let mut s = decimal_format(v, false); + s.push('%'); + s +} + +/// A percentage computed the way Qualimap does it: `(100. * part) / total`. +/// +/// The operand order matters for the last bit of the result, and therefore for +/// how a value close to a rounding boundary is printed. +pub(crate) fn percentage_of(part: u64, total: u64) -> f64 { + (100.0 * part as f64) / total as f64 +} + +/// Java's `Double.toString(v)` (Java 19+), which Qualimap uses when it writes +/// chart data such as the coverage profiles in `raw_data_qualimapReport/`. +/// +/// The digits are the shortest that round-trip, as Rust prints them. Values +/// in `[1e-3, 1e7)` are plain decimals with at least one fraction digit +/// (`0.0`, `12.0`, `0.0041`); others use computerized scientific notation +/// (`1.0E-4`, `1.2345678E7`). +pub(crate) fn java_double_to_string(v: f64) -> String { + if v.is_nan() { + return "NaN".to_string(); + } + let sign = if v.is_sign_negative() { "-" } else { "" }; + if v.is_infinite() { + return format!("{sign}Infinity"); + } + let abs = v.abs(); + let (mantissa, exponent) = if abs == 0.0 || (1e-3..1e7).contains(&abs) { + (abs.to_string(), None) + } else { + let sci = format!("{abs:e}"); + let (m, e) = sci.split_once('e').expect("exponent in {:e} output"); + (m.to_string(), Some(e.to_string())) + }; + let point = if mantissa.contains('.') { "" } else { ".0" }; + match exponent { + None => format!("{sign}{mantissa}{point}"), + Some(e) => format!("{sign}{mantissa}{point}E{e}"), + } +} + +/// `new DecimalFormat(pattern).format(v)` for Qualimap's two decimal patterns: +/// at most two fraction digits, at least one integer digit, HALF_EVEN rounding, +/// optional grouping by three. +/// +/// `DecimalFormat` rounds the double's `FloatingDecimal` digits (17 significant +/// digits at most) and corrects ties for whether those digits are above or +/// below the exact value (`java.text.DigitList.shouldRoundUp`). While a +/// hundredth is far larger than the spacing between doubles, as for every +/// percentage, ratio and bias Qualimap prints, that equals rounding the exact +/// binary value half to even, which is what Rust's `{:.2}` does. Whole numbers +/// from 2^53 up are printed from their shortest digits, as Java does. +fn decimal_format(v: f64, grouping: bool) -> String { + if v.is_nan() { + return JAVA_NAN.to_string(); + } + // Java prints a minus sign for any negative value, including -0.0 and + // values that round to zero. + let sign = if v.is_sign_negative() { "-" } else { "" }; + if v.is_infinite() { + return format!("{sign}{JAVA_INFINITY}"); + } + let abs = v.abs(); + let text = if abs >= EXACT_INTEGER_LIMIT { + format!("{abs}") + } else { + format!("{abs:.2}") + }; + let (int_part, frac_part) = text.split_once('.').unwrap_or((&text, "")); + let frac_part = frac_part.trim_end_matches('0'); + let int_part = if grouping { + group_thousands(int_part) + } else { + int_part.to_string() + }; + if frac_part.is_empty() { + format!("{sign}{int_part}") + } else { + format!("{sign}{int_part}.{frac_part}") + } +} + +/// Insert `,` between groups of three integer digits. +fn group_thousands(digits: &str) -> String { + let len = digits.len(); + let mut out = String::with_capacity(len + len / 3); + for (i, c) in digits.chars().enumerate() { + if i > 0 && (len - i).is_multiple_of(3) { + out.push(','); + } + out.push(c); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Expected strings below were produced by Qualimap 2.3's own + /// `StringUtilsSwing` (bioinfo-commons 0.10.1) on Java 21. + #[test] + fn format_long_groups_by_three() { + assert_eq!(format_long(0), "0"); + assert_eq!(format_long(123), "123"); + assert_eq!(format_long(1234), "1,234"); + assert_eq!(format_long(1_234_567), "1,234,567"); + assert_eq!(format_long(1_000_000_000), "1,000,000,000"); + // Above 2^53 Java formats the count as a double. + assert_eq!(format_long(9_007_199_254_740_993), "9,007,199,254,740,992"); + assert_eq!(format_long(u64::MAX >> 1), "9,223,372,036,854,776,000"); + } + + #[test] + fn percentage_drops_trailing_zeros() { + assert_eq!(format_percentage(60.0), "60%"); + assert_eq!(format_percentage(100.0), "100%"); + assert_eq!(format_percentage(0.0), "0%"); + assert_eq!(format_percentage(37.5), "37.5%"); + assert_eq!(format_percentage(86.77), "86.77%"); + assert_eq!(format_percentage(0.05), "0.05%"); + assert_eq!(format_percentage(1.0 / 3.0 * 100.0), "33.33%"); + } + + #[test] + fn percentage_is_not_grouped() { + assert_eq!(format_percentage(1234.5), "1234.5%"); + } + + #[test] + fn decimal_drops_trailing_zeros_and_groups() { + assert_eq!(format_decimal(0.5), "0.5"); + assert_eq!(format_decimal(1.0), "1"); + assert_eq!(format_decimal(1.3), "1.3"); + assert_eq!(format_decimal(0.44), "0.44"); + assert_eq!(format_decimal(2.0 / 3.0), "0.67"); + assert_eq!(format_decimal(1234.5), "1,234.5"); + assert_eq!(format_decimal(1e6 + 0.125), "1,000,000.12"); + assert_eq!(format_decimal(1e15), "1,000,000,000,000,000"); + assert_eq!(format_decimal(1e20), "100,000,000,000,000,000,000"); + assert_eq!( + format_decimal(123_456_789_012_345_678.0), + "123,456,789,012,345,680" + ); + } + + #[test] + fn rounding_is_half_even_on_the_exact_binary_value() { + // Exact binary ties go to the even neighbour. + assert_eq!(format_decimal(0.125), "0.12"); + assert_eq!(format_decimal(0.375), "0.38"); + assert_eq!(format_decimal(0.625), "0.62"); + assert_eq!(format_decimal(0.875), "0.88"); + assert_eq!(format_percentage(3.125), "3.12%"); + // Not ties: the double is just above or below the decimal literal. + assert_eq!(format_decimal(0.015), "0.01"); // 0.01499999... + assert_eq!(format_decimal(0.035), "0.04"); // 0.03500000...04 + assert_eq!(format_decimal(1.005), "1"); // 1.00499999... + assert_eq!(format_decimal(2.675), "2.67"); // 2.67499999... + assert_eq!(format_decimal(0.995), "0.99"); // 0.99499999... + assert_eq!(format_decimal(9.995), "9.99"); // 9.99499999... + assert_eq!(format_percentage(99.995), "100%"); // 99.99500000...03 + // Carry into the integer part and a new group. + assert_eq!(format_decimal(999.999), "1,000"); + } + + #[test] + fn special_values_match_java() { + assert_eq!(format_decimal(f64::NAN), "NaN"); + assert_eq!(format_percentage(f64::NAN), "NaN%"); + assert_eq!(format_decimal(f64::INFINITY), "\u{221e}"); + assert_eq!(format_decimal(f64::NEG_INFINITY), "-\u{221e}"); + assert_eq!(format_decimal(-0.0), "-0"); + assert_eq!(format_decimal(-0.004), "-0"); + assert_eq!(format_decimal(-1.5), "-1.5"); + assert_eq!(format_decimal(-1_234_567.891), "-1,234,567.89"); + assert_eq!(format_decimal(f64::from_bits(1)), "0"); + } + + #[test] + fn strand_estimation_is_formatted_as_a_float() { + // Qualimap divides in single precision: fwd / (float)(fwd + rev). + let ssp = |fwd: u64, rev: u64| f64::from(fwd as f32 / (fwd + rev) as f32); + assert_eq!(format_decimal(ssp(1, 1)), "0.5"); + assert_eq!(format_decimal(ssp(1, 7)), "0.12"); // 0.125f is a tie + assert_eq!(format_decimal(ssp(3, 0)), "1"); + } + + #[test] + fn double_to_string_matches_java() { + assert_eq!(java_double_to_string(0.0), "0.0"); + assert_eq!(java_double_to_string(-0.0), "-0.0"); + assert_eq!(java_double_to_string(1.0), "1.0"); + assert_eq!(java_double_to_string(99.0), "99.0"); + assert_eq!(java_double_to_string(0.1), "0.1"); + assert_eq!( + java_double_to_string(0.004131012097964001), + "0.004131012097964001" + ); + assert_eq!(java_double_to_string(1234.5), "1234.5"); + assert_eq!(java_double_to_string(0.001), "0.001"); + assert_eq!(java_double_to_string(0.000_999), "9.99E-4"); + assert_eq!(java_double_to_string(1e-4), "1.0E-4"); + assert_eq!(java_double_to_string(9_999_999.0), "9999999.0"); + assert_eq!(java_double_to_string(1e7), "1.0E7"); + assert_eq!(java_double_to_string(12_345_678.9), "1.23456789E7"); + assert_eq!(java_double_to_string(-2.5e-5), "-2.5E-5"); + assert_eq!(java_double_to_string(f64::NAN), "NaN"); + assert_eq!(java_double_to_string(f64::INFINITY), "Infinity"); + assert_eq!(java_double_to_string(f64::NEG_INFINITY), "-Infinity"); + } + + #[test] + fn percentage_of_uses_qualimaps_operand_order() { + assert_eq!(percentage_of(1, 3), (100.0 * 1.0) / 3.0); + assert_eq!(format_percentage(percentage_of(6, 10)), "60%"); + assert_eq!(format_percentage(percentage_of(1639, 1889)), "86.77%"); + } +} diff --git a/src/rna/qualimap/mod.rs b/src/rna/qualimap/mod.rs index ce40ee9..bb567d9 100644 --- a/src/rna/qualimap/mod.rs +++ b/src/rna/qualimap/mod.rs @@ -5,6 +5,7 @@ pub mod accumulator; pub mod coverage; +mod format; pub mod index; pub mod output; pub mod plots; @@ -26,7 +27,7 @@ use std::collections::HashMap; #[derive(Debug)] pub struct QualimapResult { // --- Read counters --- - /// Total primary alignments (excluding unmapped, secondary, supplementary, QC-fail). + /// Mapped records not flagged secondary (supplementary and QC-fail included). pub primary_alignments: u64, /// Total secondary alignments seen. pub secondary_alignments: u64, @@ -34,6 +35,9 @@ pub struct QualimapResult { pub not_aligned: u64, /// Reads skipped because NH > 1 (multi-mappers). pub alignment_not_unique: u64, + /// Mapped reads on a sequence with no annotated exon ("Missing chromosome + /// in annotation" in the HTML report). + pub seq_not_found: u64, // --- Gene assignment counters --- /// Reads assigned to exactly one gene (exonic). @@ -50,7 +54,7 @@ pub struct QualimapResult { pub overlapping_exon_reads: u64, // --- Fragment counters (PE) --- - /// Total reads counted (PE: each mate counts as 1 read). + /// Mapped records on an annotated sequence (Qualimap `readCount`). pub read_count: u64, /// Left-of-pair reads (first-of-pair in paired mode). pub left_proper_in_pair: u64, @@ -81,3 +85,124 @@ pub struct QualimapResult { /// Reverse strand estimation count for SSP. pub ssp_rev: u64, } + +// ============================================================================ +// Junction motif ordering +// ============================================================================ + +/// Number of junction motifs listed in the report. Qualimap's output loop runs +/// while `count <= 10`, so it prints at most 11 motifs. +pub(crate) const TOP_JUNCTION_MOTIFS: usize = 11; + +/// Order junction motifs for output: most frequent first, ties broken by motif +/// name (alphabetical). +/// +/// Qualimap 2.3 keeps the motif counts in a `java.util.HashMap`, sorts them by +/// percentage with a stable sort and prints the list backwards +/// (`TranscriptDataHandler.computeSortedJunctionsMap` and the junction loops in +/// `RNASeqQCAnalysis`). Tied motifs therefore come out in reverse HashMap +/// iteration order. That order depends on the table size and, for keys that +/// share a bucket, on the order the motifs were first seen in the +/// (name-sorted, for paired-end) input. RustQC reads the BAM in a different +/// order, so it cannot reproduce Qualimap's tie order. It uses the motif name +/// instead, which keeps the output identical across runs and thread counts. +pub(crate) fn sorted_junction_motifs(motifs: &HashMap) -> Vec<(&str, u64)> { + let mut sorted: Vec<(&str, u64)> = motifs.iter().map(|(m, &c)| (m.as_str(), c)).collect(); + sorted.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(b.0))); + sorted +} + +/// The junction motif rows Qualimap prints: up to [`TOP_JUNCTION_MOTIFS`] +/// motifs with their share of `reads_at_junctions`, computed as +/// `(count * 100.) / numReadsWithJunction` like +/// `TranscriptDataHandler.computeSortedJunctionsMap`. Empty when no read has a +/// junction. +pub(crate) fn junction_motif_rows( + motifs: &HashMap, + reads_at_junctions: u64, +) -> Vec<(&str, f64)> { + if reads_at_junctions == 0 { + return Vec::new(); + } + sorted_junction_motifs(motifs) + .into_iter() + .take(TOP_JUNCTION_MOTIFS) + .map(|(motif, count)| (motif, (count as f64 * 100.0) / reads_at_junctions as f64)) + .collect() +} + +/// Qualimap's strand-specificity estimation (fwd, rev). +/// +/// `ComputeCountsTask.getFwdStrandEstimation` divides in single precision, +/// `fwd / (float)(fwd + rev)`, so the value is computed as an `f32` and only +/// then widened for formatting. Both are NaN when no read overlapped a feature. +pub(crate) fn strand_estimation(fwd: u64, rev: u64) -> (f64, f64) { + let total = (fwd + rev) as f32; + (f64::from(fwd as f32 / total), f64::from(rev as f32 / total)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn motif_map(entries: &[(&str, u64)]) -> HashMap { + entries.iter().map(|&(m, c)| (m.to_string(), c)).collect() + } + + #[test] + fn junction_motifs_sorted_by_count_descending() { + let motifs = motif_map(&[("GTAG", 5), ("CTAC", 90), ("GCAG", 20)]); + assert_eq!( + sorted_junction_motifs(&motifs), + vec![("CTAC", 90), ("GCAG", 20), ("GTAG", 5)] + ); + } + + #[test] + fn junction_motif_ties_broken_by_name() { + // Four motifs tied at the same count, as seen in CI where their order + // used to change from run to run. + let motifs = motif_map(&[ + ("TGGT", 1), + ("AGGT", 1), + ("ACAA", 1), + ("TTTT", 1), + ("GTAG", 6), + ]); + assert_eq!( + sorted_junction_motifs(&motifs), + vec![ + ("GTAG", 6), + ("ACAA", 1), + ("AGGT", 1), + ("TGGT", 1), + ("TTTT", 1) + ] + ); + } + + #[test] + fn junction_motif_order_independent_of_insertion_order() { + let entries: Vec<(String, u64)> = (0..64u64) + .map(|i| { + let bases = b"ACGT"; + let motif: String = (0..4) + .map(|p| bases[((i >> (2 * p)) & 3) as usize] as char) + .collect(); + (motif, i % 3) + }) + .collect(); + let forward: HashMap = entries.iter().cloned().collect(); + let mut reversed = HashMap::with_capacity(1); + for (m, c) in entries.iter().rev() { + reversed.insert(m.clone(), *c); + } + // Many ties (64 motifs, 3 distinct counts), so the top-11 cut falls + // inside a tie group and must not depend on insertion order. + let expected = sorted_junction_motifs(&forward); + assert_eq!(expected, sorted_junction_motifs(&reversed)); + assert!(expected + .windows(2) + .all(|w| w[0].1 > w[1].1 || (w[0].1 == w[1].1 && w[0].0 < w[1].0))); + } +} diff --git a/src/rna/qualimap/output.rs b/src/rna/qualimap/output.rs index 5d53082..a4f9a18 100644 --- a/src/rna/qualimap/output.rs +++ b/src/rna/qualimap/output.rs @@ -10,6 +10,9 @@ use anyhow::{Context, Result}; use log::debug; use super::coverage::TranscriptCoverage; +use super::format::{ + format_decimal, format_long, format_percentage, java_double_to_string, percentage_of, +}; use super::index::QualimapIndex; use super::plots; use super::QualimapResult; @@ -26,73 +29,17 @@ const HIGH_TIER_COUNT: usize = 500; /// Number of transcripts for the "low" expression tier. const LOW_TIER_COUNT: usize = 500; -/// Number of top transcripts used for 5'-3' bias calculation. -const NUM_TRANSCRIPTS_FOR_BIAS: usize = 1000; +/// Number of top transcripts used for 5'-3' bias calculation, as Qualimap +/// prints it. Its selection code actually keeps the top 1001 (see +/// [`compute_bias`]). +pub(super) const NUM_TRANSCRIPTS_FOR_BIAS: usize = 1000; /// Number of bases at 5'/3' ends used for bias calculation. -const NUM_PRIME_BASES: usize = 100; +pub(super) const NUM_PRIME_BASES: usize = 100; /// Minimum transcript length for bias calculation. const MIN_TRANSCRIPT_LENGTH_FOR_BIAS: usize = 500; -// ============================= Number Formatting =============================== - -/// Format an integer with comma separators (e.g., 1234567 → "1,234,567"). -use crate::io::format_with_commas; - -/// Format a percentage with Qualimap-style precision. -/// -/// Qualimap uses Java's default `String.format("%.2f", val)` but with -/// trailing-zero trimming on the decimal part. Looking at real output: -/// - 68.3% (not 68.30%) -/// - 29.69% -/// - 2.01% -/// - 9.31% -/// -/// The pattern is: 2 decimal places, then strip trailing zeros (but keep -/// at least one decimal digit). -fn format_percentage(val: f64) -> String { - let s = format!("{:.2}", val); - // Strip trailing zeros after decimal point, but keep at least one decimal - if s.contains('.') { - let trimmed = s.trim_end_matches('0'); - let trimmed = if trimmed.ends_with('.') { - // e.g., "68." → keep at least "68.0" - // Actually Qualimap shows "68.3" not "68.0" — but if we get exactly - // an integer like 68.00, it would show "68.0" based on the trim logic. - // However looking at real data, Qualimap never shows ".0" — it shows - // integers as "68" etc. Let's check: the real data shows "68.3%", "29.69%" - // etc. When the value is exactly integer, Qualimap shows e.g. "9.31%". - // There's no case of exactly-integer percentages in the reference. - // Be safe: keep "X.0" format. - &s[..trimmed.len() + 1] - } else { - trimmed - }; - trimmed.to_string() - } else { - s - } -} - -/// Format a bias value with Qualimap-style precision. -/// -/// Qualimap uses 2 decimal places with trailing-zero trimming. -/// Examples: 0.71, 0.57, 1.3, 1.47, 0.31, 0.22 -fn format_bias(val: f64) -> String { - let s = format!("{:.2}", val); - if s.contains('.') { - let trimmed = s.trim_end_matches('0'); - if trimmed.ends_with('.') { - format!("{}.0", trimmed.trim_end_matches('.')) - } else { - trimmed.to_string() - } - } else { - s - } -} - // ============================= Coverage Profile ================================ /// Per-transcript coverage data used for profile computation. @@ -154,121 +101,137 @@ fn compute_coverage_profile(entries: &[&TranscriptCoverageEntry]) -> [f64; NUM_B /// Compute 5'-3' bias values from per-transcript coverage. /// -/// For each qualifying transcript (length >= 500, mean >= 1.0): -/// - Compute mean coverage of first `NUM_PRIME_BASES` bases (5' end) -/// - Compute mean coverage of last `NUM_PRIME_BASES` bases (3' end) -/// - Compute mean coverage of entire transcript -/// - 5' bias = 5' mean / whole mean -/// - 3' bias = 3' mean / whole mean -/// - 5'-3' bias = 5' mean / 3' mean +/// Follows Qualimap's `TranscriptDataHandler.calculateCoverageBias()` and +/// `pickTranscripts()` (themselves ported from Picard's `RnaMetricsCollector`): /// -/// For negative-strand transcripts, the coverage array is reversed before -/// computing 5'/3' regions. -/// -/// Returns (5' bias, 3' bias, 5'-3' bias) as medians across all qualifying -/// transcripts. -fn compute_bias(entries: &[TranscriptCoverageEntry]) -> (f64, f64, f64) { +/// 1. Per gene, pick the transcript with the highest mean coverage among +/// those at least 500 bp long with mean coverage >= 1. Transcripts are +/// visited in Java `HashMap` order (`order`) and only a strictly higher +/// mean replaces the current best, so on ties the first one visited wins. +/// 2. Keep every picked transcript whose mean is at least the 1001st highest +/// mean (`coverages[max(0, n - 1001)]` in the sorted means), so up to 1001 +/// transcripts plus ties, not 1000. +/// 3. For each, with the coverage reversed for minus-strand genes: +/// 5' bias = mean(first 100 bases) / mean, 3' bias = mean(last 100) / mean, +/// 5'-3' bias = mean(first 100) / mean(last 100). No value is filtered: +/// a transcript with no coverage in either end gives 0/0 = NaN. +/// 4. Report `StatUtils.percentile(values, 50)` of each list (Commons Math +/// 2.0, see [`commons_math_median`]). +fn compute_bias(entries: &[TranscriptCoverageEntry], order: &[usize]) -> (f64, f64, f64) { use std::collections::HashMap; - // Step 1: Pick best transcript per gene (highest mean coverage). - // Qualimap selects one transcript per gene, then filters by length >= 500 - // and mean >= 1.0, then takes the top 1000 by mean coverage. - // Java qualimap uses strict > with HashMap iteration order (effectively - // non-deterministic across JVM versions). We use >= so that when two - // transcripts tie, the later one in GTF order wins. This is deterministic - // within RustQC and closer to HashMap's overwrite-on-put semantics. - let mut best_per_gene: HashMap = HashMap::new(); - for entry in entries { + // Step 1: best transcript per gene. + let mut best_per_gene: HashMap = HashMap::new(); + for &idx in order { + let entry = &entries[idx]; if entry.coverage.len() < MIN_TRANSCRIPT_LENGTH_FOR_BIAS || entry.mean_coverage < 1.0 { continue; } - let gene = entry.gene_idx; - let dominated = match best_per_gene.get(&gene) { + let better = match best_per_gene.get(&entry.gene_idx) { None => true, - Some(best) => entry.mean_coverage >= best.mean_coverage, + Some(&best) => entry.mean_coverage > entries[best].mean_coverage, }; - if dominated { - best_per_gene.insert(gene, entry); + if better { + best_per_gene.insert(entry.gene_idx, idx); } } - - // Collect qualifying transcripts and sort by mean coverage descending - let mut qualifying: Vec<(f64, &TranscriptCoverageEntry)> = best_per_gene - .values() - .map(|e| (e.mean_coverage, *e)) - .collect(); - - if qualifying.is_empty() { + if best_per_gene.is_empty() { return (f64::NAN, f64::NAN, f64::NAN); } - // Sort by mean coverage descending, take top N - qualifying.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal)); - qualifying.truncate(NUM_TRANSCRIPTS_FOR_BIAS); + // Step 2: keep transcripts at or above the 1001st best mean coverage. + let mut means: Vec = best_per_gene + .values() + .map(|&i| entries[i].mean_coverage) + .collect(); + means.sort_by(java_double_cmp); + let min_mean = means[means.len().saturating_sub(NUM_TRANSCRIPTS_FOR_BIAS + 1)]; - let mut five_prime_biases = Vec::with_capacity(qualifying.len()); - let mut three_prime_biases = Vec::with_capacity(qualifying.len()); - let mut five_three_biases = Vec::with_capacity(qualifying.len()); + let mut five_prime_biases = Vec::new(); + let mut three_prime_biases = Vec::new(); + let mut five_three_biases = Vec::new(); - for (_, entry) in &qualifying { - let cov = &entry.coverage; - let len = cov.len(); - if len < NUM_PRIME_BASES { + for &idx in best_per_gene.values() { + let entry = &entries[idx]; + if entry.mean_coverage < min_mean { continue; } - - // For negative strand, reverse the array conceptually - let (five_prime_sum, three_prime_sum, whole_sum) = if entry.strand == '-' { - // 5' end is at the END of the array for negative strand - let five_sum: f64 = cov[len - NUM_PRIME_BASES..].iter().map(|&v| v as f64).sum(); - let three_sum: f64 = cov[..NUM_PRIME_BASES].iter().map(|&v| v as f64).sum(); - let whole_sum: f64 = cov.iter().map(|&v| v as f64).sum(); - (five_sum, three_sum, whole_sum) + let cov = &entry.coverage; + let len = cov.len(); + // Picard's MathUtil.mean: sequential sum / count. For minus-strand + // genes the array is reversed, so the 5' end is at the end. + let mean_of = |range: std::ops::Range| -> f64 { + let n = range.len() as f64; + range.map(|i| cov[i] as f64).sum::() / n + }; + let (five_mean, three_mean) = if entry.strand == '-' { + ( + mean_of(len - NUM_PRIME_BASES..len), + mean_of(0..NUM_PRIME_BASES), + ) } else { - let five_sum: f64 = cov[..NUM_PRIME_BASES].iter().map(|&v| v as f64).sum(); - let three_sum: f64 = cov[len - NUM_PRIME_BASES..].iter().map(|&v| v as f64).sum(); - let whole_sum: f64 = cov.iter().map(|&v| v as f64).sum(); - (five_sum, three_sum, whole_sum) + ( + mean_of(0..NUM_PRIME_BASES), + mean_of(len - NUM_PRIME_BASES..len), + ) }; - - let five_mean = five_prime_sum / NUM_PRIME_BASES as f64; - let three_mean = three_prime_sum / NUM_PRIME_BASES as f64; - let whole_mean = whole_sum / len as f64; + let whole_mean = mean_of(0..len); five_prime_biases.push(five_mean / whole_mean); three_prime_biases.push(three_mean / whole_mean); - // The 5'/3' ratio can be Infinity or NaN when three_mean == 0. - // Filter NaN values only (not Infinity) to match upstream qualimap - // behavior — Java's StatUtils.percentile handles Infinity correctly - // via Arrays.sort but NaN would produce meaningless results. - let ratio = five_mean / three_mean; - if !ratio.is_nan() { - five_three_biases.push(ratio); - } + five_three_biases.push(five_mean / three_mean); } - let five = median(&mut five_prime_biases); - let three = median(&mut three_prime_biases); - let five_three = median(&mut five_three_biases); + debug!( + "Qualimap 5'-3' bias: {} transcripts, {} with no coverage at either end (NaN)", + five_three_biases.len(), + five_three_biases.iter().filter(|v| v.is_nan()).count() + ); + + ( + commons_math_median(&mut five_prime_biases), + commons_math_median(&mut three_prime_biases), + commons_math_median(&mut five_three_biases), + ) +} - (five, three, five_three) +/// Order doubles as Java's `Arrays.sort(double[])` does: NaN sorts after +/// +Infinity (whatever its sign bit) and -0.0 before 0.0. +fn java_double_cmp(a: &f64, b: &f64) -> std::cmp::Ordering { + match (a.is_nan(), b.is_nan()) { + (false, false) => a.total_cmp(b), + (a_nan, b_nan) => a_nan.cmp(&b_nan), + } } -/// Compute the median of a slice of f64 values. +/// Commons Math 2.0 `StatUtils.percentile(values, 50)`, as Qualimap uses it. /// -/// Qualimap uses Apache Commons Math 2.0 `StatUtils.percentile(array, 50)`, -/// which filters NaN values and computes a standard median. -fn median(values: &mut [f64]) -> f64 { - if values.is_empty() { - return f64::NAN; +/// The values are sorted with `Arrays.sort` (NaN last, not removed), then +/// `pos = p * (n + 1) / 100` is interpolated between its neighbours as +/// `lower + (pos - floor(pos)) * (upper - lower)`. +fn commons_math_median(values: &mut [f64]) -> f64 { + const P: f64 = 50.0; + let length = values.len(); + match length { + 0 => return f64::NAN, + 1 => return values[0], + _ => {} } - values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); - let n = values.len(); - if n.is_multiple_of(2) { - (values[n / 2 - 1] + values[n / 2]) / 2.0 - } else { - values[n / 2] + let n = length as f64; + let pos = P * (n + 1.0) / 100.0; + let fpos = pos.floor(); + let int_pos = fpos as usize; + let dif = pos - fpos; + values.sort_by(java_double_cmp); + if pos < 1.0 { + return values[0]; } + if pos >= n { + return values[length - 1]; + } + let lower = values[int_pos - 1]; + let upper = values[int_pos]; + lower + dif * (upper - lower) } // ============================= Coverage Histogram ============================== @@ -304,6 +267,8 @@ fn compute_mean_coverage_histogram( /// Write the coverage profile TSV file. /// /// Format: tab-separated, header line starting with `#`, 100 rows (0.0–99.0). +/// Qualimap writes both columns by string concatenation, i.e. with +/// `Double.toString` (`BamQCChart.exportData`). fn write_coverage_profile(profile: &[f64; NUM_BINS], path: &Path) -> Result<()> { use std::fs::File; @@ -313,7 +278,12 @@ fn write_coverage_profile(profile: &[f64; NUM_BINS], path: &Path) -> Result<()> writeln!(f, "#Transcript position\tTranscript coverage profile")?; for (i, &val) in profile.iter().enumerate() { - writeln!(f, "{:.1}\t{}", i as f64, val)?; + writeln!( + f, + "{}\t{}", + java_double_to_string(i as f64), + java_double_to_string(val) + )?; } Ok(()) @@ -434,7 +404,17 @@ pub fn write_qualimap_results( let high_profile = compute_coverage_profile(&high_entries); // --- Compute bias --- - let (five_bias, three_bias, five_three_bias) = compute_bias(&entries); + // TranscriptDataHandler.calculateCoverageBias returns early when no + // transcript received any coverage, leaving the three medians at 0.0. + let (five_bias, three_bias, five_three_bias) = if result + .transcript_coverage_raw + .num_transcripts_with_coverage() + == 0 + { + (0.0, 0.0, 0.0) + } else { + compute_bias(&entries, &java_ordered_indices) + }; // --- Compute mean coverage histogram --- let coverage_histogram = compute_mean_coverage_histogram(&entries); @@ -550,6 +530,7 @@ pub fn write_qualimap_results( primary_alignments: result.primary_alignments, secondary_alignments: result.secondary_alignments, alignment_not_unique: result.alignment_not_unique, + seq_not_found: result.seq_not_found, exonic_reads: result.exonic_reads, ambiguous_reads: result.ambiguous_reads, no_feature: result.no_feature, @@ -622,66 +603,62 @@ fn write_results_file( writeln!( f, " reads aligned (left/right) = {} / {}", - format_with_commas(result.left_proper_in_pair), - format_with_commas(result.right_proper_in_pair) + format_long(result.left_proper_in_pair), + format_long(result.right_proper_in_pair) )?; writeln!( f, " read pairs aligned = {}", - format_with_commas(result.both_proper_in_pair / 2) + format_long(result.both_proper_in_pair / 2) )?; } else { writeln!( f, " reads aligned = {}", - format_with_commas(result.read_count) + format_long(result.primary_alignments) )?; } writeln!( f, " total alignments = {}", - format_with_commas(result.primary_alignments + result.secondary_alignments) + format_long(result.primary_alignments + result.secondary_alignments) )?; writeln!( f, " secondary alignments = {}", - format_with_commas(result.secondary_alignments) + format_long(result.secondary_alignments) )?; writeln!( f, " non-unique alignments = {}", - format_with_commas(result.alignment_not_unique) + format_long(result.alignment_not_unique) )?; writeln!( f, " aligned to genes = {}", - format_with_commas(result.exonic_reads) + format_long(result.exonic_reads) )?; writeln!( f, " ambiguous alignments = {}", - format_with_commas(result.ambiguous_reads) + format_long(result.ambiguous_reads) )?; writeln!( f, " no feature assigned = {}", - format_with_commas(result.no_feature) - )?; - writeln!( - f, - " not aligned = {}", - format_with_commas(result.not_aligned) + format_long(result.no_feature) )?; + writeln!(f, " not aligned = {}", format_long(result.not_aligned))?; - // SSP estimation — only written when protocol was not pre-specified (unstranded) - // When the user specifies --stranded, Qualimap does not output this line. + // SSP estimation: only when the protocol is not strand-specific. if stranded == Strandedness::Unstranded { - let ssp_total = result.ssp_fwd + result.ssp_rev; - if ssp_total > 0 { - let fwd = result.ssp_fwd as f64 / ssp_total as f64; - let rev = result.ssp_rev as f64 / ssp_total as f64; - writeln!(f, " SSP estimation (fwd/rev) = {:.2} / {:.2}", fwd, rev)?; - } + let (fwd, rev) = super::strand_estimation(result.ssp_fwd, result.ssp_rev); + writeln!( + f, + " SSP estimation (fwd/rev) = {} / {}", + format_decimal(fwd), + format_decimal(rev) + )?; } writeln!(f)?; writeln!(f)?; @@ -690,39 +667,19 @@ fn write_results_file( writeln!(f, ">>>>>>> Reads genomic origin")?; writeln!(f)?; - let total_classified = result.exonic_reads + result.intronic_reads + result.intergenic_reads; - if total_classified > 0 { - let exonic_pct = result.exonic_reads as f64 / total_classified as f64 * 100.0; - let intronic_pct = result.intronic_reads as f64 / total_classified as f64 * 100.0; - let intergenic_pct = result.intergenic_reads as f64 / total_classified as f64 * 100.0; - - // overlapping exon percentage is relative to total classified - let overlapping_pct = - result.overlapping_exon_reads as f64 / total_classified as f64 * 100.0; - - writeln!( - f, - " exonic = {} ({}%)", - format_with_commas(result.exonic_reads), - format_percentage(exonic_pct) - )?; + // Qualimap divides by exonic + "no feature" reads (RNASeqQCAnalysis.writeReport). + let total_reads = result.exonic_reads + result.no_feature; + for (label, count) in [ + ("exonic = ", result.exonic_reads), + ("intronic =", result.intronic_reads), + ("intergenic =", result.intergenic_reads), + ("overlapping exon =", result.overlapping_exon_reads), + ] { writeln!( f, - " intronic = {} ({}%)", - format_with_commas(result.intronic_reads), - format_percentage(intronic_pct) - )?; - writeln!( - f, - " intergenic = {} ({}%)", - format_with_commas(result.intergenic_reads), - format_percentage(intergenic_pct) - )?; - writeln!( - f, - " overlapping exon = {} ({}%)", - format_with_commas(result.overlapping_exon_reads), - format_percentage(overlapping_pct) + " {label} {} ({})", + format_long(count), + format_percentage(percentage_of(count, total_reads)) )?; } writeln!(f)?; @@ -731,9 +688,9 @@ fn write_results_file( // >>>>>>> Transcript coverage profile writeln!(f, ">>>>>>> Transcript coverage profile")?; writeln!(f)?; - writeln!(f, " 5' bias = {}", format_bias(five_bias))?; - writeln!(f, " 3' bias = {}", format_bias(three_bias))?; - writeln!(f, " 5'-3' bias = {}", format_bias(five_three_bias))?; + writeln!(f, " 5' bias = {}", format_decimal(five_bias))?; + writeln!(f, " 3' bias = {}", format_decimal(three_bias))?; + writeln!(f, " 5'-3' bias = {}", format_decimal(five_three_bias))?; writeln!(f)?; writeln!(f)?; @@ -743,25 +700,15 @@ fn write_results_file( writeln!( f, " reads at junctions = {}", - format_with_commas(result.reads_at_junctions) + format_long(result.reads_at_junctions) )?; writeln!(f)?; - // Sort junction motifs by percentage descending - if result.reads_at_junctions > 0 { - let total_junctions = result.reads_at_junctions as f64; - let mut motif_pcts: Vec<(String, f64)> = result - .junction_motifs - .iter() - .map(|(motif, &count)| (motif.clone(), count as f64 * 100.0 / total_junctions)) - .collect(); - motif_pcts.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal)); - - // Qualimap shows top 11 motifs (count <= 10 in their loop) - for (motif, pct) in motif_pcts.iter().take(11) { - // Match Java DecimalFormat("###.##"): trailing-zero trimming. - writeln!(f, " {} : {}%", motif, format_bias(*pct))?; - } + // Junction motifs by percentage descending, ties broken by motif name + for (motif, pct) in + super::junction_motif_rows(&result.junction_motifs, result.reads_at_junctions) + { + writeln!(f, " {} : {}", motif, format_percentage(pct))?; } Ok(()) @@ -938,37 +885,20 @@ mod tests { use super::*; #[test] - fn test_format_with_commas() { - assert_eq!(format_with_commas(0), "0"); - assert_eq!(format_with_commas(999), "999"); - assert_eq!(format_with_commas(1000), "1,000"); - assert_eq!(format_with_commas(1234567), "1,234,567"); - assert_eq!(format_with_commas(87559392), "87,559,392"); - } - - #[test] - fn test_format_percentage() { - assert_eq!(format_percentage(68.30), "68.3"); - assert_eq!(format_percentage(29.69), "29.69"); - assert_eq!(format_percentage(2.01), "2.01"); - assert_eq!(format_percentage(9.31), "9.31"); - assert_eq!(format_percentage(100.00), "100.0"); - } - - #[test] - fn test_format_bias() { - assert_eq!(format_bias(0.71), "0.71"); - assert_eq!(format_bias(0.57), "0.57"); - assert_eq!(format_bias(1.30), "1.3"); - assert_eq!(format_bias(1.47), "1.47"); - assert_eq!(format_bias(0.22), "0.22"); - } - - #[test] - fn test_median() { - assert_eq!(median(&mut [1.0, 3.0, 2.0]), 2.0); - assert_eq!(median(&mut [1.0, 2.0, 3.0, 4.0]), 2.5); - assert!(median(&mut []).is_nan()); + fn test_commons_math_median() { + assert_eq!(commons_math_median(&mut [1.0, 3.0, 2.0]), 2.0); + assert_eq!(commons_math_median(&mut [1.0, 2.0, 3.0, 4.0]), 2.5); + assert_eq!(commons_math_median(&mut [7.0]), 7.0); + assert!(commons_math_median(&mut []).is_nan()); + // NaN is kept and sorts last (whatever its sign), like Java's + // Arrays.sort, which moves the median up; +Infinity sorts before NaN. + assert_eq!(commons_math_median(&mut [f64::NAN, 1.0, 2.0, 3.0]), 2.5); + assert_eq!( + commons_math_median(&mut [-f64::NAN, f64::INFINITY, 1.0, 2.0]), + f64::INFINITY + ); + // `lower + 0 * (NaN - lower)` is NaN, as in Java. + assert!(commons_math_median(&mut [f64::NAN, 1.0, 2.0]).is_nan()); } /// Helper: build a single-transcript slice for compute_coverage_profile. diff --git a/src/rna/qualimap/report.rs b/src/rna/qualimap/report.rs index bf0b488..f30e632 100644 --- a/src/rna/qualimap/report.rs +++ b/src/rna/qualimap/report.rs @@ -9,6 +9,8 @@ use std::path::Path; use anyhow::{Context, Result}; +use super::format::{format_decimal, format_long, format_percentage, percentage_of}; +use super::output::{NUM_PRIME_BASES, NUM_TRANSCRIPTS_FOR_BIAS}; use crate::Strandedness; use log::debug; @@ -125,6 +127,8 @@ pub struct ReportData<'a> { pub secondary_alignments: u64, /// Non-unique alignments. pub alignment_not_unique: u64, + /// Mapped reads on a sequence with no annotated exon. + pub seq_not_found: u64, /// Reads aligned to genes (exonic). pub exonic_reads: u64, /// Ambiguous reads. @@ -292,26 +296,26 @@ fn write_input_section(html: &mut String, data: &ReportData) { let rows = [ ("Analysis date: ", date_str), ("BAM file: ", data.bam_path.to_string()), - ("Counting algorithm:", " uniquely-mapped-reads".to_string()), + ("Counting algorithm:", "uniquely-mapped-reads".to_string()), ("GTF file: ", data.gtf_path.to_string()), ( "Number of bases for 5'-3' bias computation:", - " 100".to_string(), + format_long(NUM_PRIME_BASES as u64), ), ( "Number of transcripts for 5'-3' bias computation:", - " 1,000".to_string(), + format_long(NUM_TRANSCRIPTS_FOR_BIAS as u64), ), ( "Paired-end sequencing:", if data.paired { - " yes".to_string() + "yes".to_string() } else { - " no".to_string() + "no".to_string() }, ), ("Protocol: ", protocol.to_string()), - ("Sorting performed:", " no".to_string()), + ("Sorting performed:", "no".to_string()), ]; for (label, value) in &rows { @@ -327,183 +331,115 @@ fn write_summary_section(html: &mut String, data: &ReportData) { html.push_str("
\n"); html.push_str("

Summary 

\n"); - // --- Reads alignment --- - html.push_str("
\n
\n"); - html.push_str("

Reads alignment

\n"); - html.push_str("\n"); - + // --- Reads alignment (RNASeqQCAnalysis.prepareHtmlSummary) --- + let mut alignment: Vec<(&str, String)> = Vec::new(); if data.paired { - // Qualimap uses a SINGLE row: "Number of mapped reads (left/right):" / "N / M" - table_row( - html, + alignment.push(( "Number of mapped reads (left/right):", - &format!( + format!( "{} / {}", - format_with_commas(data.left_proper), - format_with_commas(data.right_proper) + format_long(data.left_proper), + format_long(data.right_proper) ), - ); - table_row( - html, + )); + alignment.push(( "Number of aligned pairs (without duplicates):", - &format_with_commas(data.both_proper / 2), - ); + format_long(data.both_proper / 2), + )); + } else { + alignment.push(( + "Number of mapped reads:", + format_long(data.primary_alignments), + )); } - - table_row( - html, - "Total number of alignments:", - &format_with_commas(data.primary_alignments + data.secondary_alignments), - ); - table_row( - html, - "Number of secondary alignments:", - &format_with_commas(data.secondary_alignments), - ); - table_row( - html, - "Number of non-unique alignments:", - &format_with_commas(data.alignment_not_unique), - ); - table_row( - html, - "Aligned to genes:", - &format_with_commas(data.exonic_reads), - ); - table_row( - html, - "Ambiguous alignments:", - &format_with_commas(data.ambiguous_reads), - ); - table_row( - html, - "No feature assigned:", - &format_with_commas(data.no_feature), - ); - table_row(html, "Not aligned:", &format_with_commas(data.not_aligned)); - - // SSP estimation (if unstranded) + alignment.extend([ + ( + "Total number of alignments:", + format_long(data.primary_alignments + data.secondary_alignments), + ), + ( + "Number of secondary alignments:", + format_long(data.secondary_alignments), + ), + ( + "Number of non-unique alignments:", + format_long(data.alignment_not_unique), + ), + ("Aligned to genes:", format_long(data.exonic_reads)), + ("Ambiguous alignments:", format_long(data.ambiguous_reads)), + ("No feature assigned:", format_long(data.no_feature)), + ]); + if data.seq_not_found > 0 { + alignment.push(( + "Missing chromosome in annotation: ", + format_long(data.seq_not_found), + )); + } + alignment.push(("Not aligned:", format_long(data.not_aligned))); if data.stranded == Strandedness::Unstranded { - let total_ssp = data.ssp_fwd + data.ssp_rev; - if total_ssp > 0 { - let fwd_pct = data.ssp_fwd as f64 / total_ssp as f64 * 100.0; - let rev_pct = data.ssp_rev as f64 / total_ssp as f64 * 100.0; - table_row( - html, - "Strand specificity estimation (fwd/rev):", - &format!("{:.2}% / {:.2}%", fwd_pct, rev_pct), - ); - } + let (fwd, rev) = super::strand_estimation(data.ssp_fwd, data.ssp_rev); + alignment.push(( + "Strand specificity estimation (fwd/rev):", + format!("{} / {}", format_decimal(fwd), format_decimal(rev)), + )); } - - html.push_str("
\n
\n
\n"); + summary_table(html, "Reads alignment", &alignment); // --- Reads genomic origin --- - html.push_str("
\n
\n"); - html.push_str("

Reads genomic origin

\n"); - html.push_str("\n"); - - let total_classified = data.exonic_reads + data.intronic_reads + data.intergenic_reads; - let exonic_pct = if total_classified > 0 { - data.exonic_reads as f64 / total_classified as f64 * 100.0 - } else { - 0.0 + // Percentages of exonic + "no feature" reads, as in the text report. + let total_reads = data.exonic_reads + data.no_feature; + let origin_row = |count: u64| { + format!( + "{} / {}", + format_long(count), + format_percentage(percentage_of(count, total_reads)) + ) }; - let intronic_pct = if total_classified > 0 { - data.intronic_reads as f64 / total_classified as f64 * 100.0 - } else { - 0.0 - }; - let intergenic_pct = if total_classified > 0 { - data.intergenic_reads as f64 / total_classified as f64 * 100.0 - } else { - 0.0 - }; - - // Qualimap format: "Exonic: " / "126,404,800 / 76.4%" (slash separator, variable decimals) - table_row( + summary_table( html, - "Exonic: ", - &format!( - "{} / {:.2}%", - format_with_commas(data.exonic_reads), - exonic_pct - ), - ); - table_row( - html, - "Intronic: ", - &format!( - "{} / {:.2}%", - format_with_commas(data.intronic_reads), - intronic_pct - ), - ); - table_row( - html, - "Intergenic: ", - &format!( - "{} / {:.2}%", - format_with_commas(data.intergenic_reads), - intergenic_pct - ), + "Reads genomic origin", + &[ + ("Exonic: ", origin_row(data.exonic_reads)), + ("Intronic: ", origin_row(data.intronic_reads)), + ("Intergenic: ", origin_row(data.intergenic_reads)), + ( + "Intronic/intergenic overlapping exon: ", + origin_row(data.overlapping_exon_reads), + ), + ], ); - let overlapping_pct = if total_classified > 0 { - data.overlapping_exon_reads as f64 / total_classified as f64 * 100.0 - } else { - 0.0 - }; - table_row( + // --- Transcript coverage profile --- + summary_table( html, - "Intronic/intergenic overlapping exon: ", - &format!( - "{} / {:.2}%", - format_with_commas(data.overlapping_exon_reads), - overlapping_pct - ), + "Transcript coverage profile", + &[ + ("5' bias:", format_decimal(data.five_bias)), + ("3' bias:", format_decimal(data.three_bias)), + ("5'-3' bias:", format_decimal(data.five_three_bias)), + ], ); - html.push_str("
\n
\n
\n"); - - // --- Transcript coverage profile --- - html.push_str("
\n
\n"); - html.push_str("

Transcript coverage profile

\n"); - html.push_str("\n"); - - table_row(html, "5' bias:", &format_bias(data.five_bias)); - table_row(html, "3' bias:", &format_bias(data.three_bias)); - table_row(html, "5'-3' bias:", &format_bias(data.five_three_bias)); + // --- Junction analysis --- + let mut junctions: Vec<(&str, String)> = + vec![("Reads at junctions:", format_long(data.reads_at_junctions))]; + for (motif, pct) in super::junction_motif_rows(data.junction_motifs, data.reads_at_junctions) { + junctions.push((motif, format_percentage(pct))); + } + summary_table(html, "Junction analysis", &junctions); - html.push_str("
\n
\n
\n"); + html.push_str("
\n"); +} - // --- Junction analysis --- +/// One `

` summary table, as Qualimap's `HtmlReportGenerator.appendTableFromStats`. +fn summary_table(html: &mut String, title: &str, rows: &[(&str, String)]) { html.push_str("
\n
\n"); - html.push_str("

Junction analysis

\n"); + html.push_str(&format!("

{title}

\n")); html.push_str("\n"); - - table_row( - html, - "Reads at junctions:", - &format_with_commas(data.reads_at_junctions), - ); - - // Top junction motifs sorted by count descending — Qualimap shows motif / percentage - // Use reads_at_junctions as denominator (matches text file output and upstream Qualimap) - let mut motifs: Vec<(&String, &u64)> = data.junction_motifs.iter().collect(); - motifs.sort_by(|a, b| b.1.cmp(a.1)); - let total_junctions = data.reads_at_junctions; - for (motif, &count) in motifs.iter().take(11) { - let pct = if total_junctions > 0 { - count as f64 / total_junctions as f64 * 100.0 - } else { - 0.0 - }; - table_row(html, motif, &format!("{:.2}%", pct)); + for (label, value) in rows { + table_row(html, label, value); } - html.push_str("
\n
\n
\n"); - html.push_str("\n"); } /// Sections 3+: Image plots (matches Qualimap section structure exactly). @@ -624,8 +560,6 @@ fn table_row(html: &mut String, label: &str, value: &str) { html.push_str("\n"); } -use crate::io::format_with_commas; - /// Format the current local date/time as `YYYY/MM/DD HH:MM:SS`. /// /// Uses `time` crate's `OffsetDateTime` (already an indirect dependency via `env_logger`). @@ -672,15 +606,6 @@ fn days_to_ymd(days: u64) -> (u64, u64, u64) { (y, mo, d) } -/// Format a bias value (2 decimal places, or "NA"). -fn format_bias(v: f64) -> String { - if v.is_nan() || v.is_infinite() { - "NA".to_string() - } else { - format!("{:.2}", v) - } -} - // =================================================================== // Tests // =================================================================== @@ -689,23 +614,6 @@ fn format_bias(v: f64) -> String { mod tests { use super::*; - #[test] - fn test_format_with_commas() { - assert_eq!(format_with_commas(0), "0"); - assert_eq!(format_with_commas(999), "999"); - assert_eq!(format_with_commas(1_000), "1,000"); - assert_eq!(format_with_commas(1_234_567), "1,234,567"); - assert_eq!(format_with_commas(87_677_544), "87,677,544"); - } - - #[test] - fn test_format_bias() { - assert_eq!(format_bias(0.85), "0.85"); - assert_eq!(format_bias(1.0), "1.00"); - assert_eq!(format_bias(f64::NAN), "NA"); - assert_eq!(format_bias(f64::INFINITY), "NA"); - } - #[test] fn test_table_row_html() { let mut html = String::new();