-
Notifications
You must be signed in to change notification settings - Fork 0
/
Calculation.cpp
executable file
·106 lines (95 loc) · 2.8 KB
/
Calculation.cpp
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#ifndef __CALCULATION_CPP
#define __CALCULATION_CPP
#include "Calculation.h"
// Calculate column mean
template <typename T>
vector<T> Calculations<T>::mean_col(QSMatrix<T> &m) {
int cols = m.get_cols();
int rows = m.get_rows();
vector<T> result(cols);
T sum = 0;
for (int i = 0; i < cols; ++i) {
for (int j = 0; j < rows; ++j) {
sum += m(j, i);
}
result[i] = sum/rows;
sum = 0;
}
return result;
}
// Calculate covariance matrix
template <typename T>
QSMatrix<T> Calculations<T>::covariance(vector<T> &mean,
QSMatrix<T> &m) {
int cols = m.get_cols();
int rows = m.get_rows();
QSMatrix<T> centered(rows, cols, 0);
centered = m - mean;
QSMatrix<T> sum(cols, cols, 0);
for (int i = 0; i < rows; ++i) {
vector<T> tmp = centered.row(i);
sum += transposeMultiply(tmp);
}
return sum/(rows-1);
}
template <typename T>
vector<T> Calculations<T>::mahDistance(vector<T> &mean,
QSMatrix<T> &cov) {
int n = data.get_rows();
int m = data.get_cols();
vector<T> md(n);
// Symmetric positive definite matrix -> using cholesky for efficiency
Cholesky<T> cho;
cov = cho.inverse(cov);
for (int i = 0; i < n; ++i) {
vector<T> tmp(n);
for (int j = 0; j < m; ++j)
tmp[j] = (data.row(i))[j] - mean[j];
md[i] = mahProduct(tmp, cov);
}
return md;
}
// seperate product function from mahalanobis function
template <typename T>
T Calculations<T>::mahProduct(vector<T> ¢ered,
QSMatrix<T> &inversecov) {
vector<T> tmp = inversecov * centered;
T sum = 0;
for (int i = 0; i < centered.size(); ++i) {
sum += centered[i] * tmp[i];
}
return sum;
}
// Transpose matrix and multiply itself
template <typename T>
QSMatrix<T> Calculations<T>::transposeMultiply(vector<T> &v) {
int size = (int) v.size();
QSMatrix<T> result(size, size, 0);
#pragma omp parallel for
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
result(i, j) = v[i] * v[j];
}
}
return result;
};
// Concentration-step in FastMCD paper
template <typename T>
QSMatrix<T> Calculations<T>::Cstep(QSMatrix<T> &Hold, int h) {
vector<T> Told = mean_col(Hold);
QSMatrix<T> Sold = covariance(Told, Hold);
vector<T> md = mahDistance(Told, Sold);
vector<size_t> index = sort_indexes(md);
QSMatrix<T> out(h, Hold.get_cols(), 0);
for (int i = 0; i < h; ++i) {
out.row(i) = data.row((const unsigned int &) index[i]);
}
return out;
}
// Calculate median of vector of numbers
template <typename T>
T Calculations<T>::median(vector<T> &v) {
int size = (int) v.size();
return v[(int) (size+1)/2];
}
#endif