-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
99 lines (81 loc) · 2.45 KB
/
index.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
'use strict';
var _exports = module.exports = {};
var math = require('mathjs');
_exports.colSum = function colSum(A) {
var ones = math.ones(A.size()[0]);
return math.multiply(math.transpose(A), ones);
};
_exports.repmat = function repmat(row, n) {
// Should really do ones(n, 1)*row but mathjs has very
// limited support for vector multiplication.
var repMatrix = [];
for (var i = 0; i < n; i++) {
repMatrix.push(row._data);
}
return math.matrix(repMatrix);
};
_exports.rowMatrixToArray = function rowMatrixToArray(M) {
var nbrCols = M.size()[1];
var r = Array(nbrCols);
for (var i = 0; i < nbrCols; i++) {
r[i] = M.subset(math.index(0, i));
}
return r;
};
_exports.normalizeColumns = function normalizeColumns(A) {
var colSums = this.colSum(A);
var colSumMatrix = this.repmat(colSums, A.size()[0]);
var newMatrix = math.dotDivide(A, colSumMatrix);
return newMatrix;
};
_exports.inflate = function inflate(A, factor) {
return this.normalizeColumns(math.dotPow(A, factor));
};
_exports.expand = function expand(A, factor) {
return math.pow(A, factor);
};
_exports.addDiagonal = function addDiagonal(A, value) {
var diag = math.eye(A.size());
return math.add(A, math.multiply(value, diag));
};
/* A is a square matrix */
_exports.getClusters = function getClusters(A) {
var clusters = [];
var n = A.size()[0];
for (var i = 0; i < n; i++) {
if (A.subset(math.index(i, i)) > 0.0001) {
var rowMatrix = A.subset(math.index(i, math.range(0, n)));
var cluster = this.rowMatrixToArray(rowMatrix).map(function (x, index) {
return x > 0.001 ? index : -1;
});
cluster = cluster.filter(function (x) {
return x >= 0;
});
clusters.push(cluster);
}
}
return clusters;
};
_exports.done = function done(M, i) {
var testMatrix = math.dotPow(M, 2);
var m = math.max(testMatrix) - math.min(testMatrix);
return m === 0;
};
// Takes an adjectancy matrix and options
_exports.cluster = function cluster(M, options) {
var opt = options || {};
var expandFactor = opt.expandFactor || 2;
var inflateFactor = opt.inflateFactor || 2;
var maxLoops = opt.maxLoops || 10;
var multFactor = opt.multFactor || 1;
var A = this.addDiagonal(M, multFactor);
A = this.normalizeColumns(A);
for (var i = 0; i < maxLoops; i++) {
A = this.inflate(A, inflateFactor);
A = this.expand(A, expandFactor);
if (this.done(A, i)) {
break;
}
}
return this.getClusters(A);
};