8#include <RobotsIO/Utils/FileToEigen.h>
17std::pair<bool, Eigen::MatrixXd> RobotsIO::Utils::file_to_eigen(
const std::string& file_path,
const std::size_t& skip_rows,
const std::size_t skip_cols,
const std::size_t& expected_cols)
21 std::ifstream istrm(file_path);
24 std::cerr <<
"RobotsIO::Utils::file_to_eigen. Error: failed to open " << file_path << std::endl;
26 return std::make_pair(
false, MatrixXd());
29 std::vector<std::string> istrm_strings;
32 std::size_t rows = -1;
33 while (std::getline(istrm, line))
40 istrm_strings.push_back(line);
46 data.resize(expected_cols, istrm_strings.size());
47 std::size_t found_lines = 0;
48 for (
auto line : istrm_strings)
50 std::size_t cols = -1;
51 std::size_t found_fields = 0;
52 std::string number_str;
53 std::istringstream iss(line);
55 while (iss >> number_str)
62 if ((found_fields + 1) > expected_cols)
64 std::cerr <<
"RobotsIO::Utils::file_to_eigen. Error: malformed input file " << file_path <<
"." << std::endl
65 <<
"Detailed error: found more columns (" << found_fields + 1 <<
") than expected (" << expected_cols <<
")." << std::endl;
67 return std::make_pair(
false, MatrixXd());
72 std::size_t index = (expected_cols * found_lines) + found_fields;
73 *(data.data() + index) = std::stod(number_str);
75 catch (std::invalid_argument)
77 std::cerr <<
"RobotsIO::Utils::file_to_eigen. Error: malformed input file " << file_path <<
"." << std::endl
78 <<
"Detailed error: data cannot be interpreted as double "
79 <<
"at line " + std::to_string(skip_cols + found_lines) <<
", "
80 <<
"token " + std::to_string(found_fields) << std::endl;
82 return std::make_pair(
false, MatrixXd());
88 if (found_fields != expected_cols)
90 std::cerr <<
"RobotsIO::Utils::read_data_from_file. Error: malformed input file " << file_path << std::endl
91 <<
"Detailed error: found less columns (" << found_fields <<
") than expected (" << expected_cols <<
")." << std::endl;
93 return std::make_pair(
false, MatrixXd());
98 return std::make_pair(
true, data);