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
use super::*;

use std::io::{BufReader, BufRead};
use std::fs::File;
use std::fmt;
use std::path::Path;
use std::str::FromStr;

#[derive(Debug, Default, Clone, Eq, PartialEq)]
pub struct DataLine {
    pub raw_samples: Vec<String>
}

impl DataLine {
    fn new() -> DataLine {
        DataLine {
            raw_samples: Vec::new()
        }
    }

    fn push(&mut self, string: String) {
        self.raw_samples.push(string)
    }

    pub fn from(raw_samples: Vec<String>) -> DataLine {
        DataLine { raw_samples }
    }

    pub fn insert(&mut self, index: usize, s: &str) {
        self.raw_samples.insert(index, String::from(s))
    }
}

#[derive(Debug, Default, Clone, Eq, PartialEq)]
pub struct DataVec {
    pub lines: Vec<DataLine>
}

impl DataVec {
    pub fn new() -> DataVec {
        DataVec{
            lines: Vec::new()
        }
    }

    pub fn insert(&mut self, index: usize, s: &str) {
        self.lines.insert(index, DataLine::from(vec![String::from(s)]))
    }

    pub fn from(lines: Vec<DataLine>) -> DataVec {
        DataVec { lines }
    }

    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<DataVec> {
        let mut data_vec = DataVec::new();

        // Loop through lines and trim trailing whitespace
        for line in BufReader::new(File::open(path)?).lines() {
            let text = match line {
                Ok(txt) => txt.trim().to_string(),
                Err(_)  => "".to_string()
            };

            // If the file uses carriage returns, split those up as well
            let v_cr = text.split("\r")
                .filter(|l| !l.is_empty())
                .map(|l| l.trim());

            // Push each item in a line into a Vector
            for split_line in v_cr {
                let split = split_line.split("\t");
                let mut v = DataLine::new();

                for item in split {
                    v.push(item.trim().to_string());
                }

                // Push the Vectors into the RawVec
                data_vec.lines.push(v);
            }
        }

        // Make sure the file is not empty
        if data_vec.lines.is_empty() {
            Err(Error::EmptyFile)
        } else {
            Ok(data_vec)
        }
    }

    pub fn to_data_map(&self) -> Result<DataMap> {
        let mut map = DataMap::new();
        
        let data = self.extract_data()?;

        for (index, line) in data.lines.iter().enumerate() {
            let values = line.raw_samples.iter()
                .map(|val|
                    CgatsValue::from_str(&val).unwrap_or(CgatsValue::default())
                ).collect();
            let sample = Sample  { values };
            map.insert(index, sample);
        }

        Ok(map)
    }

    // Extract the DATA_FORMAT into a Vector of DataFormatTypes (DataFormat)
    pub fn extract_data_format(&self) -> Result<DataFormat> {
        // We need at least 2 lines to extract DATA_FORMAT
        // OK, really 3 lines, but we only need to see 2
        if self.lines.len() < 2 {
            return Err(Error::NoDataFormat);
        }

        // Use implicit format type for ColorBurst LinFiles
        let vendor = &self.get_vendor();
        if let Some(Vendor::ColorBurst) = vendor {
            return Ok(field::ColorBurstFormat());
        }

        let mut data_format = DataFormat::new();

        // Loop through the RawVec and find the BEGIN_DATA_FORMAT tag
        // then take the next line as a tab-delimited Vector
        for (index, item) in self.lines.iter().enumerate() {
            match item.raw_samples[0].as_str() {
                "BEGIN_DATA_FORMAT" => {
                    for format_type in self.lines[index + 1].raw_samples.iter() {
                        let format = Field::from_str(&format_type)?;
                        data_format.push(format);
                    }
                    break;
                },
                _ => continue
            };
        }

        // Check that the DATA_FORMAT is not empty
        if data_format.len() < 1 {
            Err(Error::NoDataFormat)
        } else {
            Ok(data_format)
        }

    }

    // Extract the data betweeen BEGIN_DATA and END_DATA into a RawVec
    pub fn extract_data(&self) -> Result<DataVec> {
        // We need at least 3 lines to define DATA
        if self.lines.len() < 3 {
            return Err(Error::NoData);
        }

        // Push DATA here
        let mut data_vec = DataVec::new();

        // Loop through the first item of each line and look for the tags.
        for (index, item) in self.lines.iter().enumerate() {
            match item.raw_samples[0].as_str() {
                "BEGIN_DATA" => {
                    // Loop through each line after BEGIN_DATA and push the next
                    for format_type in self.lines[index + 1..].iter() {
                        data_vec.lines.push(format_type.clone());
                    }
                },
                "END_DATA" => {
                    // Pop the last line off the Vector and stop looking
                    data_vec.lines.pop();
                    break;
                },
                _ => continue
            };
        }

        // Check that we actually found some data
        if data_vec.lines.is_empty() {
            Err(Error::NoData)
        } else {
            Ok(data_vec)
        }

    }

    // Extract metadata from CGATS file: anything that is not between bookends:
    // e.g. BEGIN_DATA_FORMAT...END_DATA_FORMAT // BEGIN_DATA...END_DATA
    pub fn extract_meta_data(&self) -> DataVec {
        // Push metadata here
        let mut meta_vec = DataVec::new();

        // Don't push anything between these tags (or the the tags themselves)
        let bookends = &[
            "BEGIN_DATA_FORMAT", "END_DATA_FORMAT",
            "BEGIN_DATA", "END_DATA"
        ];

        // Loop through the raw_vec and toggle pushing to meta_vec
        // based on the presence of bookend tags
        let mut index = 0;
        let mut tag_switch = true;
        while index < self.lines.len() {
            let item = &self.lines[index];
            if bookends.contains(&item.raw_samples[0].as_str()) {
                if tag_switch { tag_switch = false } else { tag_switch = true };
                index += 1;
                continue;
            }
            if tag_switch {
                meta_vec.lines.push(item.clone());
            }
            index += 1;
        }

        meta_vec
    }

    // Get the CgatsType from the first line in the RawVec (first line in file)
    pub fn get_vendor(&self) -> Option<Vendor> {
        let s = self.lines.first()?.raw_samples.iter()
            .map(|s| s.to_lowercase())
            .collect::<String>();

        // Search the string for a CgatsType
        match Vendor::from_str(&s) {
            Ok(cgt) => Some(cgt),
            Err(_) => None,
        }
    }

    pub fn meta_renumber_sets(&mut self, num: usize) {
        for line in self.lines.iter_mut() {
            if line.raw_samples[0].contains("NUMBER_OF_SETS") {
                *line = DataLine::from(vec!["NUMBER_OF_SETS".to_string(), num.to_string()]);
            }
        }
    }
}

impl fmt::Display for DataLine {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut values = self.raw_samples.iter()
            .map(|line| format!("{}\t", line))
            .collect::<String>();

        values.pop();

        write!(f, "{}", values)
    }
}

impl fmt::Display for DataVec {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}",
            self.lines.iter()
                .map(|line| format!("{}\n", line))
                .collect::<String>()
        )
    }
}

#[test]
fn from_file() -> Result<()> {
    let raw = DataVec::from_file("test_files/curve0.txt")?;
    println!("{:?}", raw);
    Ok(())
}