noodles_vcf/header/
builder.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
use super::{
    record::{
        self,
        value::{
            map::{AlternativeAllele, Contig, Filter, Format, Info},
            Map,
        },
    },
    AlternativeAlleles, Contigs, FileFormat, Filters, Formats, Header, Infos, OtherRecords,
    SampleNames, StringMaps,
};

use indexmap::IndexMap;

/// A VCF header builder.
#[derive(Debug, Default)]
pub struct Builder {
    file_format: FileFormat,
    infos: Infos,
    filters: Filters,
    formats: Formats,
    alternative_alleles: AlternativeAlleles,
    contigs: Contigs,
    sample_names: SampleNames,
    other_records: OtherRecords,
}

impl Builder {
    /// Sets the fileformat record (`fileformat`).
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_vcf::{self as vcf, header::FileFormat};
    ///
    /// let header = vcf::Header::builder()
    ///     .set_file_format(FileFormat::default())
    ///     .build();
    ///
    /// assert_eq!(header.file_format(), FileFormat::default());
    /// ```
    pub fn set_file_format(mut self, file_format: FileFormat) -> Self {
        self.file_format = file_format;
        self
    }

    /// Adds an information record (`INFO`).
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_vcf::{
    ///     self as vcf,
    ///     header::record::value::{map::Info, Map},
    ///     variant::record::info::field::key,
    /// };
    ///
    /// let id = key::SAMPLES_WITH_DATA_COUNT;
    /// let info = Map::<Info>::from(id);
    ///
    /// let header = vcf::Header::builder()
    ///     .add_info(id, info.clone())
    ///     .build();
    ///
    /// let infos = header.infos();
    /// assert_eq!(infos.len(), 1);
    /// assert_eq!(&infos[0], &info);
    /// ```
    pub fn add_info<I>(mut self, id: I, info: Map<Info>) -> Self
    where
        I: Into<String>,
    {
        self.infos.insert(id.into(), info);
        self
    }

    /// Adds a filter record (`FILTER`).
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_vcf::{self as vcf, header::record::value::{map::Filter, Map}};
    ///
    /// let filter = Map::<Filter>::new("Quality below 10");
    ///
    /// let header = vcf::Header::builder()
    ///     .add_filter("q10", filter.clone())
    ///     .build();
    ///
    /// let filters = header.filters();
    /// assert_eq!(filters.len(), 1);
    /// assert_eq!(&filters[0], &filter);
    /// ```
    pub fn add_filter<I>(mut self, id: I, filter: Map<Filter>) -> Self
    where
        I: Into<String>,
    {
        self.filters.insert(id.into(), filter);
        self
    }

    /// Adds a genotype format record (`FORMAT`).
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_vcf::{
    ///     self as vcf,
    ///     header::record::value::{map::Format, Map},
    ///     variant::record::samples::keys::key,
    /// };
    ///
    /// let id = key::GENOTYPE;
    /// let format = Map::<Format>::from(id);
    ///
    /// let header = vcf::Header::builder()
    ///     .add_format(id, format.clone())
    ///     .build();
    ///
    /// let formats = header.formats();
    /// assert_eq!(formats.len(), 1);
    /// assert_eq!(&formats[0], &format);
    /// ```
    pub fn add_format<I>(mut self, id: I, format: Map<Format>) -> Self
    where
        I: Into<String>,
    {
        self.formats.insert(id.into(), format);
        self
    }

    /// Adds an alternative allele record (`ALT`).
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_vcf::{
    ///     self as vcf,
    ///     header::record::value::{map::AlternativeAllele, Map},
    /// };
    ///
    /// let alt = Map::<AlternativeAllele>::new("Deletion");
    ///
    /// let header = vcf::Header::builder()
    ///     .add_alternative_allele("DEL", alt.clone())
    ///     .build();
    ///
    /// let alternative_alleles = header.alternative_alleles();
    /// assert_eq!(alternative_alleles.len(), 1);
    /// assert_eq!(&alternative_alleles[0], &alt);
    /// ```
    pub fn add_alternative_allele<I>(
        mut self,
        id: I,
        alternative_allele: Map<AlternativeAllele>,
    ) -> Self
    where
        I: Into<String>,
    {
        self.alternative_alleles
            .insert(id.into(), alternative_allele);

        self
    }

    /// Adds a contig record (`contig`).
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_vcf::{self as vcf, header::record::value::{map::Contig, Map}};
    ///
    /// let contig = Map::<Contig>::new();
    ///
    /// let header = vcf::Header::builder()
    ///     .add_contig("sq0", contig.clone())
    ///     .build();
    ///
    /// let contigs = header.contigs();
    /// assert_eq!(contigs.len(), 1);
    /// assert_eq!(&contigs[0], &contig);
    /// ```
    pub fn add_contig<I>(mut self, id: I, contig: Map<Contig>) -> Self
    where
        I: Into<String>,
    {
        self.contigs.insert(id.into(), contig);
        self
    }

    /// Sets sample names.
    ///
    /// # Examples
    ///
    /// ```
    /// use indexmap::IndexSet;
    /// use noodles_vcf as vcf;
    ///
    /// let sample_names: IndexSet<_> = [String::from("sample0")]
    ///     .into_iter()
    ///     .collect();
    ///
    /// let header = vcf::Header::builder()
    ///     .set_sample_names(sample_names.clone())
    ///     .build();
    ///
    /// assert_eq!(header.sample_names(), &sample_names);
    /// ```
    pub fn set_sample_names(mut self, sample_names: SampleNames) -> Self {
        self.sample_names = sample_names;
        self
    }

    /// Adds a sample name.
    ///
    /// Duplicate names are discarded.
    ///
    /// # Examples
    ///
    /// ```
    /// use indexmap::IndexSet;
    /// use noodles_vcf as vcf;
    ///
    /// let header = vcf::Header::builder()
    ///     .add_sample_name("sample0")
    ///     .add_sample_name("sample1")
    ///     .build();
    ///
    /// let expected: IndexSet<_> = [String::from("sample0"), String::from("sample1")]
    ///     .into_iter()
    ///     .collect();
    ///
    /// assert_eq!(header.sample_names(), &expected);
    /// ```
    pub fn add_sample_name<I>(mut self, sample_name: I) -> Self
    where
        I: Into<String>,
    {
        self.sample_names.insert(sample_name.into());
        self
    }

    /// Inserts a key-value pair representing an unstructured record into the header.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_vcf::{
    ///     self as vcf,
    ///     header::record::{value::Collection, Value},
    /// };
    ///
    /// let header = vcf::Header::builder()
    ///     .insert("fileDate".parse()?, Value::from("20200709"))?
    ///     .build();
    ///
    /// assert_eq!(
    ///     header.get("fileDate"),
    ///     Some(&Collection::Unstructured(vec![String::from("20200709")]))
    /// );
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    pub fn insert(
        mut self,
        key: record::key::Other,
        value: record::Value,
    ) -> Result<Self, super::record::value::collection::AddError> {
        let collection = self
            .other_records
            .entry(key)
            .or_insert_with(|| match value {
                record::Value::String(_) => record::value::Collection::Unstructured(Vec::new()),
                record::Value::Map(..) => record::value::Collection::Structured(IndexMap::new()),
            });

        collection.add(value)?;

        Ok(self)
    }

    /// Builds a VCF header.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_vcf as vcf;
    /// let header = vcf::Header::builder().build();
    /// ```
    pub fn build(self) -> Header {
        Header {
            file_format: self.file_format,
            infos: self.infos,
            filters: self.filters,
            formats: self.formats,
            alternative_alleles: self.alternative_alleles,
            contigs: self.contigs,
            sample_names: self.sample_names,
            other_records: self.other_records,
            string_maps: StringMaps::default(),
        }
    }
}

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

    #[test]
    fn test_default() {
        let header = Builder::default().build();

        assert_eq!(header.file_format(), FileFormat::default());
        assert!(header.infos().is_empty());
        assert!(header.filters().is_empty());
        assert!(header.formats().is_empty());
        assert!(header.alternative_alleles().is_empty());
        assert!(header.contigs().is_empty());
        assert!(header.sample_names().is_empty());
    }

    #[test]
    fn test_build() -> Result<(), Box<dyn std::error::Error>> {
        use crate::{
            header,
            variant::record::{info::field::key as info_key, samples::keys::key as format_key},
        };

        let (key, value) = (
            "fileDate".parse::<header::record::key::Other>()?,
            header::record::Value::from("20200709"),
        );

        let header = Builder::default()
            .set_file_format(FileFormat::new(4, 3))
            .add_info(
                info_key::SAMPLES_WITH_DATA_COUNT,
                Map::<Info>::from(info_key::SAMPLES_WITH_DATA_COUNT),
            )
            .add_filter("q10", Map::<Filter>::new("Quality below 10"))
            .add_format(
                format_key::GENOTYPE,
                Map::<Format>::from(format_key::GENOTYPE),
            )
            .add_alternative_allele("DEL", Map::<AlternativeAllele>::new("Deletion"))
            .add_contig("sq0", Map::<Contig>::new())
            .add_contig("sq1", Map::<Contig>::new())
            .add_sample_name("sample0")
            .insert(key.clone(), value.clone())?
            .insert(key.clone(), value)?
            .build();

        assert_eq!(header.file_format(), FileFormat::new(4, 3));
        assert_eq!(header.infos().len(), 1);
        assert_eq!(header.filters().len(), 1);
        assert_eq!(header.formats().len(), 1);
        assert_eq!(header.alternative_alleles().len(), 1);
        assert_eq!(header.contigs().len(), 2);
        assert_eq!(header.get(&key).map(|collection| collection.len()), Some(2));

        Ok(())
    }
}