zoe 0.0.30

A nightly library for viral genomics
Documentation
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
use crate::{
    alignment::{AlignmentIter, AlignmentStates, pairwise_align_with},
    data::{cigar::Ciglet, views::IndexAdjustable},
};
use std::ops::Range;

/// The output of an alignment algorithm, allowing unmapped and overflowed
/// alignments to be represented.
///
/// Often this is some [`Alignment`], but if no portion of the query mapped to
/// the reference, [`Unmapped`] is used. [`Overflowed`] is used when the score
/// exceeded numeric type range.
///
/// [`Some`]: MaybeAligned::Some
/// [`Overflowed`]: MaybeAligned::Overflowed
/// [`Unmapped`]: MaybeAligned::Unmapped
#[derive(Clone, Eq, PartialEq, Debug)]
pub enum MaybeAligned<T> {
    /// Contains a successful alignment result
    Some(T),
    /// Indicates the alignment score overflowed the numeric type
    Overflowed,
    /// Indicates the sequence could not be mapped/aligned
    Unmapped,
}

impl<T> MaybeAligned<T> {
    /// Unwraps the alignment, consuming the [`MaybeAligned<T>`] and returning
    /// the contained [`Alignment<T>`].
    ///
    /// # Panics
    ///
    /// Panics if the value is [`MaybeAligned::Overflowed`] or
    /// [`MaybeAligned::Unmapped`].
    #[inline]
    #[must_use]
    pub fn unwrap(self) -> T {
        match self {
            MaybeAligned::Some(aln) => aln,
            MaybeAligned::Overflowed => panic!("Alignment score overflowed!"),
            MaybeAligned::Unmapped => panic!("Sequence could not be mapped!"),
        }
    }

    /// Gets the contained [`Alignment`] as an [`Option`].
    #[inline]
    #[must_use]
    pub fn get(self) -> Option<T> {
        match self {
            MaybeAligned::Some(aln) => Some(aln),
            _ => None,
        }
    }

    /// Converts from `&MaybeAligned<T>` to `MaybeAligned<&T>`.
    #[inline]
    #[must_use]
    pub const fn as_ref(&self) -> MaybeAligned<&T> {
        match *self {
            MaybeAligned::Some(ref x) => MaybeAligned::Some(x),
            MaybeAligned::Overflowed => MaybeAligned::Overflowed,
            MaybeAligned::Unmapped => MaybeAligned::Unmapped,
        }
    }

    /// Converts from `&mut MaybeAligned<T>` to `MaybeAligned<&mut T>`.
    #[inline]
    #[must_use]
    pub const fn as_mut(&mut self) -> MaybeAligned<&mut T> {
        match *self {
            MaybeAligned::Some(ref mut x) => MaybeAligned::Some(x),
            MaybeAligned::Overflowed => MaybeAligned::Overflowed,
            MaybeAligned::Unmapped => MaybeAligned::Unmapped,
        }
    }

    /// Returns the alignment if it did not overflow, otherwise calls `f` and
    /// returns the result.
    #[inline]
    #[must_use]
    pub fn or_else_overflowed(self, f: impl FnOnce() -> Self) -> Self {
        if let MaybeAligned::Overflowed = self { f() } else { self }
    }

    /// Maps a [`MaybeAligned<T>`] to [`MaybeAligned<U>`] by applying a function
    /// to the contained value. Leaves [`Overflowed`] and [`Unmapped`] variants
    /// unchanged.
    ///
    /// [`Overflowed`]: MaybeAligned::Overflowed
    /// [`Unmapped`]: MaybeAligned::Unmapped
    #[inline]
    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> MaybeAligned<U> {
        match self {
            MaybeAligned::Some(value) => MaybeAligned::Some(f(value)),
            MaybeAligned::Overflowed => MaybeAligned::Overflowed,
            MaybeAligned::Unmapped => MaybeAligned::Unmapped,
        }
    }

    /// Returns [`Unmapped`] if the [`MaybeAligned`] is [`Unmapped`],
    /// [`Overflowed`] if it is [`Overflowed`], otherwise calls `f` with the
    /// wrapped value and returns the result.
    ///
    /// [`Overflowed`]: MaybeAligned::Overflowed
    /// [`Unmapped`]: MaybeAligned::Unmapped
    #[inline]
    #[must_use]
    pub fn and_then<U, F>(self, f: F) -> MaybeAligned<U>
    where
        F: FnOnce(T) -> MaybeAligned<U>, {
        match self {
            MaybeAligned::Some(x) => f(x),
            MaybeAligned::Overflowed => MaybeAligned::Overflowed,
            MaybeAligned::Unmapped => MaybeAligned::Unmapped,
        }
    }
}

impl<T> MaybeAligned<Alignment<T>>
where
    T: Copy,
{
    /// Gets the alignment for when the query and reference are both reversed.
    ///
    /// See [`Reversibility`](Alignment#reversibility) for more details.
    #[inline]
    #[must_use]
    pub fn to_reverse(&self) -> Self {
        self.as_ref().map(Alignment::to_reverse)
    }

    /// Converts an alignment in-place so that it represents the alignment
    /// between the reversed query and reference.
    ///
    /// See [`Reversibility`](Alignment#reversibility) for more details.
    #[inline]
    pub fn make_reverse(&mut self) {
        self.as_mut().map(Alignment::make_reverse);
    }
}

/// An alignment output for helper functions returning the score, an index in
/// the reference, and an index in the query.
///
/// For user-facing algorithms, [`ScoreStarts`] or [`ScoreEnds`] should be used
/// to make the meanings of the fields explicit. This is used only on internal
/// helper functions that can return either one.
pub(crate) struct ScoreIndices<T> {
    pub score:     T,
    pub ref_idx:   usize,
    pub query_idx: usize,
}

impl<T> ScoreIndices<T> {
    /// Converts the [`ScoreIndices`] to the more explicit [`ScoreStarts`].
    ///
    /// ## Validity
    ///
    /// This should only be called when the indices in `self` represent the
    /// start of the alignment in each sequence.
    #[inline]
    #[must_use]
    pub fn into_score_starts(self) -> ScoreStarts<T> {
        ScoreStarts {
            score:       self.score,
            ref_start:   self.ref_idx,
            query_start: self.query_idx,
        }
    }

    /// Converts the [`ScoreIndices`] to the more explicit [`ScoreEnds`].
    ///
    /// ## Validity
    ///
    /// This should only be called when the indices in `self` represent the end
    /// of the alignment in each sequence.
    #[inline]
    #[must_use]
    pub fn into_score_ends(self) -> ScoreEnds<T> {
        ScoreEnds {
            score:     self.score,
            ref_end:   self.ref_idx,
            query_end: self.query_idx,
        }
    }
}

/// An alignment output for algorithms returning the score, the starting index
/// in the reference, and the starting index in the query.
pub struct ScoreStarts<T> {
    /// The score of the alignment.
    pub score:       T,
    /// The starting index of the alignment within the reference.
    pub ref_start:   usize,
    /// The starting index of the alignment within the query.
    pub query_start: usize,
}

/// An alignment output for algorithms returning the score, the ending index in
/// the reference, and the ending index in the query.
pub struct ScoreEnds<T> {
    /// The score of the alignment.
    pub score:     T,
    /// The ending index of the alignment within the reference.
    pub ref_end:   usize,
    /// The ending index of the alignment within the query.
    pub query_end: usize,
}

/// An alignment output for algorithms returning the score, the range of indices
/// aligned in the reference, and the range of indices aligned in the query.
pub struct ScoreAndRanges<T> {
    /// The score of the alignment.
    pub score:       T,
    /// The range of indices in the alignment for the reference sequence.
    pub ref_range:   Range<usize>,
    /// The range of indices in the alignment for the query sequence.
    pub query_range: Range<usize>,
}

// For the `Alignment` struct below, both ranges are 0-based and end-exclusive.
// For a global alignment, the ranges will each be encompass the full length of
// the sequences. For local alignment, `query_range` does NOT include hard or
// soft clipped bases, even though `states` does contain this information.

/// A struct representing the information for an alignment, such as its score
/// and where in the sequences it occurs.
///
/// To convert this to a [`SamData`] record, see [`SamData::from_alignment`].
/// Some additional information will need to be provided, such as any flags, the
/// query sequence and quality scores if present, etc.
///
/// ## Reversibility
///
/// [`Alignment`] and `MaybeAligned<Alignment<_>>` both offer methods for
/// reversing an alignment. For example, given an alignment between `query` and
/// `reference`, calling [`Alignment::to_reverse`] will return a new optimal
/// alignment between `query.to_reverse()` and `reference.to_reverse()`, without
/// recomputing the alignment. [`Alignment::make_reverse`] does the same thing
/// in-place.
///
/// Notably, since there may be many optimal alignments with the same score,
/// this is not guaranteed to equal the same alignment that an alignment routine
/// would return when provided the reversed sequences.
///
/// This can also be interpreted as an alignment between
/// `query.to_reverse_complement()` and `reference.to_reverse_complement()` if
/// the [`WeightMatrix`] is compatible with this. For example, the score for
/// `A→A` must be the same as `T→T`, `A→G` must be the same as `T→C`, and so on.
/// This property holds for simple weight matrices with a fixed match and
/// mismatch score, but it also holds for many other custom matrices.
///
/// One use-case for these functions is when the reverse complements of the
/// references are precomputed. In this case, it may be necessary to reverse the
/// alignment, so that it corresponds to the alignment between a
/// reverse-complemented query and the original reference.
///
/// [`SamData`]: crate::data::records::sam::SamData
/// [`SamData::from_alignment`]:
///     crate::data::records::sam::SamData::from_alignment
/// [`WeightMatrix`]: crate::data::WeightMatrix
#[non_exhaustive]
#[derive(Clone, Eq, PartialEq, Debug, Default)]
pub struct Alignment<T> {
    /// The score of the alignment
    pub score:       T,
    /// A range for the indices of the reference that are included in the
    /// alignment
    pub ref_range:   Range<usize>,
    /// A range for the indices of the query that are included in the alignment,
    /// already **excludes** clipped bases
    pub query_range: Range<usize>,
    /// States mapping reference and query.
    pub states:      AlignmentStates,
    /// The length of the reference sequence
    pub ref_len:     usize,
    /// The length of the query sequence
    pub query_len:   usize,
}

impl<T> Alignment<T> {
    /// Returns an [`Alignment`] struct representing a global alignment.
    ///
    /// This sets `ref_range` to `0..ref_len` and `query_range` to
    /// `0..query_len`.
    #[inline]
    #[must_use]
    pub fn new_global(score: T, states: AlignmentStates, ref_len: usize, query_len: usize) -> Self {
        Self {
            score,
            ref_range: 0..ref_len,
            query_range: 0..query_len,
            states,
            ref_len,
            query_len,
        }
    }

    /// Given the output of an alignment algorithm, generate the aligned
    /// sequences, using `-` as a gap character.
    ///
    /// The arguments `reference` and `query` should be the full sequences
    /// originally passed to the alignment algorithm.
    ///
    /// The first output is the aligned reference, and the second is the aligned
    /// query. Portions of the reference that were not matched are not included
    /// in the output, nor are clipped portions of the query.
    ///
    /// ## Panics
    ///
    /// This function requires the following assumptions to avoid panicking.
    /// Note that any [`Alignment`] struct returned by a *Zoe* alignment
    /// function will satisfy these.
    ///
    /// - All operations must be valid state, e.g, bytes in `MIDNSHP=X`.
    /// - The query and reference must be at least as long as the length implied
    ///   by the alignment operations (and the start of `self.ref_range`).
    #[inline]
    #[must_use]
    pub fn get_aligned_seqs(&self, reference: &[u8], query: &[u8]) -> (Vec<u8>, Vec<u8>) {
        pairwise_align_with(reference, query, &self.states, self.ref_range.start)
    }

    /// Returns an iterator over the pairs of aligned bases in `reference` and
    /// `query`. `None` is used to represent gaps.
    ///
    /// This has equivalent behavior as [`get_aligned_seqs`] but as an iterator.
    /// [`get_aligned_seqs`] may offer faster performance, but
    /// [`get_aligned_iter`] avoids allocations and may offer a more convenient
    /// syntax for handling gaps.
    ///
    /// The same conditions are required as [`get_aligned_seqs`] in order for
    /// the iterator to be non-panicking.
    ///
    /// [`get_aligned_seqs`]: Alignment::get_aligned_seqs
    /// [`get_aligned_iter`]: Alignment::get_aligned_iter
    #[inline]
    #[must_use]
    pub fn get_aligned_iter<'a>(
        &'a self, reference: &'a [u8], query: &'a [u8],
    ) -> AlignmentIter<'a, std::iter::Copied<std::slice::Iter<'a, Ciglet>>> {
        AlignmentIter::new(reference, query, &self.states, self.ref_range.start)
    }

    /// Given the output of an alignment algorithm, generate the aligned query,
    /// using `-` as a gap character.
    ///
    /// This is similar to [`get_aligned_seqs`], but only requires passing the
    /// query (and only returns the aligned query). This is useful when the
    /// alignment is against a model or family of references (e.g., a pHMM).
    ///
    /// Portions of the query that were clipped are not included.
    ///
    /// ## Panics
    ///
    /// This function requires the following assumptions to avoid panicking.
    /// Note that any [`Alignment`] struct returned by a *Zoe* alignment
    /// function will satisfy these.
    ///
    /// - All operations must be valid state (bytes in `MIDNSHP=X`).
    /// - The query must be at least as long as the length implied by the
    ///   alignment operations.
    ///
    /// [`get_aligned_seqs`]: Alignment::get_aligned_seqs
    pub fn get_aligned_query(&self, query: &[u8]) -> Vec<u8> {
        let mut query_index = 0;
        let mut query_aln = Vec::with_capacity(query.len() + (self.ref_range.len() / 2));

        for Ciglet { inc, op } in &self.states {
            match op {
                b'M' | b'=' | b'X' | b'I' => {
                    query_aln.extend_from_slice(&query[query_index..query_index + inc]);
                    query_index += inc;
                }
                b'D' => {
                    query_aln.extend(std::iter::repeat_n(b'-', inc));
                }

                b'S' => query_index += inc,
                b'N' => {
                    query_aln.extend(std::iter::repeat_n(b'N', inc));
                }
                b'H' | b'P' => {}
                // TODO: Could ignore if we allow only valid CIGAR by default.
                _ => panic!("CIGAR op '{op}' not supported.\n"),
            }
        }

        query_aln
    }
}

impl<T: Copy> Alignment<T> {
    /// Gets the alignment for when the query and reference are swapped.
    #[must_use]
    pub fn invert(&self) -> Self {
        let mut states = AlignmentStates::new();
        states.soft_clip(self.ref_range.start);
        let inverted_ciglets = self.states.0.iter().filter_map(|&ciglet| match ciglet.op {
            b'S' | b'H' => None,
            b'D' => Some(Ciglet {
                inc: ciglet.inc,
                op:  b'I',
            }),
            b'I' => Some(Ciglet {
                inc: ciglet.inc,
                op:  b'D',
            }),
            _ => Some(ciglet),
        });
        // Validity: No adjacent ciglets have the same operation since this is
        // true of AlignmentStates and the filter_map call is injective. The
        // increments are non-zero since the same is true of AlignmentStates.
        states.extend_from_ciglets(inverted_ciglets);
        states.soft_clip(self.ref_len - self.ref_range.end);

        Self {
            score: self.score,
            ref_range: self.query_range.clone(),
            query_range: self.ref_range.clone(),
            states,
            ref_len: self.query_len,
            query_len: self.ref_len,
        }
    }

    /// Gets the alignment for when the query and reference are both reversed.
    ///
    /// See [`Reversibility`](Alignment#reversibility) for more details.
    #[must_use]
    pub fn to_reverse(&self) -> Self {
        let ref_range = (self.ref_len - self.ref_range.end)..(self.ref_len - self.ref_range.start);
        let query_range = (self.query_len - self.query_range.end)..(self.query_len - self.query_range.start);
        let states = self.states.to_reverse();

        Alignment {
            score: self.score,
            ref_range,
            query_range,
            states,
            ref_len: self.ref_len,
            query_len: self.query_len,
        }
    }

    /// Converts an alignment in-place so that it represents the alignment
    /// between the reversed query and reference.
    ///
    /// See [`Reversibility`](Alignment#reversibility) for more details.
    pub fn make_reverse(&mut self) {
        self.ref_range = (self.ref_len - self.ref_range.end)..(self.ref_len - self.ref_range.start);
        self.query_range = (self.query_len - self.query_range.end)..(self.query_len - self.query_range.start);
        self.states.make_reverse();
    }

    /// Generates a new alignment replacing `M` in `states` with either `=` for
    /// matches and `X` for mismatches.
    ///
    /// The first argument should contain the full reference that was used to
    /// generate the alignment.
    ///
    /// ## Panics
    ///
    /// If either `reference` or `query` are of a shorter length than implied by
    /// the alignment, then this will panic due to out of bounds indexing.
    #[inline]
    #[must_use]
    pub fn to_verbose_sequence_matching(&self, reference: &[u8], query: &[u8]) -> Self {
        Self {
            score:       self.score,
            ref_range:   self.ref_range.clone(),
            query_range: self.query_range.clone(),
            states:      self
                .states
                .to_verbose_sequence_matching(reference, query, self.ref_range.start),
            ref_len:     self.ref_len,
            query_len:   self.query_len,
        }
    }

    /// Clips an [`Alignment`] so that it corresponds to the provided reference
    /// range.
    ///
    /// If the reference range is out of bounds, then `None` is returned. The
    /// `score`, `ref_len`, and `query_len` fields are not changed.
    ///
    /// ## Panics
    ///
    /// This function requires the following assumptions to avoid panicking.
    /// Note that any [`Alignment`] struct returned by a *Zoe* alignment
    /// function will satisfy these.
    ///
    /// - The `query_len` field must be greater than or equal to the number of
    ///   residues that the `states` field consumes in the query.
    ///
    /// ## Example
    ///
    /// ```
    /// # use zoe::{
    /// #     alignment::{AlignmentStates, ScalarProfile, SeqSrc},
    /// #     data::WeightMatrix,
    /// #     prelude::*,
    /// # };
    /// const MATRIX: WeightMatrix<'_, i8, 5> = WeightMatrix::new_dna_matrix(1, -1, None);
    /// const GAP_OPEN: i8 = -3;
    /// const GAP_EXTEND: i8 = -1;
    ///
    /// let reference = Nucleotides::from(b"GATAATCACATGTGTTGCACGTTGTAAGGTAGCATGCCTTGA");
    /// let query = Nucleotides::from(b"GATATCAAATGCGTGCTTGCACGATGTAAGGTAGC");
    ///
    /// let profile = ScalarProfile::new(&query, &MATRIX, GAP_OPEN, GAP_EXTEND).unwrap();
    /// let alignment = profile.sw_align(SeqSrc::Reference(&reference)).unwrap();
    ///
    /// assert_eq!(alignment.states, AlignmentStates::try_from(b"4M1D10M3I18M").unwrap());
    ///
    /// let coding_alignment = alignment.slice_to_ref_range(9..27).unwrap();
    /// assert_eq!(coding_alignment.states, AlignmentStates::try_from(b"8S6M3I12M6S").unwrap());
    /// assert_eq!(coding_alignment.query_range, 8..29);
    /// ```
    pub fn slice_to_ref_range(&self, ref_range: Range<usize>) -> Option<Self> {
        // Adjust the requested ref_range to be an offset from the start of
        // self.ref_range
        let rel_ref_range = if ref_range.start >= self.ref_range.start {
            ref_range.sub(self.ref_range.start)
        } else {
            // We are trying to access a portion of the reference range that was
            // not aligned to
            return None;
        };

        let mut query_idx = 0;
        let mut ref_idx = 0;

        let mut ciglets = self.states.iter().copied();
        let mut states = AlignmentStates::new();

        // Find the first ciglet overlapping the reference range. Strict
        // inequality ensures that any hard or soft clipping ciglets are
        // skipped.
        let Some(mut first_ciglet) = ciglets.find_map(|ciglet| {
            (query_idx, ref_idx) = (query_idx, ref_idx).increment_idxs_by(ciglet);
            let num_in_range = ref_idx.saturating_sub(rel_ref_range.start);
            (num_in_range > 0).then_some(Ciglet {
                op:  ciglet.op,
                inc: num_in_range,
            })
        }) else {
            // If the requested reference range is empty AND is using a number
            // in the appropriate range, then this function will return an empty
            // alignment instead of `None`. The specific range was chosen to
            // mimic `get`.
            if ref_range.is_empty() && (self.ref_range.start..=self.ref_range.end).contains(&ref_range.start) {
                let mut states = AlignmentStates::with_capacity(1);
                states.soft_clip(self.query_len);
                return Some(Alignment {
                    score: self.score,
                    ref_range: ref_range.clone(),
                    query_range: 0..0,
                    states,
                    ref_len: self.ref_len,
                    query_len: self.query_len,
                });
            }

            if !self.ref_range.is_empty() {
                debug_assert!(ref_range.start >= self.ref_range.end);
            }

            return None;
        };

        // Calculates where the sliced alignment starts in the query
        let (query_start, ref_start) = (query_idx, ref_idx).decrement_idxs_by(first_ciglet);
        debug_assert_eq!(ref_start, rel_ref_range.start);

        // Add soft clipping at start
        states.soft_clip(query_start);

        // Check whether the sliced alignment is only a single ciglet
        if ref_idx >= rel_ref_range.end {
            first_ciglet.inc = first_ciglet.inc.saturating_sub(ref_idx - rel_ref_range.end);
            states.add_ciglet(first_ciglet);
            let (query_end, ref_end) = (query_start, ref_start).increment_idxs_by(first_ciglet);
            states.soft_clip(self.query_len - query_end);

            debug_assert_eq!(ref_end, rel_ref_range.end);

            return Some(Self {
                score: self.score,
                ref_range,
                query_range: query_start..query_end,
                states,
                ref_len: self.ref_len,
                query_len: self.query_len,
            });
        }

        // Add the first ciglet
        states.add_ciglet(first_ciglet);

        for mut ciglet in ciglets {
            // Add the contribution of the next ciglet, but don't update idxs
            // yet
            let (new_query_idx, new_ref_idx) = (query_idx, ref_idx).increment_idxs_by(ciglet);

            // Check whether ciglet caused us to meet or pass the end of
            // rel_ref_range
            if let Some(num_past) = new_ref_idx.checked_sub(rel_ref_range.end) {
                ciglet.inc = ciglet.inc.saturating_sub(num_past);
                states.add_ciglet(ciglet);
                let (query_end, ref_end) = (query_idx, ref_idx).increment_idxs_by(ciglet);
                states.soft_clip(self.query_len - query_end);

                debug_assert!(ciglet.inc > 0);
                debug_assert_eq!(ref_end, rel_ref_range.end);

                return Some(Self {
                    score: self.score,
                    ref_range,
                    query_range: query_start..query_end,
                    states,
                    ref_len: self.ref_len,
                    query_len: self.query_len,
                });
            }

            // Add ciglet and update idxs
            states.add_ciglet(ciglet);
            (query_idx, ref_idx) = (new_query_idx, new_ref_idx);
        }

        if ref_idx < rel_ref_range.end {
            debug_assert!(ref_range.end > self.ref_range.end);
            return None;
        }

        debug_assert_eq!(ref_idx, rel_ref_range.end);
        let query_range = query_start..query_idx;
        states.soft_clip(self.query_len - query_idx);
        Some(Self {
            score: self.score,
            ref_range,
            query_range,
            states,
            ref_len: self.ref_len,
            query_len: self.query_len,
        })
    }
}

/// An extension trait for adding or subtracting a [`Ciglet`] to a tuple
/// representing the query index and reference index.
pub(crate) trait AlignmentIndices {
    /// Adds the contribution of the [`Ciglet`] to a query and reference index.
    fn increment_idxs_by(self, ciglet: Ciglet) -> Self;

    /// Subtracts the contribution of the [`Ciglet`] to a query and reference
    /// index.
    fn decrement_idxs_by(self, ciglet: Ciglet) -> Self;
}

impl AlignmentIndices for (usize, usize) {
    #[inline]
    fn increment_idxs_by(self, ciglet: Ciglet) -> Self {
        let (query_idx, ref_idx) = self;
        match ciglet.op {
            b'M' | b'=' | b'X' => (query_idx + ciglet.inc, ref_idx + ciglet.inc),
            b'D' | b'N' => (query_idx, ref_idx + ciglet.inc),
            b'I' | b'S' => (query_idx + ciglet.inc, ref_idx),
            _ => (query_idx, ref_idx),
        }
    }

    #[inline]
    fn decrement_idxs_by(self, ciglet: Ciglet) -> Self {
        let (query_idx, ref_idx) = self;
        match ciglet.op {
            b'M' | b'=' | b'X' => (query_idx - ciglet.inc, ref_idx - ciglet.inc),
            b'D' | b'N' => (query_idx, ref_idx - ciglet.inc),
            b'I' | b'S' => (query_idx - ciglet.inc, ref_idx),
            _ => (query_idx, ref_idx),
        }
    }
}