Alexandria  2.25.0
SDC-CH common library for the Euclid project
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
AsciiReaderHelper.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2012-2022 Euclid Science Ground Segment
3  *
4  * This library is free software; you can redistribute it and/or modify it under
5  * the terms of the GNU Lesser General Public License as published by the Free
6  * Software Foundation; either version 3.0 of the License, or (at your option)
7  * any later version.
8  *
9  * This library is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12  * details.
13  *
14  * You should have received a copy of the GNU Lesser General Public License
15  * along with this library; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18 
25 #include "AsciiReaderHelper.h"
27 #include "ElementsKernel/Logging.h"
28 #include "NdArray/NdArray.h"
29 #include <boost/algorithm/string.hpp>
30 #include <boost/lexical_cast.hpp>
31 #include <boost/spirit/include/qi.hpp>
32 #include <boost/tokenizer.hpp>
33 #include <set>
34 #include <sstream>
35 
36 namespace Euclid {
37 namespace Table {
38 
39 using NdArray::NdArray;
40 
42 
43 size_t countColumns(std::istream& in, const std::string& comment) {
44  StreamRewinder rewinder{in};
45  size_t count = 0;
46 
47  while (in) {
48  std::string line;
49  getline(in, line);
50  // Remove any comments
51  size_t comment_pos = line.find(comment);
52  if (comment_pos != std::string::npos) {
53  line = line.substr(0, comment_pos);
54  }
55  boost::trim(line);
56  if (!line.empty()) {
57  std::string token;
58  std::stringstream line_stream(line);
59  line_stream >> boost::io::quoted(token);
60  while (line_stream) {
61  line_stream >> boost::io::quoted(token);
62  ++count;
63  }
64  break;
65  }
66  }
67  if (count == 0) {
68  throw Elements::Exception() << "No data lines found";
69  }
70  return count;
71 }
72 
76  // Boolean
77  {"bool", typeid(bool)},
78  {"boolean", typeid(bool)},
79  // Integers
80  {"int", typeid(int32_t)},
81  {"long", typeid(int64_t)},
82  {"int32", typeid(int32_t)},
83  {"int64", typeid(int64_t)},
84  // Floating point
85  {"float", typeid(float)},
86  {"double", typeid(double)},
87  // Strings
88  {"string", typeid(std::string)},
89  // Arrays
90  {"[bool]", typeid(std::vector<bool>)},
91  {"[boolean]", typeid(std::vector<bool>)},
92  {"[int]", typeid(std::vector<int32_t>)},
93  {"[long]", typeid(std::vector<int64_t>)},
94  {"[int32]", typeid(std::vector<int32_t>)},
95  {"[int64]", typeid(std::vector<int64_t>)},
96  {"[float]", typeid(std::vector<float>)},
97  {"[double]", typeid(std::vector<double>)},
98  // NdArrays
99  {"[int+]", typeid(NdArray<int32_t>)},
100  {"[long+]", typeid(NdArray<int64_t>)},
101  {"[int32+]", typeid(NdArray<int32_t>)},
102  {"[int64+]", typeid(NdArray<int64_t>)},
103  {"[float+]", typeid(NdArray<float>)},
104  {"[double+]", typeid(NdArray<double>)},
105 };
106 
108  for (auto p = KeywordTypeMap.begin(); p != KeywordTypeMap.end(); ++p) {
109  if (p->first == keyword) {
110  return p->second;
111  }
112  }
113  throw Elements::Exception() << "Unknown column type keyword " << keyword;
114 }
115 
117  StreamRewinder rewinder{in};
119  while (in) {
120  std::string line;
121  getline(in, line);
122  boost::trim(line);
123  if (line.empty()) {
124  continue; // We skip empty lines
125  }
126  if (boost::starts_with(line, comment)) {
127  // If we have a comment we remove all comment characters and check if we have
128  // a column description
129  boost::replace_all(line, comment, "");
130  boost::trim(line);
131  if (boost::starts_with(line, "Column:")) {
132  line.erase(0, 7);
133  boost::trim(line);
134  if (!line.empty()) {
135  std::string token;
136  std::stringstream line_stream(line);
137  std::string name;
138  line_stream >> boost::io::quoted(name);
139  if (descriptions.count(name) != 0) {
140  throw Elements::Exception() << "Duplicate column name " << name;
141  }
142  line_stream >> boost::io::quoted(token);
143  std::type_index type = typeid(std::string);
144  if (line_stream) {
145  if (!boost::starts_with(token, "(") && token != "-") {
146  type = keywordToType(token);
147  line_stream >> boost::io::quoted(token);
148  }
149  }
150  std::string unit = "";
151  if (line_stream) {
152  if (boost::starts_with(token, "(")) {
153  unit = token;
154  unit.erase(unit.begin());
155  unit.erase(unit.end() - 1);
156  line_stream >> boost::io::quoted(token);
157  }
158  }
159  if (line_stream && token == "-") {
160  line_stream >> boost::io::quoted(token);
161  }
162  std::stringstream desc;
163  while (line_stream) {
164  desc << token << ' ';
165  line_stream >> boost::io::quoted(token);
166  }
167  std::string desc_str = desc.str();
168  boost::trim(desc_str);
169  descriptions.emplace(std::piecewise_construct, std::forward_as_tuple(name),
170  std::forward_as_tuple(name, type, unit, desc_str));
171  }
172  }
173  } else {
174  break; // here we reached the first data line
175  }
176  }
177  return descriptions;
178 }
179 
180 std::vector<std::string> autoDetectColumnNames(std::istream& in, const std::string& comment, size_t columns_number) {
181  StreamRewinder rewinder{in};
182  std::vector<std::string> names{};
183 
184  // Find the last comment line and at the same time read the names of the
185  // column info description comments
186  std::string last_comment{};
187  std::vector<std::string> desc_names{};
188  while (in) {
189  std::string line;
190  getline(in, line);
191  boost::trim(line);
192  if (line.empty()) {
193  continue; // We skip empty lines
194  }
195  if (boost::starts_with(line, comment)) {
196  // If we have a comment we remove all comment characters and check if we have
197  // the correct number of tokens
198  boost::replace_all(line, comment, "");
199  boost::trim(line);
200  if (!line.empty()) {
201  last_comment = line;
202  }
203  if (boost::starts_with(line, "Column:")) {
204  std::string temp = line;
205  temp.erase(0, 7);
206  boost::trim(temp);
207  auto space_i = temp.find(' ');
208  if (space_i > 0) {
209  temp = temp.substr(0, space_i);
210  }
211  desc_names.emplace_back(std::move(temp));
212  }
213  } else {
214  break; // here we reached the first data line
215  }
216  }
217 
218  // Check if the last comment line contains the names of the columns
219  if (!last_comment.empty()) {
220  std::stringstream line_stream(last_comment);
221  std::string token;
222  line_stream >> boost::io::quoted(token);
223  while (line_stream) {
224  names.push_back(token);
225  line_stream >> boost::io::quoted(token);
226  }
227  if (names.size() != columns_number) {
228  names.clear();
229  }
230  }
231 
232  // If the names are empty we fill them with the column descriprion ones
233  if (names.empty()) {
234  if (desc_names.size() != 0 && desc_names.size() != columns_number) {
235  logger.warn() << "Number of column descriptions does not matches the number"
236  << " of the columns";
237  }
238  names = desc_names;
239  }
240 
241  if (names.size() < columns_number) {
242  for (size_t i = names.size() + 1; i <= columns_number; ++i) {
243  names.push_back("col" + std::to_string(i));
244  }
245  }
246  // Check for duplicate names
247  std::set<std::string> set{};
248  for (auto name : names) {
249  if (!set.insert(name).second) {
250  throw Elements::Exception() << "Duplicate column name " << name;
251  }
252  }
253  return names;
254 }
255 
256 namespace {
257 
258 template <typename T>
259 std::vector<T> convertStringToVector(const std::string& str) {
260  std::vector<T> result{};
261  boost::char_separator<char> sep{","};
262  boost::tokenizer<boost::char_separator<char>> tok{str, sep};
263  for (auto& s : tok) {
264  result.push_back(boost::get<T>(convertToCellType(s, typeid(T))));
265  }
266  return result;
267 }
268 
269 template <typename T>
270 NdArray<T> convertStringToNdArray(const std::string& str) {
271  if (str.empty()) {
272  throw Elements::Exception() << "Cannot convert an empty string to a NdArray";
273  } else if (str[0] != '<') {
274  throw Elements::Exception() << "Unexpected initial character for a NdArray: " << str[0];
275  }
276 
277  auto closing_char = str.find('>');
278  if (closing_char == std::string::npos) {
279  throw Elements::Exception() << "Could not find '>'";
280  }
281 
282  auto shape_str = str.substr(1, closing_char - 1);
283  auto shape_i = convertStringToVector<int32_t>(shape_str);
284  auto data = convertStringToVector<T>(str.substr(closing_char + 1));
285 
286  std::vector<size_t> shape_u;
287  std::copy(shape_i.begin(), shape_i.end(), std::back_inserter(shape_u));
288  return NdArray<T>(shape_u, data);
289 }
290 
291 } // namespace
292 
294  // Boolean
295  {typeid(bool),
296  [](const std::string& value) {
297  if (value == "true" || value == "t" || value == "yes" || value == "y" || value == "1") {
298  return true;
299  } else if (value == "false" || value == "f" || value == "no" || value == "n" || value == "0") {
300  return false;
301  }
302  throw Elements::Exception() << "Invalid boolean value " << value;
303  }},
304  // Integers
305  {typeid(int32_t), boost::lexical_cast<int32_t, const std::string&>},
306  {typeid(int64_t), boost::lexical_cast<int64_t, const std::string&>},
307  // Floating point
308  {typeid(float), boost::lexical_cast<float, const std::string&>},
309  {typeid(double), boost::lexical_cast<double, const std::string&>},
310  // String
311  {typeid(std::string), boost::lexical_cast<std::string, const std::string&>},
312  // Arrays
313  {typeid(std::vector<bool>), convertStringToVector<bool>},
314  {typeid(std::vector<int32_t>), convertStringToVector<int32_t>},
315  {typeid(std::vector<int64_t>), convertStringToVector<int64_t>},
316  {typeid(std::vector<float>), convertStringToVector<float>},
317  {typeid(std::vector<double>), convertStringToVector<double>},
318  // NdArray
319  {typeid(NdArray<int32_t>), convertStringToNdArray<int32_t>},
320  {typeid(NdArray<int64_t>), convertStringToNdArray<int64_t>},
321  {typeid(NdArray<float>), convertStringToNdArray<float>},
322  {typeid(NdArray<double>), convertStringToNdArray<double>},
323 };
324 
326  try {
327  auto i = sCellConverter.find(type);
328  if (i == sCellConverter.end()) {
329  throw Elements::Exception() << "Unknown type name " << type.name();
330  }
331  return i->second(value);
332  } catch (boost::bad_lexical_cast const&) {
333  throw Elements::Exception() << "Cannot convert " << value << " to " << type.name();
334  }
335 }
336 
337 bool hasNextRow(std::istream& in, const std::string& comment) {
338  StreamRewinder rewinder{in};
339  while (in) {
340  std::string line;
341  getline(in, line);
342  size_t comment_pos = line.find(comment);
343  if (comment_pos != std::string::npos) {
344  line = line.substr(0, comment_pos);
345  }
346  boost::trim(line);
347  if (!line.empty()) {
348  return true;
349  }
350  }
351  return false;
352 }
353 
355  StreamRewinder rewinder{in};
356  std::size_t count = 0;
357  while (in) {
358  std::string line;
359  getline(in, line);
360  size_t comment_pos = line.find(comment);
361  if (comment_pos != std::string::npos) {
362  line = line.substr(0, comment_pos);
363  }
364  boost::trim(line);
365  if (!line.empty()) {
366  ++count;
367  }
368  }
369  return count;
370 }
371 
374  size_t comment_pos = line.find(comment);
375 
376  if (comment_pos != std::string::npos) {
377  line = line.substr(0, comment_pos);
378  }
379  boost::trim(line);
380  if (!line.empty()) {
381  std::stringstream line_stream(line);
382  size_t count = 0;
383  std::string token;
384  line_stream >> boost::io::quoted(token);
385  while (line_stream) {
386  cells.emplace_back(token);
387  line_stream >> boost::io::quoted(token);
388  ++count;
389  }
390  }
391  return cells;
392 }
393 
395  StreamRewinder rewinder{in};
396  std::string line(comment);
397  while (in && boost::starts_with(line, comment)) {
398  getline(in, line);
399  }
400  return splitLine(line, comment);
401 }
402 
404  namespace qi = boost::spirit::qi;
405  double d;
406  long l;
407 
408  auto it1 = token.begin(), it2 = it1;
409  if (qi::parse(it1, token.end(), qi::long_, l) && it1 == token.end()) {
410  return {typeid(long), 0};
411  }
412  if (qi::parse(it2, token.end(), qi::double_, d) && it2 == token.end()) {
413  return {typeid(double), 0};
414  }
415  return {typeid(std::string), std::size_t(0)};
416 }
417 
418 } // namespace Table
419 } // end of namespace Euclid
std::size_t countRemainingRows(std::istream &in, const std::string &comment)
T empty(T...args)
T copy(T...args)
T forward_as_tuple(T...args)
const std::vector< std::pair< std::string, std::type_index > > KeywordTypeMap
T to_string(T...args)
static Elements::Logging logger
std::vector< std::string > splitLine(std::string line, const std::string &comment)
T end(T...args)
Row::cell_type convertToCellType(const std::string &value, std::type_index type)
Converts the given value to a Row::cell_type of the given type.
STL class.
STL class.
const std::map< std::type_index, std::function< Row::cell_type(const std::string &)> > sCellConverter
std::type_index keywordToType(const std::string &keyword)
STL class.
T push_back(T...args)
void warn(const std::string &logMessage)
T erase(T...args)
T str(T...args)
std::pair< std::type_index, std::size_t > guessColumnType(const std::string &token)
T move(T...args)
std::map< std::string, ColumnDescription > autoDetectColumnDescriptions(std::istream &in, const std::string &comment)
Reads the column descriptions of the given stream.
This class gets a stream as argument during construction and when it is deleted it sets the position ...
T count(T...args)
boost::variant< bool, int32_t, int64_t, float, double, std::string, std::vector< bool >, std::vector< int32_t >, std::vector< int64_t >, std::vector< float >, std::vector< double >, NdArray::NdArray< int32_t >, NdArray::NdArray< int64_t >, NdArray::NdArray< float >, NdArray::NdArray< double > > cell_type
The possible cell types.
Definition: Row.h:71
bool hasNextRow(std::istream &in, const std::string &comment)
T find(T...args)
std::string quoted(const std::string &str)
STL class.
STL class.
T name(T...args)
T begin(T...args)
T back_inserter(T...args)
T emplace(T...args)
T substr(T...args)
static Logging getLogger(const std::string &name="")
size_t countColumns(std::istream &in, const std::string &comment)
Returns the number of whitespace separated tokens of the first non commented line.
std::vector< std::string > firstDataLine(std::istream &in, const std::string &comment)
std::vector< std::string > autoDetectColumnNames(std::istream &in, const std::string &comment, size_t columns_number)
Reads the column names of the given stream.
T emplace_back(T...args)