Brush C++ API
A flexible interpretable machine learning framework
Loading...
Searching...
No Matches
utils.h
Go to the documentation of this file.
1/* Brush
2copyright 2020 William La Cava
3license: GNU/GPL v3
4*/
5
6#ifndef UTILS_H
7#define UTILS_H
8
9#include <Eigen/Dense>
10#include <vector>
11#include <set>
12#include <fstream>
13#include <chrono>
14#include <ostream>
15#include <map>
16#include "../init.h"
17#include "error.h"
18#include <typeindex>
19#include <iterator> // needed for std::ostram_iterator
20// #include <execution> // parallel policies
21
22using namespace Eigen;
23using namespace std;
24
29
30// serializing vector of shared ptr: https://github.com/nlohmann/json/discussions/2377
31// (used in population.h, which has a shared_ptr vector)
32namespace nlohmann
33{
34template <typename T>
35struct adl_serializer<std::shared_ptr<T>>
36{
37 static void to_json(json& j, const std::shared_ptr<T>& opt)
38 {
39 if (opt)
40 {
41 j = *opt;
42 }
43 else
44 {
45 j = nullptr;
46 }
47 }
48
49 static void from_json(const json& j, std::shared_ptr<T>& opt)
50 {
51 if (j.is_null())
52 {
53 opt = nullptr;
54 }
55 else
56 {
57 opt.reset(new T(j.get<T>()));
58 }
59 }
60};
61}
62
63// to overload operators and compare our individuals, we need to be able to
64// serialize vectors.
65// this is intended to be used with DEAP (so our brush individuals
66// can be hashed and compared to each other in python side)
67template <>
68struct std::hash<std::vector<float>> {
69 std::size_t operator()(const std::vector<float>& v) const {
70 std::size_t seed = v.size();
71 for (const auto& elem : v) {
72 seed ^= std::hash<float>{}(elem) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
73 }
74 return seed;
75 }
76};
77
78
79// namespace std
80// {
81// /**
82// * @brief A std::hash specialization for tuples.
83// *
84// * See
85// *
86// * @tparam TTypes
87// */
88// template<typename... TTypes>
89// class hash<std::tuple<TTypes...>>
90// {
91// private:
92// typedef std::tuple<TTypes...> Tuple;
93
94// template<int N>
95// size_t operator()(Tuple value) const { return 0; }
96
97// template<int N, typename THead, typename... TTail>
98// size_t operator()(Tuple value) const
99// {
100// constexpr int Index = N - sizeof...(TTail) - 1;
101// return hash<THead>()(std::get<Index>(value)) ^ operator()<N, TTail...>(value);
102// }
103
104// public:
105// size_t operator()(Tuple value) const
106// {
107// return operator()<sizeof...(TTypes), TTypes...>(value);
108// }
109// };
110// }
111
112#include <tuple>
113namespace std{
114 namespace
115 {
116
117 // Code from boost
118 // Reciprocal of the golden ratio helps spread entropy
119 // and handles duplicates.
120 // See Mike Seymour in magic-numbers-in-boosthash-combine:
121 // http://stackoverflow.com/questions/4948780
122
123 template <class T>
124 inline void hash_combine(std::size_t& seed, T const& v)
125 {
126 seed ^= std::hash<T>()(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
127 }
128
129 // Recursive template code derived from Matthieu M.
130 template <class Tuple, size_t Index = std::tuple_size<Tuple>::value - 1>
131 struct HashValueImpl
132 {
133 static void apply(size_t& seed, Tuple const& tuple)
134 {
135 HashValueImpl<Tuple, Index-1>::apply(seed, tuple);
136 hash_combine(seed, std::get<Index>(tuple));
137 }
138 };
139
140 template <class Tuple>
141 struct HashValueImpl<Tuple,0>
142 {
143 static void apply(size_t& seed, Tuple const& tuple)
144 {
145 hash_combine(seed, std::get<0>(tuple));
146 }
147 };
148 }
149
150 template <typename ... TT>
151 struct hash<std::tuple<TT...>>
152 {
153 size_t
154 operator()(std::tuple<TT...> const& tt) const
155 {
156 size_t seed = 0;
157 HashValueImpl<std::tuple<TT...> >::apply(seed, tt);
158 return seed;
159 }
160
161 };
162}
163
164namespace Brush{
165namespace Util{
166
167extern string PBSTR;
168
169extern int PBWIDTH;
170
171// tuple hash
172// https://stackoverflow.com/questions/15103975/my-stdhash-for-stdtuples-any-improvements
173
174template<typename T>
175using TypeMap = std::map<std::type_index, T>;
177// enum class TYPES; // int;
178// extern TypeMap<TYPES> type_enum;
179// using TypeMap = std::unordered_map<TypeInfoPtr, T, Hasher, EqualTo>;
181void clean(ArrayXf& x);
182
183std::string ltrim(std::string str, const std::string& chars = "\t\n\v\f\r ");
184
185std::string rtrim(std::string str, const std::string& chars = "\t\n\v\f\r ");
186
187std::string trim(std::string str, const std::string& chars = "\t\n\v\f\r ");
188
190template<typename V, typename T>
191// template<template<class> class C, class T>
192bool in(const V& v, const T& i)
193{
194 return std::find(v.begin(), v.end(), i) != v.end();
195}
196
198// float median(const ArrayXf& v);
200// float median(const Eigen::Ref<const ArrayXf>& v);
201template<typename T, typename Scalar=T::Scalar>
202Scalar median(const T& v)
203{
204 // instantiate a vector
205 vector<Scalar> x(v.size());
206 x.assign(v.data(),v.data()+v.size());
207 // middle element
208 size_t n = x.size()/2;
209 // sort nth element of array
210 nth_element(x.begin(),x.begin()+n,x.end());
211 // if evenly sized, return average of middle two elements
212 if (x.size() % 2 == 0) {
213 nth_element(x.begin(),x.begin()+n-1,x.end());
214 return (x[n] + x[n-1]) / Scalar(2);
215 }
216 // otherwise return middle element
217 else
218 return x[n];
219};
220
222float variance(const ArrayXf& v, float mean);
223
225float variance(const ArrayXf& v);
226
228float skew(const ArrayXf& v);
229
231float kurtosis(const ArrayXf& v);
232
234float covariance(const ArrayXf& x, const ArrayXf& y);
235
237float slope(const ArrayXf& x, const ArrayXf& y);
238
240float pearson_correlation(const ArrayXf& x, const ArrayXf& y);
241
243float mad(const ArrayXf& x);
244
246template <typename T>
247vector<size_t> argsort(const vector<T> &v, bool ascending=true)
248{
249 // initialize original index locations
250 vector<size_t> idx(v.size());
251 std::iota(idx.begin(), idx.end(), 0);
252
253 // sort indexes based on comparing values in v
254 if (ascending)
255 {
256 sort(idx.begin(), idx.end(),
257 [&v](size_t i1, size_t i2) {return v[i1] < v[i2];});
258 }
259 else
260 {
261 sort(idx.begin(), idx.end(),
262 [&v](size_t i1, size_t i2) {return v[i1] > v[i2];});
263 }
264
265 return idx;
266}
267
269class Timer
270{
271 typedef std::chrono::high_resolution_clock high_resolution_clock;
272
273 typedef std::chrono::seconds seconds;
274
275 public:
276 explicit Timer(bool run = false);
277
278 void Reset();
279
280 std::chrono::duration<float> Elapsed() const;
281
282 template <typename T, typename Traits>
283 friend std::basic_ostream<T, Traits>& operator<<(std::basic_ostream<T, Traits>& out,
284 const Timer& timer)
285 {
286 return out << timer.Elapsed().count();
287 }
288
289 private:
290 high_resolution_clock::time_point _start;
291
292};
293
295template <typename T>
296vector<T> softmax(const vector<T>& w)
297{
298 int x;
299 T sum = 0;
300 vector<T> w_new;
301
302 for(x = 0; x < w.size(); ++x)
303 sum += exp(w[x]);
304
305 for(x = 0; x < w.size(); ++x)
306 w_new.push_back(exp(w[x])/sum);
307
308 return w_new;
309}
310
313{
314 Normalizer(bool sa=true): scale_all(sa) {};
315 vector<float> scale;
316 vector<float> offset;
317 vector<char> dtypes;
319
321 void fit(MatrixXf& X, const vector<char>& dt);
322
324 void normalize(MatrixXf& X);
325
326 void fit_normalize(MatrixXf& X, const vector<char>& dtypes);
327};
328
330vector<type_index> get_dtypes(MatrixXf &X);
331
333template <typename T>
334vector<T> unique(vector<T> w)
335{
336 std::sort(w.begin(),w.end());
337 typename vector<T>::iterator it;
338 it = std::unique(w.begin(),w.end());
339 w.resize(std::distance(w.begin(), it));
340 return w;
341}
342
344template <typename T>
345vector<T> unique(Matrix<T, -1, -1> w)
346{
347 vector<T> wv( w.data(), w.data()+w.size());
348 return unique(wv);
349}
350
352template <typename T>
353vector<T> unique(Matrix<T, -1, 1> w)
354{
355 vector<T> wv( w.data(), w.data()+w.size());
356 return unique(wv);
357}
358
360template <typename T>
361vector<T> unique(Array<T, -1, 1> w)
362{
363 vector<T> wv( w.data(), w.data()+w.rows()*w.cols());
364 return unique(wv);
365}
366
368template <typename T>
369string to_string(const T& value)
370{
371 std::stringstream ss;
372 ss << value;
373 return ss.str();
374}
375
376std::string ReplaceString(std::string subject, const std::string& search,
377 const std::string& replace);
378
380void ReplaceStringInPlace(std::string& subject, const std::string& search,
381 const std::string& replace);
382
383
384
386float condition_number(const MatrixXf& X);
387
389MatrixXf corrcoef(const MatrixXf& X);
390
391// returns the mean of the pairwise correlations of a matrix.
392float mean_square_corrcoef(const MatrixXf& X);
393
395int argmiddle(vector<float>& v);
396
398{
399 vector<int> generation;
400 vector<float> time;
401
402 vector<float> best_score;
403 vector<float> best_score_v;
404 vector<float> med_score;
405 vector<float> med_score_v;
406
407 vector<unsigned> med_size;
408 vector<unsigned> med_complexity;
409 vector<unsigned> max_size;
410 vector<unsigned> max_complexity;
411
412 // Keep stats vectors non-empty so .back() calls are always safe for logging/printing.
414 : generation{0},
415 time{0.0f},
416 best_score{0.0f},
417 best_score_v{0.0f},
418 med_score{0.0f},
419 med_score_v{0.0f},
420 med_size{0},
422 max_size{0},
424 {}
425
426 void update(int index,
427 float timer_count,
428
429 float bst_score,
430 float bst_score_v,
431 float md_score,
432 float md_score_v,
433
434 unsigned md_size,
435 unsigned md_complexity,
436 unsigned mx_size,
437 unsigned mx_complexity
438 );
439};
440
441typedef struct Log_Stats Log_stats;
442
444 generation,
445 time,
446
447 best_score,
448 best_score_v,
449 med_score,
450 med_score_v,
451
452 med_size,
453 med_complexity,
454 max_size,
455 max_complexity
456);
457
459template<typename T>
460std::enable_if_t<std::is_scalar_v<T>, T>
462{
463 if (isnan(x))
464 return 0;
465 else if (x > MAX_FLT)
466 return MAX_FLT;
467 else if (x < MIN_FLT)
468 return MIN_FLT;
469
470 return x;
471};
472
473template<typename T>
474std::enable_if_t<std::is_base_of_v<Eigen::ArrayBase<T>, T>, T>
476{
477 x = (isnan(x)).select(0,x);
478 x = (x < MIN_FLT).select(MIN_FLT,x);
479 x = (x > MAX_FLT).select(MAX_FLT,x);
480 return x;
481};
482
483template<typename T>
484void reorder(vector<T> &v, vector<int> const &order )
485{
486 for ( int s = 1; s < order.size(); ++ s )
487 {
488 for ( int d = order[s]; d < s; d = order[d] )
489 {
490 if ( d == s )
491 {
492 while ( d = order[d], d != s )
493 swap( v[s], v[d] );
494 }
495 }
496 }
497};
498
499
501vector<size_t> mask_to_index(const ArrayXb& mask);
503tuple<vector<size_t>,vector<size_t>> mask_to_indices(const ArrayXb& mask);
504
505// /// cast a float array to bool or integer if its values comply
506// auto typecast(ArrayXf& x);
507
509template<typename T>
510array<Array<T,-1, 1>, 2> split(const Array<T,-1,1>& v, const ArrayXb& mask)
511// array<DenseBase<T>, 2> split(const DenseBase<T>& v, const ArrayXb& mask)
512{
513 int size1 = mask.count();
514 int size2 = mask.size() - size1;
515 Array<T,-1,1> L(size1), R(size2);
516 // DenseBase<T> L(size1), R(size2);
517
518 int idx1 = 0, idx2 = 0;
519 for (int i = 0; i < mask.size(); ++i)
520 {
521 if (mask(i))
522 {
523 L(idx1) = v(i);
524 ++idx1;
525 }
526 else
527 {
528 R(idx2) = v(i);
529 ++idx2;
530 }
531 }
532 return { L, R };
533};
534
536template<std::ranges::range T>
537void print(T t)
538{
539 /* auto out = fmt::memory_buffer(); */
540 /* vector<char> out; */
541 /* std::for_each(first, last, [&](const auto& i){fmt::format_to(std::back_inserter(out), "{}",i);}); */
542 /* fmt::print(to_string(out)); */
543 fmt::print("{}",t);
544}
545
546
547// /*
548// *
549// * Convert Eigen::Tensor --> Eigen::Matrix
550// *
551// */
552
553
554// // Evaluates tensor expressions if needed
555// template<typename T, typename Device = Eigen::DefaultDevice>
556// auto asEval(const Eigen::TensorBase<T, Eigen::ReadOnlyAccessors> &expr, // An Eigen::TensorBase object (Tensor, TensorMap, TensorExpr... )
557// const Device & device = Device() // Override to evaluate on another device, e.g. thread pool or gpu.
558// ) {
559// using Evaluator = Eigen::TensorEvaluator<const Eigen::TensorForcedEvalOp<const T>, Device>;
560// Eigen::TensorForcedEvalOp<const T> eval = expr.eval();
561// Evaluator tensor(eval, device);
562// tensor.evalSubExprsIfNeeded(nullptr);
563// return tensor;
564// }
565
566// // Converts any Eigen::Tensor (or expression) to an Eigen::Matrix with shape rows/cols
567// template<typename T, typename sizeType, typename Device = Eigen::DefaultDevice>
568// auto MatrixCast(const Eigen::TensorBase<T, Eigen::ReadOnlyAccessors> &expr, const sizeType rows, const sizeType cols, const Device &device = Device()) {
569// auto tensor = asEval(expr, device);
570// using Scalar = typename Eigen::internal::remove_const<typename decltype(tensor)::Scalar>::type;
571// return static_cast<MatrixType<Scalar>>(Eigen::Map<const MatrixType<Scalar>>(tensor.data(), rows, cols));
572// }
573
574// // Converts any Eigen::Tensor (or expression) to an Eigen::Vector with the same size
575// template<typename T, typename Device = Eigen::DefaultDevice>
576// auto VectorCast(const Eigen::TensorBase<T, Eigen::ReadOnlyAccessors> &expr, const Device &device = Device()) {
577// auto tensor = asEval(expr, device);
578// auto size = Eigen::internal::array_prod(tensor.dimensions());
579// using Scalar = typename Eigen::internal::remove_const<typename decltype(tensor)::Scalar>::type;
580// return static_cast<VectorType<Scalar>>(Eigen::Map<const VectorType<Scalar>>(tensor.data(), size));
581// }
582
583// // View an existing Eigen::Tensor as an Eigen::Map<Eigen::Matrix>
584// template<typename Scalar, auto rank, typename sizeType>
585// auto MatrixMap(const Eigen::Tensor<Scalar, rank> &tensor, const sizeType rows, const sizeType cols) {
586// return Eigen::Map<const MatrixType<Scalar>>(tensor.data(), rows, cols);
587// }
588
589// // View an existing Eigen::Tensor of rank 2 as an Eigen::Map<Eigen::Matrix>
590// // Rows/Cols are determined from the matrix
591// template<typename Scalar>
592// auto MatrixMap(const Eigen::Tensor<Scalar, 2> &tensor) {
593// return Eigen::Map<const MatrixType<Scalar>>(tensor.data(), tensor.dimension(0), tensor.dimension(1));
594// }
595
596// // View an existing Eigen::Tensor of rank 1 as an Eigen::Map<Eigen::Vector>
597// // Rows is the same as the size of the tensor.
598// template<typename Scalar, auto rank>
599// auto VectorMap(const Eigen::Tensor<Scalar, rank> &tensor) {
600// return Eigen::Map<const VectorType<Scalar>>(tensor.data(), tensor.size());
601// }
602
603
604// /*
605// *
606// * Convert Eigen::Matrix --> Eigen::Tensor
607// *
608// * example usage:
609// *
610// * Eigen::Tensor<double,4> my_rank4 (2,2,2,2);
611// * my_rank4.setRandom();
612// *
613// * Eigen::MatrixXd mymatrix = MatrixCast(my_rank4, 4,4); // Cast Eigen::Tensor --> Eigen::Matrix
614// * Eigen::Tensor<double,3> my_rank3 = TensorCast(mymatrix, 2,2,4); // Cast Eigen::Matrix --> Eigen::Tensor
615// */
616
617
618// // Converts an Eigen::Matrix (or expression) to Eigen::Tensor
619// // with dimensions specified in std::array
620// template<typename Derived, typename T, auto rank>
621// Eigen::Tensor<typename Derived::Scalar, rank>
622// TensorCast(const Eigen::EigenBase<Derived> &matrix, const std::array<T, rank> &dims) {
623// return Eigen::TensorMap<const Eigen::Tensor<const typename Derived::Scalar, rank>>
624// (matrix.derived().eval().data(), dims);
625// }
626
627// // Converts an Eigen::Matrix (or expression) to Eigen::Tensor
628// // with dimensions specified in Eigen::DSizes
629// template<typename Derived, typename T, auto rank>
630// Eigen::Tensor<typename Derived::Scalar, rank>
631// TensorCast(const Eigen::EigenBase<Derived> &matrix, const Eigen::DSizes<T, rank> &dims) {
632// return Eigen::TensorMap<const Eigen::Tensor<const typename Derived::Scalar, rank>>
633// (matrix.derived().eval().data(), dims);
634// }
635
636// // Converts an Eigen::Matrix (or expression) to Eigen::Tensor
637// // with dimensions as variadic arguments
638// template<typename Derived, typename... Dims>
639// auto TensorCast(const Eigen::EigenBase<Derived> &matrix, const Dims... dims) {
640// static_assert(sizeof...(Dims) > 0, "TensorCast: sizeof... (Dims) must be larger than 0");
641// return TensorCast(matrix, std::array<Eigen::Index, sizeof...(Dims)>{dims...});
642// }
643
644// // Converts an Eigen::Matrix (or expression) to Eigen::Tensor
645// // with dimensions directly as arguments in a variadic template
646// template<typename Derived>
647// auto TensorCast(const Eigen::EigenBase<Derived> &matrix) {
648// if constexpr(Derived::ColsAtCompileTime == 1 or Derived::RowsAtCompileTime == 1) {
649// return TensorCast(matrix, matrix.size());
650// } else {
651// return TensorCast(matrix, matrix.rows(), matrix.cols());
652// }
653// }
654
655// // View an existing Eigen::Matrix as Eigen::TensorMap
656// // with dimensions specified in std::array
657// template<typename Derived, auto rank>
658// auto TensorMap(const Eigen::PlainObjectBase<Derived> &matrix, const std::array<long, rank> &dims) {
659// return Eigen::TensorMap<const Eigen::Tensor<const typename Derived::Scalar, rank>>(matrix.derived().data(), dims);
660// }
661
662// // View an existing Eigen::Matrix as Eigen::TensorMap
663// // with dimensions as variadic arguments
664// template<typename Derived, typename... Dims>
665// auto TensorMap(const Eigen::PlainObjectBase<Derived> &matrix, const Dims... dims) {
666// return TensorMap(matrix, std::array<long, static_cast<int>(sizeof...(Dims))>{dims...});
667// }
668
669// // View an existing Eigen::Matrix as Eigen::TensorMap
670// // with dimensions determined automatically from the given matrix
671// template<typename Derived>
672// auto TensorMap(const Eigen::PlainObjectBase<Derived> &matrix) {
673// if constexpr(Derived::ColsAtCompileTime == 1 or Derived::RowsAtCompileTime == 1) {
674// return TensorMap(matrix, matrix.size());
675// } else {
676// return TensorMap(matrix, matrix.rows(), matrix.cols());
677// }
678// }
679
683template <class Vector, class T>
684void unique_insert(Vector& v, const T& t)
685{
686 typename Vector::iterator i = std::lower_bound(v.begin(), v.end(), t);
687 if (i == v.end() || t < *i)
688 v.insert(i, t);
689}
690
691// tupleize a vector.
692// https://stackoverflow.com/questions/28410697/c-convert-vector-to-tuple
693template <typename T, std::size_t... Indices>
694auto vectorToTupleHelper(const std::vector<T>& v, std::index_sequence<Indices...>) {
695 return std::make_tuple(v[Indices]...);
696}
697
698template <std::size_t N, typename T>
699auto vectorToTuple(const std::vector<T>& v) {
700 assert(v.size() >= N);
701 return vectorToTupleHelper(v, std::make_index_sequence<N>());
702}
703
704// template<typename R, typename Arg, typename... Args>
705// R apply(const std::function<R(Args...)>& f, const vector<Arg>& inputs)
706// {
707// R output;
708// switch (inputs.size())
709// {
710// case 1:
711// std::transform(
712// std::execution::par_unseq,
713// inputs.at(0).begin(),
714// inputs.at(0).end(),
715// output.begin(),
716// f
717// );
718// break;
719// case 2:
720// std::transform(
721// std::execution::par_unseq,
722// inputs.at(0).begin(),
723// inputs.at(0).end(),
724// inputs.at(1).begin(),
725// // inputs.at(1).end(),
726// output.begin(),
727// f
728// );
729// break;
730// default:
731// HANDLE_ERROR_THROW("Wrong number of inputs for operator");
732// break;
733
734// };
735
736// return output;
737// };
738
739template<class T, class U>
740std::vector<T> slice(const vector<T>& v, const U& idx)
741{
742 vector<T> result;
743 for (const auto& i : idx)
744 {
745 result.push_back(v.at(i));
746 }
747 return result;
748}
749
751template<typename K, typename V>
752static map<V, K> reverse_map(const map<K, V>& m) {
753 map<V, K> r;
754 for (const auto& kv : m)
755 r[kv.second] = kv.first;
756 return r;
757};
758
759template<typename T>
760ostream &operator<<( ostream &os, const vector<T>& v )
761{
762 int j = 1;
763 size_t len = v.size();
764 for (const auto& i : v)
765 {
766 os << i ;
767 if (j != len)
768 os << ", ";
769 }
770 os << endl;
771
772 return os;
773};
774
775
776// template<typename VariantType, typename T, std::size_t index = 0>
777// constexpr std::size_t variant_index() {
778// static_assert(std::variant_size_v<VariantType> > index,
779// "Type not found in variant");
780// if constexpr (index == std::variant_size_v<VariantType>) {
781// return index;
782// } else if constexpr (std::is_same_v<std::variant_alternative_t<index, VariantType>, T>) {
783// return index;
784// } else {
785// return variant_index<VariantType, T, index + 1>();
786// }
787// }
788
789
790} // Util
791} // Brush
792#endif
std::chrono::duration< float > Elapsed() const
Definition utils.cpp:94
Timer(bool run=false)
Definition utils.cpp:85
std::chrono::seconds seconds
Definition utils.h:273
std::chrono::high_resolution_clock high_resolution_clock
Definition utils.h:271
friend std::basic_ostream< T, Traits > & operator<<(std::basic_ostream< T, Traits > &out, const Timer &timer)
Definition utils.h:283
high_resolution_clock::time_point _start
Definition utils.h:290
STL iterator class.
static float MAX_FLT
Definition init.h:61
static float MIN_FLT
Definition init.h:62
namespace containing various utility functions
Definition error.cpp:11
float mean_square_corrcoef(const MatrixXf &X)
Definition utils.cpp:219
std::string ReplaceString(std::string subject, const std::string &search, const std::string &replace)
find and replace string
Definition utils.cpp:387
void print(T t)
prints comma delimited container contents.
Definition utils.h:537
static map< V, K > reverse_map(const map< K, V > &m)
Given a map from keys to values, creates a new map from values to keys.
Definition utils.h:752
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Log_Stats, generation, time, best_score, best_score_v, med_score, med_score_v, med_size, med_complexity, max_size, max_complexity)
MatrixXf corrcoef(const MatrixXf &X)
returns the pearson correlation coefficients of matrix.
Definition utils.cpp:200
vector< type_index > get_dtypes(MatrixXf &X)
calculates data types for each column of X
Definition utils.cpp:41
void reorder(vector< T > &v, vector< int > const &order)
Definition utils.h:484
float slope(const ArrayXf &x, const ArrayXf &y)
slope of x/y
Definition utils.cpp:359
float mad(const ArrayXf &x)
median absolute deviation
Definition utils.cpp:373
float condition_number(const MatrixXf &X)
returns true for elements of x that are infinite
Definition utils.cpp:172
std::string ltrim(std::string str, const std::string &chars)
Definition utils.cpp:24
vector< size_t > argsort(const vector< T > &v, bool ascending=true)
return indices that sort a vector
Definition utils.h:247
float skew(const ArrayXf &v)
calculate skew
Definition utils.cpp:323
float pearson_correlation(const ArrayXf &x, const ArrayXf &y)
the normalized covariance of x and y
Definition utils.cpp:366
tuple< vector< size_t >, vector< size_t > > mask_to_indices(const ArrayXb &mask)
returns 2 indices: first where mask is true, and second where mask is false.
Definition utils.cpp:421
vector< T > softmax(const vector< T > &w)
return the softmax transformation of a vector.
Definition utils.h:296
Scalar median(const T &v)
calculate median
Definition utils.h:202
void clean(ArrayXf &x)
limits node output to be between MIN_FLT and MAX_FLT
Definition utils.cpp:17
float kurtosis(const ArrayXf &v)
calculate kurtosis
Definition utils.cpp:335
TypeMap< std::string > type_names
Definition utils.cpp:281
std::enable_if_t< std::is_scalar_v< T >, T > limited(T x)
limits the output to finite real numbers
Definition utils.h:461
auto vectorToTupleHelper(const std::vector< T > &v, std::index_sequence< Indices... >)
Definition utils.h:694
auto vectorToTuple(const std::vector< T > &v)
Definition utils.h:699
std::string rtrim(std::string str, const std::string &chars)
Definition utils.cpp:30
struct Log_Stats Log_stats
Definition utils.h:441
array< Array< T,-1, 1 >, 2 > split(const Array< T,-1, 1 > &v, const ArrayXb &mask)
split Eigen matrix or array into two by mask
Definition utils.h:510
string to_string(const T &value)
template function to convert objects to string for logging
Definition utils.h:369
void ReplaceStringInPlace(std::string &subject, const std::string &search, const std::string &replace)
string find and replace in place
Definition utils.cpp:398
bool in(const V &v, const T &i)
check if element is in vector.
Definition utils.h:192
vector< T > unique(vector< T > w)
returns unique elements in vector
Definition utils.h:334
std::vector< T > slice(const vector< T > &v, const U &idx)
Definition utils.h:740
void unique_insert(Vector &v, const T &t)
unique insertion into a vector. allows a vector to be used like a set. source: http://www....
Definition utils.h:684
std::string trim(std::string str, const std::string &chars)
Definition utils.cpp:36
float variance(const ArrayXf &v)
calculate variance
Definition utils.cpp:317
std::map< std::type_index, T > TypeMap
Definition utils.h:175
float covariance(const ArrayXf &x, const ArrayXf &y)
covariance of x and y
Definition utils.cpp:346
static Rnd & r
Definition rnd.h:176
ostream & operator<<(ostream &os, const vector< T > &v)
Definition utils.h:760
string PBSTR
Definition utils.cpp:13
int argmiddle(vector< float > &v)
returns the (first) index of the element with the middlest value in v
Definition utils.cpp:300
vector< size_t > mask_to_index(const ArrayXb &mask)
convert a boolean mask to an index array
Definition utils.cpp:409
int PBWIDTH
Definition utils.cpp:14
< nsga2 selection operator for getting the front
Definition bandit.cpp:4
Eigen::Array< bool, Eigen::Dynamic, 1 > ArrayXb
Definition types.h:39
STL namespace.
vector< unsigned > max_size
Definition utils.h:409
void update(int index, float timer_count, float bst_score, float bst_score_v, float md_score, float md_score_v, unsigned md_size, unsigned md_complexity, unsigned mx_size, unsigned mx_complexity)
Definition utils.cpp:227
vector< unsigned > max_complexity
Definition utils.h:410
vector< float > med_score_v
Definition utils.h:405
vector< unsigned > med_size
Definition utils.h:407
vector< float > med_score
Definition utils.h:404
vector< float > best_score_v
Definition utils.h:403
vector< unsigned > med_complexity
Definition utils.h:408
vector< float > best_score
Definition utils.h:402
vector< float > time
Definition utils.h:400
vector< int > generation
Definition utils.h:399
vector< float > offset
Definition utils.h:316
void fit(MatrixXf &X, const vector< char > &dt)
fit the scale and offset of data.
Definition utils.cpp:100
vector< char > dtypes
Definition utils.h:317
Normalizer(bool sa=true)
Definition utils.h:314
void fit_normalize(MatrixXf &X, const vector< char > &dtypes)
Definition utils.cpp:137
vector< float > scale
Definition utils.h:315
void normalize(MatrixXf &X)
normalize matrix.
Definition utils.cpp:117
static void to_json(json &j, const std::shared_ptr< T > &opt)
Definition utils.h:37
static void from_json(const json &j, std::shared_ptr< T > &opt)
Definition utils.h:49
size_t operator()(std::tuple< TT... > const &tt) const
Definition utils.h:154
std::size_t operator()(const std::vector< float > &v) const
Definition utils.h:69