1bd146966324f63f87adc75db41eea53c8958b0d
[platform/core/ml/nntrainer.git] / nntrainer / utils / util_func.cpp
1 /**
2  * Copyright (C) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *   http://www.apache.org/licenses/LICENSE-2.0
8  * Unless required by applicable law or agreed to in writing, software
9  * distributed under the License is distributed on an "AS IS" BASIS,
10  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11  * See the License for the specific language governing permissions and
12  * limitations under the License.
13  *
14  * @file        util_func.cpp
15  * @date        08 April 2020
16  * @brief       This is collection of math functions
17  * @see         https://github.com/nnstreamer/nntrainer
18  * @author      Jijoong Moon <jijoong.moon@samsung.com>
19  * @bug         No known bugs except for NYI items
20  *
21  */
22
23 #include <cmath>
24 #include <fstream>
25 #include <random>
26
27 #include <nntrainer_log.h>
28 #include <util_func.h>
29
30 namespace nntrainer {
31
32 static auto rng = [] {
33   std::mt19937 rng;
34   rng.seed(getSeed());
35   return rng;
36 }();
37 static std::uniform_real_distribution<float> dist(-0.5, 0.5);
38
39 unsigned int getSeed() { return 0; }
40
41 float sqrtFloat(float x) { return sqrt(x); };
42
43 double sqrtDouble(double x) { return sqrt(x); };
44
45 float logFloat(float x) { return log(x + 1.0e-20); }
46
47 float exp_util(float x) { return exp(x); }
48
49 Tensor rotate_180(Tensor in) {
50   Tensor output(in.getDim());
51   output.setZero();
52   for (unsigned int i = 0; i < in.batch(); ++i) {
53     for (unsigned int j = 0; j < in.channel(); ++j) {
54       for (unsigned int k = 0; k < in.height(); ++k) {
55         for (unsigned int l = 0; l < in.width(); ++l) {
56           output.setValue(
57             i, j, k, l,
58             in.getValue(i, j, (in.height() - k - 1), (in.width() - l - 1)));
59         }
60       }
61     }
62   }
63   return output;
64 }
65
66 bool isFileExist(std::string file_name) {
67   std::ifstream infile(file_name);
68   return infile.good();
69 }
70
71 template <typename T>
72 static void checkFile(const T &file, const char *error_msg) {
73   if (file.bad() | file.eof() | !file.good() | file.fail()) {
74     throw std::runtime_error(error_msg);
75   }
76 }
77
78 void checkedRead(std::ifstream &file, char *array, std::streamsize size,
79                  const char *error_msg) {
80   file.read(array, size);
81
82   checkFile(file, error_msg);
83 }
84
85 void checkedWrite(std::ostream &file, const char *array, std::streamsize size,
86                   const char *error_msg) {
87   file.write(array, size);
88
89   checkFile(file, error_msg);
90 }
91
92 std::string readString(std::ifstream &file, const char *error_msg) {
93   std::string str;
94   size_t size;
95
96   checkedRead(file, (char *)&size, sizeof(size), error_msg);
97   str.resize(size);
98   checkedRead(file, (char *)&str[0], size, error_msg);
99
100   return str;
101 }
102
103 void writeString(std::ofstream &file, const std::string &str,
104                  const char *error_msg) {
105   size_t size = str.size();
106
107   checkedWrite(file, (char *)&size, sizeof(size), error_msg);
108   checkedWrite(file, (char *)&str[0], size, error_msg);
109 }
110
111 bool endswith(const std::string &target, const std::string &suffix) {
112   if (target.size() < suffix.size()) {
113     return false;
114   }
115   size_t spos = target.size() - suffix.size();
116   return target.substr(spos) == suffix;
117 }
118
119 int getKeyValue(const std::string &input_str, std::string &key,
120                 std::string &value) {
121   int status = ML_ERROR_NONE;
122   auto input_trimmed = input_str;
123
124   std::vector<std::string> list;
125   static const std::regex words_regex("[^\\s=]+");
126   input_trimmed.erase(
127     std::remove(input_trimmed.begin(), input_trimmed.end(), ' '),
128     input_trimmed.end());
129   auto words_begin = std::sregex_iterator(input_trimmed.begin(),
130                                           input_trimmed.end(), words_regex);
131   auto words_end = std::sregex_iterator();
132   int nwords = std::distance(words_begin, words_end);
133
134   if (nwords != 2) {
135     ml_loge("Error: input string must be 'key = value' format "
136             "(e.g.{\"key1=value1\",\"key2=value2\"}), \"%s\" given",
137             input_trimmed.c_str());
138     return ML_ERROR_INVALID_PARAMETER;
139   }
140
141   for (std::sregex_iterator i = words_begin; i != words_end; ++i) {
142     list.push_back((*i).str());
143   }
144
145   key = list[0];
146   value = list[1];
147
148   return status;
149 }
150
151 int getValues(int n_str, std::string str, int *value) {
152   int status = ML_ERROR_NONE;
153   static const std::regex words_regex("[^\\s.,:;!?]+");
154   str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
155   auto words_begin = std::sregex_iterator(str.begin(), str.end(), words_regex);
156   auto words_end = std::sregex_iterator();
157
158   int num = std::distance(words_begin, words_end);
159   if (num != n_str) {
160     ml_loge("Number of Data is not match");
161     return ML_ERROR_INVALID_PARAMETER;
162   }
163   int cn = 0;
164   for (std::sregex_iterator i = words_begin; i != words_end; ++i) {
165     value[cn] = std::stoi((*i).str());
166     cn++;
167   }
168   return status;
169 }
170
171 std::vector<std::string> split(const std::string &s, const std::regex &reg) {
172   std::vector<std::string> out;
173   const int NUM_SKIP_CHAR = 3;
174   char char_to_remove[NUM_SKIP_CHAR] = {' ', '[', ']'};
175   std::string str = s;
176   for (unsigned int i = 0; i < NUM_SKIP_CHAR; ++i) {
177     str.erase(std::remove(str.begin(), str.end(), char_to_remove[i]),
178               str.end());
179   }
180   std::regex_token_iterator<std::string::iterator> end;
181   std::regex_token_iterator<std::string::iterator> iter(str.begin(), str.end(),
182                                                         reg, -1);
183
184   while (iter != end) {
185     out.push_back(*iter);
186     ++iter;
187   }
188   return out;
189 }
190
191 bool istrequal(const std::string &a, const std::string &b) {
192   if (a.size() != b.size())
193     return false;
194
195   return std::equal(a.begin(), a.end(), b.begin(), [](char a_, char b_) {
196     return tolower(a_) == tolower(b_);
197   });
198 }
199
200 } // namespace nntrainer