common.h 14 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
2
3
4
#ifndef LIGHTGBM_UTILS_COMMON_FUN_H_
#define LIGHTGBM_UTILS_COMMON_FUN_H_

#include <LightGBM/utils/log.h>
5
#include <LightGBM/utils/openmp_wrapper.h>
Guolin Ke's avatar
Guolin Ke committed
6
7
8
9
10
11

#include <cstdio>
#include <string>
#include <vector>
#include <sstream>
#include <cstdint>
12
#include <algorithm>
13
#include <cmath>
Guolin Ke's avatar
Guolin Ke committed
14
#include <functional>
Guolin Ke's avatar
Guolin Ke committed
15
#include <memory>
16
#include <iterator>
Guolin Ke's avatar
Guolin Ke committed
17
#include <type_traits>
18
#include <iomanip>
Guolin Ke's avatar
Guolin Ke committed
19
20
21
22
23

namespace LightGBM {

namespace Common {

Guolin Ke's avatar
Guolin Ke committed
24
25
26
27
28
29
inline char tolower(char in) {
  if (in <= 'Z' && in >= 'A')
    return in - ('Z' - 'z');
  return in;
}

Guolin Ke's avatar
Guolin Ke committed
30
inline static std::string& Trim(std::string& str) {
Guolin Ke's avatar
Guolin Ke committed
31
  if (str.empty()) {
Guolin Ke's avatar
Guolin Ke committed
32
33
34
35
36
37
38
    return str;
  }
  str.erase(str.find_last_not_of(" \f\n\r\t\v") + 1);
  str.erase(0, str.find_first_not_of(" \f\n\r\t\v"));
  return str;
}

39
inline static std::string& RemoveQuotationSymbol(std::string& str) {
Guolin Ke's avatar
Guolin Ke committed
40
  if (str.empty()) {
41
42
43
44
45
46
    return str;
  }
  str.erase(str.find_last_not_of("'\"") + 1);
  str.erase(0, str.find_first_not_of("'\""));
  return str;
}
Guolin Ke's avatar
Guolin Ke committed
47
48
49
50
51
52
53
inline static bool StartsWith(const std::string& str, const std::string prefix) {
  if (str.substr(0, prefix.size()) == prefix) {
    return true;
  } else {
    return false;
  }
}
Guolin Ke's avatar
Guolin Ke committed
54
inline static std::vector<std::string> Split(const char* c_str, char delimiter) {
Guolin Ke's avatar
Guolin Ke committed
55
  std::vector<std::string> ret;
Guolin Ke's avatar
Guolin Ke committed
56
57
58
59
60
61
62
  std::string str(c_str);
  size_t i = 0;
  size_t pos = str.find(delimiter);
  while (pos != std::string::npos) {
    ret.push_back(str.substr(i, pos - i));
    i = ++pos;
    pos = str.find(delimiter, pos);
Guolin Ke's avatar
Guolin Ke committed
63
  }
Guolin Ke's avatar
Guolin Ke committed
64
  ret.push_back(str.substr(i));
Guolin Ke's avatar
Guolin Ke committed
65
66
67
  return ret;
}

Guolin Ke's avatar
Guolin Ke committed
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
inline static std::vector<std::string> Split(const char* c_str, const char* delimiters) {
  // will split when met any chars in delimiters
  std::vector<std::string> ret;
  std::string str(c_str);
  size_t i = 0;
  size_t pos = str.find_first_of(delimiters);
  while (pos != std::string::npos) {
    ret.push_back(str.substr(i, pos - i));
    i = ++pos;
    pos = str.find_first_of(delimiters, pos);
  }
  ret.push_back(str.substr(i));
  return ret;
}

83
84
85
86
87
88
inline static std::string FindFromLines(const std::vector<std::string>& lines, const char* key_word) {
  for (auto& line : lines) {
    size_t find_pos = line.find(key_word);
    if (find_pos != std::string::npos) {
      return line;
    }
89
  }
90
  return "";
91
92
}

Guolin Ke's avatar
Guolin Ke committed
93
94
95
96
97
98
99
100
101
inline static const char* Atoi(const char* p, int* out) {
  int sign, value;
  while (*p == ' ') {
    ++p;
  }
  sign = 1;
  if (*p == '-') {
    sign = -1;
    ++p;
102
  } else if (*p == '+') {
Guolin Ke's avatar
Guolin Ke committed
103
104
105
106
107
108
109
110
111
112
113
114
    ++p;
  }
  for (value = 0; *p >= '0' && *p <= '9'; ++p) {
    value = value * 10 + (*p - '0');
  }
  *out = sign * value;
  while (*p == ' ') {
    ++p;
  }
  return p;
}

115
inline static const char* Atof(const char* p, double* out) {
Guolin Ke's avatar
Guolin Ke committed
116
  int frac;
117
  double sign, value, scale;
Guolin Ke's avatar
Guolin Ke committed
118
  *out = 0;
Guolin Ke's avatar
Guolin Ke committed
119
120
121
122
123
124
  // Skip leading white space, if any.
  while (*p == ' ') {
    ++p;
  }

  // Get sign, if any.
125
  sign = 1.0;
Guolin Ke's avatar
Guolin Ke committed
126
  if (*p == '-') {
127
    sign = -1.0;
Guolin Ke's avatar
Guolin Ke committed
128
    ++p;
129
  } else if (*p == '+') {
Guolin Ke's avatar
Guolin Ke committed
130
131
132
    ++p;
  }

Guolin Ke's avatar
Guolin Ke committed
133
134
135
  // is a number
  if ((*p >= '0' && *p <= '9') || *p == '.' || *p == 'e' || *p == 'E') {
    // Get digits before decimal point or exponent, if any.
136
137
    for (value = 0.0; *p >= '0' && *p <= '9'; ++p) {
      value = value * 10.0 + (*p - '0');
Guolin Ke's avatar
Guolin Ke committed
138
    }
Guolin Ke's avatar
Guolin Ke committed
139

Guolin Ke's avatar
Guolin Ke committed
140
141
    // Get digits after decimal point, if any.
    if (*p == '.') {
142
      double pow10 = 10.0;
Guolin Ke's avatar
Guolin Ke committed
143
      ++p;
Guolin Ke's avatar
Guolin Ke committed
144
145
      while (*p >= '0' && *p <= '9') {
        value += (*p - '0') / pow10;
146
        pow10 *= 10.0;
Guolin Ke's avatar
Guolin Ke committed
147
148
        ++p;
      }
Guolin Ke's avatar
Guolin Ke committed
149
150
    }

Guolin Ke's avatar
Guolin Ke committed
151
152
    // Handle exponent, if any.
    frac = 0;
153
    scale = 1.0;
Guolin Ke's avatar
Guolin Ke committed
154
    if ((*p == 'e') || (*p == 'E')) {
Guolin Ke's avatar
Guolin Ke committed
155
      uint32_t expon;
Guolin Ke's avatar
Guolin Ke committed
156
      // Get sign of exponent, if any.
Guolin Ke's avatar
Guolin Ke committed
157
      ++p;
Guolin Ke's avatar
Guolin Ke committed
158
159
160
161
162
163
164
165
166
167
      if (*p == '-') {
        frac = 1;
        ++p;
      } else if (*p == '+') {
        ++p;
      }
      // Get digits of exponent, if any.
      for (expon = 0; *p >= '0' && *p <= '9'; ++p) {
        expon = expon * 10 + (*p - '0');
      }
168
169
170
      if (expon > 308) expon = 308;
      // Calculate scaling factor.
      while (expon >= 50) { scale *= 1E50; expon -= 50; }
Guolin Ke's avatar
Guolin Ke committed
171
      while (expon >= 8) { scale *= 1E8;  expon -= 8; }
172
      while (expon > 0) { scale *= 10.0; expon -= 1; }
Guolin Ke's avatar
Guolin Ke committed
173
    }
Guolin Ke's avatar
Guolin Ke committed
174
175
176
    // Return signed and scaled floating point result.
    *out = sign * (frac ? (value / scale) : (value * scale));
  } else {
177
    size_t cnt = 0;
178
    while (*(p + cnt) != '\0' && *(p + cnt) != ' '
179
180
      && *(p + cnt) != '\t' && *(p + cnt) != ','
      && *(p + cnt) != '\n' && *(p + cnt) != '\r'
181
      && *(p + cnt) != ':') {
182
183
      ++cnt;
    }
184
    if (cnt > 0) {
Guolin Ke's avatar
Guolin Ke committed
185
      std::string tmp_str(p, cnt);
Guolin Ke's avatar
Guolin Ke committed
186
      std::transform(tmp_str.begin(), tmp_str.end(), tmp_str.begin(), Common::tolower);
Guolin Ke's avatar
Guolin Ke committed
187
      if (tmp_str == std::string("na") || tmp_str == std::string("nan")) {
188
        *out = 0;
189
      } else if (tmp_str == std::string("inf") || tmp_str == std::string("infinity")) {
190
        *out = sign * 1e308;
191
      } else {
192
        Log::Fatal("Unknown token %s in data file", tmp_str.c_str());
Guolin Ke's avatar
Guolin Ke committed
193
194
      }
      p += cnt;
195
    }
Guolin Ke's avatar
Guolin Ke committed
196
  }
Guolin Ke's avatar
Guolin Ke committed
197

Guolin Ke's avatar
Guolin Ke committed
198
199
200
  while (*p == ' ') {
    ++p;
  }
Guolin Ke's avatar
Guolin Ke committed
201

Guolin Ke's avatar
Guolin Ke committed
202
203
204
  return p;
}

205
206


207
208
209
210
211
212
213
214
inline bool AtoiAndCheck(const char* p, int* out) {
  const char* after = Atoi(p, out);
  if (*after != '\0') {
    return false;
  }
  return true;
}

215
inline bool AtofAndCheck(const char* p, double* out) {
216
217
218
219
220
221
222
  const char* after = Atof(p, out);
  if (*after != '\0') {
    return false;
  }
  return true;
}

Guolin Ke's avatar
Guolin Ke committed
223
224
225
226
227
228
229
230
231
232
233
234
235
236
inline static const char* SkipSpaceAndTab(const char* p) {
  while (*p == ' ' || *p == '\t') {
    ++p;
  }
  return p;
}

inline static const char* SkipReturn(const char* p) {
  while (*p == '\n' || *p == '\r' || *p == ' ') {
    ++p;
  }
  return p;
}

Guolin Ke's avatar
Guolin Ke committed
237
238
239
240
241
template<typename T, typename T2>
inline static std::vector<T2> ArrayCast(const std::vector<T>& arr) {
  std::vector<T2> ret;
  for (size_t i = 0; i < arr.size(); ++i) {
    ret.push_back(static_cast<T2>(arr[i]));
Guolin Ke's avatar
Guolin Ke committed
242
  }
Guolin Ke's avatar
Guolin Ke committed
243
  return ret;
Guolin Ke's avatar
Guolin Ke committed
244
245
}

246
template<typename T>
Guolin Ke's avatar
Guolin Ke committed
247
inline static std::string ArrayToString(const std::vector<T>& arr, char delimiter) {
Guolin Ke's avatar
Guolin Ke committed
248
  if (arr.empty()) {
249
    return std::string("");
Guolin Ke's avatar
Guolin Ke committed
250
  }
251
  std::stringstream str_buf;
252
  str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2);
253
254
255
256
  str_buf << arr[0];
  for (size_t i = 1; i < arr.size(); ++i) {
    str_buf << delimiter;
    str_buf << arr[i];
Guolin Ke's avatar
Guolin Ke committed
257
  }
258
  return str_buf.str();
Guolin Ke's avatar
Guolin Ke committed
259
260
}

Guolin Ke's avatar
Guolin Ke committed
261
262
263
264
265
266
template<typename T>
inline static std::string ArrayToString(const std::vector<T>& arr, size_t n, char delimiter) {
  if (arr.empty() || n == 0) {
    return std::string("");
  }
  std::stringstream str_buf;
267
  str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2);
Guolin Ke's avatar
Guolin Ke committed
268
269
270
271
272
273
274
275
  str_buf << arr[0];
  for (size_t i = 1; i < std::min(n, arr.size()); ++i) {
    str_buf << delimiter;
    str_buf << arr[i];
  }
  return str_buf.str();
}

276
277
278
279
280
281
282
283
284
285
286
287
288
289
template<typename T, bool is_float>
struct __StringToTHelper {
  T operator()(const std::string& str) const {
    return static_cast<T>(std::stol(str));
  }
};

template<typename T>
struct __StringToTHelper<T, true> {
  T operator()(const std::string& str) const {
    return static_cast<T>(std::stod(str));
  }
};

Guolin Ke's avatar
Guolin Ke committed
290
291
template<typename T>
inline static std::vector<T> StringToArray(const std::string& str, char delimiter, size_t n) {
Guolin Ke's avatar
Guolin Ke committed
292
293
294
  if (n == 0) {
    return std::vector<T>();
  }
Guolin Ke's avatar
Guolin Ke committed
295
296
  std::vector<std::string> strs = Split(str.c_str(), delimiter);
  if (strs.size() != n) {
Guolin Ke's avatar
Guolin Ke committed
297
    Log::Fatal("StringToArray error, size doesn't match.");
Guolin Ke's avatar
Guolin Ke committed
298
  }
Guolin Ke's avatar
Guolin Ke committed
299
  std::vector<T> ret(n);
300
301
302
  __StringToTHelper<T, std::is_floating_point<T>::value> helper;
  for (size_t i = 0; i < n; ++i) {
    ret[i] = helper(strs[i]);
Guolin Ke's avatar
Guolin Ke committed
303
304
305
306
  }
  return ret;
}

Guolin Ke's avatar
Guolin Ke committed
307
308
template<typename T>
inline static std::vector<T> StringToArray(const std::string& str, char delimiter) {
Guolin Ke's avatar
Guolin Ke committed
309
  std::vector<std::string> strs = Split(str.c_str(), delimiter);
Guolin Ke's avatar
Guolin Ke committed
310
  std::vector<T> ret;
311
312
313
314
  ret.reserve(strs.size());
  __StringToTHelper<T, std::is_floating_point<T>::value> helper;
  for (const auto& s : strs) {
    ret.push_back(helper(s));
Guolin Ke's avatar
Guolin Ke committed
315
316
317
318
  }
  return ret;
}

319
template<typename T>
Guolin Ke's avatar
Guolin Ke committed
320
inline static std::string Join(const std::vector<T>& strs, const char* delimiter) {
Guolin Ke's avatar
Guolin Ke committed
321
  if (strs.empty()) {
Guolin Ke's avatar
Guolin Ke committed
322
323
    return std::string("");
  }
324
  std::stringstream str_buf;
325
  str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2);
326
  str_buf << strs[0];
Guolin Ke's avatar
Guolin Ke committed
327
  for (size_t i = 1; i < strs.size(); ++i) {
328
329
    str_buf << delimiter;
    str_buf << strs[i];
Guolin Ke's avatar
Guolin Ke committed
330
  }
331
  return str_buf.str();
Guolin Ke's avatar
Guolin Ke committed
332
333
}

334
template<typename T>
Guolin Ke's avatar
Guolin Ke committed
335
inline static std::string Join(const std::vector<T>& strs, size_t start, size_t end, const char* delimiter) {
Guolin Ke's avatar
Guolin Ke committed
336
337
338
  if (end - start <= 0) {
    return std::string("");
  }
Guolin Ke's avatar
Guolin Ke committed
339
340
  start = std::min(start, static_cast<size_t>(strs.size()) - 1);
  end = std::min(end, static_cast<size_t>(strs.size()));
341
  std::stringstream str_buf;
342
  str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2);
343
  str_buf << strs[start];
Guolin Ke's avatar
Guolin Ke committed
344
  for (size_t i = start + 1; i < end; ++i) {
345
346
    str_buf << delimiter;
    str_buf << strs[i];
Guolin Ke's avatar
Guolin Ke committed
347
  }
348
  return str_buf.str();
Guolin Ke's avatar
Guolin Ke committed
349
350
351
352
353
354
355
356
357
358
359
360
361
}

static inline int64_t Pow2RoundUp(int64_t x) {
  int64_t t = 1;
  for (int i = 0; i < 64; ++i) {
    if (t >= x) {
      return t;
    }
    t <<= 1;
  }
  return 0;
}

362
363
364
365
/*!
 * \brief Do inplace softmax transformaton on p_rec
 * \param p_rec The input/output vector of the values.
 */
366
367
368
inline void Softmax(std::vector<double>* p_rec) {
  std::vector<double> &rec = *p_rec;
  double wmax = rec[0];
369
370
371
  for (size_t i = 1; i < rec.size(); ++i) {
    wmax = std::max(rec[i], wmax);
  }
372
  double wsum = 0.0f;
373
374
375
376
377
  for (size_t i = 0; i < rec.size(); ++i) {
    rec[i] = std::exp(rec[i] - wmax);
    wsum += rec[i];
  }
  for (size_t i = 0; i < rec.size(); ++i) {
378
    rec[i] /= static_cast<double>(wsum);
379
380
381
  }
}

Guolin Ke's avatar
Guolin Ke committed
382
383
inline void Softmax(const double* input, double* output, int len) {
  double wmax = input[0];
384
  for (int i = 1; i < len; ++i) {
Guolin Ke's avatar
Guolin Ke committed
385
    wmax = std::max(input[i], wmax);
386
387
388
  }
  double wsum = 0.0f;
  for (int i = 0; i < len; ++i) {
Guolin Ke's avatar
Guolin Ke committed
389
390
    output[i] = std::exp(input[i] - wmax);
    wsum += output[i];
391
392
  }
  for (int i = 0; i < len; ++i) {
Guolin Ke's avatar
Guolin Ke committed
393
    output[i] /= static_cast<double>(wsum);
394
395
396
  }
}

Guolin Ke's avatar
Guolin Ke committed
397
398
399
400
401
template<typename T>
std::vector<const T*> ConstPtrInVectorWrapper(const std::vector<std::unique_ptr<T>>& input) {
  std::vector<const T*> ret;
  for (size_t i = 0; i < input.size(); ++i) {
    ret.push_back(input.at(i).get());
402
  }
Guolin Ke's avatar
Guolin Ke committed
403
  return ret;
404
405
}

Guolin Ke's avatar
Guolin Ke committed
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
template<typename T1, typename T2>
inline void SortForPair(std::vector<T1>& keys, std::vector<T2>& values, size_t start, bool is_reverse = false) {
  std::vector<std::pair<T1, T2>> arr;
  for (size_t i = start; i < keys.size(); ++i) {
    arr.emplace_back(keys[i], values[i]);
  }
  if (!is_reverse) {
    std::sort(arr.begin(), arr.end(), [](const std::pair<T1, T2>& a, const std::pair<T1, T2>& b) {
      return a.first < b.first;
    });
  } else {
    std::sort(arr.begin(), arr.end(), [](const std::pair<T1, T2>& a, const std::pair<T1, T2>& b) {
      return a.first > b.first;
    });
  }
  for (size_t i = start; i < arr.size(); ++i) {
    keys[i] = arr[i].first;
    values[i] = arr[i].second;
  }

}

428
429
430
431
432
/*
* approximate hessians of absolute loss with Gaussian function
* cf. https://en.wikipedia.org/wiki/Gaussian_function
*
* y is a prediction.
Tsukasa OMOTO's avatar
Tsukasa OMOTO committed
433
434
* t means true target.
* g means gradient.
435
* eta is a parameter to control the width of Gaussian function.
436
437
* w means weights.
*/
438
439
inline static double ApproximateHessianWithGaussian(const double y, const double t, const double g,
                                                    const double eta, const double w=1.0f) {
440
  const double diff = y - t;
Tsukasa OMOTO's avatar
Tsukasa OMOTO committed
441
442
443
  const double pi = 4.0 * std::atan(1.0);
  const double x = std::fabs(diff);
  const double a = 2.0 * std::fabs(g) * w;  // difference of two first derivatives, (zero to inf) and (zero to -inf).
444
  const double b = 0.0;
445
  const double c = std::max((std::fabs(y) + std::fabs(t)) * eta, 1.0e-10);
Tsukasa OMOTO's avatar
Tsukasa OMOTO committed
446
  return w * std::exp(-(x - b) * (x - b) / (2.0 * c * c)) * a / (c * std::sqrt(2 * pi));
447
448
}

449
template <typename T>
Guolin Ke's avatar
Guolin Ke committed
450
451
inline static std::vector<T*> Vector2Ptr(std::vector<std::vector<T>>& data) {
  std::vector<T*> ptr(data.size());
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
  for (size_t i = 0; i < data.size(); ++i) {
    ptr[i] = data[i].data();
  }
  return ptr;
}

template <typename T>
inline static std::vector<int> VectorSize(const std::vector<std::vector<T>>& data) {
  std::vector<int> ret(data.size());
  for (size_t i = 0; i < data.size(); ++i) {
    ret[i] = static_cast<int>(data[i].size());
  }
  return ret;
}

Guolin Ke's avatar
Guolin Ke committed
467
468
469
inline static double AvoidInf(double x) {
  if (x >= std::numeric_limits<double>::max()) {
    return std::numeric_limits<double>::max();
Guolin Ke's avatar
Guolin Ke committed
470
471
  } else if(x <= std::numeric_limits<double>::lowest()) {
    return std::numeric_limits<double>::lowest();
Guolin Ke's avatar
Guolin Ke committed
472
473
474
475
476
  } else {
    return x;
  }
}

477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
template<class _Iter> inline
static typename std::iterator_traits<_Iter>::value_type* IteratorValType(_Iter) {
  return (0);
}

template<class _RanIt, class _Pr, class _VTRanIt> inline
static void ParallelSort(_RanIt _First, _RanIt _Last, _Pr _Pred, _VTRanIt*) {
  size_t len = _Last - _First;
  const size_t kMinInnerLen = 1024;
  int num_threads = 1;
  #pragma omp parallel
  #pragma omp master
  {
    num_threads = omp_get_num_threads();
  }
  if (len <= kMinInnerLen || num_threads <= 1) {
    std::sort(_First, _Last, _Pred);
    return;
  }
  size_t inner_size = (len + num_threads - 1) / num_threads;
  inner_size = std::max(inner_size, kMinInnerLen);
  num_threads = static_cast<int>((len + inner_size - 1) / inner_size);
  #pragma omp parallel for schedule(static,1)
  for (int i = 0; i < num_threads; ++i) {
    size_t left = inner_size*i;
    size_t right = left + inner_size;
    right = std::min(right, len);
    if (right > left) {
      std::sort(_First + left, _First + right, _Pred);
    }
  }
  // Buffer for merge.
  std::vector<_VTRanIt> temp_buf(len);
  _RanIt buf = temp_buf.begin();
  int s = inner_size;
  // Recursive merge
  while (s < len) {
    int loop_size = static_cast<int>((len + s * 2 - 1) / (s * 2));
    #pragma omp parallel for schedule(static,1)
    for (int i = 0; i < loop_size; ++i) {
      size_t left = i * 2 * s;
      size_t mid = left + s;
      size_t right = mid + s;
      right = std::min(len, right);
      std::copy(_First + left, _First + mid, buf + left);
      std::merge(buf + left, buf + mid, _First + mid, _First + right, _First + left, _Pred);
    }
    s *= 2;
  }
}

template<class _RanIt, class _Pr> inline
static void ParallelSort(_RanIt _First, _RanIt _Last, _Pr _Pred) {
  return ParallelSort(_First, _Last, _Pred, IteratorValType(_First));
}

Guolin Ke's avatar
Guolin Ke committed
533
534
535
536
}  // namespace Common

}  // namespace LightGBM

Guolin Ke's avatar
Guolin Ke committed
537
#endif   // LightGBM_UTILS_COMMON_FUN_H_