pf
data_reader.h
1 #ifndef DATA_READER_H
2 #define DATA_READER_H
3 
4 #include <vector>
5 #include <Eigen/Dense>
6 #include <string>
7 #include <fstream>
8 #include <iostream>
9 
10 
11 // this csv file must not have a header
12 template<typename float_t, size_t dimobs>
13 std::vector<Eigen::Matrix<float_t,dimobs,1> > readInData(const std::string &fileLoc, char delim)
14 {
15 
16  // build this up and return it
17  std::vector<Eigen::Matrix<float_t,dimobs,1> > data;
18 
19  // start reading
20  std::string line;
21  std::ifstream ifs(fileLoc);
22  std::string one_number;
23  unsigned int num_col;
24  if(!ifs.is_open()){
25  std::cerr << "readInData() failed to read data from: " << fileLoc << "\n";
26  }
27 
28  // didn't fail...keep going
29  while(std::getline(ifs, line)){
30 
31  std::vector<float_t> data_row;
32  try{
33 
34  // get a single element in a single row
35  std::istringstream buff(line);
36 
37  // use commas to split up the line
38  num_col = 0;
39  while(std::getline(buff, one_number, delim)){
40  data_row.push_back(std::stod(one_number));
41  num_col ++;
42  }
43 
44  } catch(const std::invalid_argument& ia){
45  std::cerr << "Invalid Argument: " << ia.what() << "\n";
46  continue;
47  }
48 
49  // now append this vector to your collection
50  Eigen::Map<Eigen::Matrix<float_t,dimobs,1>> drw(&data_row[0], num_col);
51  data.push_back(drw);
52  }
53 
54  return data;
55 }
56 
57 
58 #endif // DATA_READER_H