1 #ifndef MEDUSA_BITS_IO_CSV_EIGEN_HPP_
2 #define MEDUSA_BITS_IO_CSV_EIGEN_HPP_
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));
18 std::vector<std::vector<std::string>> lines;
20 while (getline(f, s)) lines.push_back(
split(s, separator));
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());
30 Eigen::MatrixXd M(m, n);
31 for (
size_t i = 0; i < m; ++i) {
32 for (
size_t j = 0; j < n; ++j) {
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]);
43 template <
typename Derived>
44 void CSV::writeEigen(
const std::string& filename,
const Eigen::MatrixBase <Derived>& expr,
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;
61 #endif // MEDUSA_BITS_IO_CSV_EIGEN_HPP_