-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathhcluster.js
413 lines (356 loc) · 11.8 KB
/
hcluster.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.hcluster = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
//
//
//
module.exports = {
euclidean: require('./src/euclidean'),
manhattan: require('./src/manhattan'),
chebyshev: require('./src/chebyshev'),
angular: require('./src/angular'),
cosineSimilarity: require('./src/cosine-similarity'),
angularSimilarity: require('./src/angular-similarity')
};
},{"./src/angular":3,"./src/angular-similarity":2,"./src/chebyshev":4,"./src/cosine-similarity":5,"./src/euclidean":6,"./src/manhattan":7}],2:[function(require,module,exports){
//
//
//
var cosineSimilarity = require('./cosine-similarity');
//
module.exports = function(a, b, accessor) {
var cosSimValue = cosineSimilarity.apply(null, arguments);
return 1 - ( (2 * Math.acos(cosSimValue)) / Math.PI);
};
},{"./cosine-similarity":5}],3:[function(require,module,exports){
//
//
//
var cosineSimilarity = require('./cosine-similarity');
//
module.exports = function(a, b, accessor) {
var cosSimValue = cosineSimilarity.apply(null, arguments);
return (2 * Math.acos(cosSimValue)) / Math.PI;
};
},{"./cosine-similarity":5}],4:[function(require,module,exports){
//
//
//
//
module.exports = function(a, b, accessor) {
var x = accessor ? a.map(accessor) : a,
y = accessor ? b.map(accessor) : b,
distance = Math.abs(x[0] - y[0]);
for(var ndx = 1; ndx < x.length; ndx++) {
distance = Math.max(distance, Math.abs(x[ndx] - y[ndx]));
}
return distance;
};
},{}],5:[function(require,module,exports){
//
//
//
//
module.exports = function(a, b, accessor) {
var x = accessor ? a.map(accessor) : a,
y = accessor ? b.map(accessor) : b,
dotProduct = 0,
xMagnitude = 0,
yMagnitude = 0;
for(var ndx = 0; ndx < x.length; ndx++) {
xMagnitude += x[ndx] * x[ndx];
yMagnitude += y[ndx] * y[ndx];
dotProduct += x[ndx] * y[ndx];
}
return dotProduct / ( Math.sqrt(xMagnitude) * Math.sqrt(yMagnitude) );
};
},{}],6:[function(require,module,exports){
//
//
//
//
module.exports = function(a, b, accessor) {
var x = accessor ? a.map(accessor) : a,
y = accessor ? b.map(accessor) : b,
distance = 0;
for(var ndx = 0; ndx < x.length; ndx++) {
distance += (x[ndx] - y[ndx]) * (x[ndx] - y[ndx]);
}
return Math.sqrt(distance);
};
},{}],7:[function(require,module,exports){
//
//
//
//
module.exports = function(a, b, accessor) {
var x = accessor ? a.map(accessor) : a,
y = accessor ? b.map(accessor) : b,
distance = 0;
for(var ndx = 0; ndx < x.length; ndx++) {
distance += Math.abs(x[ndx] - y[ndx]);
}
return distance;
};
},{}],8:[function(require,module,exports){
'use strict';
var hasOwn = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var isArray = function isArray(arr) {
if (typeof Array.isArray === 'function') {
return Array.isArray(arr);
}
return toStr.call(arr) === '[object Array]';
};
var isPlainObject = function isPlainObject(obj) {
if (!obj || toStr.call(obj) !== '[object Object]') {
return false;
}
var hasOwnConstructor = hasOwn.call(obj, 'constructor');
var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
// Not own constructor property must be Object
if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for (key in obj) {/**/}
return typeof key === 'undefined' || hasOwn.call(obj, key);
};
module.exports = function extend() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0],
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if (typeof target === 'boolean') {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
} else if ((typeof target !== 'object' && typeof target !== 'function') || target == null) {
target = {};
}
for (; i < length; ++i) {
options = arguments[i];
// Only deal with non-null/undefined values
if (options != null) {
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target !== copy) {
// Recurse if we're merging plain objects or arrays
if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && isArray(src) ? src : [];
} else {
clone = src && isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[name] = extend(deep, clone, copy);
// Don't bring in undefined values
} else if (typeof copy !== 'undefined') {
target[name] = copy;
}
}
}
}
}
// Return the modified object
return target;
};
},{}],9:[function(require,module,exports){
//
//
//
var distance = require('distancejs'),
extend = require('extend');
//
var hcluster = function() {
var data,
clusters,
clustersGivenK,
treeRoot,
posKey = 'position',
distanceName = 'angular',
distanceFn = distance.angular,
linkage = 'avg',
verbose = false;
//
// simple constructor
function clust() { }
//
// getters, setters a la D3
// return data or set data and build tree
clust.data = function(value) {
if(!arguments.length) return data;
// dataset will be mutated
data = value;
clust._buildTree();
return clust;
};
clust.posKey = function(value) {
if(!arguments.length) return posKey;
posKey = value;
return clust;
};
clust.linkage = function(value) {
if(!arguments.length) return linkage;
linkage = value;
return clust;
};
clust.verbose = function(value) {
if(!arguments.length) return verbose;
verbose = value;
return clust;
};
clust.distance = function(value) {
if(!arguments.length) return distanceName;
distanceName = value;
distanceFn = {
angular: distance.angular,
euclidean: distance.euclidean
}[value] || distance.angular;
return clust;
}
//
// get tree properties
clust.orderedNodes = function() {
if(!treeRoot) throw new Error('Need to passin data and build tree first.');
return treeRoot.indexes.map(function(ndx) {
return data[ndx];
});
};
clust.tree = function() {
if(!treeRoot) throw new Error('Need to passin data and build tree first.');
return treeRoot;
};
clust.getClusters = function(n) {
if(!treeRoot) throw new Error('Need to passin data and build tree first.');
if(n > data.length) throw new Error('n must be less than the size of the dataset');
return clustersGivenK[data.length - n]
.map(function(indexes) {
return indexes.map(function(ndx) { return data[ndx]; });
});
};
//
// math, matrix utility fn's
// return unique pairs of indexes on n x n matrix above the diagonal
clust._squareMatrixPairs = function(n) {
var pairs = [];
for(var row = 0; row < n; row++) {
for(var col = row + 1; col < n; col++) {
pairs.push([row, col]);
}
}
return pairs;
};
// average distance between set of cluster indexes
clust._avgDistance = function(setA, setB) {
var distance = 0;
for(var ndxA = 0; ndxA < setA.length; ndxA++) {
for(var ndxB = 0; ndxB < setB.length; ndxB++) {
distance += data[setA[ndxA]]._distances[setB[ndxB]];
}
}
return distance / setA.length / setB.length;
};
// min distance between set of cluster indexes
clust._minDistance = function(setA, setB) {
var distances = [];
for(var ndxA = 0; ndxA < setA.length; ndxA++) {
for(var ndxB = 0; ndxB < setB.length; ndxB++) {
distances.push(data[setA[ndxA]]._distances[setB[ndxB]]);
}
}
return distances.sort()[0];
};
// max distance between set of cluster indexes
clust._maxDistance = function(setA, setB) {
var distances = [];
for(var ndxA = 0; ndxA < setA.length; ndxA++) {
for(var ndxB = 0; ndxB < setB.length; ndxB++) {
distances.push(data[setA[ndxA]]._distances[setB[ndxB]]);
}
}
return distances.sort()[distances.length-1];
};
//
// tree construction
//
clust._buildTree = function() {
if(!data || !data.length) throw new Error('Need `data` to build tree');
//
var node, clusterPairs, nearestPair, newCluster;
clusters = [];
clustersGivenK = [];
tree = {};
// calculate distances and build single datum clusters
data.forEach(function(d, ndx) {
d._distances = data.map(function(compareTo) {
return distanceFn(d[posKey], compareTo[posKey]);
});
clusters.push(extend(d, {
height: 0,
indexes: [ndx]
}));
});
// for tree of n leafs, n-1 linkages
for(var iter = 0; iter < data.length - 1; iter++) {
verbose && console.log(iter + ': ' +
clusters.map(function(c) { return c.indexes; }).join('|'));
// find closest pair of clusters, pair[2] is distance
clusterPairs = clust._squareMatrixPairs(clusters.length);
clusterPairs.forEach(function(pair) {
pair[2] = clust['_'+linkage+'Distance'](
clusters[pair[0]].indexes,
clusters[pair[1]].indexes ); });
nearestPair = clusterPairs
.reduce(function(pairA, pairB) { return pairA[2] <= pairB[2] ? pairA : pairB; },
[0, 0, Infinity]);
newCluster = {
name: 'Node ' + iter,
height: nearestPair[2],
indexes: clusters[nearestPair[0]].indexes.concat(clusters[nearestPair[1]].indexes),
children: [ clusters[nearestPair[0]], clusters[nearestPair[1]] ],
};
verbose && console.log(newCluster);
clustersGivenK.push(clusters.map(function(c) { return c.indexes; }));
// remove merged nodes and push new node
clusters.splice(Math.max(nearestPair[0], nearestPair[1]),1);
clusters.splice(Math.min(nearestPair[0], nearestPair[1]),1);
clusters.push(newCluster);
}
treeRoot = clusters[0];
// clust._rebalanceTree(treeRoot);
};
// TODO: better rebalancing algo? ... this is just for presentation
// rebalance after tree is built (b/c it is top down operation)
// clust._rebalanceTree = function(node) {
// if(node.parent && node.parent.children && node.parent.children.length &&
// node.children && node.children.length) {
// var rightDistance = clust['_'+linkage+'Distance'](
// node.parent.children[1].indexes,
// node.children[0].indexes);
// var leftDistance = clust['_'+linkage+'Distance'](
// node.parent.children[1].indexes,
// node.children[1].indexes);
// // switch order of node.children
// if(leftDistance > rightDistance) {
// node.children = [ node.children[1], node.children[0] ];
// node.indexes = node.children[0].indexes.concat(node.children[1].indexes);
// }
// }
// if(node.children) {
// clust._rebalanceTree(node.children[0]);
// clust._rebalanceTree(node.children[1]);
// }
// };
return clust;
};
module.exports = hcluster;
},{"distancejs":1,"extend":8}]},{},[9])(9)
});