data_utils.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /******************************************************************************
  2. *
  3. * Copyright (C) 2020 by
  4. * The Salk Institute for Biological Studies
  5. *
  6. * Use of this source code is governed by an MIT-style
  7. * license that can be found in the LICENSE file or at
  8. * https://opensource.org/licenses/MIT.
  9. *
  10. ******************************************************************************/
  11. #include <fstream>
  12. #include <cerrno>
  13. #include "generated/gen_data_utils.h"
  14. using namespace std;
  15. namespace MCell {
  16. namespace API {
  17. namespace data_utils {
  18. // trim from start (in place)
  19. static void ltrim(std::string &s) {
  20. s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) {
  21. return !std::isspace(ch);
  22. }));
  23. }
  24. // trim from end (in place)
  25. static void rtrim(std::string &s) {
  26. s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
  27. return !std::isspace(ch);
  28. }).base(), s.end());
  29. }
  30. // trim from both ends (in place)
  31. static void trim(std::string &s) {
  32. ltrim(s);
  33. rtrim(s);
  34. }
  35. std::vector<std::vector<double>> load_dat_file(const std::string& file_name) {
  36. std::vector<std::vector<double>> res;
  37. ifstream fin;
  38. fin.open(file_name, ios::in);
  39. int linenr = 1;
  40. string line;
  41. while(getline(fin, line)) {
  42. // is only whitespace? -> skip
  43. trim(line);
  44. if (line == "") {
  45. continue;
  46. }
  47. size_t pos = line.find_first_of(" \t");
  48. if (pos == string::npos) {
  49. throw RuntimeError("Invalid format of input file " + file_name +
  50. ", did not find a column separator on line " + to_string(linenr) + ".");
  51. }
  52. string col1 = line.substr(0, pos);
  53. string col2 = line.substr(pos + 1);
  54. char* end;
  55. errno = 0;
  56. double col1_value = strtod(col1.c_str(), &end);
  57. if (errno != 0 || *end != '\0') {
  58. throw RuntimeError("Invalid format of input file " + file_name +
  59. ", could not convert value in the first column " + col1 + " to a float, error on line " +
  60. to_string(linenr) + ".");
  61. }
  62. errno = 0;
  63. double col2_value = strtod(col2.c_str(), &end);
  64. if (errno != 0 || *end != '\0') {
  65. throw RuntimeError("Invalid format of input file " + file_name +
  66. ", could not convert value in the second column " + col2 + " to a float, error on line " +
  67. to_string(linenr) + ".");
  68. }
  69. res.push_back(std::vector<double>());
  70. res.back().push_back(col1_value);
  71. res.back().push_back(col2_value);
  72. linenr++;
  73. }
  74. return res;
  75. }
  76. } // namespace data_utils
  77. } // namespace API
  78. } // namespace MCell