-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkgraph.js
661 lines (604 loc) · 24.5 KB
/
kgraph.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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
(function (kgraph, $, undefined) {
var Vertex = (function () {
class Vertex {
constructor(id, label = id) {
this.id = id;
this.label = label;
}
toString() {
return '{id: ' + this.id + ', label: ' + this.label + '}';
}
}
return Vertex
})()
var Edge = (function () {
class Edge {
constructor(from, to, weight = 1) {
this.from = from;
this.to = to;
this.weight = weight;
}
toString() {
return '{from: ' + this.from + ', to: ' + this.to + ', weight: ' + this.weight.toFixed(2) + '}';
}
}
return Edge
})()
const GraphTypes = {
SIMPLE: 1,
DIRECTED_SIMPLE: 2,
WEIGHTED: 3,
DIRECTED_WEIGHTED: 4
};
var GraphFactory = (function () {
class GraphFactory {
constructor() { }
createUndirectedGraph(nodes = [], edges = []) {
return this._createGraph(nodes, edges, GraphTypes.SIMPLE);
}
createUndirectedWeightedGraph(nodes = [], edges = []) {
return this._createGraph(nodes, edges, GraphTypes.WEIGHTED);
}
createDirectedGraph(nodes = [], edges = []) {
return this._createGraph(nodes, edges, GraphTypes.DIRECTED_SIMPLE);
}
createDirectedWeightedGraph(nodes = [], edges = []) {
return this._createGraph(nodes, edges, GraphTypes.DIRECTED_WEIGHTED);
}
_createGraph(nodes, edges, graphType) {
switch (graphType) {
case GraphTypes.SIMPLE:
return new SimpleGraph(nodes, edges);
case GraphTypes.DIRECTED_SIMPLE:
return new DirectedSimpleGraph(nodes, edges);
case GraphTypes.WEIGHTED:
return new WeightedGraph(nodes, edges);
case GraphTypes.DIRECTED_WEIGHTED:
return new DirectedWeightedGraph(nodes, edges);
}
}
}
class Graph {
constructor(nodes) {
this.nodes = nodes;
this.edges = [];
this.edgeCount = 0;
this.neighbourList = [];
this.edgeWeights = [];
this.adjacencyMatrix = [];
for (var i = 0; i < nodes.length; i++) {
this.neighbourList.push([]);
this.edgeWeights.push(new Array(nodes.length).fill(Infinity));
this.edgeWeights[i][i] = 0;
this.adjacencyMatrix.push(new Array(nodes.length).fill(0));
}
}
size() {
return this.nodes.length;
}
getNodes() {
return this.nodes;
}
getEdges() {
return this.edges;
}
getAdjacencyMatrix() {
return this.adjacencyMatrix;
}
getWeightMatrix() {
return this.edgeWeights;
}
addNode(object) {
this.nodes.push(object);
this.neighbourList.push([]);
this.edgeWeights.push(new Array(this.size()).fill(Infinity));
this.edgeWeights[this.size() - 1][this.size() - 1] = 0;
this.adjacencyMatrix.forEach(row => row.push(0));
this.adjacencyMatrix.push(new Array(this.size()).fill(0));
}
get(node) {
return this.nodes[node];
}
getNeighbours(node) {
return this.neighbourList[node];
}
// FIXME: Not true for directed graphs.
getDegreeCentrality(node) {
return this.degree(node) / this.size() - 1;
}
getEdgeWeight(node, neighbour) {
return this.edgeWeights[node][neighbour];
}
// FIXME: Only true for simple graphs.
localClusteringCoefficient(node) {
var neighbours = this.getNeighbours(node);
if (neighbours.length < 2)
return 0;
var maxNeighbourEdges = neighbours.length * (neighbours.length - 1);
var neighbourEdges = 0;
for (var i = 0; i < neighbours.length; i++) {
for (var j = 0; j < neighbours.length; j++) {
neighbourEdges += this.adjacencyMatrix[i][j];
}
}
return neighbourEdges / maxNeighbourEdges;
}
isConnected() {
for (var node = 0; node < this.size(); node++)
if (this.isIsolated(node))
return false;
return true;
}
isIsolated(node) {
return this.degree(node) === 0;
}
isAdjacent(node, neighbour) {
return this.adjacencyMatrix[node][neighbour] === 1;
}
degrees() {
var degrees = [];
for (var node = 0; node < this.size(); node++)
degrees.push(this.degree(node));
return degrees;
}
maxDegree() {
return this.degrees().reduce((max,value) => Math.max(max,value), -1)
}
minDegree() {
return this.degrees().reduce((min,value) => Math.min(min,value), Infinity)
}
degreeSum() {
return this.degrees().reduce((sum,value) => sum + value, 0);
}
averageDegree() {
return this.degreeSum() / (this.size() -1);
}
centralisation() {
var maxDegree = this.maxDegree();
var maxSum = (this.size() - 1) * (this.size() - 2)
var sum = 0;
for (var node = 0; node < this.size(); node++)
sum += maxDegree - this.degree(node);
return sum / maxSum;
}
// FIXME: Only true for simple graphs
globalClusteringCoefficient() {
var localSum = 0;
for (var node = 0; node < this.size(); node++) {
localSum += this.getLocalClusteringCoefficient(node);
console.log(localSum);
}
return localSum / this.size();
}
contains(node) {
if (node instanceof Array)
return this.containsAll(node);
if (typeof node === 'number')
return this.nodes[node] ? true : false;
if (typeof node === 'object')
return this.nodes.includes(node);
return false;
}
containsAll(nodes) {
return nodes.every(node => this.contains(node));
}
_addEdge(from, to, weight, undirected) {
this.neighbourList[from].push(to);
this.adjacencyMatrix[from][to] = 1;
this.edgeWeights[from][to] = weight;
this.edgeCount++;
this.edges.push(new Edge(from, to, weight))
if (undirected) {
this.edgeCount--;
this._addEdge(to, from, weight, false);
}
}
_centralisation(normalised, directed) {
/**
* Returns the centralisation of the graph.
*
* Centralisation is a network measure, describing how unevenly
* degrees are distributed between high degree and low degree
* nodes. A high centralisation (close to 1), indicates that the
* difference between all nodes and the ones with the highest
* centrality is high.
*
*/
var centralisation = this.maxDegree() * this.size() - this.degreeSum();
if (normalised) {
var normalisation = directed ?
(this.size() - 1) * (this.size() - 2) * 2:
(this.size() - 1) * (this.size() - 2);
centralisation /= normalisation;
}
return centralisation;
}
_degree(id, directed) {
var neighbours = this.getNeighbours(id);
var degree = neighbours.length;
if (directed) {
neighbours.forEach(neighbour => {
if (this.isAdjacent(neighbour, node))
degree++;
})
}
return degree;
}
_show(directed, weighted) {
for (var node = 0; node < this.size(); node++) {
for (var neighbour = 0; neighbour < this.size(); neighbour++) {
var weight = this.getEdgeWeight(node, neighbour);
if (0 < weight && weight < Infinity)
console.log(showString(node, weight.toFixed(2), neighbour, directed, weighted));
}
}
function showString(node, weight, neighbour, directed, weighted) {
var leftArrow = '<'
if (!weighted)
weight = '';
if (directed)
leftArrow = '';
return `${node} ${leftArrow}-${weight}-> ${neighbour}`
}
}
}
class SimpleGraph extends Graph {
constructor(nodes = [], edges = []) {
super(nodes);
edges.forEach(edge => {
this.addEdge(edge.from, edge.to);
});
}
addEdge(from, to) {
this._addEdge(from, to, 1, true);
}
centralisation(normalised = true) {
return this._centralisation(normalised, false);
}
degree(node) {
return this._degree(node, false);
}
show() {
this._show(false, false);
}
}
class DirectedSimpleGraph extends Graph {
constructor(nodes = [], edges = []) {
super(nodes);
edges.forEach(edge => {
this.addEdge(edge.from, edge.to);
})
}
addEdge(from, to) {
this._addEdge(from, to, 1, false);
}
centralisation(normalised = true) {
return this._centralisation(normalised, false);
}
degree(node) {
return this._degree(node, true);
}
show() {
return this._show(true, false);
}
}
class WeightedGraph extends Graph {
constructor(nodes = [], edges = []) {
super(nodes);
edges.forEach(edge => {
this.addEdge(edge.from, edge.to, edge.weight);
})
}
addEdge(from, to, weight) {
this._addEdge(from, to, weight, true);
}
centralisation(normalised = true) {
return this._centralisation(normalised, false);
}
degree(node) {
return this._degree(node, false);
}
show() {
return this._show(false, true);
}
}
class DirectedWeightedGraph extends Graph {
constructor(nodes = [], edges = []) {
super(nodes);
edges.forEach(edge => {
this.addEdge(edge.from, edge.to, edge.weight);
})
}
addEdge(from, to, weight) {
this._addEdge(from, to, weight, false);
}
centralisation(normalised = true) {
return this._centralisation(normalised, true);
}
degree(node) {
return this._degree(node, true);
}
show() {
return this._show(true, true);
}
}
return GraphFactory
})()
var GraphSearcher = (function () {
class GraphSearcher {
constructor(graph) {
this.graph = graph;
this.distanceMatrix;
this.pathNeighbour;
}
distance(start, target) {
var path = this.bfs(start, target)
if (path.length > 0)
return path.length
return Infinity
}
pathLengths() {
var lengths = []
for (let i = 0; i < this.graph.size(); i++) {
for (let j = 0; j < this.graph.size(); j++) {
var path = this.bfs(i, j)
lengths.push(path.length)
}
}
return lengths
}
// FIXME: Edge cases when node is isolated.
eccentricity(node) {
if (this.graph.isIsolated(node))
return Infinity;
var distances = this.distanceMatrix || this.getDistanceMatrix()
return distances[node]
.filter(value => 0 < value && value < Infinity)
.reduce((max,value) => Math.max(max, value), 0)
}
eccentricities(nodes) {
if (nodes === undefined) {
nodes = [];
for (var node = 0; node < this.graph.size(); node++)
nodes.push(node)
return this.eccentricities(nodes)
}
if (nodes instanceof Array)
return nodes.map(node => this.eccentricity(node), this)
console.log('Illegal input passed to Graphsearcher.eccentricities.\n Expected array, got ' + nodes)
return []
}
diameter() {
var max = 0;
for (var node = 0; node < this.graph.size(); node++) {
var eccentricity = this.eccentricity(node);
max = eccentricity > max ? eccentricity : max;
}
return max;
}
radius() {
var min = Infinity;
for (var node = 0; node < this.graph.size(); node++) {
var eccentricity = this.eccentricity(node);
min = eccentricity < min ? eccentricity : min;
}
return min;
}
depthFirstSearch(start, target) {
var startTime = window.performance.now();
var startNode = new SimpleSearchNode(start, null);
var frontier = [startNode];
var explored = {};
while (frontier.length > 0) {
var candidate = frontier.pop();
if (candidate.id == target) {
console.log("DFS Elapsed Time:" + (window.performance.now() - startTime));
return retrievePathTo(candidate);
}
explored[candidate.id] = true;
var neighbours = graph.getNeighbours(candidate.id);
for (var i in neighbours) {
if (!explored[neighbours[i]])
frontier.push(new SimpleSearchNode(neighbours[i], candidate));
}
}
return [];
}
breadthFirstSearch(start, target) {
if (start === target)
return [start]
var explored = {};
var queue = [new SimpleSearchNode(start, null)];
while (queue.length > 0) {
var candidate = queue.shift();
var neighbours = this.graph.getNeighbours(candidate.id);
if (neighbours !== undefined) {
if (neighbours.includes(target)) {
return retrievePathTo(new SimpleSearchNode(target, candidate));
}
neighbours.forEach(visitNeighbour);
}
}
return [];
function visitNeighbour(neighbour) {
if (!explored[neighbour]) {
explored[neighbour] = true;
queue.push(new SimpleSearchNode(neighbour, candidate));
}
}
}
getPath(start, target, directed) {
directed = directed === undefined ? true : directed;
var path = this.bfs(start, target);
if (path.length === 0 && directed === false) {
path = this.bfs(target, start);
}
return path;
}
aStarSearch(start, target, heuristicFunction, costFunction) {
var startTime = window.performance.now();
var heuristic = function (vertex) {
return heuristicFunction(graph.get(vertex), graph.get(target));
};
var costs = function (vertex, anotherVertex) {
return costFunction(graph.get(vertex), graph.get(anotherVertex));
};
var frontier = new PriorityQueue();
var explored = {};
var startNode = new SearchNode(start, null);
frontier.add(startNode, startNode.estimatedCosts);
while (frontier.size() > 0) {
var candidate = frontier.poll();
if (isTarget(candidate)) {
console.log("A* Elapsed Time:" + (window.performance.now() - startTime));
return retrievePathTo(candidate);
}
expandFrontier(candidate);
}
console.log("No Path between nodes found. Returning closest path.");
return retrievePathTo(candidate);
function expandFrontier(searchNode) {
explored[searchNode.id] = true;
var neighbours = graph.getNeighbours(searchNode.id);
neighbours.forEach(function (neighbour) {
if (!explored[neighbour]) {
var neighbourNode = new SearchNode(neighbour, searchNode);
frontier.add(neighbourNode, neighbourNode.estimatedCosts);
}
});
}
function retrievePathTo(searchNode) {
if (searchNode.parent == null)
return [searchNode.id];
else
return [searchNode.id].concat(retrievePathTo(searchNode.parent));
}
function isTarget(searchNode) {
return searchNode.id == target;
}
function SearchNode(vertex, parent) {
this.id = vertex;
this.parent = parent;
this.costs = (parent !== null) ? costs(parent.id, vertex) + parent.costs : 0;
this.estimatedCosts = heuristic(vertex) + this.costs;
}
}
getPathNeighbours() {
/**
* Returns a matrix M of closest neighbours on a path from
* Node a to Node b.
*
* M[a][b] returns the closest neighbour of a on the path to b.
* The returned neighbour is the node index in the source graph.
*/
var graph = this.graph;
var pathDistance = this.distanceMatrix || this.getDistanceMatrix();
var pathNeighbour = new Array(graph.size());
for (var n = 0; n < graph.size(); n++) {
pathNeighbour[n] = new Array(graph.size()).fill(null);
}
for (var start = 0; start < graph.size(); start++) {
for (var target = 0; target < graph.size(); target++) {
if (pathDistance[start][target] != Infinity && start !== target) {
var neighbours = graph.getNeighbours(start);
var closest = null;
var min = Infinity;
neighbours.forEach(neighbour => {
if (pathDistance[neighbour][target] < min) {
min = pathDistance[neighbour][target];
closest = neighbour;
}
})
pathNeighbour[start][target] = closest;
}
}
}
this.pathNeighbour = pathNeighbour;
return pathNeighbour;
}
getDistanceMatrix() {
/**
* Returns a matrix M of distances between two Nodes a and b,
* based on the Floyd-Warshall Algorithm.
*
* M[a][b] returns the distance between a and b. The distance
* is the length of the shortest path between a and b.
*/
var graph = this.graph;
var distances = graph.getWeightMatrix();
for (var n = 0; n < graph.size(); n++) {
for (var i = 0; i < graph.size(); i++) {
for (var j = 0; j < graph.size(); j++) {
var directPath = distances[i][j];
var indirectPath = distances[i][n] + distances[n][j];
if (directPath > indirectPath)
distances[i][j] = indirectPath;
}
}
}
this.distanceMatrix = distances;
return distances;
}
}
GraphSearcher.prototype.dfs = GraphSearcher.prototype.depthFirstSearch;
GraphSearcher.prototype.bfs = GraphSearcher.prototype.breadthFirstSearch;
function retrievePathTo(searchNode) {
if (searchNode.parent === null)
return [searchNode.id];
else
return [searchNode.id].concat(retrievePathTo(searchNode.parent));
}
function SimpleSearchNode(vertex, parentNode) {
this.id = vertex;
this.parent = parentNode;
}
function PriorityQueue() {
var dataStore = [];
this.size = function size() {
return dataStore.length;
}
this.poll = function poll() {
if (this.size() === 0)
return null;
return dataStore.pop().data;
}
this.peek = function peek() {
if (this.size() === 0)
return null;
return dataStore.peek().data;
}
this.add = function add(data, priority) {
dataStore.splice(findInsertionIndex(priority), 0, new PriorityNode(data, priority));
}
function findInsertionIndex(value) {
if (dataStore.length === 0)
return 0;
var minIndex = 0;
var maxIndex = dataStore.length;
do {
var currentIndex = Math.floor((minIndex + maxIndex) / 2);
var currentValue = dataStore[currentIndex].priority;
if (currentValue > value)
minIndex = currentIndex + 1;
else
maxIndex = currentIndex;
} while (minIndex < maxIndex);
return minIndex;
}
function PriorityNode(data, priority) {
this.data = data;
this.priority = priority;
}
}
return GraphSearcher
})()
function isSubGraph(graph, anotherGraph) {
}
function isDisjoint(graph, anotherGraph) {
}
kgraph.Vertex = Vertex
kgraph.Edge = Edge
kgraph.GraphFactory = new GraphFactory()
kgraph.GraphSearcher = GraphSearcher
return kgraph;
})(window.kgraph = window.kgraph || {}, jQuery)