BornAgain  1.18.0
Simulate and fit neutron and x-ray scattering at grazing incidence
OutputDataReadNumpyTXTStrategy Class Reference
Inheritance diagram for OutputDataReadNumpyTXTStrategy:
Collaboration diagram for OutputDataReadNumpyTXTStrategy:

Public Member Functions

OutputData< double > * readOutputData (std::istream &input_stream)
 

Detailed Description

Strategy to read OutputData from simple ASCII file with the layout as in numpy.savetxt.

Definition at line 53 of file OutputDataReadStrategy.h.

Member Function Documentation

◆ readOutputData()

OutputData< double > * OutputDataReadNumpyTXTStrategy::readOutputData ( std::istream &  input_stream)
virtual

Implements IOutputDataReadStrategy.

Definition at line 130 of file OutputDataReadStrategy.cpp.

131 {
132  std::string line;
133  std::vector<std::vector<double>> data;
134 
135  // Read numbers from input stream:
136  while (std::getline(input_stream, line)) {
137  line = trim(line);
138  if (line.empty() || !isDoubleStartChar(line[0]))
139  continue;
140 
141  try {
142  std::vector<double> dataInRow = DataFormatUtils::parse_doubles(line);
143  data.push_back(dataInRow);
144  } catch (...) {
145  continue;
146  }
147  }
148 
149  // validating
150  size_t nrows = data.size();
151  size_t ncols(0);
152  if (nrows)
153  ncols = data[0].size();
154 
155  if (ncols == 0)
156  throw std::runtime_error("OutputDataReadNumpyTXTStrategy::readOutputData() -> Error. "
157  "Can't parse file");
158 
159  for (size_t row = 0; row < nrows; row++) {
160  if (data[row].size() != ncols)
161  throw std::runtime_error("OutputDataReadNumpyTXTStrategy::readOutputData() -> Error. "
162  "Number of elements is different from row to row.");
163  }
164 
165  if (nrows < 2) {
166  return ArrayUtils::createData(std::move(data[0])).release();
167  } else if (ncols < 2) {
168  const size_t size = data.size();
169  std::vector<double> vector1d(size);
170  for (size_t i = 0; i < size; ++i) {
171  vector1d[i] = data[i][0];
172  }
173  return ArrayUtils::createData(std::move(vector1d)).release();
174  } else {
175  return ArrayUtils::createData(data).release();
176  }
177 }
CreateDataImpl::ReturnType< T > createData(const T &vec)
Creates OutputData array from input vector.
Definition: ArrayUtils.h:61
std::vector< double > parse_doubles(const std::string &str)
Parse double values from string to vector of double.
std::string trim(const std::string &str, const std::string &whitespace=" \t")

References ArrayUtils::createData(), anonymous_namespace{OutputDataReadStrategy.cpp}::isDoubleStartChar(), DataFormatUtils::parse_doubles(), and anonymous_namespace{OutputDataReadStrategy.cpp}::trim().

Here is the call graph for this function:

The documentation for this class was generated from the following files: