nanalogue 0.1.9

BAM/Mod BAM parsing and analysis tool with a single-molecule focus
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
//! `OrdPair` struct for ordered pairs with low <= high guarantee
//! Provides ordered pair datatype with validation and interval operations

use super::contains::Contains;
use crate::{Error, F32Bw0and1};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::fmt::Debug;
use std::num::NonZeroU64;
use std::ops::RangeInclusive;
use std::str::FromStr;

/// Datatype holding two values low, high such that low <= high is guaranteed at creation.
#[derive(Debug, Clone, Copy, PartialOrd, PartialEq, Serialize, Deserialize)]
pub struct OrdPair<T: Clone + Copy + Debug + PartialEq + PartialOrd> {
    /// low value of the ordered pair
    low: T,
    /// high value of the ordered pair
    high: T,
}

impl Eq for OrdPair<u8> {}
impl Eq for OrdPair<u64> {}
impl Eq for OrdPair<NonZeroU64> {}
impl Eq for OrdPair<F32Bw0and1> {}

impl<T: Clone + Copy + Debug + Default + Ord> Default for OrdPair<T> {
    fn default() -> Self {
        OrdPair {
            low: T::default(),
            high: T::default(),
        }
    }
}

impl<T: Clone + Copy + Debug + PartialEq + PartialOrd> OrdPair<T> {
    /// Constructor with two values, will fail if ordering in input is not respected.
    ///
    /// ```should_panic
    /// use nanalogue_core::OrdPair;
    /// let x = OrdPair::<f32>::new(1.0,0.0).unwrap();
    /// ```
    /// ```
    /// # use nanalogue_core::OrdPair;
    /// let x = OrdPair::<f32>::new(0.0, 1.0)?;
    /// # Ok::<(), nanalogue_core::Error>(())
    /// ```
    ///
    /// # Errors
    /// Returns an error if `low` is greater than `high`.
    pub fn new(low: T, high: T) -> Result<Self, Error> {
        if low <= high {
            Ok(OrdPair { low, high })
        } else {
            Err(Error::WrongOrder(
                "wrong order in OrdPair creation".to_owned(),
            ))
        }
    }
    /// Gets the low value
    ///
    /// ```
    /// use nanalogue_core::OrdPair;
    /// let x = OrdPair::<u8>::new(10,11).expect("no failure");
    /// assert_eq!(x.low(),10);
    /// ```
    pub fn low(&self) -> T {
        self.low
    }
    /// Gets the high value
    ///
    /// ```
    /// use nanalogue_core::OrdPair;
    /// let x = OrdPair::<u8>::new(10,11).expect("no failure");
    /// assert_eq!(x.high(),11);
    /// ```
    pub fn high(&self) -> T {
        self.high
    }
    /// Updates the low value with a given value if possible
    ///
    /// # Errors
    ///
    /// If update not possible because `low < high` is violated.
    ///
    /// # Examples
    ///
    /// ```
    /// use nanalogue_core::OrdPair;
    /// let mut x = OrdPair::<u8>::new(10, 11).expect("no failure");
    /// x.update_low(9).unwrap();
    /// assert_eq!(x.low(), 9);
    /// assert_eq!(x.high(), 11);
    /// ```
    ///
    /// ```should_panic
    /// use nanalogue_core::OrdPair;
    /// let mut x = OrdPair::<u8>::new(10, 11).expect("no failure");
    /// x.update_low(12).unwrap();
    /// ```
    pub fn update_low(&mut self, value: T) -> Result<(), Error> {
        if value <= self.high() {
            self.low = value;
            Ok(())
        } else {
            Err(Error::WrongOrder(
                "wrong order in OrdPair `update_low`".to_owned(),
            ))
        }
    }
    /// Updates the high value with a given value if possible
    ///
    /// # Errors
    ///
    /// If update not possible because `low < high` is violated.
    ///
    /// # Examples
    ///
    /// ```
    /// use nanalogue_core::OrdPair;
    /// let mut x = OrdPair::<u8>::new(10, 11).expect("no failure");
    /// x.update_high(20).unwrap();
    /// assert_eq!(x.low(), 10);
    /// assert_eq!(x.high(), 20);
    /// ```
    ///
    /// ```should_panic
    /// use nanalogue_core::OrdPair;
    /// let mut x = OrdPair::<u8>::new(10, 11).expect("no failure");
    /// x.update_high(9).unwrap();
    /// ```
    pub fn update_high(&mut self, value: T) -> Result<(), Error> {
        if value >= self.low() {
            self.high = value;
            Ok(())
        } else {
            Err(Error::WrongOrder(
                "wrong order in OrdPair `update_high`".to_owned(),
            ))
        }
    }
}

impl OrdPair<u64> {
    /// Parse an interval string specifically for genomic regions.
    /// Supports formats like "1000-2000" and "1000-" (where end defaults to `u64::MAX`).
    /// Enforces strict inequality (start < end).
    ///
    /// ```
    /// use nanalogue_core::OrdPair;
    ///
    /// // Standard interval
    /// let interval = OrdPair::<u64>::from_interval("1000-2000")?;
    /// assert_eq!(interval.low(), 1000);
    /// assert_eq!(interval.high(), 2000);
    /// # Ok::<(), nanalogue_core::Error>(())
    /// ```
    ///
    /// ```
    /// # use nanalogue_core::OrdPair;
    /// #
    /// // Open-ended interval (end defaults to u64::MAX)
    /// let interval = OrdPair::<u64>::from_interval("1000-")?;
    /// assert_eq!(interval.low(), 1000);
    /// assert_eq!(interval.high(), u64::MAX);
    /// # Ok::<(), nanalogue_core::Error>(())
    /// ```
    ///
    /// ```should_panic
    /// # use nanalogue_core::OrdPair;
    /// #
    /// // Equal start and end should fail
    /// let interval = OrdPair::<u64>::from_interval("1000-1000")?;
    /// # Ok::<(), nanalogue_core::Error>(())
    /// ```
    ///
    /// # Errors
    /// Returns an error if the interval format is invalid, coordinates cannot be parsed,
    /// or if start is not strictly less than end.
    ///
    #[expect(
        clippy::missing_panics_doc,
        reason = "This function does not panic. The internal `.expect()` \
calls are only used after verifying the length of the parts vector, ensuring safe access."
    )]
    pub fn from_interval(interval_str: &str) -> Result<Self, Error> {
        let parts: Vec<&str> = interval_str.split('-').collect();

        match parts.len() {
            2 => {
                let start = parts
                    .first()
                    .expect("parts has exactly 2 elements")
                    .trim()
                    .parse::<u64>()
                    .map_err(|_err| {
                        Error::OrdPairConversion(
                            "Invalid start coordinate in interval!".to_string(),
                        )
                    })?;

                let end = if parts
                    .get(1)
                    .expect("parts has exactly 2 elements")
                    .trim()
                    .is_empty()
                {
                    // Open-ended interval: "1000-"
                    u64::MAX
                } else {
                    // Closed interval: "1000-2000"
                    parts
                        .get(1)
                        .expect("parts has exactly 2 elements")
                        .trim()
                        .parse::<u64>()
                        .map_err(|_err| {
                            Error::OrdPairConversion(
                                "Invalid end coordinate in interval!".to_string(),
                            )
                        })?
                };

                // Enforce strict inequality (start < end)
                if start < end {
                    Ok(OrdPair {
                        low: start,
                        high: end,
                    })
                } else {
                    Err(Error::OrdPairConversion(
                        "Genomic intervals require start < end (strict inequality)".to_string(),
                    ))
                }
            }
            _ => Err(Error::OrdPairConversion(
                "Invalid interval format! Expected 'start-end' or 'start-'".to_string(),
            )),
        }
    }
}

impl<T: Clone + Copy + Debug + PartialEq + PartialOrd + FromStr> FromStr for OrdPair<T> {
    type Err = Error;

    /// Parse a string to obtain an Ordered Pair, return Error if cannot be done.
    fn from_str(val_str: &str) -> Result<Self, Self::Err> {
        macro_rules! parse_error {
            () => {
                Err(Error::OrdPairConversion(
                    "Bad ordered pair inputs!".to_string(),
                ))
            };
        }
        let v: Vec<&str> = val_str.split(',').map(str::trim).collect();
        match v.len() {
            2 => {
                let Ok(low) = T::from_str(v.first().expect("v has exactly 2 elements")) else {
                    return parse_error!();
                };
                let Ok(high) = T::from_str(v.get(1).expect("v has exactly 2 elements")) else {
                    return parse_error!();
                };
                OrdPair::<T>::new(low, high)
            }
            _ => parse_error!(),
        }
    }
}

impl<T: Clone + Copy + Debug + PartialEq + PartialOrd> From<OrdPair<T>> for RangeInclusive<T> {
    /// Convert the `OrdPair` into a `RangeInclusive` i.e. (start..=end)
    fn from(value: OrdPair<T>) -> Self {
        RangeInclusive::<T>::new(value.low(), value.high())
    }
}

impl<T: Clone + Copy + Debug + PartialEq + PartialOrd> Contains<T> for OrdPair<T> {
    /// Check if the provided value is within the Range of the `OrdPair`
    fn contains(&self, val: &T) -> bool {
        RangeInclusive::<T>::from(*self).contains(val)
    }
}

impl<T: Clone + Copy + Debug + fmt::Display + PartialEq + PartialOrd> fmt::Display for OrdPair<T> {
    /// converts to string for display i.e. "low, high"
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}, {}", self.low(), self.high())
    }
}

/// Shorthand notation for an ordered pair of `NonZeroU64`.
///
/// # Examples
/// ```
/// use nanalogue_core::{Error, OrdPair};
/// use std::num::NonZeroU64;
/// let v = OrdPair::<NonZeroU64>::try_from((2u64, 3u64))?;
/// assert_eq!(v, OrdPair::new(NonZeroU64::new(2).unwrap(), NonZeroU64::new(3).unwrap()).unwrap());
/// # Ok::<(), nanalogue_core::Error>(())
/// ```
impl TryFrom<(u64, u64)> for OrdPair<NonZeroU64> {
    type Error = Error;

    fn try_from(value: (u64, u64)) -> Result<Self, Self::Error> {
        OrdPair::new(
            NonZeroU64::new(value.0).ok_or(Error::InvalidState(String::from(
                "did you pass positive integers < 2^64?",
            )))?,
            NonZeroU64::new(value.1).ok_or(Error::InvalidState(String::from(
                "did you pass positive integers < 2^64?",
            )))?,
        )
    }
}

/// Shorthand notation for an ordered pair of `F32Bw0and1`.
///
/// # Examples
/// ```
/// use nanalogue_core::{Error, F32Bw0and1, OrdPair};
/// let v = OrdPair::<F32Bw0and1>::try_from((0.2, 0.3))?;
/// assert_eq!(v, OrdPair::new(F32Bw0and1::new(0.2).unwrap(), F32Bw0and1::new(0.3).unwrap()).unwrap());
/// # Ok::<(), nanalogue_core::Error>(())
/// ```
impl TryFrom<(f32, f32)> for OrdPair<F32Bw0and1> {
    type Error = Error;

    fn try_from(value: (f32, f32)) -> Result<Self, Self::Error> {
        OrdPair::new(F32Bw0and1::new(value.0)?, F32Bw0and1::new(value.1)?)
    }
}

/// Shorthand notation for an ordered pair of a generic type.
///
/// # Examples
/// ```
/// use nanalogue_core::{Error, F32Bw0and1, OrdPair};
/// let v = OrdPair::<u8>::try_from((10, 11))?;
/// assert_eq!(v, OrdPair::new(10u8, 11u8).unwrap());
/// # Ok::<(), nanalogue_core::Error>(())
/// ```
impl<T: Clone + Copy + Debug + PartialEq + PartialOrd> TryFrom<(T, T)> for OrdPair<T> {
    type Error = Error;

    fn try_from(value: (T, T)) -> Result<Self, Self::Error> {
        OrdPair::new(value.0, value.1)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Tests default `OrdPair` construction
    #[test]
    fn ord_pair_default_from_u8() {
        assert_eq!(
            OrdPair::<u8>::default(),
            OrdPair::<u8>::new(0u8, 0u8).unwrap()
        );
    }

    /// Tests if our Ordered Pair struct (of f32s) can be correctly obtained from strings
    #[test]
    #[expect(
        clippy::float_cmp,
        reason = "we expect perfect float conversion for the two examples below"
    )]
    fn ord_pair_from_str_f32() {
        assert_eq!(
            OrdPair::<f32>::from_str("1.0,2.0")
                .expect("no failure")
                .low(),
            1.0
        );
        assert_eq!(
            OrdPair::<f32>::from_str("1.0,2.0")
                .expect("no failure")
                .high(),
            2.0
        );
    }

    /// Tests if our Ordered Pair struct (of u8s) can be correctly obtained from strings
    #[test]
    fn ord_pair_from_str_u8() {
        assert_eq!(
            OrdPair::<u8>::from_str("1, 2").expect("no failure").low(),
            1
        );
        assert_eq!(
            OrdPair::<u8>::from_str("1, 2").expect("no failure").high(),
            2
        );
    }

    #[test]
    #[should_panic(expected = "OrdPairConversion")]
    fn ord_pair_from_str_empty_first_value_panics() {
        let _: OrdPair<u8> = OrdPair::<u8>::from_str(",2").unwrap();
    }

    #[test]
    #[should_panic(expected = "WrongOrder")]
    fn ord_pair_from_str_wrong_order_panics() {
        let _: OrdPair<u8> = OrdPair::<u8>::from_str("2,1").unwrap();
    }

    /// Tests if `OrdPair` can be converted into a range
    #[test]
    fn ord_pair_to_range() {
        assert_eq!(
            (3..=5),
            RangeInclusive::from(OrdPair::new(3, 5).expect("no failure"))
        );
    }

    /// Tests `OrdPair::from_interval` method for genomic intervals
    #[expect(
        clippy::shadow_unrelated,
        reason = "repetition is fine; each block is clearly separated"
    )]
    #[test]
    fn ord_pair_from_interval() {
        // Standard interval
        let interval = OrdPair::<u64>::from_interval("1000-2000").expect("should parse");
        assert_eq!(interval.low(), 1000);
        assert_eq!(interval.high(), 2000);

        // Open-ended interval
        let interval = OrdPair::<u64>::from_interval("1000-").expect("should parse");
        assert_eq!(interval.low(), 1000);
        assert_eq!(interval.high(), u64::MAX);
    }

    #[test]
    #[should_panic(expected = "OrdPairConversion")]
    fn ord_pair_from_interval_equal_start_end_panics() {
        let _: OrdPair<u64> = OrdPair::<u64>::from_interval("1000-1000").unwrap();
    }

    #[test]
    #[should_panic(expected = "OrdPairConversion")]
    fn ord_pair_from_interval_start_greater_than_end_panics() {
        let _: OrdPair<u64> = OrdPair::<u64>::from_interval("2000-1000").unwrap();
    }

    #[test]
    #[should_panic(expected = "OrdPairConversion")]
    fn ord_pair_from_interval_no_dash_panics() {
        let _: OrdPair<u64> = OrdPair::<u64>::from_interval("1000").unwrap();
    }

    #[test]
    #[should_panic(expected = "OrdPairConversion")]
    fn ord_pair_from_interval_too_many_dashes_panics() {
        let _: OrdPair<u64> = OrdPair::<u64>::from_interval("1000-2000-3000").unwrap();
    }

    #[test]
    #[should_panic(expected = "OrdPairConversion")]
    fn ord_pair_from_interval_invalid_start_panics() {
        let _: OrdPair<u64> = OrdPair::<u64>::from_interval("abc-2000").unwrap();
    }

    #[test]
    #[should_panic(expected = "OrdPairConversion")]
    fn ord_pair_from_interval_invalid_end_panics() {
        let _: OrdPair<u64> = OrdPair::<u64>::from_interval("1000-xyz").unwrap();
    }

    #[test]
    #[should_panic(expected = "OrdPairConversion")]
    fn ord_pair_from_interval_empty_string_panics() {
        let _: OrdPair<u64> = OrdPair::<u64>::from_interval("").unwrap();
    }

    #[test]
    #[should_panic(expected = "OrdPairConversion")]
    fn ord_pair_from_interval_just_dash_panics() {
        let _: OrdPair<u64> = OrdPair::<u64>::from_interval("-").unwrap();
    }

    #[test]
    #[should_panic(expected = "OrdPairConversion")]
    fn ord_pair_from_interval_negative_numbers_panics() {
        let _: OrdPair<u64> = OrdPair::<u64>::from_interval("-100-200").unwrap();
    }

    #[test]
    fn ord_pair_contains() {
        let pair = OrdPair::new(10, 20).expect("should create");
        assert!(pair.contains(&15));
        assert!(pair.contains(&10)); // inclusive lower bound
        assert!(pair.contains(&20)); // inclusive upper bound
        assert!(!pair.contains(&5));
        assert!(!pair.contains(&25));
    }

    #[test]
    fn ord_pair_display() {
        let pair = OrdPair::new(10, 20).expect("should create");
        assert_eq!(format!("{pair}"), "10, 20");

        let float_pair = OrdPair::new(1.5, 2.5).expect("should create");
        assert_eq!(format!("{float_pair}"), "1.5, 2.5");
    }

    #[test]
    #[should_panic(expected = "OrdPairConversion")]
    fn ord_pair_from_str_empty_string_panics() {
        let _: OrdPair<i32> = OrdPair::<i32>::from_str("").unwrap();
    }

    #[test]
    #[should_panic(expected = "OrdPairConversion")]
    fn ord_pair_from_str_single_value_panics() {
        let _: OrdPair<i32> = OrdPair::<i32>::from_str("1").unwrap();
    }

    #[test]
    #[should_panic(expected = "OrdPairConversion")]
    fn ord_pair_from_str_too_many_values_panics() {
        let _: OrdPair<i32> = OrdPair::<i32>::from_str("1,2,3").unwrap();
    }

    #[test]
    #[should_panic(expected = "OrdPairConversion")]
    fn ord_pair_from_str_non_numeric_panics() {
        let _: OrdPair<i32> = OrdPair::<i32>::from_str("abc,def").unwrap();
    }

    /// Tests `update_low` method successfully updates the low value
    #[test]
    fn ord_pair_update_low_success() {
        let mut x = OrdPair::<u8>::new(10, 11).expect("no failure");
        x.update_low(9).unwrap();
        assert_eq!(x.low(), 9);
        assert_eq!(x.high(), 11);
    }

    /// Tests `update_low` method panics when violating the low <= high invariant
    #[test]
    #[should_panic(expected = "WrongOrder")]
    fn ord_pair_update_low_violates_order_panics() {
        let mut x = OrdPair::<u8>::new(10, 11).expect("no failure");
        x.update_low(12).unwrap();
    }

    /// Tests `update_high` method successfully updates the high value
    #[test]
    fn ord_pair_update_high_success() {
        let mut x = OrdPair::<u8>::new(10, 11).expect("no failure");
        x.update_high(20).unwrap();
        assert_eq!(x.low(), 10);
        assert_eq!(x.high(), 20);
    }

    /// Tests `update_high` method panics when violating the low <= high invariant
    #[test]
    #[should_panic(expected = "WrongOrder")]
    fn ord_pair_update_high_violates_order_panics() {
        let mut x = OrdPair::<u8>::new(10, 11).expect("no failure");
        x.update_high(9).unwrap();
    }
}