Medusa  1.1
Coordinate Free Mehless Method implementation
CSV_Eigen.hpp
Go to the documentation of this file.
1 #ifndef MEDUSA_BITS_IO_CSV_EIGEN_HPP_
2 #define MEDUSA_BITS_IO_CSV_EIGEN_HPP_
3 
9 #include "CSV_fwd.hpp"
10 #include <Eigen/Core>
11 
12 namespace mm {
13 
14 inline Eigen::MatrixXd CSV::readEigen(const std::string& filename, char separator) {
15  std::ifstream f(filename);
16  assert_msg(f.good(), "Error opening CSV file '%s': %s.", filename, strerror(errno));
17 
18  std::vector<std::vector<std::string>> lines;
19  std::string s;
20  while (getline(f, s)) lines.push_back(split(s, separator));
21 
22  size_t m = lines.size();
23  size_t n = lines[0].size();
24  for (size_t i = 1; i < m; ++i) {
25  assert_msg(lines[i].size() == n, "Not all rows in CSV file have the same number of "
26  "elements, row 1 has %d and row %d has %d.",
27  n, i, lines[i].size());
28  }
29 
30  Eigen::MatrixXd M(m, n);
31  for (size_t i = 0; i < m; ++i) {
32  for (size_t j = 0; j < n; ++j) {
33  try {
34  M(i, j) = std::stod(lines[i][j]);
35  } catch(const std::invalid_argument& e) {
36  assert_msg(false, "Failed parsing '%s' to double.", lines[i][j]);
37  }
38  }
39  }
40  return M;
41 }
42 
43 template <typename Derived>
44 void CSV::writeEigen(const std::string& filename, const Eigen::MatrixBase <Derived>& expr,
45  char separator) {
46  std::ofstream f(filename);
47  assert_msg(f.good(), "Error opening CSV file '%s': %s.", filename, strerror(errno));
48  f << std::setprecision(16);
49  int r = expr.rows(), c = expr.cols();
50  for (int i = 0; i < r; ++i) {
51  for (int j = 0; j < c; ++j) {
52  if (j > 0) f << separator;
53  f << expr(i, j);
54  }
55  f << '\n';
56  }
57 }
58 
59 } // namespace mm
60 
61 #endif // MEDUSA_BITS_IO_CSV_EIGEN_HPP_
mm
Root namespace for the whole library.
Definition: Gaussian.hpp:14
mm::CSV::writeEigen
static void writeEigen(const std::string &filename, const Eigen::MatrixBase< Derived > &expr, char separator=',')
Writes given Eigen matrix to a CSV file.
Definition: CSV_Eigen.hpp:44
assert_msg
#define assert_msg(cond,...)
Assert with better error reporting.
Definition: assert.hpp:75
CSV_fwd.hpp
mm::CSV::readEigen
static Eigen::Matrix< double, -1, -1, 0, -1, -1 > readEigen(const std::string &filename, char separator=',')
Reads a CSV file to an Eigen matrix.
Definition: CSV_Eigen.hpp:14
mm::CSV::split
static std::vector< std::string > split(const std::string &str, char separator)
Splits given string into a vector of strings on the given separator.
Definition: CSV.cpp:55