forpy  2
shannonentropy.h
Go to the documentation of this file.
1 /* Author: Christoph Lassner. */
2 #pragma once
3 #ifndef FORPY_IMPURITIES_SHANNONENTROPY_H_
4 #define FORPY_IMPURITIES_SHANNONENTROPY_H_
5 
6 #include "../global.h"
7 
8 #include "../util/serialization/basics.h"
9 
10 #include <numeric>
11 #include <vector>
12 
13 #include "../types.h"
14 #include "../util/checks.h"
15 #include "../util/exponentials.h"
16 #include "./ientropyfunction.h"
17 
18 namespace forpy {
35  public:
38 
39  inline virtual float operator()(const float *class_members_numbers,
40  const size_t &n, const float &fsum) const {
41  // In debug mode, run checks.
42  FASSERT(static_cast<float>(std::accumulate(class_members_numbers,
43  class_members_numbers + n,
44  static_cast<float>(0))) == fsum);
45  // Deal with the special case quickly.
46  if (fsum == 0.f) return 0.f;
47 
48  float entropy_sum = 0.f;
49  float quot;
50  // Calculate classical entropy.
51  for (size_t i = 0; i < n; ++i, class_members_numbers++) {
52  // The value -0*log2(0) is defined to be 0, according to the limit
53  // lim_{p->0}{p*log2(p)}.
54  if (*class_members_numbers == 0.f) continue;
55  // All good, so calculate the normal parts.
56  quot = *class_members_numbers / fsum;
57  entropy_sum -= quot * log2f(quot);
58  }
59  return entropy_sum;
60  };
61 
62  inline friend std::ostream &operator<<(std::ostream &stream,
63  const ShannonEntropy & /*self*/) {
64  stream << "forpy::ShannonEntropy";
65  return stream;
66  };
67  bool operator==(const IEntropyFunction &rhs) const;
68 
69  private:
71 
72  friend class cereal::access;
73  template <class Archive>
74  void serialize(Archive &ar, const uint &) {
75  ar(cereal::make_nvp("base", cereal::base_class<IEntropyFunction>(this)));
76  }
77 };
78 } // namespace forpy
79 
81 #endif // FORPY_IMPURITIES_SHANNONENTROPY_H_
CEREAL_REGISTER_TYPE(forpy::ShannonEntropy)
Interface for an entropy calculation functor.
#define FASSERT(condition)
Definition: global.h:124
Computes the classical Shannon-Entropy.
friend class cereal::access
virtual float operator()(const float *class_members_numbers, const size_t &n, const float &fsum) const
void serialize(Archive &ar, const uint &)
friend std::ostream & operator<<(std::ostream &stream, const ShannonEntropy &)
DISALLOW_COPY_AND_ASSIGN(ShannonEntropy)
bool operator==(const IEntropyFunction &rhs) const
unsigned int uint
Convenience typedef for unsigned int.
Definition: types.h:113