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
//! SAM header read group and fields.

pub mod builder;
pub mod platform;
pub mod tag;

pub use self::{builder::Builder, platform::Platform, tag::Tag};

use std::{collections::HashMap, convert::TryFrom, error, fmt, num};

use super::{
    record::{self, value::Fields},
    Record,
};

/// A SAM header read group.
///
/// A read group typically defines the set of reads that came from the same run on a sequencing
/// instrument. The read group ID is guaranteed to be set.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ReadGroup {
    id: String,
    barcode: Option<String>,
    sequencing_center: Option<String>,
    description: Option<String>,
    produced_at: Option<String>,
    flow_order: Option<String>,
    key_sequence: Option<String>,
    library: Option<String>,
    program: Option<String>,
    predicted_median_insert_size: Option<i32>,
    platform: Option<Platform>,
    platform_model: Option<String>,
    platform_unit: Option<String>,
    sample: Option<String>,
    fields: HashMap<Tag, String>,
}

impl ReadGroup {
    /// Creates a SAM header read group builder.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_sam::header::ReadGroup;
    /// let builder = ReadGroup::builder();
    /// ```
    pub fn builder() -> Builder {
        Builder::default()
    }

    /// Creates a read group with an ID.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_sam::header::ReadGroup;
    /// let read_group = ReadGroup::new("rg0");
    /// assert_eq!(read_group.id(), "rg0");
    /// ```
    pub fn new<I>(id: I) -> Self
    where
        I: Into<String>,
    {
        Self {
            id: id.into(),
            barcode: None,
            sequencing_center: None,
            description: None,
            produced_at: None,
            flow_order: None,
            key_sequence: None,
            library: None,
            program: None,
            predicted_median_insert_size: None,
            platform: None,
            platform_model: None,
            platform_unit: None,
            sample: None,
            fields: HashMap::new(),
        }
    }

    /// Returns the read group ID.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_sam::header::ReadGroup;
    /// let read_group = ReadGroup::new("rg0");
    /// assert_eq!(read_group.id(), "rg0");
    /// ```
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Returns a mutable reference to the read group ID.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_sam::header::ReadGroup;
    ///
    /// let mut read_group = ReadGroup::new("rg0");
    /// assert_eq!(read_group.id(), "rg0");
    ///
    /// *read_group.id_mut() = String::from("rg1");
    /// assert_eq!(read_group.id(), "rg1");
    /// ```
    pub fn id_mut(&mut self) -> &mut String {
        &mut self.id
    }

    /// Returns the barcode sequence.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_sam::header::ReadGroup;
    /// let read_group = ReadGroup::new("rg0");
    /// assert!(read_group.barcode().is_none());
    /// ```
    pub fn barcode(&self) -> Option<&str> {
        self.barcode.as_deref()
    }

    /// Returns the sequencing center.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_sam::header::ReadGroup;
    /// let read_group = ReadGroup::new("rg0");
    /// assert!(read_group.sequencing_center().is_none());
    /// ```
    pub fn sequencing_center(&self) -> Option<&str> {
        self.sequencing_center.as_deref()
    }

    /// Returns the description.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_sam::header::ReadGroup;
    /// let read_group = ReadGroup::new("rg0");
    /// assert!(read_group.description().is_none());
    /// ```
    pub fn description(&self) -> Option<&str> {
        self.description.as_deref()
    }

    /// Returns the datatime of run.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_sam::header::ReadGroup;
    /// let read_group = ReadGroup::new("rg0");
    /// assert!(read_group.produced_at().is_none());
    /// ```
    pub fn produced_at(&self) -> Option<&str> {
        self.produced_at.as_deref()
    }

    /// Returns the flow order.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_sam::header::ReadGroup;
    /// let read_group = ReadGroup::new("rg0");
    /// assert!(read_group.flow_order().is_none());
    /// ```
    pub fn flow_order(&self) -> Option<&str> {
        self.flow_order.as_deref()
    }

    /// Returns the key sequence.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_sam::header::ReadGroup;
    /// let read_group = ReadGroup::new("rg0");
    /// assert!(read_group.key_sequence().is_none());
    /// ```
    pub fn key_sequence(&self) -> Option<&str> {
        self.key_sequence.as_deref()
    }

    /// Returns the library.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_sam::header::ReadGroup;
    /// let read_group = ReadGroup::new("rg0");
    /// assert!(read_group.library().is_none());
    /// ```
    pub fn library(&self) -> Option<&str> {
        self.library.as_deref()
    }

    /// Returns the programs used.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_sam::header::ReadGroup;
    /// let read_group = ReadGroup::new("rg0");
    /// assert!(read_group.program().is_none());
    /// ```
    pub fn program(&self) -> Option<&str> {
        self.program.as_deref()
    }

    /// Returns the predicted median insert size.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_sam::header::ReadGroup;
    /// let read_group = ReadGroup::new("rg0");
    /// assert!(read_group.predicted_median_insert_size().is_none());
    /// ```
    pub fn predicted_median_insert_size(&self) -> Option<i32> {
        self.predicted_median_insert_size
    }

    /// Returns the platform used.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_sam::header::ReadGroup;
    /// let read_group = ReadGroup::new("rg0");
    /// assert!(read_group.platform().is_none());
    /// ```
    pub fn platform(&self) -> Option<Platform> {
        self.platform
    }

    /// Returns the platform model.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_sam::header::ReadGroup;
    /// let read_group = ReadGroup::new("rg0");
    /// assert!(read_group.platform_model().is_none());
    /// ```
    pub fn platform_model(&self) -> Option<&str> {
        self.platform_model.as_deref()
    }

    /// Returns the platform unit.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_sam::header::ReadGroup;
    /// let read_group = ReadGroup::new("rg0");
    /// assert!(read_group.platform_unit().is_none());
    /// ```
    pub fn platform_unit(&self) -> Option<&str> {
        self.platform_unit.as_deref()
    }

    /// Returns the sample.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_sam::header::ReadGroup;
    /// let read_group = ReadGroup::new("rg0");
    /// assert!(read_group.sample().is_none());
    /// ```
    pub fn sample(&self) -> Option<&str> {
        self.sample.as_deref()
    }

    /// Returns the raw fields of the read group.
    ///
    /// This includes any field that is not specially handled by the structure itself. For example,
    /// this will not include the ID field, as it is parsed and available as [`Self::id`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use noodles_sam::header::read_group::builder;
    /// use noodles_sam::header::{read_group::Tag, ReadGroup};
    ///
    /// let read_group = ReadGroup::builder()
    ///     .set_id("rg0")
    ///     .insert(Tag::Other(String::from("zn")), String::from("noodles"))
    ///     .build()?;
    ///
    /// let fields = read_group.fields();
    /// assert_eq!(fields.len(), 1);
    /// assert_eq!(
    ///     fields.get(&Tag::Other(String::from("zn"))),
    ///     Some(&String::from("noodles"))
    /// );
    ///
    /// assert_eq!(fields.get(&Tag::Id), None);
    /// assert_eq!(read_group.id(), "rg0");
    /// # Ok::<(), builder::BuildError>(())
    /// ```
    pub fn fields(&self) -> &HashMap<Tag, String> {
        &self.fields
    }
}

impl fmt::Display for ReadGroup {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", record::Kind::ReadGroup)?;
        write!(f, "\t{}:{}", Tag::Id, self.id)?;

        if let Some(barcode) = self.barcode() {
            write!(f, "\t{}:{}", Tag::Barcode, barcode)?;
        }

        if let Some(sequencing_center) = self.sequencing_center() {
            write!(f, "\t{}:{}", Tag::SequencingCenter, sequencing_center)?;
        }

        if let Some(description) = self.description() {
            write!(f, "\t{}:{}", Tag::Description, description)?;
        }

        if let Some(produced_at) = self.produced_at() {
            write!(f, "\t{}:{}", Tag::ProducedAt, produced_at)?;
        }

        if let Some(flow_order) = self.flow_order() {
            write!(f, "\t{}:{}", Tag::FlowOrder, flow_order)?;
        }

        if let Some(key_sequence) = self.key_sequence() {
            write!(f, "\t{}:{}", Tag::KeySequence, key_sequence)?;
        }

        if let Some(library) = self.library() {
            write!(f, "\t{}:{}", Tag::Library, library)?;
        }

        if let Some(program) = self.program() {
            write!(f, "\t{}:{}", Tag::Program, program)?;
        }

        if let Some(predicted_median_insert_size) = self.predicted_median_insert_size() {
            write!(
                f,
                "\t{}:{}",
                Tag::PredictedMedianInsertSize,
                predicted_median_insert_size
            )?;
        }

        if let Some(platform) = self.platform() {
            write!(f, "\t{}:{}", Tag::Platform, platform)?;
        }

        if let Some(platform_model) = self.platform_model() {
            write!(f, "\t{}:{}", Tag::PlatformModel, platform_model)?;
        }

        if let Some(platform_unit) = self.platform_unit() {
            write!(f, "\t{}:{}", Tag::PlatformUnit, platform_unit)?;
        }

        if let Some(sample) = self.sample() {
            write!(f, "\t{}:{}", Tag::Sample, sample)?;
        }

        for (tag, value) in &self.fields {
            write!(f, "\t{}:{}", tag, value)?;
        }

        Ok(())
    }
}

/// An error returned when a raw SAM header read group fails to parse.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum TryFromRecordError {
    /// The record is invalid.
    InvalidRecord,
    /// A required tag is missing.
    MissingRequiredTag(Tag),
    /// A tag is invalid.
    InvalidTag(tag::ParseError),
    /// The predicted median insert size is invalid.
    InvalidPredictedMedianInsertSize(num::ParseIntError),
    /// The platform is invalid.
    InvalidPlatform(platform::ParseError),
}

impl error::Error for TryFromRecordError {}

impl fmt::Display for TryFromRecordError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidRecord => f.write_str("invalid record"),
            Self::MissingRequiredTag(tag) => write!(f, "missing required tag: {:?}", tag),
            Self::InvalidTag(e) => write!(f, "invalid tag: {}", e),
            Self::InvalidPredictedMedianInsertSize(e) => {
                write!(f, "invalid predicted median insert size: {}", e)
            }
            Self::InvalidPlatform(e) => write!(f, "invalid platform: {}", e),
        }
    }
}

impl TryFrom<Record> for ReadGroup {
    type Error = TryFromRecordError;

    fn try_from(record: Record) -> Result<Self, Self::Error> {
        match record.into() {
            (record::Kind::ReadGroup, record::Value::Map(fields)) => parse_map(fields),
            _ => Err(TryFromRecordError::InvalidRecord),
        }
    }
}

fn parse_map(raw_fields: Fields) -> Result<ReadGroup, TryFromRecordError> {
    use builder::BuildError;

    let mut builder = ReadGroup::builder();

    for (raw_tag, value) in raw_fields {
        let tag = raw_tag.parse().map_err(TryFromRecordError::InvalidTag)?;

        builder = match tag {
            Tag::Id => builder.set_id(value),
            Tag::Barcode => builder.set_barcode(value),
            Tag::SequencingCenter => builder.set_sequencing_center(value),
            Tag::Description => builder.set_description(value),
            Tag::ProducedAt => builder.set_produced_at(value),
            Tag::FlowOrder => builder.set_flow_order(value),
            Tag::KeySequence => builder.set_key_sequence(value),
            Tag::Library => builder.set_library(value),
            Tag::Program => builder.set_program(value),
            Tag::PredictedMedianInsertSize => {
                let predicted_median_insert_size = value
                    .parse()
                    .map_err(TryFromRecordError::InvalidPredictedMedianInsertSize)?;

                builder.set_predicted_median_insert_size(predicted_median_insert_size)
            }
            Tag::Platform => {
                let platform = value.parse().map_err(TryFromRecordError::InvalidPlatform)?;
                builder.set_platform(platform)
            }
            Tag::PlatformModel => builder.set_platform_model(value),
            Tag::PlatformUnit => builder.set_platform_unit(value),
            Tag::Sample => builder.set_sample(value),
            Tag::Other(..) => builder.insert(tag, value),
        }
    }

    match builder.build() {
        Ok(rg) => Ok(rg),
        Err(BuildError::MissingId) => Err(TryFromRecordError::MissingRequiredTag(Tag::Id)),
    }
}

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

    #[test]
    fn test_fmt() -> Result<(), builder::BuildError> {
        let read_group = ReadGroup::builder()
            .set_id("rg0")
            .set_program("noodles")
            .build()?;

        assert_eq!(read_group.to_string(), "@RG\tID:rg0\tPG:noodles");

        Ok(())
    }

    #[test]
    fn test_try_from_record_for_read_group_with_invalid_record() {
        let record = Record::new(
            record::Kind::Comment,
            record::Value::String(String::from("noodles-sam")),
        );

        assert_eq!(
            ReadGroup::try_from(record),
            Err(TryFromRecordError::InvalidRecord)
        );
    }

    #[test]
    fn test_try_from_record_for_read_group_with_no_id(
    ) -> Result<(), record::value::TryFromIteratorError> {
        let record = Record::new(
            record::Kind::ReadGroup,
            record::Value::try_from_iter(vec![("PG", "noodles")])?,
        );

        assert_eq!(
            ReadGroup::try_from(record),
            Err(TryFromRecordError::MissingRequiredTag(Tag::Id))
        );

        Ok(())
    }

    #[test]
    fn test_try_from_record_for_read_group_with_invalid_predicted_median_insert_size(
    ) -> Result<(), record::value::TryFromIteratorError> {
        let record = Record::new(
            record::Kind::ReadGroup,
            record::Value::try_from_iter(vec![("ID", "rg0"), ("PI", "unknown")])?,
        );

        assert!(matches!(
            ReadGroup::try_from(record),
            Err(TryFromRecordError::InvalidPredictedMedianInsertSize(_))
        ));

        Ok(())
    }

    #[test]
    fn test_try_from_record_for_read_group_with_invalid_platform(
    ) -> Result<(), record::value::TryFromIteratorError> {
        let record = Record::new(
            record::Kind::ReadGroup,
            record::Value::try_from_iter(vec![("ID", "rg0"), ("PL", "unknown")])?,
        );

        assert!(matches!(
            ReadGroup::try_from(record),
            Err(TryFromRecordError::InvalidPlatform(_))
        ));

        Ok(())
    }
}