MCPcopy Create free account
hub / github.com/daniel-e/rustml / from_csv_string

Function from_csv_string

src/csv.rs:62–100  ·  view source on GitHub ↗

Reads a matrix from a CSV. The elements are of the type f64.

(s: &str, sep: &str)

Source from the content-addressed store, hash-verified

60///
61/// The elements are of the type f64.
62pub fn from_csv_string(s: &str, sep: &str) -> Result<Matrix<f64>, &'static str> {
63
64 // TODO
65 let v = s.split('\n')
66 .map(|x| match x.find('#') { // remove comments
67 Some(pos) => {
68 let mut tmp = x.to_string();
69 tmp.truncate(pos);
70 tmp
71 }
72 _ => x.to_string()
73 })
74 .filter(|x| x.trim().len() > 0)
75 .map(|x| x.split(sep) // split each line by the given separator
76 .map(|x| x.trim())
77 .map(|x| f64::from_str(x).unwrap_or(f64::NAN))
78 .collect::<Vec<f64>>()
79 )
80 .collect::<Vec<Vec<f64>>>();
81
82 let rows = v.len();
83 let cols = v.first().unwrap_or(&Vec::new()).len();
84 let data = v.iter().flat_map(|x| x.iter()).cloned().collect::<Vec<f64>>();
85
86 // now we have the data two times in memory
87 // performance
88
89 if rows == 0
90 || cols == 0
91 || v.iter().any(|x| x.len() != cols)
92 || data.iter().any(|x| x.is_nan()) {
93 return Err("Invalid format.");
94 }
95
96 match Matrix::from_vec(data, rows, cols) {
97 Some(m) => Ok(m),
98 _ => Err("Could not create matrix.")
99 }
100}
101
102pub fn from_csv_file(fname: &str, sep: &str) -> Result<Matrix<f64>, &'static str> {
103

Callers 2

from_csv_fileFunction · 0.85
test_from_csv_stringFunction · 0.85

Calls 5

mapMethod · 0.80
findMethod · 0.80
to_stringMethod · 0.80
lenMethod · 0.45
iterMethod · 0.45

Tested by 1

test_from_csv_stringFunction · 0.68