omics-coordinate 0.4.0

Foundational representations of coordinates in the Rust omics ecosystem
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
//! Coordinates.

use omics_core::VARIANT_SEPARATOR;
use thiserror::Error;

use crate::Contig;
use crate::Position;
use crate::Strand;
use crate::System;
use crate::contig;
use crate::position;
use crate::position::Number;
use crate::strand;

pub mod base;
pub mod interbase;

////////////////////////////////////////////////////////////////////////////////////////
// Errors
////////////////////////////////////////////////////////////////////////////////////////

/// A parsing error related to a coordinate.
#[derive(Error, Debug, PartialEq, Eq)]
pub enum ParseError {
    /// An invalid format was encountered.
    ///
    /// This generally occurs when an incorrect number of colons (`:`) is used.
    #[error("invalid coordinate format: {value}")]
    Format {
        /// The value that was passed.
        value: String,
    },
}

/// A [`Result`](std::result::Result) with a [`ParseError`].
pub type ParseResult<T> = std::result::Result<T, ParseError>;

/// An error related to a coordinate.
#[derive(Error, Debug, PartialEq, Eq)]
pub enum Error {
    /// A contig error.
    #[error("contig error: {0}")]
    Contig(#[from] contig::Error),

    /// A strand error.
    #[error("strand error: {0}")]
    Strand(#[from] strand::Error),

    /// A parse error.
    #[error("parse error: {0}")]
    Parse(#[from] ParseError),

    /// A position error.
    #[error("position error: {0}")]
    Position(#[from] position::Error),
}

/// A [`Result`](std::result::Result) with an [`Error`](enum@Error).
pub type Result<T> = std::result::Result<T, Error>;

////////////////////////////////////////////////////////////////////////////////////////
// The `Coordinate` trait
////////////////////////////////////////////////////////////////////////////////////////

/// Traits related to a coordinate.
pub mod r#trait {
    use super::*;

    /// Requirements to be a coordinate.
    pub trait Coordinate<S: System>:
        std::fmt::Display
        + std::fmt::Debug
        + PartialEq
        + Eq
        + PartialOrd
        + Ord
        + std::str::FromStr<Err = Error>
    where
        Self: Sized,
    {
        /// Attempts to create a new coordinate.
        fn try_new(
            contig: impl TryInto<Contig, Error = contig::Error>,
            strand: impl TryInto<Strand, Error = strand::Error>,
            position: Number,
        ) -> Result<Self>;
    }
}

////////////////////////////////////////////////////////////////////////////////////////
// Coordinate
////////////////////////////////////////////////////////////////////////////////////////

/// A coordinate.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Coordinate<S: System> {
    /// The coordinate system.
    system: S,

    /// The contig.
    contig: Contig,

    /// The strand.
    strand: Strand,

    /// The position.
    position: Position<S>,
}

impl<S: System> Coordinate<S>
where
    Position<S>: position::r#trait::Position<S>,
{
    /// Creates a new coordinate;
    ///
    /// # Examples
    ///
    /// ```
    /// use omics_coordinate::Contig;
    /// use omics_coordinate::Coordinate;
    /// use omics_coordinate::Strand;
    /// use omics_coordinate::position::interbase::Position;
    /// use omics_coordinate::system::Interbase;
    ///
    /// let contig = Contig::new_unchecked("chr1");
    /// let position = Position::new(0);
    /// let strand = Strand::Positive;
    ///
    /// let coordinate = Coordinate::new(contig, strand, position);
    /// ```
    pub fn new(
        contig: impl Into<Contig>,
        strand: impl Into<Strand>,
        position: impl Into<Position<S>>,
    ) -> Self {
        let contig = contig.into();
        let strand = strand.into();
        let position = position.into();

        Self {
            system: Default::default(),
            contig,
            strand,
            position,
        }
    }

    /// Attempts to create a new coordinate.
    pub fn try_new(
        contig: impl TryInto<Contig, Error = contig::Error>,
        strand: impl TryInto<Strand, Error = strand::Error>,
        position: Number,
    ) -> Result<Self>
    where
        Self: r#trait::Coordinate<S>,
    {
        <Self as r#trait::Coordinate<S>>::try_new(contig, strand, position)
    }

    /// Gets the contig for this coordinate by reference.
    ///
    /// # Examples
    ///
    /// ```
    /// use omics_coordinate::Coordinate;
    /// use omics_coordinate::system::Interbase;
    ///
    /// let coordinate = "seq0:+:1".parse::<Coordinate<Interbase>>()?;
    /// assert_eq!(coordinate.contig().as_str(), "seq0");
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn contig(&self) -> &Contig {
        &self.contig
    }

    /// Consumes `self` and returns the inner contig from this
    /// coordinate.
    ///
    /// # Examples
    ///
    /// ```
    /// use omics_coordinate::Coordinate;
    /// use omics_coordinate::system::Interbase;
    ///
    /// let coordinate = "seq0:+:1".parse::<Coordinate<Interbase>>()?;
    /// assert_eq!(coordinate.into_contig().to_string(), String::from("seq0"));
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn into_contig(self) -> Contig {
        self.contig
    }

    /// Gets the strand for this coordinate by reference.
    ///
    /// # Examples
    ///
    /// ```
    /// use omics_coordinate::Coordinate;
    /// use omics_coordinate::Strand;
    /// use omics_coordinate::system::Interbase;
    ///
    /// let coordinate = "seq0:+:1".parse::<Coordinate<Interbase>>()?;
    /// assert_eq!(coordinate.strand(), Strand::Positive);
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn strand(&self) -> Strand {
        self.strand
    }

    /// Gets the position for this coordinate by reference.
    ///
    /// # Examples
    ///
    /// ```
    /// use omics_coordinate::Coordinate;
    /// use omics_coordinate::Position;
    /// use omics_coordinate::system::Interbase;
    ///
    /// let coordinate = "seq0:+:1".parse::<Coordinate<Interbase>>()?;
    /// assert_eq!(coordinate.position().get(), 1);
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn position(&self) -> &Position<S> {
        &self.position
    }

    /// Consumes `self` and returns the inner position from this
    /// coordinate.
    ///
    /// # Examples
    ///
    /// ```
    /// use omics_coordinate::Coordinate;
    /// use omics_coordinate::Strand;
    /// use omics_coordinate::system::Interbase;
    ///
    /// let coordinate = "seq0:+:1".parse::<Coordinate<Interbase>>()?;
    /// assert_eq!(coordinate.into_position().get(), 1);
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn into_position(self) -> Position<S> {
        self.position
    }

    /// Consumes `self` to return the parts that comprise this coordinate.
    ///
    /// # Examples
    ///
    /// ```
    /// use omics_coordinate::Contig;
    /// use omics_coordinate::Coordinate;
    /// use omics_coordinate::Strand;
    /// use omics_coordinate::system::Interbase;
    ///
    /// let coordinate = "seq0:+:1".parse::<Coordinate<Interbase>>()?;
    ///
    /// let (contig, strand, position) = coordinate.into_parts();
    /// assert_eq!(contig.to_string(), String::from("seq0"));
    /// assert_eq!(strand, Strand::Positive);
    /// assert_eq!(position.get(), 1);
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn into_parts(self) -> (Contig, Strand, Position<S>) {
        (self.contig, self.strand, self.position)
    }

    /// Attempts to move the position forward by `magnitude` in place.
    ///
    /// This method is dependent on the strand of the coordinate:
    ///
    /// - a coordinate on the [`Strand::Positive`] moves positively, and
    /// - a coordinate on the [`Strand::Negative`] moves negatively.
    ///
    /// Returns `true` if the move succeeded, `false` if it would overflow.
    ///
    /// # Examples
    ///
    /// ```
    /// use omics_coordinate::Coordinate;
    /// use omics_coordinate::Strand;
    /// use omics_coordinate::position::Number;
    /// use omics_coordinate::system::Base;
    /// use omics_coordinate::system::Interbase;
    ///
    /// // Interbase.
    ///
    /// let mut coordinate = "seq0:+:0".parse::<Coordinate<Interbase>>()?;
    /// assert!(coordinate.move_forward(10));
    /// assert_eq!(coordinate.position().get(), 10);
    ///
    /// let mut coordinate = "seq0:+:0".parse::<Coordinate<Interbase>>()?;
    /// assert!(coordinate.move_forward(Number::MAX));
    /// assert_eq!(coordinate.position().get(), Number::MAX);
    /// assert!(!coordinate.move_forward(1));
    ///
    /// // Base.
    ///
    /// let mut coordinate = "seq0:+:1".parse::<Coordinate<Base>>()?;
    /// assert!(coordinate.move_forward(10));
    /// assert_eq!(coordinate.position().get(), 11);
    ///
    /// let mut coordinate = "seq0:+:1".parse::<Coordinate<Base>>()?;
    /// assert!(coordinate.move_forward(Number::MAX - 1));
    /// assert_eq!(coordinate.position().get(), Number::MAX);
    /// assert!(!coordinate.move_forward(1));
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn move_forward(&mut self, magnitude: Number) -> bool {
        if magnitude == 0 {
            return true;
        }

        let result = match self.strand {
            Strand::Positive => self.position.checked_add(magnitude),
            Strand::Negative => self.position.checked_sub(magnitude),
        };

        match result {
            Some(position) => {
                self.position = position;
                true
            }
            None => false,
        }
    }

    /// Consumes `self` and attempts to move the position forward by
    /// `magnitude`.
    ///
    /// This method is dependent on the strand of the coordinate:
    ///
    /// - a coordinate on the [`Strand::Positive`] moves positively, and
    /// - a coordinate on the [`Strand::Negative`] moves negatively.
    ///
    /// # Examples
    ///
    /// ```
    /// use omics_coordinate::Coordinate;
    /// use omics_coordinate::Strand;
    /// use omics_coordinate::position::Number;
    /// use omics_coordinate::system::Base;
    /// use omics_coordinate::system::Interbase;
    ///
    /// // Interbase.
    ///
    /// let coordinate = "seq0:+:0".parse::<Coordinate<Interbase>>()?;
    /// let moved = coordinate
    ///     .into_move_forward(10)
    ///     .expect("coordinate to move");
    /// assert_eq!(moved.position().get(), 10);
    ///
    /// let coordinate = "seq0:+:0".parse::<Coordinate<Interbase>>()?;
    /// let moved = coordinate.into_move_forward(Number::MAX).unwrap();
    /// assert!(moved.into_move_forward(1).is_none());
    ///
    /// // Base.
    ///
    /// let coordinate = "seq0:+:1".parse::<Coordinate<Base>>()?;
    /// let moved = coordinate
    ///     .into_move_forward(10)
    ///     .expect("coordinate to move");
    /// assert_eq!(moved.position().get(), 11);
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[must_use = "this method returns a new coordinate"]
    pub fn into_move_forward(self, magnitude: Number) -> Option<Coordinate<S>> {
        if magnitude == 0 {
            return Some(self);
        }

        match self.strand {
            Strand::Positive => self.position.checked_add(magnitude),
            Strand::Negative => self.position.checked_sub(magnitude),
        }
        .map(|position| Self::new(self.contig, self.strand, position))
    }

    /// Attempts to move the position backward by `magnitude` in place.
    ///
    /// This method is dependent on the strand of the coordinate:
    ///
    /// - a coordinate on the [`Strand::Positive`] moves negatively, and
    /// - a coordinate on the [`Strand::Negative`] moves positively.
    ///
    /// Returns `true` if the move succeeded, `false` if it would overflow.
    ///
    /// # Examples
    ///
    /// ```
    /// use omics_coordinate::Coordinate;
    /// use omics_coordinate::Strand;
    /// use omics_coordinate::position::Number;
    /// use omics_coordinate::system::Base;
    /// use omics_coordinate::system::Interbase;
    ///
    /// let value = format!("seq0:+:{}", Number::MAX);
    ///
    /// // Interbase.
    ///
    /// let mut coordinate = value.clone().parse::<Coordinate<Interbase>>()?;
    /// assert!(coordinate.move_backward(10));
    /// assert_eq!(coordinate.position().get(), Number::MAX - 10);
    ///
    /// let mut coordinate = "seq0:+:0".parse::<Coordinate<Interbase>>()?;
    /// assert!(!coordinate.move_backward(1));
    ///
    /// // Base.
    ///
    /// let mut coordinate = value.parse::<Coordinate<Base>>()?;
    /// assert!(coordinate.move_backward(10));
    /// assert_eq!(coordinate.position().get(), Number::MAX - 10);
    ///
    /// let mut coordinate = "seq0:+:1".parse::<Coordinate<Base>>()?;
    /// assert!(!coordinate.move_backward(1));
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn move_backward(&mut self, magnitude: Number) -> bool {
        if magnitude == 0 {
            return true;
        }

        let result = match self.strand {
            Strand::Positive => self.position.checked_sub(magnitude),
            Strand::Negative => self.position.checked_add(magnitude),
        };

        match result {
            Some(position) => {
                self.position = position;
                true
            }
            None => false,
        }
    }

    /// Consumes `self` and attempts to move the position backwards by
    /// `magnitude`.
    ///
    /// This method is dependent on the strand of the coordinate:
    ///
    /// - a coordinate on the [`Strand::Positive`] moves negatively, and
    /// - a coordinate on the [`Strand::Negative`] moves positively.
    ///
    /// # Examples
    ///
    /// ```
    /// use omics_coordinate::Coordinate;
    /// use omics_coordinate::Strand;
    /// use omics_coordinate::position::Number;
    /// use omics_coordinate::system::Base;
    /// use omics_coordinate::system::Interbase;
    ///
    /// let value = format!("seq0:+:{}", Number::MAX);
    ///
    /// // Interbase.
    ///
    /// let coordinate = value.clone().parse::<Coordinate<Interbase>>()?;
    /// let moved = coordinate
    ///     .into_move_backward(10)
    ///     .expect("coordinate to move");
    /// assert_eq!(moved.position().get(), Number::MAX - 10);
    ///
    /// let coordinate = "seq0:+:0".parse::<Coordinate<Interbase>>()?;
    /// assert!(coordinate.into_move_backward(1).is_none());
    ///
    /// // Base.
    ///
    /// let coordinate = value.parse::<Coordinate<Base>>()?;
    /// let moved = coordinate
    ///     .into_move_backward(10)
    ///     .expect("coordinate to move");
    /// assert_eq!(moved.position().get(), Number::MAX - 10);
    ///
    /// let coordinate = "seq0:+:1".parse::<Coordinate<Base>>()?;
    /// assert!(coordinate.into_move_backward(1).is_none());
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[must_use = "this method returns a new coordinate"]
    pub fn into_move_backward(self, magnitude: Number) -> Option<Coordinate<S>> {
        if magnitude == 0 {
            return Some(self);
        }

        match self.strand {
            Strand::Positive => self.position.checked_sub(magnitude),
            Strand::Negative => self.position.checked_add(magnitude),
        }
        .map(|position| Self::new(self.contig, self.strand, position))
    }

    /// Swaps the strand of the coordinate.
    ///
    /// # Examples
    ///
    /// ```
    /// use omics_coordinate::Coordinate;
    /// use omics_coordinate::Strand;
    /// use omics_coordinate::system::Base;
    /// use omics_coordinate::system::Interbase;
    ///
    /// //===========//
    /// // Interbase //
    /// //===========//
    ///
    /// let coordinate = Coordinate::<Interbase>::try_new("seq0", "+", 10)?;
    /// let swapped = coordinate.swap_strand();
    /// assert_eq!(swapped.contig().as_str(), "seq0");
    /// assert_eq!(swapped.strand(), Strand::Negative);
    /// assert_eq!(swapped.position().get(), 10);
    ///
    /// //======//
    /// // Base //
    /// //======//
    ///
    /// let coordinate = Coordinate::<Base>::try_new("seq0", "-", 10)?;
    /// let swapped = coordinate.swap_strand();
    /// assert_eq!(swapped.contig().as_str(), "seq0");
    /// assert_eq!(swapped.strand(), Strand::Positive);
    /// assert_eq!(swapped.position().get(), 10);
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[must_use = "this method returns a new coordinate"]
    pub fn swap_strand(self) -> Coordinate<S> {
        let (contig, strand, position) = self.into_parts();
        Coordinate::new(contig, strand.complement(), position)
    }
}

////////////////////////////////////////////////////////////////////////////////////////
// Trait implementations
////////////////////////////////////////////////////////////////////////////////////////

impl<S: System> std::fmt::Display for Coordinate<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if !f.alternate() {
            write!(f, "{}:{}:{}", self.contig, self.strand, self.position)
        } else {
            write!(
                f,
                "{}:{}:{} ({})",
                self.contig, self.strand, self.position, self.system
            )
        }
    }
}

impl<S: System> std::str::FromStr for Coordinate<S>
where
    Position<S>: position::r#trait::Position<S>,
{
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        let parts = s.split(VARIANT_SEPARATOR).collect::<Vec<_>>();

        if parts.len() != 3 {
            return Err(Error::Parse(ParseError::Format {
                value: s.to_owned(),
            }));
        }

        let mut parts = parts.iter();

        // SAFETY: we checked that there are three parts above. Given that we
        // haven't pulled anything from the iterator, we can always safely
        // unwrap this.
        let contig = parts.next().unwrap().parse::<Contig>().map_err(|_| {
            Error::Parse(ParseError::Format {
                value: s.to_string(),
            })
        })?;

        // SAFETY: we checked that there are three parts above. Given that we
        // have only pulled one item from the iterator, we can always safely
        // unwrap this.
        let strand = parts
            .next()
            .unwrap()
            .parse::<Strand>()
            .map_err(Error::Strand)?;

        // SAFETY: we checked that there are three parts above. Given that we
        // have only pulled two items from the iterator, we can always safely
        // unwrap this.
        let position = parts
            .next()
            .unwrap()
            .parse::<Position<S>>()
            .map_err(Error::Position)?;

        Ok(Self::new(contig, strand, position))
    }
}