packed_seq/
traits.rs

1use super::u32x8;
2use mem_dbg::{MemDbg, MemSize};
3use std::ops::Range;
4
5/// A non-owned slice of characters.
6///
7/// The represented character values are expected to be in `[0, 2^b)`,
8/// but they can be encoded in various ways. E.g.:
9/// - A `&[u8]` of ASCII characters, returning 8-bit values.
10/// - An `AsciiSeq` of DNA characters `ACGT`, interpreted 2-bit values.
11/// - A `PackedSeq` of packed DNA characters (4 per byte), returning 2-bit values.
12///
13/// Each character is assumed to fit in 8 bits. Some functions take or return
14/// this 'unpacked' (ASCII) character.
15pub trait Seq<'s>: Copy + Eq + Ord {
16    /// Number of encoded characters per byte of memory of the `Seq`.
17    const BASES_PER_BYTE: usize;
18    /// Number of bits `b` to represent each character returned by `iter_bp` and variants..
19    const BITS_PER_CHAR: usize;
20
21    /// The corresponding owned sequence type.
22    type SeqVec: SeqVec;
23
24    /// Convenience function that returns `b=Self::BITS_PER_CHAR`.
25    fn bits_per_char(&self) -> usize {
26        Self::BITS_PER_CHAR
27    }
28
29    /// The length of the sequence in characters.
30    fn len(&self) -> usize;
31
32    /// Returns `true` if the sequence is empty.
33    fn is_empty(&self) -> bool;
34
35    /// Get the character at the given index.
36    fn get(&self, _index: usize) -> u8;
37
38    /// Get the ASCII character at the given index, _without_ mapping to `b`-bit values.
39    fn get_ascii(&self, _index: usize) -> u8;
40
41    /// Convert a short sequence (kmer) to a packed representation as `u64`.
42    fn as_u64(&self) -> u64;
43
44    /// Convert a short sequence (kmer) to a packed representation of its reverse complement as `u64`.
45    fn revcomp_as_u64(&self) -> u64;
46
47    /// Convert a short sequence (kmer) to a packed representation as `usize`.
48    #[deprecated = "Prefer `to_u64`."]
49    #[inline(always)]
50    fn to_word(&self) -> usize {
51        self.as_u64() as usize
52    }
53
54    /// Convert a short sequence (kmer) to a packed representation of its reverse complement as `usize`.
55    #[deprecated = "Prefer `revcomp_to_u64`."]
56    #[inline(always)]
57    fn to_word_revcomp(&self) -> usize {
58        self.revcomp_as_u64() as usize
59    }
60
61    /// Convert to an owned version.
62    fn to_vec(&self) -> Self::SeqVec;
63
64    /// Compute the reverse complement of this sequence.
65    fn to_revcomp(&self) -> Self::SeqVec;
66
67    /// Get a sub-slice of the sequence.
68    /// `range` indicates character indices.
69    fn slice(&self, range: Range<usize>) -> Self;
70
71    /// Extract a k-mer from this sequence.
72    #[inline(always)]
73    fn read_kmer(&self, k: usize, pos: usize) -> u64 {
74        self.slice(pos..pos + k).as_u64()
75    }
76
77    /// Extract a reverse complement k-mer from this sequence.
78    #[inline(always)]
79    fn read_revcomp_kmer(&self, k: usize, pos: usize) -> u64 {
80        self.slice(pos..pos + k).revcomp_as_u64()
81    }
82
83    /// Iterate over the `b`-bit characters of the sequence.
84    fn iter_bp(self) -> impl ExactSizeIterator<Item = u8> + Clone;
85
86    /// Iterate over 8 chunks of `b`-bit characters of the sequence in parallel.
87    ///
88    /// This splits the input into 8 chunks and streams over them in parallel.
89    /// The second output returns the number of 'padding' characters that was added to get a full number of SIMD lanes.
90    /// Thus, the last `padding` number of returned elements (from the last lane(s)) should be ignored.
91    /// The context can be e.g. the k-mer size being iterated.
92    /// When `context>1`, consecutive chunks overlap by `context-1` bases.
93    ///
94    /// Expected to be implemented using SIMD instructions.
95    fn par_iter_bp(self, context: usize) -> (impl ExactSizeIterator<Item = u32x8> + Clone, usize);
96
97    /// Iterate over 8 chunks of the sequence in parallel, returning two characters offset by `delay` positions.
98    ///
99    /// Returned pairs are `(add, remove)`, and the first `delay` 'remove' characters are always `0`.
100    ///
101    /// For example, when the sequence starts as `ABCDEF...`, and `delay=2`,
102    /// the first returned tuples in the first lane are:
103    /// `(b'A', 0)`, `(b'B', 0)`, `(b'C', b'A')`, `(b'D', b'B')`.
104    ///
105    /// When `context>1`, consecutive chunks overlap by `context-1` bases:
106    /// the first `context-1` 'added' characters of the second chunk overlap
107    /// with the last `context-1` 'added' characters of the first chunk.
108    fn par_iter_bp_delayed(
109        self,
110        context: usize,
111        delay: usize,
112    ) -> (impl ExactSizeIterator<Item = (u32x8, u32x8)> + Clone, usize);
113
114    /// Iterate over 8 chunks of the sequence in parallel, returning three characters:
115    /// the char added, the one `delay` positions before, and the one `delay2` positions before.
116    ///
117    /// Requires `delay1 <= delay2`.
118    ///
119    /// Returned pairs are `(add, d1, d2)`. The first `delay1` `d1` characters and first `delay2` `d2` are always `0`.
120    ///
121    /// For example, when the sequence starts as `ABCDEF...`, and `delay1=2` and `delay2=3`,
122    /// the first returned tuples in the first lane are:
123    /// `(b'A', 0, 0)`, `(b'B', 0, 0)`, `(b'C', b'A', 0)`, `(b'D', b'B', b'A')`.
124    ///
125    /// When `context>1`, consecutive chunks overlap by `context-1` bases:
126    /// the first `context-1` 'added' characters of the second chunk overlap
127    /// with the last `context-1` 'added' characters of the first chunk.
128    fn par_iter_bp_delayed_2(
129        self,
130        context: usize,
131        delay1: usize,
132        delay2: usize,
133    ) -> (
134        impl ExactSizeIterator<Item = (u32x8, u32x8, u32x8)> + Clone,
135        usize,
136    );
137
138    /// Compare and return the LCP of the two sequences.
139    fn cmp_lcp(&self, other: &Self) -> (std::cmp::Ordering, usize);
140}
141
142// Some hacky stuff to make conditional supertraits.
143cfg_if::cfg_if! {
144    if #[cfg(feature = "epserde")] {
145        pub use epserde::{deser::DeserializeInner, ser::SerializeInner};
146    } else {
147        pub trait SerializeInner {}
148        pub trait DeserializeInner {}
149
150        impl SerializeInner for Vec<u8> {}
151        impl DeserializeInner for Vec<u8> {}
152        impl SerializeInner for crate::AsciiSeqVec {}
153        impl DeserializeInner for crate::AsciiSeqVec {}
154        impl SerializeInner for crate::PackedSeqVec {}
155        impl DeserializeInner for crate::PackedSeqVec {}
156    }
157}
158
159/// An owned sequence.
160/// Can be constructed from either ASCII input or the underlying non-owning `Seq` type.
161///
162/// Implemented for:
163/// - A `Vec<u8>` of ASCII characters, returning 8-bit values.
164/// - An `AsciiSeqVec` of DNA characters `ACGT`, interpreted as 2-bit values.
165/// - A `PackedSeqVec` of packed DNA characters (4 per byte), returning 2-bit values.
166pub trait SeqVec:
167    Default + Sync + SerializeInner + DeserializeInner + MemSize + MemDbg + Clone + 'static
168{
169    type Seq<'s>: Seq<'s>;
170
171    /// Get a non-owning slice to the underlying sequence.
172    ///
173    /// Unfortunately, `Deref` into a `Seq` can not be supported.
174    fn as_slice(&self) -> Self::Seq<'_>;
175
176    /// Get a sub-slice of the sequence. Indices are character offsets.
177    #[inline(always)]
178    fn slice(&self, range: Range<usize>) -> Self::Seq<'_> {
179        self.as_slice().slice(range)
180    }
181
182    /// Extract a k-mer from this sequence.
183    #[inline(always)]
184    fn read_kmer(&self, k: usize, pos: usize) -> u64 {
185        self.as_slice().read_kmer(k, pos)
186    }
187
188    /// Extract a k-mer from this sequence.
189    #[inline(always)]
190    fn read_revcomp_kmer(&self, k: usize, pos: usize) -> u64 {
191        self.as_slice().read_revcomp_kmer(k, pos)
192    }
193
194    /// The length of the sequence in characters.
195    fn len(&self) -> usize;
196
197    /// Returns `true` if the sequence is empty.
198    fn is_empty(&self) -> bool;
199
200    /// Empty the sequence.
201    fn clear(&mut self);
202
203    /// Convert into the underlying raw representation.
204    fn into_raw(self) -> Vec<u8>;
205
206    /// Generate a random sequence with the given number of characters.
207    #[cfg(feature = "rand")]
208    fn random(n: usize) -> Self;
209
210    /// Create a `SeqVec` from ASCII input.
211    #[inline(always)]
212    fn from_ascii(seq: &[u8]) -> Self {
213        let mut packed_vec = Self::default();
214        packed_vec.push_ascii(seq);
215        packed_vec
216    }
217
218    /// Append the given sequence to the underlying storage.
219    ///
220    /// This may leave gaps (padding) between consecutively pushed sequences to avoid re-aligning the pushed data.
221    /// Returns the range of indices corresponding to the pushed sequence.
222    /// Use `self.slice(range)` to get the corresponding slice.
223    fn push_seq(&mut self, seq: Self::Seq<'_>) -> Range<usize>;
224
225    /// Append the given ASCII sequence to the underlying storage.
226    ///
227    /// This may leave gaps (padding) between consecutively pushed sequences to avoid re-aligning the pushed data.
228    /// Returns the range of indices corresponding to the pushed sequence.
229    /// Use `self.slice(range)` to get the corresponding slice.
230    fn push_ascii(&mut self, seq: &[u8]) -> Range<usize>;
231}