bed_utils/
bed.rs

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
pub mod io;
pub mod map;

mod bed_trait;
pub use bed_trait::*;
mod score;
pub use score::Score;
mod strand;
pub use strand::Strand;

use std::{fmt::{self, Write}, ops::Deref, str::FromStr};
use serde::{Serialize, Deserialize};

const DELIMITER: char = '\t';
const MISSING_ITEM : &str = ".";

/// A minimal BED record with only 3 fields.
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct GenomicRange(String, u64, u64);

impl GenomicRange {
    pub fn new<C>(chrom: C, start: u64, end: u64) -> Self
    where
        C: Into<String>,
    { Self(chrom.into(), start, end) }

    /// Convert the record to a string representation: chr:start-end
    pub fn pretty_show(&self) -> String {
        format!("{}:{}-{}", self.0, self.1, self.2)
    }
}

/// Convert string to GenomicRange. '\t', ':', and '-' are all considered as
/// valid delimiters. So any of the following formats is valid:
/// * chr1\t100\t200
/// * chr1:100-200
impl FromStr for GenomicRange {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut fields = s.split(&['\t', ':', '-']);
        let chrom = parse_chrom(&mut fields)?;
        let start = parse_start(&mut fields)?;
        let end = parse_end(&mut fields)?;
        Ok(GenomicRange::new(chrom, start, end))
    }
}

impl BEDLike for GenomicRange {
    fn chrom(&self) -> &str { &self.0 }
    fn set_chrom(&mut self, chrom: &str) -> &mut Self {
        self.0 = chrom.to_string();
        self
    }
    fn start(&self) -> u64 { self.1 }
    fn set_start(&mut self, start: u64) -> &mut Self {
        self.1 = start;
        self
    }
    fn end(&self) -> u64 { self.2 }
    fn set_end(&mut self, end: u64) -> &mut Self {
        self.2 = end;
        self
    }
    fn name(&self) -> Option<&str> { None }
    fn score(&self) -> Option<Score> { None }
    fn strand(&self) -> Option<Strand> { None }
}

impl fmt::Display for GenomicRange {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{}{}{}{}", self.chrom(), DELIMITER, self.start(),
            DELIMITER, self.end()
        )?;
        Ok(())
    }
}


/// A standard BED record.
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct BED<const N: u8> {
    chrom: String,
    start: u64,
    end: u64,
    pub name: Option<String>,
    pub score: Option<Score>,
    pub strand: Option<Strand>,
    pub optional_fields: OptionalFields,
}

impl<const N: u8> BED<N> {
    pub fn new<C>(chrom: C, start: u64, end: u64, name: Option<String>,
        score: Option<Score>, strand: Option<Strand>, optional_fields: OptionalFields) -> Self
    where
        C: Into<String>,
    { Self { chrom: chrom.into(), start, end, name, score, strand, optional_fields } }
}

impl<const N: u8> BEDLike for BED<N> {
    fn chrom(&self) -> &str { &self.chrom }
    fn set_chrom(&mut self, chrom: &str) -> &mut Self {
        self.chrom = chrom.to_string();
        self
    }
    fn start(&self) -> u64 { self.start }
    fn set_start(&mut self, start: u64) -> &mut Self {
        self.start = start;
        self
    }
    fn end(&self) -> u64 { self.end }
    fn set_end(&mut self, end: u64) -> &mut Self {
        self.end = end;
        self
    }
    fn name(&self) -> Option<&str> { self.name.as_deref() }
    fn score(&self) -> Option<Score> { self.score }
    fn strand(&self) -> Option<Strand> { self.strand }
}

// Display trait
impl<const N: u8> fmt::Display for BED<N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}{}{}{}{}",
            self.chrom(),
            DELIMITER,
            self.start(),
            DELIMITER,
            self.end()
        )?;
        if N > 3 {
            write!(f, "{}{}", DELIMITER, self.name().unwrap_or(MISSING_ITEM))?;
            if N > 4 {
                f.write_char(DELIMITER)?;
                if let Some(score) = self.score() {
                    write!(f, "{}", score)?;
                } else { f.write_str(MISSING_ITEM)?; }

                if N > 5 {
                    f.write_char(DELIMITER)?;
                    if let Some(strand) = self.strand() {
                        write!(f, "{}", strand)?;
                    } else { f.write_str(MISSING_ITEM)?; }
                }
            }
        }
        Ok(())
    }
}

impl<const N: u8> FromStr for BED<N> {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut fields = s.split(DELIMITER);
        let chrom = parse_chrom(&mut fields)?;
        let start = parse_start(&mut fields)?;
        let end = parse_end(&mut fields)?;
        let name = if N > 3 { parse_name(&mut fields)? } else { None };
        let score = if N > 4 { parse_score(&mut fields)? } else { None };
        let strand = if N > 5 { parse_strand(&mut fields)? } else { None };
        Ok(BED::new(chrom, start, end, name, score, strand, OptionalFields::default()))
    }
}

/// Generic BED record optional fields.
#[derive(Serialize, Deserialize, Clone, Debug, Default, Eq, PartialEq)]
pub struct OptionalFields(Vec<String>);

impl Deref for OptionalFields {
    type Target = [String];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl fmt::Display for OptionalFields {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, field) in self.0.iter().enumerate() {
            if i > 0 {
                f.write_char(DELIMITER)?;
            }

            f.write_str(field)?;
        }

        Ok(())
    }
}

impl From<Vec<String>> for OptionalFields {
    fn from(fields: Vec<String>) -> Self {
        Self(fields)
    }
}


/// A standard BED record.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct NarrowPeak {
    pub chrom: String,
    pub start: u64,
    pub end: u64,
    pub name: Option<String>,
    pub score: Option<Score>,
    pub strand: Option<Strand>,
    pub signal_value: f64,
    pub p_value: f64, 
    pub q_value: f64, 
    pub peak: u64, 
}

impl BEDLike for NarrowPeak {
    fn chrom(&self) -> &str { &self.chrom }
    fn set_chrom(&mut self, chrom: &str) -> &mut Self {
        self.chrom = chrom.to_string();
        self
    }
    fn start(&self) -> u64 { self.start }
    fn set_start(&mut self, start: u64) -> &mut Self {
        self.start = start;
        self
    }
    fn end(&self) -> u64 { self.end }
    fn set_end(&mut self, end: u64) -> &mut Self {
        self.end = end;
        self
    }
    fn name(&self) -> Option<&str> { self.name.as_deref() }
    fn score(&self) -> Option<Score> { self.score }
    fn strand(&self) -> Option<Strand> { self.strand }
}

impl fmt::Display for NarrowPeak {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}{}{}{}{}{}{}",
            self.chrom(),
            DELIMITER, self.start(),
            DELIMITER, self.end(),
            DELIMITER, self.name().unwrap_or(MISSING_ITEM),
        )?;

        f.write_char(DELIMITER)?;
        if let Some(x) = self.score() {
            write!(f, "{}", x)?;
        } else {
            f.write_str(MISSING_ITEM)?;
        }
        f.write_char(DELIMITER)?;
        if let Some(x) = self.strand() {
            write!(f, "{}", x)?;
        } else {
            f.write_str(MISSING_ITEM)?;
        }
        write!(
            f,
            "{}{}{}{}{}{}{}{}",
            DELIMITER, self.signal_value,
            DELIMITER, self.p_value,
            DELIMITER, self.q_value,
            DELIMITER, self.peak,
        )?;

        Ok(())
    }
}

impl FromStr for NarrowPeak {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut fields = s.split(DELIMITER);
        Ok(Self {
            chrom: parse_chrom(&mut fields)?.to_string(),
            start: parse_start(&mut fields)?,
            end: parse_end(&mut fields)?,
            name: parse_name(&mut fields)?,
            score: parse_score(&mut fields)?,
            strand: parse_strand(&mut fields)?,
            signal_value: fields.next().unwrap().parse().unwrap(),
            p_value: fields.next().unwrap().parse().unwrap(),
            q_value: fields.next().unwrap().parse().unwrap(),
            peak: fields.next().unwrap().parse().unwrap(),
        })
    }
}

/// The bedGraph format allows display of continuous-valued data in track format.
/// This display type is useful for probability scores and transcriptome data. 
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct BedGraph<V> {
    pub chrom: String,
    pub start: u64,
    pub end: u64,
    pub value: V,
}

impl<V> BedGraph<V> {
    pub fn new<C>(chrom: C, start: u64, end: u64, value: V) -> Self
    where
        C: Into<String>,
    { Self { chrom: chrom.into(), start, end, value } }

    pub fn from_bed<B: BEDLike>(bed: &B, value: V) -> Self {
        Self::new(bed.chrom(), bed.start(), bed.end(), value)
    }
}

impl<V> BEDLike for BedGraph<V> {
    fn chrom(&self) -> &str { &self.chrom }
    fn set_chrom(&mut self, chrom: &str) -> &mut Self {
        self.chrom = chrom.to_string();
        self
    }
    fn start(&self) -> u64 { self.start }
    fn set_start(&mut self, start: u64) -> &mut Self {
        self.start = start;
        self
    }
    fn end(&self) -> u64 { self.end }
    fn set_end(&mut self, end: u64) -> &mut Self {
        self.end = end;
        self
    }
    fn name(&self) -> Option<&str> { None }
    fn score(&self) -> Option<Score> { None }
    fn strand(&self) -> Option<Strand> { None }
}

impl<V> fmt::Display for BedGraph<V>
where
    V: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
    {
        write!(
            f,
            "{}{}{}{}{}{}{}",
            self.chrom(),
            DELIMITER, self.start(),
            DELIMITER, self.end(),
            DELIMITER, self.value,
        )
    }
}

impl<V> FromStr for BedGraph<V>
where
    V: FromStr,
    <V as FromStr>::Err: std::fmt::Debug,
{
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err>
    {
        let mut fields = s.split(DELIMITER);
        Ok(Self {
            chrom: parse_chrom(&mut fields)?.to_string(),
            start: parse_start(&mut fields)?,
            end: parse_end(&mut fields)?,
            value: fields.next().unwrap().parse().unwrap(),
        })
    }
}

fn parse_chrom<'a, I>(fields: &mut I) -> Result<&'a str, ParseError>
where
    I: Iterator<Item = &'a str>,
{
    fields
        .next()
        .ok_or(ParseError::MissingReferenceSequenceName)
}

fn parse_start<'a, I>(fields: &mut I) -> Result<u64, ParseError>
where
    I: Iterator<Item = &'a str>,
{
    fields
        .next()
        .ok_or(ParseError::MissingStartPosition)
        .and_then(|s| lexical::parse(s).map_err(ParseError::InvalidStartPosition))
}

fn parse_end<'a, I>(fields: &mut I) -> Result<u64, ParseError>
where
    I: Iterator<Item = &'a str>,
{
    fields
        .next()
        .ok_or(ParseError::MissingEndPosition)
        .and_then(|s| lexical::parse(s).map_err(ParseError::InvalidEndPosition))
}

fn parse_name<'a, I>(fields: &mut I) -> Result<Option<String>, ParseError>
where
    I: Iterator<Item = &'a str>,
{
    fields
        .next()
        .ok_or(ParseError::MissingName)
        .map(|s| match s {
            MISSING_ITEM => None,
            _ => Some(s.into()),
        })
}

fn parse_score<'a, I>(fields: &mut I) -> Result<Option<Score>, ParseError>
where
    I: Iterator<Item = &'a str>,
{
    fields
        .next()
        .ok_or(ParseError::MissingScore)
        .and_then(|s| match s {
            MISSING_ITEM => Ok(None),
            _ => s.parse().map(Some).map_err(ParseError::InvalidScore),
        })
}

fn parse_strand<'a, I>(fields: &mut I) -> Result<Option<Strand>, ParseError>
where
    I: Iterator<Item = &'a str>,
{
    fields
        .next()
        .ok_or(ParseError::MissingStrand)
        .and_then(|s| match s {
            MISSING_ITEM => Ok(None),
            _ => s.parse().map(Some).map_err(ParseError::InvalidStrand),
        })
}

/// An error returned when a raw BED record fails to parse.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ParseError {
    /// The reference sequence name is missing.
    MissingReferenceSequenceName,
    /// The start position is missing.
    MissingStartPosition,
    /// The start position is invalid.
    InvalidStartPosition(lexical::Error),
    /// The end position is missing.
    MissingEndPosition,
    /// The end position is invalid.
    InvalidEndPosition(lexical::Error),
    /// The name is missing.
    MissingName,
    /// The score is missing.
    MissingScore,
    /// The score is invalid.
    InvalidScore(score::ParseError),
    /// The strand is missing.
    MissingStrand,
    /// The strand is invalid.
    InvalidStrand(strand::ParseError),
}

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

    #[test]
    fn test_fmt() {
        let fields = OptionalFields::default();
        assert_eq!(fields.to_string(), "");

        let fields = OptionalFields::from(vec![String::from("n")]);
        assert_eq!(fields.to_string(), "n");

        let fields = OptionalFields::from(vec![String::from("n"), String::from("d")]);
        assert_eq!(fields.to_string(), "n\td");

        let genomic_range = GenomicRange::new("chr1", 100, 200);
        assert_eq!(genomic_range, GenomicRange::from_str("chr1\t100\t200").unwrap());
        assert_eq!(genomic_range, GenomicRange::from_str("chr1-100-200").unwrap());
        assert_eq!(genomic_range, GenomicRange::from_str("chr1:100-200").unwrap());
        assert_eq!(genomic_range, GenomicRange::from_str("chr1:100:200").unwrap());
        assert_eq!(genomic_range, GenomicRange::from_str(&genomic_range.pretty_show()).unwrap());
    }
}