-
Notifications
You must be signed in to change notification settings - Fork 5
/
pch.cpp
380 lines (328 loc) · 9.31 KB
/
pch.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
#include "pch.hpp"
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdexcept> // std::runtime_error
#include <ios> // std::ios_base::failure
#include <dirent.h> // list files in directory
#include <cstdlib> // for string -> number conversion
#include <cstring> // for strcmp/strlen when reading json
#
#include "json/gason.h"
namespace cnn_sr {
bool warn_about_blocking_operation = false;
namespace utils {
///
/// Utils
///
void require(bool check, const char* msg) {
if (!check) {
throw std::runtime_error(msg);
}
}
void dump_vector(std::ostream& os, std::vector<float>& data,
const char* line_prefix, size_t per_line,
bool add_line_numbers) {
auto len = data.size();
size_t lines;
if (per_line == 0) {
lines = 1;
per_line = len;
} else {
lines = len / per_line;
}
line_prefix = line_prefix ? line_prefix : "";
for (size_t i = 0; i < lines; i++) {
os << line_prefix;
if (add_line_numbers) os << "[" << i << "] ";
for (size_t j = 0; j < per_line; j++) {
size_t idx = i * per_line + j;
if (idx < len) os << data[idx];
if (j + 1 < per_line) os << ", ";
}
if (i + 1 < lines) os << std::endl;
}
}
size_t closest_power_of_2(int x) {
if (x < 0) return 0;
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return static_cast<size_t>(x + 1);
}
///
/// File system
///
void get_file_content(const char* const filename, std::stringstream& sstr) {
// TODO use to load kernel file too
std::fstream file(filename);
if (!file.is_open()) {
throw std::ios_base::failure("File not found");
}
std::string line;
while (file.good()) {
getline(file, line);
sstr << line;
}
}
void list_files(const char* const path, std::vector<std::string>& target) {
DIR* d;
struct dirent* dir;
d = opendir(path);
if (d) {
while ((dir = readdir(d)) != NULL) {
target.push_back(dir->d_name);
// if (dir->d_type == DT_REG) { // regular (non dirs/links)
// printf("%s\n", dir->d_name);
// }
// printf("%s\n", dir->d_name);
}
closedir(d);
}
}
///
/// Json utils
///
void read_json_file(const char* const file, JsonValue& value,
JsonAllocator& allocator, std::string& file_content,
int root_type) {
if (strlen(file) > 250) {
throw IOException("Filepath is too long");
}
std::stringstream sstr;
get_file_content(file, sstr);
file_content = sstr.str();
char* source = const_cast<char*>(file_content.c_str());
char* endptr;
auto status = jsonParse(source, &endptr, &value, allocator);
if (status != JSON_OK) {
char buf[255];
snprintf(buf, 255, "Json parsing error: %s in: '%-20s'",
jsonStrError(status), endptr);
throw IOException(buf);
}
if (value.getTag() != root_type) {
throw std::runtime_error("Expected root of JSON file had invalid type");
}
}
bool try_read_float(JsonNode& node, float& lhs, const char* key) {
if (strcmp(node.key, key) == 0 && node.value.getTag() == JSON_NUMBER) {
lhs = (float)node.value.toNumber();
return true;
}
return false;
}
bool try_read_uint(JsonNode& node, unsigned int& lhs, const char* key) {
if (strcmp(node.key, key) == 0 && node.value.getTag() == JSON_NUMBER) {
lhs = (unsigned int)node.value.toNumber();
return true;
}
return false;
}
bool try_read_vector(JsonNode& node, std::vector<float>& lhs, const char* key) {
// std::cout << "key >> '" << node.key << "' vs '" << key
// << "' == " << (strcmp(node.key, key)) << std::endl;
if (strcmp(node.key, key) == 0 && node.value.getTag() == JSON_ARRAY) {
auto arr_raw = node.value;
for (auto val : arr_raw) {
/* ASSERT(val->value.getTag() == JSON_NUMBER);*/
float v = (float)val->value.toNumber();
lhs.push_back(v);
}
return true;
}
return false;
}
bool try_read_string(JsonNode& node, std::string& lhs, const char* key) {
if (strcmp(node.key, key) == 0 && node.value.getTag() == JSON_STRING) {
lhs.assign(node.value.toString());
return true;
}
return false;
}
///
/// Cmd line args parsing
///
ArgOption& ArgOption::help(const char* text) {
_help.assign(text);
return *this;
}
ArgOption& ArgOption::required() {
_required = true;
return *this;
}
Argparse::Argparse(const char* exec, const char* help)
: _general_help(help), _exec_name(exec) {
add_argument("help", "-h").help("Print this help");
}
ArgOption& Argparse::add_argument(const char* m1) {
return add_argument(1, &m1);
}
ArgOption& Argparse::add_argument(const char* m1, const char* m2) {
const char* tmp[2] = {m1, m2};
return add_argument(2, tmp);
}
bool is_valid_arg(size_t len, const char* ms) {
bool valid = len > 0;
for (size_t i = 0; i < len; i++) {
auto c = ms[i];
valid &= isalpha(c) || (c == '-');
}
if (!valid) std::cout << "'" << ms << "' is not valid mnemonic" << std::endl;
return valid;
}
ArgOption& Argparse::add_argument(size_t mlen, const char** ms) {
_options.push_back(ArgOption());
ArgOption& opt = _options.back();
for (size_t i = 0; i < mlen; i++) {
auto mnemonic = const_cast<char*>(ms[i]);
// std::cout << mnemonic << std::endl;
auto len = strlen(mnemonic);
if (!is_valid_arg(len, mnemonic)) continue;
char* name = nullptr;
if (mnemonic[0] != '-')
name = mnemonic;
else if (len > 2 && mnemonic[0] == '-' && mnemonic[1] == '-')
name = mnemonic + 2;
// name = mnemonic;
if (name) {
opt._name.assign(name);
// std::cout << "NAME: " << name << std::endl;
}
opt._mnemonics.push_back(std::string(mnemonic));
}
if (opt._mnemonics.empty())
throw std::runtime_error("Argument does not have valid mnemonic");
if (opt._name.empty())
throw std::runtime_error(
"Argument does not have valid name (at least one mnemonic should: "
"not "
"have '-' prefix or start with '--')");
return opt;
}
bool Argparse::parse(size_t argc, char** argv) {
_values.clear();
for (size_t i = 1; i < argc; i++) { // skip file name
auto arg = argv[i];
// std::cout << "[" << i << "]" << arg << std::endl;
// find ArgOption
ArgOption* opt = nullptr;
for (auto& o : _options) {
for (auto& mnemonic : o._mnemonics) {
// std::cout << "\t" << arg << " vs " << mnemonic << std::endl;
if (mnemonic.compare(arg) == 0) opt = &o;
}
if (opt) break;
}
if (!opt) {
std::cout << "Unrecognised argument: '" << arg << "'" << std::endl;
continue;
}
// read value
bool has_value = opt->_mnemonics[0][0] == '-';
if (!has_value) {
_values.push_back(ArgValue(opt, ""));
} else if (i + 1 < argc) {
++i;
auto val = argv[i];
_values.push_back(ArgValue(opt, std::string(val)));
} else {
std::cout << "Expected value for: '" << opt->_name << "'" << std::endl;
continue;
}
// ArgValue& val = _values.back();
// std::cout << "Arg [" << val.first->_name << "] '" << val.second << "'"
// << std::endl;
}
auto only_help = has_arg("help");
if (only_help) {
print_help();
return false;
}
// check required args - all should be provided
for (auto& o : _options) {
if (!o._required) continue;
bool provided = false;
for (auto& val : _values) {
if (val.first == &o) provided |= true;
}
if (!provided) {
char buf[255];
snprintf(buf, 255, "Value not provided for argument: '%s'",
o._name.c_str());
throw std::runtime_error(buf);
}
}
return true;
}
void print_argument(std::ostream& os, ArgOption& opt) {
// print mnemonics
// bool has_value = opt._name.compare(0, 2, "--") == 0;
bool has_value = opt._mnemonics[0][0] == '-';
std::string name_upper = opt._name;
for (auto& c : name_upper) c = toupper(c);
for (size_t i = 0; i < opt._mnemonics.size(); i++) {
auto& mnemonic = opt._mnemonics[i];
os << " " << mnemonic;
if (has_value) os << " " << name_upper;
if (i != opt._mnemonics.size() - 1) os << ", ";
}
// print help
os << std::endl
<< " " // this makes things easier
<< opt._help;
}
void Argparse::print_help() {
std::ostream& os = std::cout;
os << _exec_name;
// print args line
for (auto& opt : _options) {
os << " ";
if (!opt._required) os << "[";
// if (!opt._name.empty())
// os << opt._name;
// else
// os << opt._mnemonics[0];
os << opt._mnemonics.back();
if (!opt._required) os << "]";
}
// print description
os << std::endl
<< std::endl
<< _general_help << std::endl
<< std::endl;
// arguments
os << "arguments:" << std::endl;
for (auto& opt : _options) {
print_argument(os, opt);
os << std::endl;
}
}
Argparse::ArgValue* Argparse::get_value(const char* arg_name) {
Argparse::ArgValue* v = nullptr;
for (auto& val : _values) {
if (val.first->_name.compare(arg_name) == 0) {
v = &val;
break;
}
}
return v;
}
bool Argparse::has_arg(const char* arg_name) {
return get_value(arg_name) != nullptr;
}
const char* Argparse::value(const char* arg_name) {
auto v = get_value(arg_name);
return v != nullptr ? v->second.c_str() : nullptr;
}
void Argparse::value(const char* arg_name, size_t& val) {
auto v = get_value(arg_name);
if (!v) return;
val = atoi(v->second.c_str()); // ignore value overflow..
}
//
}
}