-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathshannonEntropy.hpp
46 lines (38 loc) · 1.25 KB
/
shannonEntropy.hpp
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
#pragma once
#include <iostream>
#include <unordered_map>
#include <cmath>
#include <Eigen/Dense>
// using Eigen::ArrayXi;
using namespace std;
// using namespace arma;
using ArrayXL = Eigen::Array<int64_t, Eigen::Dynamic, 1>;
struct shannonEntropy {
typedef unordered_map<int64_t, size_t> histoMap;
static shannonEntropy::histoMap calcDistribution(const ArrayXL &seq) {
shannonEntropy::histoMap histo;
for (const uint64_t v: seq) {
shannonEntropy::histoMap::iterator it = histo.find(v);
if (it == histo.end()) {
histo.insert(std::make_pair(v, 1));
}else{
it->second = it->second + 1;
}
}
return histo;
}
static double calcProbability(const shannonEntropy::histoMap &histo, const ArrayXL &seq) {
double scale = 1.0 / seq.size();
double H=0;
for(auto v: histo) {
double prob = v.second * scale;
H = H - (prob * log2(prob));
}
return H;
}
static double calc(const ArrayXL &seq) {
shannonEntropy::histoMap histo = shannonEntropy::calcDistribution(seq);
double prob = shannonEntropy::calcProbability(histo, seq);
return prob;
}
};