bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
vector_math.h
Go to the documentation of this file.
1#ifndef BASIC_ARRAY_STATISTICS_H
2#define BASIC_ARRAY_STATISTICS_H
6
7#include "bitrl/base/bitrl_config.h"
11
12#include <algorithm>
13#include <cmath>
14#include <execution>
15#include <iostream>
16#include <iterator>
17#include <random>
18#include <stdexcept>
19
20#ifdef BITRL_DEBUG
21#include <cassert>
22#endif
23
24namespace bitrl
25{
26namespace maths
27{
28
29namespace detail_
30{
31
32template <typename T> struct randomize_handler;
33
34template <> struct randomize_handler<real_t>
35{
36 template <typename VecType> static void randomize_(VecType &v, real_t a, real_t b, uint_t seed);
37};
38
39template <typename VecType>
41{
42
43 std::mt19937 generator(seed);
44 std::uniform_real_distribution<real_t> distribution(a, b);
45
46 std::for_each(v.begin(), v.end(), [&](auto &val) { val = distribution(generator); });
47}
48
49template <> struct randomize_handler<float_t>
50{
51 template <typename VecType>
52 static void randomize_(VecType &v, float_t a, float_t b, uint_t seed);
53};
54
55template <typename VecType>
57{
58
59 std::mt19937 generator(seed);
60 std::uniform_real_distribution<float_t> distribution(a, b);
61
62 std::for_each(v.begin(), v.end(), [&](auto &val) { val = distribution(generator); });
63}
64} // namespace detail_
65
66template <utils::concepts::float_or_integral_vector VectorType>
67VectorType element_product(const VectorType &v1, const VectorType &v2)
68{
69
70 auto size1_ = v1.size();
71 auto size2_ = v2.size();
72
73 if (size1_ != size2_)
74 {
75 throw std::logic_error(
76 "Sizes not equal. Cannot compute element product of vectors with no equal sizes");
77 }
78
79 VectorType v_(v1.size(), 0);
80 for (uint_t i = 0; i < v1.size(); ++i)
81 {
82
83 v_[i] = v1[i] * v2[i];
84 }
85 return v_;
86}
87
88template <typename IteratorType>
89typename std::iterator_traits<IteratorType>::value_type sum(IteratorType begin, IteratorType end,
90 bool parallel = true)
91{
92
93 typedef typename std::iterator_traits<IteratorType>::value_type value_type;
94 value_type sum_ = value_type(0);
95
96 if (parallel)
97 {
98 sum_ = std::reduce(std::execution::par, begin, end, sum_);
99 }
100 else
101 {
102 sum_ = std::accumulate(begin, end, sum_);
103 }
104
105 return sum_;
106}
107
108template <typename VectorType>
109typename VectorType::value_type sum(const VectorType &vec, bool parallel = true)
110{
111 return sum(vec.begin(), vec.end(), parallel);
112}
113
118template <typename IteratorType>
119real_t mean(IteratorType begin, IteratorType end, bool parallel = true)
120{
121
122 auto sum_ = sum(begin, end, parallel);
123 return sum_ / static_cast<real_t>(std::distance(begin, end));
124}
125
130template <utils::concepts::float_or_integral_vector VectorType>
131real_t mean(const VectorType &vector, bool parallel = true)
132{
133 return mean(vector.begin(), vector.end(), parallel);
134}
135
139template <typename T> real_t mean(const DynVec<T> &vector, bool parallel = true)
140{
141 return mean(vector.begin(), vector.end(), parallel);
142}
143
144template <typename IteratorType>
145typename std::iterator_traits<IteratorType>::value_type
146variance(IteratorType begin, IteratorType end, bool parallel = true)
147{
148
149 typedef typename std::iterator_traits<IteratorType>::value_type value_type;
150 auto mean_val = mean(begin, end, parallel);
151 auto size = std::distance(begin, end);
152
153 std::vector<value_type> diff(size);
154 std::transform(begin, end, diff.begin(), [mean_val](value_type x) { return x - mean_val; });
155
156 value_type sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
157 return sq_sum / static_cast<value_type>(std::distance(begin, end));
158}
159
164inline real_t variance(const std::vector<real_t> &vals, bool parallel = true)
165{
166 return variance(vals.begin(), vals.end(), parallel);
167}
168
172std::vector<real_t> standardize(const std::vector<real_t> &vals,
174
181template <utils::concepts::float_vector Vec2> uint_t choice(const Vec2 &probs, uint_t seed = 42)
182{
183
184 std::mt19937 generator(seed);
185 std::discrete_distribution<int> distribution(probs.begin(), probs.end());
186 return distribution(generator);
187}
188
195template <utils::concepts::integral_vector Vec1, utils::concepts::float_vector Vec2>
196uint_t choice(const Vec1 &choices, const Vec2 &probs, uint_t seed = 42)
197{
198
199 std::mt19937 generator(seed);
200 std::discrete_distribution<int> distribution(probs.begin(), probs.end());
201 return choices[distribution(generator)];
202}
203
204template <utils::concepts::float_vector Vec>
205typename Vec::value_type choose_value(const Vec &vals, uint_t seed = 42)
206{
207
208 std::mt19937 generator(seed);
209 auto size = std::distance(vals.begin(), vals.end());
210 std::discrete_distribution<int> distribution(0, static_cast<int>(size));
211 auto rand_idx = distribution(generator);
212 return vals[rand_idx];
213}
214
219template <utils::concepts::float_or_integral_vector Vec>
220void randomize_vec(Vec &v, const Vec &walk_set, uint_t seed = 42)
221{
222 std::for_each(v.begin(), v.end(), [&](auto &val) { val += choose_value(walk_set, seed); });
223}
224
230template <typename T> std::vector<T> &randomize(std::vector<T> &vec, T a, T b, uint_t seed = 42)
231{
233 return vec;
234}
235
236template <utils::concepts::float_or_integral_vector Vec>
237Vec &divide(Vec &v1, typename Vec::value_type val)
238{
239
240 // both vectors must have the same size
241 for (uint_t i = 0; i < v1.size(); ++i)
242 {
243 v1[i] /= val;
244 }
245 return v1;
246}
247
248template <utils::concepts::float_or_integral_vector Vec> Vec &add(Vec &v1, const Vec &v2)
249{
250
251 // both vectors must have the same size
252 for (uint_t i = 0; i < v1.size(); ++i)
253 {
254 v1[i] += v2[i];
255 }
256 return v1;
257}
258
259template <utils::concepts::float_or_integral_vector VectorType>
260VectorType exponentiate(const VectorType &vec)
261{
262 VectorType vec_exp(vec.size());
263 uint_t counter = 0;
264 static auto func = [&counter](const auto &data) { return std::pow(data, counter++); };
265 std::transform(vec.begin(), vec.end(), vec_exp.begin(), func);
266 return vec_exp;
267}
268
269template <utils::concepts::float_or_integral_vector VectorType>
270VectorType exponentiate(const VectorType &vec, typename VectorType::value_type v)
271{
272 VectorType vec_exp(vec.size());
273 uint_t counter = 0;
274 static auto func = [&counter, v](const auto &) { return std::pow(v, counter++); };
275 std::transform(vec.begin(), vec.end(), vec_exp.begin(), func);
276 return vec_exp;
277}
278
279#ifdef USE_PYTORCH
280template <utils::concepts::float_or_integral_vector VectorType>
281VectorType exponentiate(const torch_tensor_t tensor, typename VectorType::value_type v)
282{
283
284#ifdef BITRL_DEBUG
285 assert(tensor.dim() == 1 && "Invalid tensor dimension. Should be 1");
286#endif
287
288 VectorType vec_exp(tensor.size(0));
289 uint_t counter = 0;
290
291 for (uint_t i = 0; i < static_cast<uint_t>(tensor.size(0)); ++i)
292 {
293
294 auto val = tensor[i].item();
295 vec_exp[i] = val.template to<typename VectorType::value_type>();
296 }
297
298 static auto func = [&counter, v](auto &val)
299 {
300 auto expo = std::pow(v, counter++);
301 return val * expo;
302 };
303
304 std::for_each(vec_exp.begin(), vec_exp.end(), func);
305 return vec_exp;
306}
307#endif
308
313template <typename T> std::vector<T> softmax_vec(const std::vector<T> &vec, real_t tau = 1.0)
314{
315
316 std::vector<T> result(vec.size());
317 auto exp_sum = 0.0;
318 auto vec_size = static_cast<uint_t>(vec.size());
319 // calculate the exponentials
320 for (uint_t i = 0; i < vec_size; ++i)
321 {
322 result[i] = std::exp(vec[i] / tau);
323 exp_sum += result[i];
324 }
325
326 for (uint_t i = 0; i < vec_size; ++i)
327 {
328 result[i] /= exp_sum;
329 }
330
331 return result;
332}
333
338template <typename T> DynVec<T> softmax_vec(const DynVec<T> &vec, real_t tau = 1.0)
339{
340
341 DynVec<T> result(vec.size());
342 auto exp_sum = 0.0;
343 auto vec_size = static_cast<uint_t>(vec.size());
344 // calculate the exponentials
345 for (uint_t i = 0; i < vec_size; ++i)
346 {
347 result[i] = std::exp(vec[i] / tau);
348 exp_sum += result[i];
349 }
350
351 result /= exp_sum;
352 return result;
353}
354
359template <typename IteratorType>
360DynVec<typename IteratorType::value_type> softmax_vec(IteratorType begin, IteratorType end,
361 real_t tau = 1.0)
362{
363 auto vec_size = std::distance(begin, end);
365 auto exp_sum = 0.0;
366
367 auto counter = 0;
368 for (; begin != end; ++begin)
369 {
370 result[counter] = std::exp(*begin / tau);
371 exp_sum += result[counter++];
372 }
373
374 result /= exp_sum;
375 return result;
376}
377
383template <typename VectorType> uint_t arg_max(const VectorType &vec)
384{
385 return static_cast<uint_t>(
386 std::distance(vec.begin(), std::max_element(vec.begin(), vec.end())));
387}
388
394template <typename VectorType> uint_t arg_min(const VectorType &vec)
395{
396 return static_cast<uint_t>(
397 std::distance(vec.begin(), std::min_element(vec.begin(), vec.end())));
398}
399
400template <typename T> std::vector<uint_t> max_indices(const DynVec<T> &vec)
401{
402
403 // find max value
404 auto max_val = vec.maxCoeff();
405
406 auto result = std::vector<uint_t>();
407
408 for (uint_t i = 0; i < static_cast<uint_t>(vec.size()); ++i)
409 {
410 T value = vec[i];
411 if (value == max_val)
412 {
413 result.push_back(i);
414 }
415 }
416
417 return result;
418}
419
424template <typename VecTp> std::vector<uint_t> max_indices(const VecTp &vec)
425{
426
427 // find max value
428 auto max_val = std::max_element(vec.begin(), vec.end());
429
430 auto result = std::vector<uint_t>();
431 auto counter = 0;
432
433 std::for_each(vec.begin(), vec.end(),
434 [&](auto val)
435 {
436 if (val == max_val)
437 {
438 result.push_back(counter);
439 }
440 ++counter;
441 });
442
443 return result;
444}
445
446template <typename T>
447std::vector<T> extract_subvector(const std::vector<T> &vec, uint_t end, bool up_to = true)
448{
449
450#ifdef BITRL_DEBUG
451 assert(end <= vec.size() && "Invalid end index");
452#endif
453
454 if (up_to)
455 {
456 return std::vector<real_t>(vec.begin(), vec.begin() + end);
457 }
458
459 return std::vector<real_t>(vec.begin() + end, vec.end());
460}
461
466template <typename SequenceTp>
467uint_t bin_index(const typename SequenceTp::value_type &x, const SequenceTp &sequence)
468{
469
470 if (sequence.size() <= 1)
471 {
473 }
474
475 auto index = 1;
476 auto begin = sequence.begin();
477 auto prev_val = *begin;
478 ++begin;
479 auto end = sequence.end();
480
481 for (; begin != end; ++begin, ++index)
482 {
483
484 auto current_val = *begin;
485
486 if ((prev_val <= x) && (x < current_val))
487 {
488 return index;
489 }
490
491 prev_val = current_val;
492 }
493
495}
496
501template <typename VectorType> VectorType zero_center(const VectorType &vec, bool parallel = true)
502{
503
504 auto vec_mean = mean(vec.begin(), vec.end(), parallel);
505 VectorType v(vec.size());
506 std::transform(vec.begin(), vec.end(), v.begin(),
507 [vec_mean](auto val) { return val - vec_mean; });
508 return v;
509}
510
519template <typename VectorType>
520VectorType normalize(const VectorType &vec, typename VectorType::value_type v)
521{
522
523 VectorType v_(vec.size(), 0);
524
525 for (uint_t i = 0; i < v_.size(); ++i)
526 {
527 v_[i] = vec[i] / v;
528 }
529 return v_;
530}
531
532template <typename T> std::vector<T> normalize_max(const std::vector<T> &vec)
533{
534
535 auto max_val = std::max_element(vec.begin(), vec.end());
536 std::vector<T> v_(vec.size(), T(0));
537
538 for (uint_t i = 0; i < v_.size(); ++i)
539 {
540 v_[i] = vec[i] / *max_val;
541 }
542 return v_;
543}
544
545template <typename T> std::vector<T> normalize_min(const std::vector<T> &vec)
546{
547
548 auto min_val = std::min_element(vec.begin(), vec.end());
549 std::vector<T> v_(vec.size(), T(0));
550
551 for (uint_t i = 0; i < v_.size(); ++i)
552 {
553 v_[i] = vec[i] / *min_val;
554 }
555 return v_;
556}
557
573std::vector<real_t> logspace(real_t start, real_t end, uint_t num, real_t base = 10.0);
574
575template <typename IteratorType>
576typename std::iterator_traits<IteratorType>::value_type
577dot_product(IteratorType bv1, IteratorType ev1, IteratorType bv2, IteratorType ev2)
578{
579
580 typedef typename std::iterator_traits<IteratorType>::value_type value_type;
581
582 auto size1_ = std::distance(bv1, ev1);
583 auto size2_ = std::distance(bv2, ev2);
584
585 if (size1_ != size2_)
586 {
587 throw std::logic_error(
588 "Sizes not equal. Cannot compute dot product of vectors with no equal sizes");
589 }
590
591 value_type sum_ = value_type(0);
592
593 for (; bv1 != ev1; ++bv1, ++bv2)
594 {
595 sum_ += (*bv1) * (*bv2);
596 }
597
598 return sum_;
599}
600
601template <typename VectorType>
602real_t dot_product(const VectorType &v1, const VectorType &v2, uint_t start_idx = 0)
603{
604
605#ifdef BITRL_DEBUG
606 assert(v1.size() == v2.size() && "Invalid vector sizes");
607 assert(start_idx < v1.size() && "Invalid start_idx");
608#endif
609
610 auto v1_begin = v1.begin();
611 std::advance(v1_begin, start_idx);
612
613 auto v2_begin = v2.begin();
614 std::advance(v2_begin, start_idx);
615 real_t dot_product = 0.0;
616
617 for (; v1_begin != v1.end(); ++v1_begin, ++v2_begin)
618 {
619 dot_product += (*v1_begin) * (*v2_begin);
620 }
621 return dot_product;
622}
623} // namespace maths
624} // namespace bitrl
625
626#endif // BASIC_ARRAY_STATISTICS_H
Definition vector_math.h:30
Definition lp_metric.h:10
std::iterator_traits< IteratorType >::value_type variance(IteratorType begin, IteratorType end, bool parallel=true)
Definition vector_math.h:146
std::vector< T > normalize_max(const std::vector< T > &vec)
Definition vector_math.h:532
void randomize_vec(Vec &v, const Vec &walk_set, uint_t seed=42)
Given a vector of intergal or floating point values and a set of values to choose from,...
Definition vector_math.h:220
VectorType normalize(const VectorType &vec, typename VectorType::value_type v)
Normalize the values of the given vector with the given value. Essentially this function divides the ...
Definition vector_math.h:520
Vec::value_type choose_value(const Vec &vals, uint_t seed=42)
Definition vector_math.h:205
Vec & add(Vec &v1, const Vec &v2)
Definition vector_math.h:248
std::vector< real_t > standardize(const std::vector< real_t > &vals, real_t tol=bitsim::consts::TOLERANCE)
Standardize the given vector.
std::vector< T > & randomize(std::vector< T > &vec, T a, T b, uint_t seed=42)
Fill in the given vector with random values.
Definition vector_math.h:230
std::vector< uint_t > max_indices(const DynVec< T > &vec)
Definition vector_math.h:400
real_t mean(IteratorType begin, IteratorType end, bool parallel=true)
mean Compute the mean value of the values in the provided iterator range
Definition vector_math.h:119
uint_t arg_max(const VectorType &vec)
Returns the index of the element that has the maximum value in the array. Implementation taken from h...
Definition vector_math.h:383
Vec & divide(Vec &v1, typename Vec::value_type val)
Definition vector_math.h:237
std::vector< T > normalize_min(const std::vector< T > &vec)
Definition vector_math.h:545
uint_t choice(const Vec2 &probs, uint_t seed=42)
choice. Implements similar functionality to numpy.choice function
Definition vector_math.h:181
VectorType element_product(const VectorType &v1, const VectorType &v2)
Definition vector_math.h:67
uint_t bin_index(const typename SequenceTp::value_type &x, const SequenceTp &sequence)
bin_index. Compute sequnce[i - 1] <= x sequnce[i] and returns the index. Sequence should be sorted
Definition vector_math.h:467
VectorType zero_center(const VectorType &vec, bool parallel=true)
zero_center. Subtracts the mean value of the given vector from every value of the vector
Definition vector_math.h:501
VectorType exponentiate(const VectorType &vec)
Definition vector_math.h:260
uint_t arg_min(const VectorType &vec)
Returns the index of the element that has the minimum value in the array. Implementation taken from h...
Definition vector_math.h:394
std::vector< T > softmax_vec(const std::vector< T > &vec, real_t tau=1.0)
applies softmax operation to the elements of the vector and returns a vector with the result
Definition vector_math.h:313
std::iterator_traits< IteratorType >::value_type sum(IteratorType begin, IteratorType end, bool parallel=true)
Definition vector_math.h:89
std::iterator_traits< IteratorType >::value_type dot_product(IteratorType bv1, IteratorType ev1, IteratorType bv2, IteratorType ev2)
Definition vector_math.h:577
std::vector< real_t > logspace(real_t start, real_t end, uint_t num, real_t base=10.0)
std::vector< T > extract_subvector(const std::vector< T > &vec, uint_t end, bool up_to=true)
Definition vector_math.h:447
Various utilities used when working with RL problems.
Definition bitrl_log.h:25
torch::Tensor torch_tensor_t
torch_tensor_t
Definition bitrl_types.h:95
const real_t TOLERANCE
Tolerance used around the library.
Definition bitsim_consts.h:26
const uint_t INVALID_ID
Invalid id.
Definition bitsim_consts.h:16
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
float float_t
float
Definition bitsim_types.h:25
double real_t
real_t
Definition bitsim_types.h:20
Eigen::RowVectorX< T > DynVec
Dynamically sized row vector.
Definition bitsim_types.h:101
static void randomize_(VecType &v, float_t a, float_t b, uint_t seed)
Definition vector_math.h:56
static void randomize_(VecType &v, real_t a, real_t b, uint_t seed)
Definition vector_math.h:40
Definition vector_math.h:32