data.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #pragma once
  2. #include <util/generic/string.h>
  3. #include <util/generic/hash.h>
  4. #include <util/generic/vector.h>
  5. #include <util/string/builder.h>
  6. #include <util/string/cast.h>
  7. #include <variant>
  8. namespace NAnalytics {
  9. using TRowValue = std::variant<i64, ui64, double, TString>;
  10. TString ToString(const TRowValue& val) {
  11. TStringBuilder builder;
  12. std::visit([&builder] (auto&& arg) {
  13. builder << arg;
  14. }, val);
  15. return builder;
  16. }
  17. struct TRow : public THashMap<TString, TRowValue> {
  18. TString Name;
  19. template<typename T>
  20. bool Get(const TString& name, T& value) const {
  21. if constexpr (std::is_same_v<double, T>) {
  22. if (name == "_count") { // Special values
  23. value = 1.0;
  24. return true;
  25. }
  26. }
  27. auto iter = find(name);
  28. if (iter != end()) {
  29. try {
  30. value = std::get<T>(iter->second);
  31. return true;
  32. } catch (...) {}
  33. }
  34. return false;
  35. }
  36. template<typename T = double>
  37. T GetOrDefault(const TString& name, T dflt = T()) {
  38. Get(name, dflt);
  39. return dflt;
  40. }
  41. bool GetAsString(const TString& name, TString& value) const {
  42. auto iter = find(name);
  43. if (iter != end()) {
  44. value = ToString(iter->second);
  45. return true;
  46. }
  47. return false;
  48. }
  49. };
  50. using TAttributes = THashMap<TString, TString>;
  51. struct TTable : public TVector<TRow> {
  52. TAttributes Attributes;
  53. };
  54. struct TMatrix : public TVector<double> {
  55. size_t Rows;
  56. size_t Cols;
  57. explicit TMatrix(size_t rows = 0, size_t cols = 0)
  58. : TVector<double>(rows * cols)
  59. , Rows(rows)
  60. , Cols(cols)
  61. {}
  62. void Reset(size_t rows, size_t cols)
  63. {
  64. Rows = rows;
  65. Cols = cols;
  66. clear();
  67. resize(rows * cols);
  68. }
  69. double& Cell(size_t row, size_t col)
  70. {
  71. Y_ABORT_UNLESS(row < Rows);
  72. Y_ABORT_UNLESS(col < Cols);
  73. return operator[](row * Cols + col);
  74. }
  75. double Cell(size_t row, size_t col) const
  76. {
  77. Y_ABORT_UNLESS(row < Rows);
  78. Y_ABORT_UNLESS(col < Cols);
  79. return operator[](row * Cols + col);
  80. }
  81. double CellSum() const
  82. {
  83. double sum = 0.0;
  84. for (double x : *this) {
  85. sum += x;
  86. }
  87. return sum;
  88. }
  89. };
  90. }