rustqc 0.1.0

Fast RNA-seq QC in a single pass: dupRadar, featureCounts, 8 RSeQC tools, preseq, samtools stats, and Qualimap — reimplemented in Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! Shared utilities for RSeQC tool reimplementations.
//!
//! Common functions used by multiple RSeQC tools, including CIGAR-based intron
//! extraction and GTF-based junction building.

use std::collections::{HashMap, HashSet};

use indexmap::IndexMap;
use log::debug;

use crate::gtf::Gene;

// ===================================================================
// CIGAR intron extraction
// ===================================================================

/// Extract intron intervals from a CIGAR string.
///
/// Matches RSeQC's `fetch_intron()` behavior: only CIGAR `N` operations produce
/// intron intervals. Soft clips do NOT advance position (unlike `fetch_exon()`).
/// `=` and `X` operations are ignored (do not advance position) — matching the
/// original Python bug.
///
/// # Arguments
/// * `start_pos` - Alignment start position (0-based, from BAM record).
/// * `cigar` - CIGAR operations from the BAM record.
///
/// # Returns
/// Vector of `(intron_start, intron_end)` tuples (0-based coordinates).
pub fn fetch_introns(start_pos: u64, cigar: &[rust_htslib::bam::record::Cigar]) -> Vec<(u64, u64)> {
    use rust_htslib::bam::record::Cigar::*;

    let mut pos = start_pos;
    let mut introns = Vec::new();

    for op in cigar {
        match op {
            Match(len) => pos += *len as u64, // M: advance position
            Ins(_) => {}                      // I: no position change
            Del(len) => pos += *len as u64,   // D: advance position
            RefSkip(len) => {
                // N: intron!
                let intron_start = pos;
                let intron_end = pos + *len as u64;
                introns.push((intron_start, intron_end));
                pos = intron_end;
            }
            SoftClip(_) => {} // S: no position change (unlike fetch_exon)
            HardClip(_) | Pad(_) | Equal(_) | Diff(_) => {} // ignored entirely
        }
    }

    introns
}

// ===================================================================
// Reference junction data structures
// ===================================================================

/// Reference annotation: sets of known intron start and end positions per chromosome.
///
/// Used by `junction_annotation` for classifying junctions as annotated,
/// partial novel, or complete novel.
#[derive(Debug, Default)]
pub struct ReferenceJunctions {
    /// Known intron start positions per chromosome (uppercased).
    pub intron_starts: HashMap<String, HashSet<u64>>,
    /// Known intron end positions per chromosome (uppercased).
    pub intron_ends: HashMap<String, HashSet<u64>>,
}

/// Classify a junction as annotated, partial novel, or complete novel
/// based on whether its start and end positions appear in the reference.
pub fn classify_junction(
    chrom: &str,
    intron_start: u64,
    intron_end: u64,
    reference: &ReferenceJunctions,
) -> super::junction_annotation::JunctionClass {
    let start_known = reference
        .intron_starts
        .get(chrom)
        .is_some_and(|s| s.contains(&intron_start));
    let end_known = reference
        .intron_ends
        .get(chrom)
        .is_some_and(|s| s.contains(&intron_end));

    use super::junction_annotation::JunctionClass;
    match (start_known, end_known) {
        (true, true) => JunctionClass::Annotated,
        (false, false) => JunctionClass::CompleteNovel,
        _ => JunctionClass::PartialNovel,
    }
}

/// Set of known junction keys in `"CHROM:start-end"` format.
///
/// Used by `junction_saturation` for classifying junctions.
#[derive(Debug, Default)]
pub struct KnownJunctionSet {
    /// Junction keys in `"CHROM:start-end"` format (uppercased chromosome).
    pub junctions: HashSet<String>,
}

// ===================================================================
// GTF-based junction extraction
// ===================================================================

/// Build reference junctions from GTF gene annotations.
///
/// Extracts intron boundaries from transcript-level exon structures. For each
/// transcript, introns are the gaps between sorted exon blocks. Exon coordinates
/// are converted from GTF 1-based inclusive to 0-based half-open.
///
/// # Arguments
/// * `genes` - Parsed GTF gene annotations with transcript-level data.
///
/// # Returns
/// A `ReferenceJunctions` with intron start and end position sets per chromosome.
pub fn build_reference_junctions_from_genes(genes: &IndexMap<String, Gene>) -> ReferenceJunctions {
    let mut result = ReferenceJunctions::default();
    let mut transcript_count = 0u64;

    for gene in genes.values() {
        for tx in &gene.transcripts {
            if tx.exons.len() <= 1 {
                continue;
            }

            let chrom = tx.chrom.to_uppercase();
            let starts_set = result.intron_starts.entry(chrom.clone()).or_default();
            let ends_set = result.intron_ends.entry(chrom).or_default();

            // Exons are already sorted by start in the Transcript struct (GTF 1-based inclusive).
            // Convert to 0-based half-open: start_0based = start - 1, end_0based = end
            // Introns are gaps between consecutive exons.
            for i in 0..tx.exons.len() - 1 {
                let intron_start = tx.exons[i].1; // exon end in GTF is inclusive, so 0-based exclusive = end
                let intron_end = tx.exons[i + 1].0 - 1; // next exon start in GTF is 1-based, so 0-based = start - 1
                starts_set.insert(intron_start);
                ends_set.insert(intron_end);
            }

            transcript_count += 1;
        }
    }

    debug!(
        "Extracted reference junctions from {} multi-exon transcripts (GTF)",
        transcript_count
    );

    result
}

/// Build known junction set from GTF gene annotations.
///
/// Returns junction keys in `"CHROM:start-end"` format, matching the BED-based
/// format for compatibility with junction saturation analysis.
///
/// # Arguments
/// * `genes` - Parsed GTF gene annotations with transcript-level data.
pub fn build_known_junctions_from_genes(genes: &IndexMap<String, Gene>) -> KnownJunctionSet {
    let mut result = KnownJunctionSet::default();

    for gene in genes.values() {
        for tx in &gene.transcripts {
            if tx.exons.len() <= 1 {
                continue;
            }

            let chrom = tx.chrom.to_uppercase();

            // Same coordinate conversion as build_reference_junctions_from_genes
            for i in 0..tx.exons.len() - 1 {
                let intron_start = tx.exons[i].1;
                let intron_end = tx.exons[i + 1].0 - 1;
                let key = format!("{chrom}:{intron_start}-{intron_end}");
                result.junctions.insert(key);
            }
        }
    }

    debug!(
        "Extracted {} known splice junctions from GTF",
        result.junctions.len()
    );

    result
}

// ===================================================================
// Unit tests
// ===================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::gtf::{Exon, Transcript};
    use std::collections::HashMap;

    #[test]
    fn test_fetch_introns_simple() {
        use rust_htslib::bam::record::Cigar::*;
        // 50M500N50M — one intron at position 100+50=150 to 150+500=650
        let cigar = vec![Match(50), RefSkip(500), Match(50)];
        let introns = fetch_introns(100, &cigar);
        assert_eq!(introns.len(), 1);
        assert_eq!(introns[0], (150, 650));
    }

    #[test]
    fn test_fetch_introns_multiple() {
        use rust_htslib::bam::record::Cigar::*;
        // 10M500N20M300N10M — two introns
        let cigar = vec![Match(10), RefSkip(500), Match(20), RefSkip(300), Match(10)];
        let introns = fetch_introns(100, &cigar);
        assert_eq!(introns.len(), 2);
        assert_eq!(introns[0], (110, 610));
        assert_eq!(introns[1], (630, 930));
    }

    #[test]
    fn test_fetch_introns_with_deletions() {
        use rust_htslib::bam::record::Cigar::*;
        // 10M5D10M500N10M
        let cigar = vec![Match(10), Del(5), Match(10), RefSkip(500), Match(10)];
        let introns = fetch_introns(100, &cigar);
        assert_eq!(introns.len(), 1);
        assert_eq!(introns[0], (125, 625)); // 100+10+5+10=125
    }

    #[test]
    fn test_fetch_introns_no_introns() {
        use rust_htslib::bam::record::Cigar::*;
        let cigar = vec![Match(100)];
        let introns = fetch_introns(100, &cigar);
        assert!(introns.is_empty());
    }

    #[test]
    fn test_fetch_introns_soft_clip_no_advance() {
        use rust_htslib::bam::record::Cigar::*;
        // 5S50M500N50M — soft clip should NOT advance position
        let cigar = vec![SoftClip(5), Match(50), RefSkip(500), Match(50)];
        let introns = fetch_introns(100, &cigar);
        assert_eq!(introns.len(), 1);
        assert_eq!(introns[0], (150, 650));
    }

    /// Helper to create a Gene with transcripts for testing.
    fn make_gene_with_transcripts(
        gene_id: &str,
        chrom: &str,
        transcripts: Vec<Transcript>,
    ) -> Gene {
        let exons: Vec<Exon> = transcripts
            .iter()
            .flat_map(|tx| {
                tx.exons.iter().map(|&(start, end)| Exon {
                    chrom: chrom.to_string(),
                    start,
                    end,
                    strand: '+',
                })
            })
            .collect();

        let start = exons.iter().map(|e| e.start).min().unwrap_or(0);
        let end = exons.iter().map(|e| e.end).max().unwrap_or(0);

        Gene {
            gene_id: gene_id.to_string(),
            chrom: chrom.to_string(),
            start,
            end,
            strand: '+',
            exons,
            effective_length: 0,
            attributes: HashMap::new(),
            transcripts,
        }
    }

    #[test]
    fn test_build_reference_junctions_from_genes() {
        // Gene with one transcript: 3 exons -> 2 introns
        // GTF coords (1-based inclusive): exon1=[101,200], exon2=[301,400], exon3=[501,600]
        // 0-based half-open: exon1=[100,200), exon2=[300,400), exon3=[500,600)
        // Introns: [200, 300) and [400, 500)
        let tx = Transcript {
            transcript_id: "TX1".to_string(),

            chrom: "chr1".to_string(),
            start: 101,
            end: 600,
            strand: '+',
            exons: vec![(101, 200), (301, 400), (501, 600)],
            cds_start: None,
            cds_end: None,
        };

        let gene = make_gene_with_transcripts("G1", "chr1", vec![tx]);
        let mut genes = IndexMap::new();
        genes.insert("G1".to_string(), gene);

        let ref_junctions = build_reference_junctions_from_genes(&genes);

        let chr1_starts = ref_junctions.intron_starts.get("CHR1").unwrap();
        let chr1_ends = ref_junctions.intron_ends.get("CHR1").unwrap();

        assert_eq!(chr1_starts.len(), 2);
        assert!(chr1_starts.contains(&200)); // exon1 end (GTF inclusive) = 0-based exclusive
        assert!(chr1_starts.contains(&400)); // exon2 end

        assert_eq!(chr1_ends.len(), 2);
        assert!(chr1_ends.contains(&300)); // exon2 start (GTF 1-based) - 1 = 300
        assert!(chr1_ends.contains(&500)); // exon3 start - 1
    }

    #[test]
    fn test_build_known_junctions_from_genes() {
        let tx = Transcript {
            transcript_id: "TX1".to_string(),

            chrom: "chr1".to_string(),
            start: 101,
            end: 600,
            strand: '+',
            exons: vec![(101, 200), (301, 400), (501, 600)],
            cds_start: None,
            cds_end: None,
        };

        let gene = make_gene_with_transcripts("G1", "chr1", vec![tx]);
        let mut genes = IndexMap::new();
        genes.insert("G1".to_string(), gene);

        let known = build_known_junctions_from_genes(&genes);

        assert_eq!(known.junctions.len(), 2);
        assert!(known.junctions.contains("CHR1:200-300"));
        assert!(known.junctions.contains("CHR1:400-500"));
    }

    #[test]
    fn test_build_junctions_skips_single_exon() {
        let tx = Transcript {
            transcript_id: "TX1".to_string(),

            chrom: "chr1".to_string(),
            start: 101,
            end: 200,
            strand: '+',
            exons: vec![(101, 200)],
            cds_start: None,
            cds_end: None,
        };

        let gene = make_gene_with_transcripts("G1", "chr1", vec![tx]);
        let mut genes = IndexMap::new();
        genes.insert("G1".to_string(), gene);

        let ref_junctions = build_reference_junctions_from_genes(&genes);
        assert!(ref_junctions.intron_starts.is_empty());

        let known = build_known_junctions_from_genes(&genes);
        assert!(known.junctions.is_empty());
    }

    #[test]
    fn test_build_junctions_multiple_transcripts() {
        // Two transcripts with different splicing patterns
        let tx1 = Transcript {
            transcript_id: "TX1".to_string(),

            chrom: "chr1".to_string(),
            start: 101,
            end: 600,
            strand: '+',
            exons: vec![(101, 200), (301, 600)],
            cds_start: None,
            cds_end: None,
        };

        let tx2 = Transcript {
            transcript_id: "TX2".to_string(),

            chrom: "chr1".to_string(),
            start: 101,
            end: 600,
            strand: '+',
            exons: vec![(101, 250), (401, 600)],
            cds_start: None,
            cds_end: None,
        };

        let gene = make_gene_with_transcripts("G1", "chr1", vec![tx1, tx2]);
        let mut genes = IndexMap::new();
        genes.insert("G1".to_string(), gene);

        let ref_junctions = build_reference_junctions_from_genes(&genes);
        let chr1_starts = ref_junctions.intron_starts.get("CHR1").unwrap();

        // TX1 intron: start=200, TX2 intron: start=250
        assert!(chr1_starts.contains(&200));
        assert!(chr1_starts.contains(&250));
    }
}