nucs 0.4.1

Library for working with nucleotide and amino acid sequences
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
//! Types related to packed ambiguous peptides.

use std::fmt::Formatter;

use crate::{Amino, Seq, iter::display};

use super::packable_array::{ArrayDefault, Sealed as ArrayDivide};
use super::{PackableArray, UnpackingIter};

// Note on storage: Aminos are packed big-endian so naive lexical sorting of bytes is correct.
// The [u8; 2] themselves are big-endian u16s, for the same reason.
//
// The last word of a non-empty `PackedPeptide` must have 1-3 elements. If it has 2 elements,
// the 5 least-significant bits are 0. If it has 1 element, the 10 least-significant bits are 0.

/// Like [`Vec<Amino>`], but takes 33% less space for long peptides.
///
/// # Examples
///
/// ```
/// use nucs::{Amino, Packed};
///
/// let peptide = Amino::arr(b"KITTYTUMSOFDANGER");
/// let packed: Packed<[Amino]> = peptide.as_slice().into();
/// let unpacked: Vec<Amino> = packed.into();
/// assert_eq!(unpacked, peptide);
/// ```
#[derive(Clone, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct PackedPeptide(Vec<[u8; 2]>);

impl PackedPeptide {
    /// Returns the number of [`Amino`]s in the packed peptide.
    #[must_use]
    pub fn len(&self) -> usize {
        // len <= `usize::MAX` is an invariant of this type, so no need to worry about overflow.
        match &*self.0 {
            [] => 0,
            bulk @ [.., tail] => {
                3 * bulk.len() - (u16::from_be_bytes(*tail).trailing_zeros() / 5) as usize
            }
        }
    }

    /// Returns `true` if the packed peptide contains no [`Amino`]s.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns an iterator over the packed peptide.
    #[must_use]
    pub fn iter(&self) -> PackedPeptideIter<'_> {
        self.into_iter()
    }
}

impl From<Seq<Vec<Amino>>> for PackedPeptide {
    fn from(peptide: Seq<Vec<Amino>>) -> PackedPeptide {
        peptide.0.into()
    }
}

impl From<Vec<Amino>> for PackedPeptide {
    fn from(peptide: Vec<Amino>) -> PackedPeptide {
        (&peptide).into()
    }
}

impl<T: AsRef<[Amino]> + ?Sized> From<&T> for PackedPeptide {
    fn from(peptide: &T) -> PackedPeptide {
        let peptide = peptide.as_ref();
        let packed_len = peptide.len().div_ceil(3);
        let mut packed = vec![[0, 0]; packed_len];
        pack(&mut packed, peptide);
        Self(packed)
    }
}

impl From<PackedPeptide> for Seq<Vec<Amino>> {
    fn from(packed_peptide: PackedPeptide) -> Seq<Vec<Amino>> {
        Seq(packed_peptide.into())
    }
}

impl From<&PackedPeptide> for Seq<Vec<Amino>> {
    fn from(packed_peptide: &PackedPeptide) -> Seq<Vec<Amino>> {
        Seq(packed_peptide.into())
    }
}

impl From<PackedPeptide> for Vec<Amino> {
    fn from(packed_peptide: PackedPeptide) -> Vec<Amino> {
        (&packed_peptide).into()
    }
}

impl From<&PackedPeptide> for Vec<Amino> {
    fn from(packed_peptide: &PackedPeptide) -> Vec<Amino> {
        let mut peptide = vec![Amino::default(); packed_peptide.len()];
        unpack(&mut peptide, &packed_peptide.0);
        peptide
    }
}

impl<'a> IntoIterator for &'a PackedPeptide {
    type Item = Amino;
    type IntoIter = PackedPeptideIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        PackedPeptideIter(UnpackingIter::new(0..self.len(), &self.0))
    }
}

impl IntoIterator for PackedPeptide {
    type Item = Amino;
    type IntoIter = PackedPeptideIntoIter;

    fn into_iter(self) -> Self::IntoIter {
        PackedPeptideIntoIter(UnpackingIter::new(0..self.len(), self.0))
    }
}

impl std::fmt::Display for PackedPeptide {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        self.iter().fmt(f)
    }
}

impl std::fmt::Debug for PackedPeptide {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        f.debug_tuple("PackedPeptide")
            .field(&display(self.iter()))
            .finish()
    }
}

/// Like [`[Amino; N]`](array), but takes 33% less space.
///
/// # Examples
///
/// ```
/// use nucs::{Amino, Packed};
///
/// let peptide = Amino::arr(b"KITTYTUMSOFDANGER");
/// assert_eq!(size_of_val(&peptide), 17);
/// let packed: Packed<[Amino; 17]> = peptide.into();
/// assert_eq!(size_of_val(&packed), 12);
/// let unpacked: [Amino; 17] = packed.into();
/// assert_eq!(unpacked, peptide);
/// ```
#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct PackedArrayPeptide<const N: usize>(PackedBuf<N>)
where
    [(); N]: PackableArray;

type PackedBuf<const N: usize> = <[(); N] as ArrayDivide>::By3<[u8; 2]>;

impl<const N: usize> PackedArrayPeptide<N>
where
    [(); N]: PackableArray,
{
    /// Returns an iterator over the packed peptide.
    #[must_use]
    pub fn iter(&self) -> PackedPeptideIter<'_> {
        self.into_iter()
    }
}

impl<const N: usize> Default for PackedArrayPeptide<N>
where
    [(); N]: PackableArray,
{
    fn default() -> Self {
        Self(ArrayDefault::array_default())
    }
}

impl<const N: usize> From<Seq<[Amino; N]>> for PackedArrayPeptide<N>
where
    [(); N]: PackableArray,
{
    fn from(peptide: Seq<[Amino; N]>) -> PackedArrayPeptide<N> {
        peptide.0.into()
    }
}

impl<const N: usize> From<&Seq<[Amino; N]>> for PackedArrayPeptide<N>
where
    [(); N]: PackableArray,
{
    fn from(peptide: &Seq<[Amino; N]>) -> PackedArrayPeptide<N> {
        peptide.0.into()
    }
}

impl<const N: usize> From<[Amino; N]> for PackedArrayPeptide<N>
where
    [(); N]: PackableArray,
{
    fn from(peptide: [Amino; N]) -> PackedArrayPeptide<N> {
        (&peptide).into()
    }
}

impl<const N: usize> From<&[Amino; N]> for PackedArrayPeptide<N>
where
    [(); N]: PackableArray,
{
    fn from(peptide: &[Amino; N]) -> PackedArrayPeptide<N> {
        let mut this = Self(ArrayDefault::array_default());
        pack(this.0.as_mut(), peptide);
        this
    }
}

impl<const N: usize> From<PackedArrayPeptide<N>> for Seq<[Amino; N]>
where
    [(); N]: PackableArray,
{
    fn from(packed_peptide: PackedArrayPeptide<N>) -> Seq<[Amino; N]> {
        Seq(packed_peptide.into())
    }
}

impl<const N: usize> From<&PackedArrayPeptide<N>> for Seq<[Amino; N]>
where
    [(); N]: PackableArray,
{
    fn from(packed_peptide: &PackedArrayPeptide<N>) -> Seq<[Amino; N]> {
        Seq(packed_peptide.into())
    }
}

impl<const N: usize> From<PackedArrayPeptide<N>> for [Amino; N]
where
    [(); N]: PackableArray,
{
    fn from(packed_peptide: PackedArrayPeptide<N>) -> [Amino; N] {
        (&packed_peptide).into()
    }
}

impl<const N: usize> From<&PackedArrayPeptide<N>> for [Amino; N]
where
    [(); N]: PackableArray,
{
    fn from(packed_peptide: &PackedArrayPeptide<N>) -> [Amino; N] {
        let mut peptide = [Amino::default(); N];
        unpack(&mut peptide, packed_peptide.0.as_ref());
        peptide
    }
}

impl<'a, const N: usize> IntoIterator for &'a PackedArrayPeptide<N>
where
    [(); N]: PackableArray,
{
    type Item = Amino;
    type IntoIter = PackedPeptideIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        PackedPeptideIter(UnpackingIter::new(0..N, self.0.as_ref()))
    }
}

impl<const N: usize> IntoIterator for PackedArrayPeptide<N>
where
    [(); N]: PackableArray,
{
    type Item = Amino;
    type IntoIter = PackedArrayPeptideIntoIter<N>;

    fn into_iter(self) -> Self::IntoIter {
        PackedArrayPeptideIntoIter(UnpackingIter::new(0..N, self.0))
    }
}

impl<const N: usize> std::fmt::Display for PackedArrayPeptide<N>
where
    [(); N]: PackableArray,
{
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        self.iter().fmt(f)
    }
}

impl<const N: usize> std::fmt::Debug for PackedArrayPeptide<N>
where
    [(); N]: PackableArray,
{
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        f.debug_tuple("PackedArrayPeptide")
            .field(&display(self.iter()))
            .finish()
    }
}

fn pack(packed: &mut [[u8; 2]], peptide: &[Amino]) {
    let (triplets, remainder) = peptide.as_chunks();
    for (pair, &[a1, a2, a3]) in packed.iter_mut().zip(triplets) {
        *pair = (a3.compress() | (a2.compress() << 5) | (a1.compress() << 10)).to_be_bytes();
    }
    match (packed.last_mut(), remainder) {
        (_, []) => {}
        (Some(pair), [a1]) => *pair = (a1.compress() << 10).to_be_bytes(),
        (Some(pair), [a1, a2]) => {
            *pair = ((a1.compress() << 10) | (a2.compress() << 5)).to_be_bytes();
        }
        _ => panic!(),
    }
}

fn unpack(peptide: &mut [Amino], packed: &[[u8; 2]]) {
    let (triplets, remainder) = peptide.as_chunks_mut();
    for ([a1, a2, a3], &pair) in triplets.iter_mut().zip(packed) {
        let val = u16::from_be_bytes(pair);
        *a1 = Amino::decompress(val >> 10);
        *a2 = Amino::decompress(val >> 5);
        *a3 = Amino::decompress(val);
    }
    match (remainder, packed.last()) {
        ([], _) => {}
        ([a1], Some(pair)) => *a1 = Amino::decompress(u16::from_be_bytes(*pair) >> 10),
        ([a1, a2], Some(pair)) => {
            let val = u16::from_be_bytes(*pair);
            *a1 = Amino::decompress(val >> 10);
            *a2 = Amino::decompress(val >> 5);
        }
        _ => panic!(),
    }
}

/// Owned [`PackedPeptide`] iterator.
#[derive(Clone)]
pub struct PackedPeptideIntoIter(UnpackingIter<5, 15, std::vec::IntoIter<[u8; 2]>>);

impl PackedPeptideIntoIter {
    fn as_ref(&self) -> PackedPeptideIter<'_> {
        PackedPeptideIter(self.0.as_ref())
    }
}

impl Iterator for PackedPeptideIntoIter {
    type Item = Amino;

    fn next(&mut self) -> Option<Amino> {
        self.0
            .next()
            .map(|(shift, bytes)| Amino::decompress(u16::from_be_bytes(bytes) >> shift))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl DoubleEndedIterator for PackedPeptideIntoIter {
    fn next_back(&mut self) -> Option<Amino> {
        self.0
            .next_back()
            .map(|(shift, bytes)| Amino::decompress(u16::from_be_bytes(bytes) >> shift))
    }
}

impl ExactSizeIterator for PackedPeptideIntoIter {
    fn len(&self) -> usize {
        self.0.len()
    }
}

impl std::fmt::Display for PackedPeptideIntoIter {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        self.as_ref().fmt(f)
    }
}

impl std::fmt::Debug for PackedPeptideIntoIter {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        f.debug_tuple("PackedPeptideIntoIter")
            .field(&display(self.as_ref()))
            .finish()
    }
}

/// Owned [`PackedArrayPeptide`] iterator.
#[derive(Clone)]
pub struct PackedArrayPeptideIntoIter<const N: usize>(
    UnpackingIter<5, 15, <PackedBuf<N> as IntoIterator>::IntoIter>,
)
where
    [(); N]: PackableArray;

impl<const N: usize> PackedArrayPeptideIntoIter<N>
where
    [(); N]: PackableArray,
{
    fn as_ref(&self) -> PackedPeptideIter<'_> {
        PackedPeptideIter(self.0.as_ref())
    }
}

impl<const N: usize> Iterator for PackedArrayPeptideIntoIter<N>
where
    [(); N]: PackableArray,
{
    type Item = Amino;

    fn next(&mut self) -> Option<Amino> {
        self.0
            .next()
            .map(|(shift, bytes)| Amino::decompress(u16::from_be_bytes(bytes) >> shift))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl<const N: usize> DoubleEndedIterator for PackedArrayPeptideIntoIter<N>
where
    [(); N]: PackableArray,
{
    fn next_back(&mut self) -> Option<Amino> {
        self.0
            .next_back()
            .map(|(shift, bytes)| Amino::decompress(u16::from_be_bytes(bytes) >> shift))
    }
}

impl<const N: usize> ExactSizeIterator for PackedArrayPeptideIntoIter<N>
where
    [(); N]: PackableArray,
{
    fn len(&self) -> usize {
        self.0.len()
    }
}

impl<const N: usize> std::fmt::Display for PackedArrayPeptideIntoIter<N>
where
    [(); N]: PackableArray,
{
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        self.as_ref().fmt(f)
    }
}

impl<const N: usize> std::fmt::Debug for PackedArrayPeptideIntoIter<N>
where
    [(); N]: PackableArray,
{
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        f.debug_tuple("PackedArrayPeptideIntoIter")
            .field(&display(self.as_ref()))
            .finish()
    }
}

/// Borrowed packed peptide iterator.
#[derive(Clone)]
pub struct PackedPeptideIter<'a>(UnpackingIter<5, 15, std::slice::Iter<'a, [u8; 2]>>);

impl Iterator for PackedPeptideIter<'_> {
    type Item = Amino;

    fn next(&mut self) -> Option<Amino> {
        self.0
            .next()
            .map(|(shift, bytes)| Amino::decompress(u16::from_be_bytes(*bytes) >> shift))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl DoubleEndedIterator for PackedPeptideIter<'_> {
    fn next_back(&mut self) -> Option<Amino> {
        self.0
            .next_back()
            .map(|(shift, bytes)| Amino::decompress(u16::from_be_bytes(*bytes) >> shift))
    }
}

impl ExactSizeIterator for PackedPeptideIter<'_> {
    fn len(&self) -> usize {
        self.0.len()
    }
}

impl std::fmt::Display for PackedPeptideIter<'_> {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        display(self.clone()).fmt(f)
    }
}

impl std::fmt::Debug for PackedPeptideIter<'_> {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        f.debug_tuple("PackedPeptideIter")
            .field(&display(self.clone()))
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use proptest::{arbitrary::any, proptest};

    use super::super::tests::{assert_both_roundtrips, assert_roundtrip};
    use crate::proptest::any_peptide;

    use super::*;

    #[cfg_attr(miri, ignore = "slow in miri; shouldn't touch unsafe code anyway")]
    #[test]
    fn all_short_roundtrips() {
        // Yes, this is hideously ugly, but arrays need a size known at compile-time,
        // and this is the simplest way to ensure I get them all.
        assert_both_roundtrips(&[] as &[Amino; 0]);
        for a1 in Amino::ALL {
            assert_both_roundtrips(&[a1]);
            for a2 in Amino::ALL {
                assert_both_roundtrips(&[a1, a2]);
                for a3 in Amino::ALL {
                    assert_both_roundtrips(&[a1, a2, a3]);
                    for a4 in Amino::ALL {
                        assert_both_roundtrips(&[a1, a2, a3, a4]);
                    }
                }
            }
        }
    }

    // The bulk of the fiddly logic is handled by UnpackingIter, which has more tests.
    // This is just sanity-checking that things were hooked up to it correctly.
    #[test]
    fn smoke_test_iters() {
        let peptide = Amino::seq(b"PEPTIDE")[..].pack();
        assert_eq!(Seq(Vec::from_iter(&peptide)), "PEPTIDE");
        assert_eq!(Seq(Vec::from_iter(peptide)), "PEPTIDE");
        let peptide = Amino::seq(b"PEPTIDE").pack();
        assert_eq!(Seq(Vec::from_iter(&peptide)), "PEPTIDE");
        assert_eq!(Seq(Vec::from_iter(peptide)), "PEPTIDE");
    }

    #[test]
    fn display() {
        let peptide = Amino::seq(b"PEPTIDE")[..].pack();
        assert_eq!(peptide.to_string(), "PEPTIDE");
        assert_eq!(peptide.iter().to_string(), "PEPTIDE");
        assert_eq!(peptide.into_iter().to_string(), "PEPTIDE");
        let peptide = Amino::seq(b"PEPTIDE").pack();
        assert_eq!(peptide.to_string(), "PEPTIDE");
        assert_eq!(peptide.iter().to_string(), "PEPTIDE");
        assert_eq!(peptide.into_iter().to_string(), "PEPTIDE");
    }

    proptest! {
        #[cfg_attr(miri, ignore = "slow in miri; shouldn't touch unsafe code anyway")]
        #[test]
        fn packed_peptide_roundtrip(
            peptide in any_peptide(5..25) // 0..=4 covered above
        ) {
            assert_roundtrip(&*peptide);
        }

        #[cfg_attr(miri, ignore = "slow in miri; shouldn't touch unsafe code anyway")]
        #[test]
        fn packed_array_peptide5_roundtrip(
            peptide in any::<[Amino; 5]>()
        ) {
            assert_roundtrip(&peptide);
        }

        #[cfg_attr(miri, ignore = "slow in miri; shouldn't touch unsafe code anyway")]
        #[test]
        fn packed_array_peptide6_roundtrip(
            peptide in any::<[Amino; 6]>()
        ) {
            assert_roundtrip(&peptide);
        }

        #[cfg_attr(miri, ignore = "slow in miri; shouldn't touch unsafe code anyway")]
        #[test]
        fn packed_array_peptide7_roundtrip(
            peptide in any::<[Amino; 7]>()
        ) {
            assert_roundtrip(&peptide);
        }

        #[cfg_attr(miri, ignore = "slow in miri; shouldn't touch unsafe code anyway")]
        #[test]
        fn packed_peptide_lexical_ordering(
            peptide1 in any_peptide(0..50),
            peptide2 in any_peptide(0..50),
        ) {
            let packed1 = PackedPeptide::from(peptide1.as_slice());
            let packed2 = PackedPeptide::from(peptide2.as_slice());
            assert_eq!(packed1.0.cmp(&packed2.0), peptide1.cmp(&peptide2));
        }

        #[cfg_attr(miri, ignore = "slow in miri; shouldn't touch unsafe code anyway")]
        #[test]
        fn packed_peptide_length(
            peptide in any_peptide(0..50)
        ) {
            let packed = PackedPeptide::from(&peptide);
            assert_eq!(packed.len(), peptide.len());
            assert_eq!(packed.is_empty(), peptide.is_empty());
        }
    }
}