Skip to main content

cyanea_align/
cigar.rs

1//! CIGAR string parsing, validation, arithmetic, and conversion utilities.
2//!
3//! Operates on the full SAM CIGAR alphabet (M, I, D, N, S, H, P, =, X).
4//!
5//! # Examples
6//!
7//! ```
8//! use cyanea_align::cigar::{parse_cigar, cigar_string, reference_consumed, query_consumed};
9//!
10//! let ops = parse_cigar("10M3I4D2S").unwrap();
11//! assert_eq!(cigar_string(&ops), "10M3I4D2S");
12//! assert_eq!(reference_consumed(&ops), 14); // M + D
13//! assert_eq!(query_consumed(&ops), 15);     // M + I + S
14//! ```
15
16use crate::types::CigarOp;
17use cyanea_core::{CyaneaError, Result};
18
19// ---------------------------------------------------------------------------
20// Parsing & formatting
21// ---------------------------------------------------------------------------
22
23/// Parse a SAM CIGAR string into a vector of operations.
24///
25/// Accepts the full SAM alphabet: `M`, `I`, `D`, `N`, `S`, `H`, `P`, `=`, `X`.
26/// The special CIGAR `*` (unavailable) returns an empty vector.
27///
28/// # Errors
29///
30/// Returns [`CyaneaError::Parse`] on invalid characters or missing counts.
31pub fn parse_cigar(s: &str) -> Result<Vec<CigarOp>> {
32    if s == "*" {
33        return Ok(Vec::new());
34    }
35    if s.is_empty() {
36        return Err(CyaneaError::Parse("empty CIGAR string".into()));
37    }
38
39    let mut ops = Vec::new();
40    let mut num_start: Option<usize> = None;
41
42    for (i, c) in s.char_indices() {
43        if c.is_ascii_digit() {
44            if num_start.is_none() {
45                num_start = Some(i);
46            }
47        } else {
48            let start = num_start.ok_or_else(|| {
49                CyaneaError::Parse(format!("CIGAR op '{}' at position {} has no count", c, i))
50            })?;
51            let n: usize = s[start..i]
52                .parse()
53                .map_err(|e| CyaneaError::Parse(format!("invalid CIGAR count: {}", e)))?;
54            let op = char_to_cigar_op(c, n)
55                .ok_or_else(|| CyaneaError::Parse(format!("invalid CIGAR op character '{}'", c)))?;
56            ops.push(op);
57            num_start = None;
58        }
59    }
60
61    if num_start.is_some() {
62        return Err(CyaneaError::Parse(
63            "CIGAR string ends with digits but no op character".into(),
64        ));
65    }
66
67    Ok(ops)
68}
69
70/// Format CIGAR operations as a compact string (e.g. `"10M3I4D"`).
71///
72/// Returns `"*"` for an empty slice.
73pub fn cigar_string(ops: &[CigarOp]) -> String {
74    if ops.is_empty() {
75        return "*".into();
76    }
77    let mut s = String::new();
78    for op in ops {
79        s.push_str(&format!("{}{}", op.len(), op.code()));
80    }
81    s
82}
83
84fn char_to_cigar_op(c: char, n: usize) -> Option<CigarOp> {
85    match c {
86        '=' => Some(CigarOp::Match(n)),
87        'X' => Some(CigarOp::Mismatch(n)),
88        'I' => Some(CigarOp::Insertion(n)),
89        'D' => Some(CigarOp::Deletion(n)),
90        'M' => Some(CigarOp::AlnMatch(n)),
91        'N' => Some(CigarOp::Skip(n)),
92        'S' => Some(CigarOp::SoftClip(n)),
93        'H' => Some(CigarOp::HardClip(n)),
94        'P' => Some(CigarOp::Padding(n)),
95        _ => None,
96    }
97}
98
99// ---------------------------------------------------------------------------
100// Validation
101// ---------------------------------------------------------------------------
102
103/// Validate a CIGAR operation sequence according to SAM spec rules.
104///
105/// Checks:
106/// - No zero-length operations
107/// - No adjacent operations of the same type
108/// - `H` (hard clip) only at the ends
109/// - `S` (soft clip) adjacent to `H` or at the ends
110///
111/// # Errors
112///
113/// Returns [`CyaneaError::InvalidInput`] describing the first violation found.
114pub fn validate_cigar(ops: &[CigarOp]) -> Result<()> {
115    if ops.is_empty() {
116        return Ok(());
117    }
118
119    for (i, op) in ops.iter().enumerate() {
120        if op.is_empty() {
121            return Err(CyaneaError::InvalidInput(format!(
122                "zero-length CIGAR op at position {}",
123                i
124            )));
125        }
126    }
127
128    // Adjacent same-type check
129    for i in 1..ops.len() {
130        if ops[i].code() == ops[i - 1].code() {
131            return Err(CyaneaError::InvalidInput(format!(
132                "adjacent CIGAR ops of same type '{}' at positions {} and {}",
133                ops[i].code(),
134                i - 1,
135                i
136            )));
137        }
138    }
139
140    // H only at ends
141    for (i, op) in ops.iter().enumerate() {
142        if matches!(op, CigarOp::HardClip(_)) && i != 0 && i != ops.len() - 1 {
143            return Err(CyaneaError::InvalidInput(format!(
144                "hard clip (H) at interior position {}",
145                i
146            )));
147        }
148    }
149
150    // S must be adjacent to H or at ends
151    for (i, op) in ops.iter().enumerate() {
152        if matches!(op, CigarOp::SoftClip(_)) {
153            let at_start = i == 0 || (i == 1 && matches!(ops[0], CigarOp::HardClip(_)));
154            let at_end = i == ops.len() - 1
155                || (i == ops.len() - 2 && matches!(ops[ops.len() - 1], CigarOp::HardClip(_)));
156            if !at_start && !at_end {
157                return Err(CyaneaError::InvalidInput(format!(
158                    "soft clip (S) at invalid position {}",
159                    i
160                )));
161            }
162        }
163    }
164
165    Ok(())
166}
167
168// ---------------------------------------------------------------------------
169// Coordinate queries
170// ---------------------------------------------------------------------------
171
172/// Number of reference bases consumed (M, =, X, D, N).
173pub fn reference_consumed(ops: &[CigarOp]) -> usize {
174    ops.iter()
175        .filter(|op| op.consumes_reference())
176        .map(|op| op.len())
177        .sum()
178}
179
180/// Number of query bases consumed (M, =, X, I, S).
181pub fn query_consumed(ops: &[CigarOp]) -> usize {
182    ops.iter()
183        .filter(|op| op.consumes_query())
184        .map(|op| op.len())
185        .sum()
186}
187
188/// Number of aligned columns (M, =, X, I, D) — excludes clips, skips, padding.
189pub fn alignment_columns(ops: &[CigarOp]) -> usize {
190    ops.iter()
191        .filter(|op| {
192            matches!(
193                op,
194                CigarOp::Match(_)
195                    | CigarOp::Mismatch(_)
196                    | CigarOp::Insertion(_)
197                    | CigarOp::Deletion(_)
198                    | CigarOp::AlnMatch(_)
199            )
200        })
201        .map(|op| op.len())
202        .sum()
203}
204
205/// Total soft-clipped and hard-clipped bases as `(soft, hard)`.
206pub fn clipped_bases(ops: &[CigarOp]) -> (usize, usize) {
207    let mut soft = 0;
208    let mut hard = 0;
209    for op in ops {
210        match op {
211            CigarOp::SoftClip(n) => soft += n,
212            CigarOp::HardClip(n) => hard += n,
213            _ => {}
214        }
215    }
216    (soft, hard)
217}
218
219// ---------------------------------------------------------------------------
220// Statistics
221// ---------------------------------------------------------------------------
222
223/// Sequence identity: `=` bases / (M + = + X + I + D) columns.
224///
225/// Returns 0.0 for empty CIGAR. When only `M` ops are present (no `=`/`X`
226/// distinction), returns 0.0 since exact matches cannot be determined.
227pub fn identity(ops: &[CigarOp]) -> f64 {
228    let cols = alignment_columns(ops);
229    if cols == 0 {
230        return 0.0;
231    }
232    let eq: usize = ops
233        .iter()
234        .filter_map(|op| match op {
235            CigarOp::Match(n) => Some(n),
236            _ => None,
237        })
238        .sum();
239    eq as f64 / cols as f64
240}
241
242/// Fraction of reference covered: `reference_consumed(ops) / ref_len`.
243///
244/// Returns 0.0 if `ref_len` is 0.
245pub fn coverage(ops: &[CigarOp], ref_len: usize) -> f64 {
246    if ref_len == 0 {
247        return 0.0;
248    }
249    reference_consumed(ops) as f64 / ref_len as f64
250}
251
252/// Number of gap openings (runs of I or D operations).
253pub fn gap_count(ops: &[CigarOp]) -> usize {
254    ops.iter()
255        .filter(|op| matches!(op, CigarOp::Insertion(_) | CigarOp::Deletion(_)))
256        .count()
257}
258
259/// Total bases in gaps (sum of I and D lengths).
260pub fn gap_bases(ops: &[CigarOp]) -> usize {
261    ops.iter()
262        .filter_map(|op| match op {
263            CigarOp::Insertion(n) | CigarOp::Deletion(n) => Some(n),
264            _ => None,
265        })
266        .sum()
267}
268
269// ---------------------------------------------------------------------------
270// Arithmetic
271// ---------------------------------------------------------------------------
272
273/// Merge consecutive operations of the same type.
274pub fn merge_adjacent(ops: &[CigarOp]) -> Vec<CigarOp> {
275    if ops.is_empty() {
276        return Vec::new();
277    }
278    let mut merged = Vec::with_capacity(ops.len());
279    merged.push(ops[0]);
280    for &op in &ops[1..] {
281        let last = merged.last_mut().unwrap();
282        if last.code() == op.code() {
283            *last = with_len(*last, last.len() + op.len());
284        } else {
285            merged.push(op);
286        }
287    }
288    merged
289}
290
291/// Reverse the order of CIGAR operations.
292pub fn reverse_cigar(ops: &[CigarOp]) -> Vec<CigarOp> {
293    ops.iter().copied().rev().collect()
294}
295
296/// Split CIGAR at a reference coordinate, returning `(left, right)`.
297///
298/// `ref_pos` is 0-based; `left` covers `[0, ref_pos)`, `right` covers
299/// `[ref_pos, end)`. Operations that don't consume reference (I, S, H, P)
300/// are attached to whichever side they fall on during the left-to-right walk.
301pub fn split_at_reference(ops: &[CigarOp], ref_pos: usize) -> (Vec<CigarOp>, Vec<CigarOp>) {
302    let mut left = Vec::new();
303    let mut right = Vec::new();
304    let mut consumed = 0usize;
305    let mut split = false;
306
307    for &op in ops {
308        if split {
309            right.push(op);
310            continue;
311        }
312        if !op.consumes_reference() {
313            left.push(op);
314            continue;
315        }
316        let remaining = ref_pos - consumed;
317        if op.len() <= remaining {
318            left.push(op);
319            consumed += op.len();
320            if consumed == ref_pos {
321                split = true;
322            }
323        } else {
324            // Split this op
325            if remaining > 0 {
326                left.push(with_len(op, remaining));
327            }
328            let rest = op.len() - remaining;
329            right.push(with_len(op, rest));
330            split = true;
331        }
332    }
333
334    (left, right)
335}
336
337/// Convert hard clips (`H`) to soft clips (`S`).
338pub fn hard_clip_to_soft(ops: &[CigarOp]) -> Vec<CigarOp> {
339    ops.iter()
340        .map(|op| match op {
341            CigarOp::HardClip(n) => CigarOp::SoftClip(*n),
342            other => *other,
343        })
344        .collect()
345}
346
347/// Collapse `=` and `X` operations into `M` (alignment match).
348pub fn collapse_matches(ops: &[CigarOp]) -> Vec<CigarOp> {
349    let collapsed: Vec<CigarOp> = ops
350        .iter()
351        .map(|op| match op {
352            CigarOp::Match(n) | CigarOp::Mismatch(n) => CigarOp::AlnMatch(*n),
353            other => *other,
354        })
355        .collect();
356    merge_adjacent(&collapsed)
357}
358
359/// Create a CigarOp of the same variant but with a different length.
360fn with_len(op: CigarOp, n: usize) -> CigarOp {
361    match op {
362        CigarOp::Match(_) => CigarOp::Match(n),
363        CigarOp::Mismatch(_) => CigarOp::Mismatch(n),
364        CigarOp::Insertion(_) => CigarOp::Insertion(n),
365        CigarOp::Deletion(_) => CigarOp::Deletion(n),
366        CigarOp::AlnMatch(_) => CigarOp::AlnMatch(n),
367        CigarOp::Skip(_) => CigarOp::Skip(n),
368        CigarOp::SoftClip(_) => CigarOp::SoftClip(n),
369        CigarOp::HardClip(_) => CigarOp::HardClip(n),
370        CigarOp::Padding(_) => CigarOp::Padding(n),
371    }
372}
373
374// ---------------------------------------------------------------------------
375// Conversion
376// ---------------------------------------------------------------------------
377
378/// Reconstruct gapped alignment sequences from CIGAR and ungapped input.
379///
380/// Walks the CIGAR operations against `query` and `target` (both ungapped),
381/// producing two gapped sequences with `-` for gaps. Soft/hard clips, skips,
382/// and padding are not included in the output alignment.
383///
384/// # Errors
385///
386/// Returns an error if the CIGAR consumes more bases than available in query
387/// or target.
388pub fn cigar_to_alignment(
389    ops: &[CigarOp],
390    query: &[u8],
391    target: &[u8],
392) -> Result<(Vec<u8>, Vec<u8>)> {
393    let mut aligned_q = Vec::new();
394    let mut aligned_t = Vec::new();
395    let mut qi = 0usize;
396    let mut ti = 0usize;
397
398    for op in ops {
399        match op {
400            CigarOp::Match(n) | CigarOp::Mismatch(n) | CigarOp::AlnMatch(n) => {
401                if qi + n > query.len() || ti + n > target.len() {
402                    return Err(CyaneaError::InvalidInput(
403                        "CIGAR consumes more bases than available in sequences".into(),
404                    ));
405                }
406                aligned_q.extend_from_slice(&query[qi..qi + n]);
407                aligned_t.extend_from_slice(&target[ti..ti + n]);
408                qi += n;
409                ti += n;
410            }
411            CigarOp::Insertion(n) => {
412                if qi + n > query.len() {
413                    return Err(CyaneaError::InvalidInput(
414                        "CIGAR insertion consumes more query bases than available".into(),
415                    ));
416                }
417                aligned_q.extend_from_slice(&query[qi..qi + n]);
418                aligned_t.extend(core::iter::repeat(b'-').take(*n));
419                qi += n;
420            }
421            CigarOp::Deletion(n) | CigarOp::Skip(n) => {
422                if ti + n > target.len() {
423                    return Err(CyaneaError::InvalidInput(
424                        "CIGAR deletion/skip consumes more target bases than available".into(),
425                    ));
426                }
427                aligned_q.extend(core::iter::repeat(b'-').take(*n));
428                aligned_t.extend_from_slice(&target[ti..ti + n]);
429                ti += n;
430            }
431            CigarOp::SoftClip(n) => {
432                qi += n;
433            }
434            CigarOp::HardClip(_) | CigarOp::Padding(_) => {}
435        }
436    }
437
438    Ok((aligned_q, aligned_t))
439}
440
441/// Extract CIGAR operations from a gapped alignment using `=`/`X` distinction.
442///
443/// Both `query` and `target` must be gapped (same length, with `-` for gaps).
444///
445/// # Errors
446///
447/// Returns an error if the sequences have different lengths.
448pub fn alignment_to_cigar(query: &[u8], target: &[u8]) -> Result<Vec<CigarOp>> {
449    if query.len() != target.len() {
450        return Err(CyaneaError::InvalidInput(
451            "gapped alignment sequences must have equal length".into(),
452        ));
453    }
454
455    let mut ops: Vec<CigarOp> = Vec::new();
456
457    for (q, t) in query.iter().zip(target.iter()) {
458        let op = match (*q, *t) {
459            (b'-', b'-') => continue,
460            (b'-', _) => CigarOp::Deletion(1),
461            (_, b'-') => CigarOp::Insertion(1),
462            (a, b) if a == b => CigarOp::Match(1),
463            _ => CigarOp::Mismatch(1),
464        };
465        // Merge with previous if same type
466        if let Some(last) = ops.last_mut() {
467            if last.code() == op.code() {
468                *last = with_len(*last, last.len() + 1);
469                continue;
470            }
471        }
472        ops.push(op);
473    }
474
475    Ok(ops)
476}
477
478// ---------------------------------------------------------------------------
479// MD tag
480// ---------------------------------------------------------------------------
481
482/// Generate a SAM MD:Z tag from CIGAR operations and ungapped sequences.
483///
484/// The MD tag records mismatched and deleted reference bases. It walks
485/// reference-consuming CIGAR ops:
486/// - `=` / match: increments match counter
487/// - `X` / mismatch: emits match count + reference base
488/// - `M`: compares query/reference and emits accordingly
489/// - `D` / `N`: emits `^` + deleted reference bases
490/// - `I`, `S`, `H`, `P`: skipped (don't consume reference)
491///
492/// # Errors
493///
494/// Returns an error if sequences are too short for the CIGAR.
495pub fn generate_md_tag(ops: &[CigarOp], query: &[u8], reference: &[u8]) -> Result<String> {
496    let mut md = String::new();
497    let mut match_count = 0usize;
498    let mut qi = 0usize;
499    let mut ri = 0usize;
500
501    for op in ops {
502        match op {
503            CigarOp::Match(n) => {
504                match_count += n;
505                qi += n;
506                ri += n;
507            }
508            CigarOp::Mismatch(n) => {
509                if ri + n > reference.len() {
510                    return Err(CyaneaError::InvalidInput(
511                        "MD tag: reference too short for mismatch".into(),
512                    ));
513                }
514                for _ in 0..*n {
515                    md.push_str(&match_count.to_string());
516                    match_count = 0;
517                    md.push(reference[ri] as char);
518                    qi += 1;
519                    ri += 1;
520                }
521            }
522            CigarOp::AlnMatch(n) => {
523                if qi + n > query.len() || ri + n > reference.len() {
524                    return Err(CyaneaError::InvalidInput(
525                        "MD tag: sequences too short for M op".into(),
526                    ));
527                }
528                for _ in 0..*n {
529                    if query[qi] == reference[ri] {
530                        match_count += 1;
531                    } else {
532                        md.push_str(&match_count.to_string());
533                        match_count = 0;
534                        md.push(reference[ri] as char);
535                    }
536                    qi += 1;
537                    ri += 1;
538                }
539            }
540            CigarOp::Deletion(n) | CigarOp::Skip(n) => {
541                if ri + n > reference.len() {
542                    return Err(CyaneaError::InvalidInput(
543                        "MD tag: reference too short for deletion".into(),
544                    ));
545                }
546                md.push_str(&match_count.to_string());
547                match_count = 0;
548                md.push('^');
549                for _ in 0..*n {
550                    md.push(reference[ri] as char);
551                    ri += 1;
552                }
553            }
554            CigarOp::Insertion(n) => {
555                qi += n;
556            }
557            CigarOp::SoftClip(n) => {
558                qi += n;
559            }
560            CigarOp::HardClip(_) | CigarOp::Padding(_) => {}
561        }
562    }
563
564    // Emit trailing match count
565    md.push_str(&match_count.to_string());
566
567    Ok(md)
568}
569
570// ---------------------------------------------------------------------------
571// Tests
572// ---------------------------------------------------------------------------
573
574#[cfg(test)]
575mod tests {
576    use super::*;
577
578    // -- Parsing --
579
580    #[test]
581    fn parse_simple() {
582        let ops = parse_cigar("10M").unwrap();
583        assert_eq!(ops, vec![CigarOp::AlnMatch(10)]);
584    }
585
586    #[test]
587    fn parse_complex() {
588        let ops = parse_cigar("5=2X3I4D1N2S3H1P").unwrap();
589        assert_eq!(
590            ops,
591            vec![
592                CigarOp::Match(5),
593                CigarOp::Mismatch(2),
594                CigarOp::Insertion(3),
595                CigarOp::Deletion(4),
596                CigarOp::Skip(1),
597                CigarOp::SoftClip(2),
598                CigarOp::HardClip(3),
599                CigarOp::Padding(1),
600            ]
601        );
602    }
603
604    #[test]
605    fn parse_all_nine_ops() {
606        let ops = parse_cigar("1M1I1D1N1S1H1P1=1X").unwrap();
607        assert_eq!(ops.len(), 9);
608        let codes: String = ops.iter().map(|op| op.code()).collect();
609        assert_eq!(codes, "MIDNSHP=X");
610    }
611
612    #[test]
613    fn parse_star() {
614        assert_eq!(parse_cigar("*").unwrap(), vec![]);
615    }
616
617    #[test]
618    fn parse_empty_is_error() {
619        assert!(parse_cigar("").is_err());
620    }
621
622    #[test]
623    fn parse_bad_char() {
624        assert!(parse_cigar("10Z").is_err());
625    }
626
627    #[test]
628    fn parse_missing_count() {
629        assert!(parse_cigar("M").is_err());
630    }
631
632    #[test]
633    fn parse_trailing_digits() {
634        assert!(parse_cigar("10M5").is_err());
635    }
636
637    #[test]
638    fn format_round_trip() {
639        let original = "3=1X2I1D4M2S5H100N1P";
640        let ops = parse_cigar(original).unwrap();
641        assert_eq!(cigar_string(&ops), original);
642    }
643
644    #[test]
645    fn format_empty() {
646        assert_eq!(cigar_string(&[]), "*");
647    }
648
649    // -- Validation --
650
651    #[test]
652    fn validate_valid() {
653        let ops = parse_cigar("5H3S10M2I3M1D5M3S5H").unwrap();
654        assert!(validate_cigar(&ops).is_ok());
655    }
656
657    #[test]
658    fn validate_empty() {
659        assert!(validate_cigar(&[]).is_ok());
660    }
661
662    #[test]
663    fn validate_zero_length() {
664        let ops = vec![CigarOp::AlnMatch(0)];
665        assert!(validate_cigar(&ops).is_err());
666    }
667
668    #[test]
669    fn validate_adjacent_duplicates() {
670        let ops = vec![CigarOp::AlnMatch(3), CigarOp::AlnMatch(2)];
671        assert!(validate_cigar(&ops).is_err());
672    }
673
674    #[test]
675    fn validate_h_not_at_ends() {
676        let ops = vec![
677            CigarOp::AlnMatch(5),
678            CigarOp::HardClip(3),
679            CigarOp::AlnMatch(5),
680        ];
681        assert!(validate_cigar(&ops).is_err());
682    }
683
684    #[test]
685    fn validate_s_at_invalid_position() {
686        let ops = vec![
687            CigarOp::AlnMatch(5),
688            CigarOp::SoftClip(3),
689            CigarOp::AlnMatch(5),
690        ];
691        assert!(validate_cigar(&ops).is_err());
692    }
693
694    #[test]
695    fn validate_s_adjacent_to_h() {
696        let ops = vec![
697            CigarOp::HardClip(2),
698            CigarOp::SoftClip(3),
699            CigarOp::AlnMatch(10),
700            CigarOp::SoftClip(2),
701            CigarOp::HardClip(1),
702        ];
703        assert!(validate_cigar(&ops).is_ok());
704    }
705
706    // -- Coordinates --
707
708    #[test]
709    fn ref_query_consumed() {
710        let ops = parse_cigar("3=2I4D1X2S3H").unwrap();
711        // ref: = (3) + D (4) + X (1) = 8
712        assert_eq!(reference_consumed(&ops), 8);
713        // query: = (3) + I (2) + X (1) + S (2) = 8
714        assert_eq!(query_consumed(&ops), 8);
715    }
716
717    #[test]
718    fn alignment_columns_excludes_clips() {
719        let ops = parse_cigar("3S10M2I3D100N5S").unwrap();
720        // M (10) + I (2) + D (3) = 15 (N excluded)
721        assert_eq!(alignment_columns(&ops), 15);
722    }
723
724    #[test]
725    fn clipped_bases_totals() {
726        let ops = parse_cigar("5H3S10M2S4H").unwrap();
727        assert_eq!(clipped_bases(&ops), (5, 9));
728    }
729
730    // -- Statistics --
731
732    #[test]
733    fn identity_with_eq_x() {
734        let ops = parse_cigar("8=2X").unwrap();
735        assert!((identity(&ops) - 0.8).abs() < 1e-10);
736    }
737
738    #[test]
739    fn identity_empty() {
740        assert!((identity(&[]) - 0.0).abs() < f64::EPSILON);
741    }
742
743    #[test]
744    fn identity_m_only_is_zero() {
745        let ops = parse_cigar("10M").unwrap();
746        // M ops cannot distinguish = from X, so identity returns 0
747        assert!((identity(&ops) - 0.0).abs() < f64::EPSILON);
748    }
749
750    #[test]
751    fn coverage_basic() {
752        let ops = parse_cigar("50M").unwrap();
753        assert!((coverage(&ops, 100) - 0.5).abs() < 1e-10);
754    }
755
756    #[test]
757    fn coverage_zero_ref() {
758        assert!((coverage(&[], 0) - 0.0).abs() < f64::EPSILON);
759    }
760
761    #[test]
762    fn gap_count_and_bases() {
763        let ops = parse_cigar("5=3I2=4D1=1I").unwrap();
764        assert_eq!(gap_count(&ops), 3); // 3I, 4D, 1I
765        assert_eq!(gap_bases(&ops), 8); // 3 + 4 + 1
766    }
767
768    // -- Arithmetic --
769
770    #[test]
771    fn merge_adjacent_combines() {
772        let ops = vec![
773            CigarOp::AlnMatch(3),
774            CigarOp::AlnMatch(2),
775            CigarOp::Insertion(1),
776            CigarOp::Insertion(4),
777        ];
778        let merged = merge_adjacent(&ops);
779        assert_eq!(merged, vec![CigarOp::AlnMatch(5), CigarOp::Insertion(5)]);
780    }
781
782    #[test]
783    fn merge_adjacent_idempotent() {
784        let ops = parse_cigar("10M3I4D").unwrap();
785        assert_eq!(merge_adjacent(&ops), ops);
786    }
787
788    #[test]
789    fn merge_adjacent_empty() {
790        assert_eq!(merge_adjacent(&[]), vec![]);
791    }
792
793    #[test]
794    fn reverse_cigar_order() {
795        let ops = parse_cigar("3=2I1D").unwrap();
796        let rev = reverse_cigar(&ops);
797        assert_eq!(
798            rev,
799            vec![
800                CigarOp::Deletion(1),
801                CigarOp::Insertion(2),
802                CigarOp::Match(3),
803            ]
804        );
805    }
806
807    #[test]
808    fn split_at_reference_basic() {
809        let ops = parse_cigar("10M").unwrap();
810        let (left, right) = split_at_reference(&ops, 4);
811        assert_eq!(left, vec![CigarOp::AlnMatch(4)]);
812        assert_eq!(right, vec![CigarOp::AlnMatch(6)]);
813    }
814
815    #[test]
816    fn split_at_reference_boundary() {
817        let ops = parse_cigar("5=3I5=").unwrap();
818        // Split at ref pos 5: first = consumes 5 ref bases → exact boundary
819        // I doesn't consume ref, so it goes to right side
820        let (left, right) = split_at_reference(&ops, 5);
821        assert_eq!(left, vec![CigarOp::Match(5)]);
822        assert_eq!(right, vec![CigarOp::Insertion(3), CigarOp::Match(5)]);
823    }
824
825    #[test]
826    fn split_at_reference_zero() {
827        let ops = parse_cigar("5M").unwrap();
828        let (left, right) = split_at_reference(&ops, 0);
829        assert!(left.is_empty());
830        assert_eq!(right, vec![CigarOp::AlnMatch(5)]);
831    }
832
833    #[test]
834    fn hard_clip_to_soft_conversion() {
835        let ops = parse_cigar("5H10M3H").unwrap();
836        let converted = hard_clip_to_soft(&ops);
837        assert_eq!(
838            converted,
839            vec![
840                CigarOp::SoftClip(5),
841                CigarOp::AlnMatch(10),
842                CigarOp::SoftClip(3),
843            ]
844        );
845    }
846
847    #[test]
848    fn collapse_matches_eq_x_to_m() {
849        let ops = parse_cigar("3=2X1=").unwrap();
850        let collapsed = collapse_matches(&ops);
851        assert_eq!(collapsed, vec![CigarOp::AlnMatch(6)]);
852    }
853
854    // -- Conversion --
855
856    #[test]
857    fn cigar_to_alignment_basic() {
858        let ops = parse_cigar("3=1I2=1D1=").unwrap();
859        let query = b"ACGTACG"; // 3 + 1 + 2 + 1 = 7
860        let target = b"ACGACGA"; // 3 + 2 + 1 + 1 = 7
861        let (aq, at) = cigar_to_alignment(&ops, query, target).unwrap();
862        assert_eq!(aq, b"ACGTAC-G");
863        assert_eq!(at, b"ACG-ACGA");
864    }
865
866    #[test]
867    fn cigar_to_alignment_with_clips() {
868        // Soft clip at start, query has extra bases
869        let ops = vec![CigarOp::SoftClip(2), CigarOp::AlnMatch(3)];
870        let query = b"NNACG";
871        let target = b"ACG";
872        let (aq, at) = cigar_to_alignment(&ops, query, target).unwrap();
873        assert_eq!(aq, b"ACG");
874        assert_eq!(at, b"ACG");
875    }
876
877    #[test]
878    fn alignment_to_cigar_basic() {
879        let query = b"ACGTAC-G";
880        let target = b"ACG-ACGA";
881        let ops = alignment_to_cigar(query, target).unwrap();
882        assert_eq!(
883            ops,
884            vec![
885                CigarOp::Match(3),
886                CigarOp::Insertion(1),
887                CigarOp::Match(2),
888                CigarOp::Deletion(1),
889                CigarOp::Mismatch(1), // G vs A
890            ]
891        );
892    }
893
894    #[test]
895    fn alignment_to_cigar_length_mismatch() {
896        assert!(alignment_to_cigar(b"ACG", b"AC").is_err());
897    }
898
899    #[test]
900    fn cigar_alignment_round_trip() {
901        // Start with gapped alignment, extract CIGAR, reconstruct
902        let query = b"AC-GT";
903        let target = b"ACAGT";
904        let ops = alignment_to_cigar(query, target).unwrap();
905        // ungapped sequences
906        let uq = b"ACGT";
907        let ut = b"ACAGT";
908        let (aq, at) = cigar_to_alignment(&ops, uq, ut).unwrap();
909        assert_eq!(&aq, query);
910        assert_eq!(&at, target);
911    }
912
913    // -- MD tag --
914
915    #[test]
916    fn md_tag_perfect_match() {
917        let ops = parse_cigar("10=").unwrap();
918        let seq = b"ACGTACGTAC";
919        let md = generate_md_tag(&ops, seq, seq).unwrap();
920        assert_eq!(md, "10");
921    }
922
923    #[test]
924    fn md_tag_with_mismatches() {
925        let ops = parse_cigar("3=1X2=").unwrap();
926        let query = b"ACGAAC";
927        let refer = b"ACGTAC";
928        let md = generate_md_tag(&ops, query, refer).unwrap();
929        assert_eq!(md, "3T2");
930    }
931
932    #[test]
933    fn md_tag_with_deletion() {
934        let ops = parse_cigar("3=2D3=").unwrap();
935        let query = b"ACGAAC";
936        let refer = b"ACGTTAAC";
937        let md = generate_md_tag(&ops, query, refer).unwrap();
938        assert_eq!(md, "3^TT3");
939    }
940
941    #[test]
942    fn md_tag_with_insertion() {
943        // Insertions are skipped in MD tag
944        let ops = parse_cigar("3=2I3=").unwrap();
945        let query = b"ACGTTACG";
946        let refer = b"ACGACG";
947        let md = generate_md_tag(&ops, query, refer).unwrap();
948        assert_eq!(md, "6");
949    }
950
951    #[test]
952    fn md_tag_with_m_ops() {
953        // M ops compare query vs reference
954        let ops = parse_cigar("3M1I2M").unwrap();
955        let query = b"ACGTAC";
956        let refer = b"ACGAC";
957        let md = generate_md_tag(&ops, query, refer).unwrap();
958        assert_eq!(md, "5");
959    }
960
961    // -- Edge cases --
962
963    #[test]
964    fn single_op() {
965        let ops = parse_cigar("1M").unwrap();
966        assert_eq!(reference_consumed(&ops), 1);
967        assert_eq!(query_consumed(&ops), 1);
968        assert_eq!(alignment_columns(&ops), 1);
969    }
970
971    #[test]
972    fn all_clips() {
973        let ops = parse_cigar("5H3S").unwrap();
974        assert_eq!(reference_consumed(&ops), 0);
975        assert_eq!(query_consumed(&ops), 3);
976        assert_eq!(alignment_columns(&ops), 0);
977        assert_eq!(clipped_bases(&ops), (3, 5));
978    }
979}
980
981#[cfg(test)]
982mod proptests {
983    use super::*;
984    use proptest::prelude::*;
985
986    fn arb_cigar_op() -> impl Strategy<Value = CigarOp> {
987        (1..100usize, 0..9u8).prop_map(|(n, kind)| match kind {
988            0 => CigarOp::Match(n),
989            1 => CigarOp::Mismatch(n),
990            2 => CigarOp::Insertion(n),
991            3 => CigarOp::Deletion(n),
992            4 => CigarOp::AlnMatch(n),
993            5 => CigarOp::Skip(n),
994            6 => CigarOp::SoftClip(n),
995            7 => CigarOp::HardClip(n),
996            _ => CigarOp::Padding(n),
997        })
998    }
999
1000    proptest! {
1001        #[test]
1002        fn parse_format_round_trip(ops in proptest::collection::vec(arb_cigar_op(), 1..20)) {
1003            let merged = merge_adjacent(&ops);
1004            let s = cigar_string(&merged);
1005            let parsed = parse_cigar(&s).unwrap();
1006            prop_assert_eq!(parsed, merged);
1007        }
1008
1009        #[test]
1010        fn ref_consumed_consistent(ops in proptest::collection::vec(arb_cigar_op(), 0..20)) {
1011            let total: usize = ops.iter()
1012                .filter(|op| op.consumes_reference())
1013                .map(|op| op.len())
1014                .sum();
1015            prop_assert_eq!(reference_consumed(&ops), total);
1016        }
1017
1018        #[test]
1019        fn query_consumed_consistent(ops in proptest::collection::vec(arb_cigar_op(), 0..20)) {
1020            let total: usize = ops.iter()
1021                .filter(|op| op.consumes_query())
1022                .map(|op| op.len())
1023                .sum();
1024            prop_assert_eq!(query_consumed(&ops), total);
1025        }
1026
1027        #[test]
1028        fn merge_preserves_lengths(ops in proptest::collection::vec(arb_cigar_op(), 0..20)) {
1029            let merged = merge_adjacent(&ops);
1030            prop_assert_eq!(reference_consumed(&ops), reference_consumed(&merged));
1031            prop_assert_eq!(query_consumed(&ops), query_consumed(&merged));
1032        }
1033    }
1034}