forked from d3/d3-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.js
128 lines (104 loc) · 2.77 KB
/
graph.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
(function(d3) {
d3.graph = function (graph) {
var graph = graph ? graph : {},
nodes = [],
links = [];
graph.description = function() {
return "d3.graph with " + nodes.length + " nodes and " + links.length + " links";
};
graph.nodes = function(x) {
if (!arguments.length) return nodes;
nodes = x;
return this;
};
graph.links = function(x) {
if (!arguments.length) return links;
links = x;
return this;
};
graph.matrix = function(x) {
if (!arguments.length) return d3.graph.listToMatrix(links);
links = d3.graph.matrixToList(x);
// TODO nodes
return this;
};
return graph;
};
// http://opendatastructures.org/ods-cpp/12_1_Representing_Graph_Mat.html
d3.graph.matrix = function(matrix) {
var matrix = matrix ? matrix : [];
var matrixObj = function(i,j) {
return matrix[i][j];
};
matrixObj.description = function() {
return "A " + matrix.length +
" by " + matrix.length +
" adjacency matrix";
};
matrixObj.data = matrixObj.matrix = function(x) {
if (!arguments.length) return matrix;
matrix = x;
return this;
};
matrixObj.set = matrixObj.addEdge = function(i,j,value) {
matrix[i][j] = value ? value : 1;
return this;
};
matrixObj.remove = matrixObj.removeEdge = function(i,j) {
matrix[i][j] = 0;
return this;
};
matrixObj.has = matrixObj.hasEdge = function(i,j) {
return !!matrix[i][j];
};
matrixObj.outE = matrixObj.outEdges = function(i) {
var edges = [],
n = matrix.length;
var j = -1; while (++j < n) {
if (matrix[i][j]) edges.push(j);
}
return edges;
};
matrixObj.inE = matrixObj.inEdges = function(i) {
var edges = [],
n = matrix.length;
var j = -1; while (++j < n) {
if (matrix[j][i]) edges.push(j);
}
return edges;
};
return matrixObj;
};
d3.graph.listToMatrix = function(links) {
var matrix = [],
n = links.length,
max = d3.max(links, function(d) {
return d3.max([d.source, d.target]);
});
// zero matrix
var i = -1; while (++i <= max) {
matrix[i] = [];
var j = -1; while (++j <= max) {
matrix[i][j] = 0;
}
}
i = -1; while (++i < n) {
matrix[ links[i].source ][ links[i].target ] = links[i].value;
}
return matrix;
};
d3.graph.matrixToList = function(matrix) {
var links = [],
n = matrix.length;
var i = -1; while (++i < n) {
var j = -1; while (++j < n) {
links.push({
source: i,
target: j,
value: matrix[i][j]
});
}
}
return links;
};
})(d3);