-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnew-dtw.js
278 lines (238 loc) · 10.1 KB
/
new-dtw.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
const debug = require('debug')('dtw');
function validateSequence(sequence, sequenceParameterName) {
if (!(sequence instanceof Array)) {
throw new TypeError(`Invalid sequence '${sequenceParameterName}' type: expected an array`);
}
if (sequence.length < 1) {
throw new Error(`Invalid number of sequence data points for '${sequenceParameterName}': expected at least one`);
}
if (typeof sequence[0] !== 'number') {
throw new TypeError(`Invalid data points types for sequence '${sequenceParameterName}': expected a number`);
}
}
const createArray = (length, value) => {
if (typeof length !== 'number') {
throw new TypeError('Invalid length type');
}
if (typeof value === 'undefined') {
throw new Error('Invalid value: expected a value to be provided');
}
const array = new Array(length);
for (let index = 0; index < length; index++) {
array[index] = value;
}
return array;
};
const createMatrix = (m, n, value) => {
const matrix = [];
for (let rowIndex = 0; rowIndex < m; rowIndex++) {
matrix.push(createArray(n, value));
}
return matrix;
};
const EPSILON = 2.2204460492503130808472633361816E-16;
const nearlyEqual = (i, j, epsilon) => {
const iAbsolute = Math.abs(i);
const jAbsolute = Math.abs(j);
const difference = Math.abs(i - j);
let equal = i === j;
if (!equal) {
equal = difference < EPSILON;
if (!equal) {
equal = difference <= Math.max(iAbsolute, jAbsolute) * epsilon;
}
}
return equal;
};
function validateOptions(options) {
if (typeof options !== 'object') {
throw new TypeError('Invalid options type: expected an object');
} else if (typeof options.distanceMetric !== 'string' && typeof options.distanceFunction !== 'function') {
throw new TypeError('Invalid distance types: expected a string distance type or a distance function');
} else if (typeof options.distanceMetric === 'string' && typeof options.distanceFunction === 'function') {
throw new Error('Invalid parameters: provide either a distance metric or function but not both');
}
if (typeof options.distanceMetric === 'string') {
const normalizedDistanceMetric = options.distanceMetric.toLowerCase();
if (normalizedDistanceMetric !== 'manhattan' && normalizedDistanceMetric !== 'euclidean' &&
normalizedDistanceMetric !== 'squaredeuclidean') {
throw new Error(`Invalid parameter value: Unknown distance metric '${options.distanceMetric}'`);
}
}
}
function retrieveDistanceFunction(distanceMetric) {
const normalizedDistanceMetric = distanceMetric.toLowerCase();
let distanceFunction = null;
if (normalizedDistanceMetric === 'manhattan') {
distanceFunction = require('./distanceFunctions/manhattan').distance;
} else if (normalizedDistanceMetric === 'euclidean') {
distanceFunction = require('./distanceFunctions/euclidean').distance;
} else if (normalizedDistanceMetric === 'squaredeuclidean') {
distanceFunction = require('./distanceFunctions/squaredEuclidean').distance;
}
return distanceFunction;
}
/**
* Create a DTWOptions object
* @class DTWOptions
* @member {string} distanceMetric The distance metric to use: `'manhattan' | 'euclidean' | 'squaredEuclidean'`.
* @member {function} distanceFunction The distance function to use. The function should accept two numeric arguments and return the numeric distance. e.g. function (a, b) { return a + b; }
*/
/**
* Create a DTW object
* @class DTW
*/
/**
* Initializes a new instance of the `DTW`. If no options are provided the squared euclidean distance function is used.
* @function DTW
* @param {DTWOptions} [options] The options to initialize the dynamic time warping instance with.
*/
/**
* Computes the optimal match between two provided sequences.
* @method compute
* @param {number[]} firstSequence The first sequence.
* @param {number[]} secondSequence The second sequence.
* @param {number} [window] The window parameter (for the locality constraint) to use.
* @returns {number} The similarity between the provided temporal sequences.
*/
/**
* Retrieves the optimal match between two provided sequences.
* @method path
* @returns {number[]} The array containing the optimal path points.
*/
const DTW = function (options) {
const state = {
distanceCostMatrix: null
};
if (typeof options === 'undefined') {
state.distance = require('./distanceFunctions/squaredEuclidean').distance;
} else {
validateOptions(options);
if (typeof options.distanceMetric === 'string') {
state.distance = retrieveDistanceFunction(options.distanceMetric);
} else if (typeof options.distanceFunction === 'function') {
state.distance = options.distanceFunction;
}
}
this.compute = (firstSequence, secondSequence, window) => {
let cost = Number.POSITIVE_INFINITY;
if (typeof window === 'undefined') {
cost = computeOptimalPath(firstSequence, secondSequence, state);
} else if (typeof window === 'number') {
cost = computeOptimalPathWithWindow(firstSequence, secondSequence, window, state);
} else {
throw new TypeError('Invalid window parameter type: expected a number');
}
return cost;
};
this.path = () => {
let path = null;
if (state.distanceCostMatrix instanceof Array) {
path = retrieveOptimalPath(state);
}
return path;
};
};
function validateComputeParameters(s, t) {
validate.sequence(s, 'firstSequence');
validate.sequence(t, 'secondSequence');
}
function computeOptimalPath(s, t, state) {
debug('> computeOptimalPath');
validateComputeParameters(s, t);
const start = new Date().getTime();
state.m = s.length;
state.n = t.length;
const distanceCostMatrix = matrix.create(state.m, state.n, Number.POSITIVE_INFINITY);
distanceCostMatrix[0][0] = state.distance(s[0], t[0]);
for (var rowIndex = 1; rowIndex < state.m; rowIndex++) {
var cost = state.distance(s[rowIndex], t[0]);
distanceCostMatrix[rowIndex][0] = cost + distanceCostMatrix[rowIndex - 1][0];
}
for (var columnIndex = 1; columnIndex < state.n; columnIndex++) {
var cost = state.distance(s[0], t[columnIndex]);
distanceCostMatrix[0][columnIndex] = cost + distanceCostMatrix[0][columnIndex - 1];
}
for (var rowIndex = 1; rowIndex < state.m; rowIndex++) {
for (var columnIndex = 1; columnIndex < state.n; columnIndex++) {
var cost = state.distance(s[rowIndex], t[columnIndex]);
distanceCostMatrix[rowIndex][columnIndex] =
cost + Math.min(
distanceCostMatrix[rowIndex - 1][columnIndex], // Insertion
distanceCostMatrix[rowIndex][columnIndex - 1], // Deletion
distanceCostMatrix[rowIndex - 1][columnIndex - 1]); // Match
}
}
const end = new Date().getTime();
const time = end - start;
debug(`< computeOptimalPath (${time} ms)`);
state.distanceCostMatrix = distanceCostMatrix;
state.similarity = distanceCostMatrix[state.m - 1][state.n - 1];
return state.similarity;
}
function computeOptimalPathWithWindow(s, t, w, state) {
debug('> computeOptimalPathWithWindow');
validateComputeParameters(s, t);
const start = new Date().getTime();
state.m = s.length;
state.n = t.length;
const window = Math.max(w, Math.abs(s.length - t.length));
let distanceCostMatrix = matrix.create(state.m + 1, state.n + 1, Number.POSITIVE_INFINITY);
distanceCostMatrix[0][0] = 0;
for (let rowIndex = 1; rowIndex <= state.m; rowIndex++) {
for (let columnIndex = Math.max(1, rowIndex - window); columnIndex <= Math.min(state.n, rowIndex + window); columnIndex++) {
const cost = state.distance(s[rowIndex - 1], t[columnIndex - 1]);
distanceCostMatrix[rowIndex][columnIndex] =
cost + Math.min(
distanceCostMatrix[rowIndex - 1][columnIndex], // Insertion
distanceCostMatrix[rowIndex][columnIndex - 1], // Deletion
distanceCostMatrix[rowIndex - 1][columnIndex - 1]); // Match
}
}
const end = new Date().getTime();
const time = end - start;
debug(`< computeOptimalPathWithWindow (${time} ms)`);
distanceCostMatrix.shift();
distanceCostMatrix = distanceCostMatrix.map(row => {
return row.slice(1, row.length);
});
state.distanceCostMatrix = distanceCostMatrix;
state.similarity = distanceCostMatrix[state.m - 1][state.n - 1];
return state.similarity;
}
function retrieveOptimalPath(state) {
debug('> retrieveOptimalPath');
const start = new Date().getTime();
let rowIndex = state.m - 1;
let columnIndex = state.n - 1;
const path = [
[rowIndex, columnIndex]
];
const epsilon = 1e-14;
while ((rowIndex > 0) || (columnIndex > 0)) {
if ((rowIndex > 0) && (columnIndex > 0)) {
const min = Math.min(
state.distanceCostMatrix[rowIndex - 1][columnIndex], // Insertion
state.distanceCostMatrix[rowIndex][columnIndex - 1], // Deletion
state.distanceCostMatrix[rowIndex - 1][columnIndex - 1]); // Match
if (comparison.nearlyEqual(min, state.distanceCostMatrix[rowIndex - 1][columnIndex - 1], epsilon)) {
rowIndex--;
columnIndex--;
} else if (comparison.nearlyEqual(min, state.distanceCostMatrix[rowIndex - 1][columnIndex], epsilon)) {
rowIndex--;
} else if (comparison.nearlyEqual(min, state.distanceCostMatrix[rowIndex][columnIndex - 1], epsilon)) {
columnIndex--;
}
} else if ((rowIndex > 0) && (columnIndex === 0)) {
rowIndex--;
} else if ((rowIndex === 0) && (columnIndex > 0)) {
columnIndex--;
}
path.push([rowIndex, columnIndex]);
}
const end = new Date().getTime();
const time = end - start;
debug(`< retrieveOptimalPath (${time} ms)`);
return path.reverse();
}
module.exports = DTW;