RobotsIO
Loading...
Searching...
No Matches
FileToEigen.cpp
1/*
2 * Copyright (C) 2020 Istituto Italiano di Tecnologia (IIT)
3 *
4 * This software may be modified and distributed under the terms of the
5 * BSD 3-Clause license. See the accompanying LICENSE file for details.
6 */
7
8#include <RobotsIO/Utils/FileToEigen.h>
9
10#include <iostream>
11#include <fstream>
12#include <vector>
13
14using namespace Eigen;
15
16
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)
18{
19 MatrixXd data;
20
21 std::ifstream istrm(file_path);
22 if (!istrm.is_open())
23 {
24 std::cerr << "RobotsIO::Utils::file_to_eigen. Error: failed to open " << file_path << std::endl;
25
26 return std::make_pair(false, MatrixXd());
27 }
28
29 std::vector<std::string> istrm_strings;
30 std::string line;
31 {
32 std::size_t rows = -1;
33 while (std::getline(istrm, line))
34 {
35 rows++;
36
37 if (rows < skip_rows)
38 continue;
39
40 istrm_strings.push_back(line);
41 }
42 }
43
44 istrm.close();
45
46 data.resize(expected_cols, istrm_strings.size());
47 std::size_t found_lines = 0;
48 for (auto line : istrm_strings)
49 {
50 std::size_t cols = -1;
51 std::size_t found_fields = 0;
52 std::string number_str;
53 std::istringstream iss(line);
54
55 while (iss >> number_str)
56 {
57 cols++;
58
59 if (cols < skip_cols)
60 continue;
61
62 if ((found_fields + 1) > expected_cols)
63 {
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;
66
67 return std::make_pair(false, MatrixXd());
68 }
69
70 try
71 {
72 std::size_t index = (expected_cols * found_lines) + found_fields;
73 *(data.data() + index) = std::stod(number_str);
74 }
75 catch (std::invalid_argument)
76 {
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;
81
82 return std::make_pair(false, MatrixXd());
83 }
84
85 found_fields++;
86 }
87
88 if (found_fields != expected_cols)
89 {
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;
92
93 return std::make_pair(false, MatrixXd());
94 }
95 found_lines++;
96 }
97
98 return std::make_pair(true, data);
99}