forked from piercus/kalman-filter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.js
218 lines (186 loc) · 6.93 KB
/
state.js
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
const sub = require('./linalgebra/sub.js');
const transpose = require('./linalgebra/transpose.js');
const matMul = require('./linalgebra/mat-mul.js');
const invert = require('./linalgebra/invert.js');
const elemWise = require('./linalgebra/elem-wise.js');
const subSquareMatrix = require('./linalgebra/sub-square-matrix');
const arrayToMatrix = require('./utils/array-to-matrix.js');
const checkMatrix = require('./utils/check-matrix.js');
const checkCovariance = require('./utils/check-covariance');
/**
* @class
* Class representing a multi dimensionnal gaussian, with his mean and his covariance
* @property {Number} [index=0] the index of the State in the process, this is not mandatory for simple Kalman Filter, but is needed for most of the use case of extended kalman filter
* @property {Array.<Array.<Number>>} covariance square matrix of size dimension
* @property {Array.<Array<Number>>} mean column matrix of size dimension x 1
*/
class State {
constructor({mean, covariance, index}) {
this.mean = mean;
this.covariance = covariance;
this.index = index;
}
/**
* Check the consistency of the State
*/
check(options) {
this.constructor.check(this, options);
}
/**
* Check the consistency of the State's attributes
*/
static check(state, {dimension = null, title = null, eigen} = {}) {
if (!(state instanceof State)) {
throw (new TypeError(
'The argument is not a state \n' +
'Tips: maybe you are using 2 different version of kalman-filter in your npm deps tree'
));
}
const {mean, covariance} = state; // Index
const meanDimension = mean.length;
if (typeof (dimension) === 'number' && meanDimension !== dimension) {
throw (new Error(`[${title}] State.mean ${mean} with dimension ${meanDimension} does not match expected dimension (${dimension})`));
}
checkMatrix(mean, [meanDimension, 1], title ? title + '-mean' : 'mean');
checkMatrix(covariance, [meanDimension, meanDimension], title ? title + '-covariance' : 'covariance');
checkCovariance({covariance, eigen}, title ? title + '-covariance' : 'covariance');
// If (typeof (index) !== 'number') {
// throw (new TypeError('t must be a number'));
// }
}
static matMul({state, matrix}) {
const covariance = matMul(
matMul(matrix, state.covariance),
transpose(matrix)
);
const mean = matMul(matrix, state.mean);
return new State({
mean,
covariance,
index: state.index
});
}
/**
* From a state in n-dimension create a state in a subspace
* If you see the state as a N-dimension gaussian,
* this can be viewed as the sub M-dimension gaussian (M < N)
* @param {Array.<Number>} obsIndexes list of dimension to extract, (M < N <=> obsIndexes.length < this.mean.length)
* @returns {State} subState in subspace, with subState.mean.length === obsIndexes.length
*/
subState(obsIndexes) {
const state = new State({
mean: obsIndexes.map(i => this.mean[i]),
covariance: subSquareMatrix(this.covariance, obsIndexes),
index: this.index
});
return state;
}
/**
* Simple Malahanobis distance between the distribution (this) and a point
* @param {Array.<[Number]>} point a Nx1 matrix representing a point
*/
rawDetailedMahalanobis(point) {
const diff = sub(this.mean, point);
this.check();
const covarianceInvert = invert(this.covariance);
if (covarianceInvert === null) {
this.check({eigen: true});
throw (new Error(`Cannot invert covariance ${JSON.stringify(this.covariance)}`));
}
const diffTransposed = transpose(diff);
// Console.log('covariance in obs space', covarianceInObservationSpace);
const value = Math.sqrt(
matMul(
matMul(
diffTransposed,
covarianceInvert
),
diff
)
);
if (Number.isNaN(value)) {
console.log({diff, covarianceInvert, this: this, point}, matMul(
matMul(
diffTransposed,
covarianceInvert
),
diff
));
throw (new Error('mahalanobis is NaN'));
}
return {
diff,
covarianceInvert,
value
};
}
/**
* Malahanobis distance is made against an observation, so the mean and covariance
* are projected into the observation space
* @param {KalmanFilter} kf kalman filter use to project the state in observation's space
* @param {Observation} observation
* @param {Array.<Number>} obsIndexes list of indexes of observation state to use for the mahalanobis distance
*/
detailedMahalanobis({kf, observation, obsIndexes}) {
if (observation.length !== kf.observation.dimension) {
throw (new Error(`Mahalanobis observation ${observation} (dimension: ${observation.length}) does not match with kf observation dimension (${kf.observation.dimension})`));
}
let correctlySizedObservation = arrayToMatrix({observation, dimension: observation.length});
const stateProjection = kf.getValue(kf.observation.stateProjection, {});
let projectedState = this.constructor.matMul({state: this, matrix: stateProjection});
if (Array.isArray(obsIndexes)) {
projectedState = projectedState.subState(obsIndexes);
correctlySizedObservation = obsIndexes.map(i => correctlySizedObservation[i]);
}
return projectedState.rawDetailedMahalanobis(correctlySizedObservation);
}
/**
* @param {KalmanFilter} kf kalman filter use to project the state in observation's space
* @param {Observation} observation
* @param {Array.<Number>} obsIndexes list of indexes of observation state to use for the mahalanobis distance
* @returns {Number}
*/
mahalanobis(options) {
const result = this.detailedMahalanobis(options).value;
if (Number.isNaN(result)) {
throw (new TypeError('mahalanobis is NaN'));
}
return result;
}
/**
* Bhattacharyya distance is made against in the observation space
* to do it in the normal space see state.bhattacharyya
* @param {KalmanFilter} kf kalman filter use to project the state in observation's space
* @param {State} state
* @param {Array.<Number>} obsIndexes list of indexes of observation state to use for the bhattacharyya distance
* @returns {Number}
*/
obsBhattacharyya({kf, state, obsIndexes}) {
const stateProjection = kf.getValue(kf.observation.stateProjection, {});
let projectedSelfState = this.constructor.matMul({state: this, matrix: stateProjection});
let projectedOtherState = this.constructor.matMul({state, matrix: stateProjection});
if (Array.isArray(obsIndexes)) {
projectedSelfState = projectedSelfState.subState(obsIndexes);
projectedOtherState = projectedOtherState.subState(obsIndexes);
}
return projectedSelfState.bhattacharyya(projectedOtherState);
}
/**
* @param {State} otherState other state to compare with
* @returns {Number}
*/
bhattacharyya(otherState) {
const state = this;
const average = elemWise([state.covariance, otherState.covariance], ([a, b]) => (a + b) / 2);
let covarInverted;
try {
covarInverted = invert(average);
} catch (error) {
console.log('Cannot invert', average);
throw (error);
}
const diff = sub(state.mean, otherState.mean);
return matMul(transpose(diff), matMul(covarInverted, diff))[0][0];
}
}
module.exports = State;