forked from philogb/mingle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.js
935 lines (724 loc) · 21 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
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
;(function () {
function descriptor(object) {
var desc = {}, p;
for (p in object) {
desc[p] = {
value: object[p],
writable: true,
enumerable: true,
configurable: true
};
}
return desc;
}
function merge(proto, object) {
return Object.create(proto, descriptor(object));
}
function extend(proto, object) {
var p;
for (p in object) {
proto[p] = object[p];
}
}
/*
* File: Graph.js
*
*/
/*
Class: Graph
A Graph Class that provides useful manipulation functions. You can find more manipulation methods in the <Graph.Util> object.
An instance of this class can be accessed by using the *graph* parameter of any tree or graph visualization.
Example:
(start code js)
//create new visualization
var viz = new $jit.Viz(options);
//load JSON data
viz.loadJSON(json);
//access model
viz.graph; //<Graph> instance
(end code)
Implements:
The following <Graph.Util> methods are implemented in <Graph>
- <Graph.Util.getNode>
- <Graph.Util.eachNode>
- <Graph.Util.computeLevels>
- <Graph.Util.eachBFS>
- <Graph.Util.clean>
- <Graph.Util.getClosestNodeToPos>
- <Graph.Util.getClosestNodeToOrigin>
*/
var Graph = function(opt) {
this.opt = merge({
node: {}
}, opt || {});
this.nodes = {};
this.edges = {};
};
Graph.fromJSON = function(json) {
var nodes = json.nodes,
edges = json.edges,
Node = Graph.Node,
Edge = Graph.Edge,
graph = new Graph(),
k;
for (k in nodes) {
nodes[k] = Node.fromJSON(nodes[k]);
}
graph.nodes = nodes;
for (k in edges) {
edges[k] = Edge.fromJSON(graph, edges[k]);
}
graph.edges = edges;
return graph;
};
Graph.prototype = {
clear: function() {
this.nodes = {};
this.edges = {};
},
//serialize
toJSON: function() {
var nodes = {},
edges = {},
gNodes = this.nodes,
gEdges = this.edges,
k;
for (k in gNodes) {
nodes[k] = gNodes[k].toJSON();
}
for (k in gEdges) {
edges[k] = gEdges[k].toJSON();
}
return { nodes: nodes, edges: edges };
},
/*
Method: getNode
Returns a <Graph.Node> by *id*.
Parameters:
id - (string) A <Graph.Node> id.
Example:
(start code js)
var node = graph.getNode('nodeId');
(end code)
*/
getNode: function(id) {
if(this.hasNode(id)) return this.nodes[id];
return false;
},
/*
Method: get
An alias for <Graph.Util.getNode>. Returns a node by *id*.
Parameters:
id - (string) A <Graph.Node> id.
Example:
(start code js)
var node = graph.get('nodeId');
(end code)
*/
get: function(id) {
return this.getNode(id);
},
/*
Method: getByName
Returns a <Graph.Node> by *name*.
Parameters:
name - (string) A <Graph.Node> name.
Example:
(start code js)
var node = graph.getByName('someName');
(end code)
*/
getByName: function(name) {
for(var id in this.nodes) {
var n = this.nodes[id];
if(n.name == name) return n;
}
return false;
},
/*
Method: getEdge
Returns a <Graph.Edge> object connecting nodes with ids *id* and *id2*.
Parameters:
id - (string) A <Graph.Node> id.
id2 - (string) A <Graph.Node> id.
*/
getEdge: function (id, id2) {
if(id in this.edges) {
return this.edges[id][id2];
}
return false;
},
/*
Method: addNode
Adds a node.
Parameters:
obj - An object with the properties described below
id - (string) A node id
name - (string) A node's name
data - (object) A node's data hash
See also:
<Graph.Node>
*/
addNode: function(obj) {
if(!this.nodes[obj.id]) {
var edges = this.edges[obj.id] = {};
this.nodes[obj.id] = new Graph.Node(merge({
'id': obj.id,
'name': obj.name,
'data': merge(obj.data || {}, {}),
'adjacencies': edges
}, this.opt.node));
}
return this.nodes[obj.id];
},
/*
Method: addEdge
Connects nodes specified by *obj* and *obj2*. If not found, nodes are created.
Parameters:
obj - (object) A <Graph.Node> object.
obj2 - (object) Another <Graph.Node> object.
data - (object) A data object. Used to store some extra information in the <Graph.Edge> object created.
See also:
<Graph.Node>, <Graph.Edge>
*/
addEdge: function (obj, obj2, data) {
if(!this.hasNode(obj.id)) { this.addNode(obj); }
if(!this.hasNode(obj2.id)) { this.addNode(obj2); }
obj = this.nodes[obj.id]; obj2 = this.nodes[obj2.id];
if(!obj.adjacentTo(obj2)) {
var adjsObj = this.edges[obj.id] = this.edges[obj.id] || {};
var adjsObj2 = this.edges[obj2.id] = this.edges[obj2.id] || {};
adjsObj[obj2.id] = adjsObj2[obj.id] = new Graph.Edge(obj, obj2, data, this.Edge, this.Label);
return adjsObj[obj2.id];
}
return this.edges[obj.id][obj2.id];
},
/*
Method: removeNode
Removes a <Graph.Node> matching the specified *id*.
Parameters:
id - (string) A node's id.
*/
removeNode: function(id) {
if(this.hasNode(id)) {
delete this.nodes[id];
var adjs = this.edges[id];
for(var to in adjs) {
delete this.edges[to][id];
}
delete this.edges[id];
}
},
/*
Method: removeEdge
Removes a <Graph.Edge> matching *id1* and *id2*.
Parameters:
id1 - (string) A <Graph.Node> id.
id2 - (string) A <Graph.Node> id.
*/
removeEdge: function(id1, id2) {
delete this.edges[id1][id2];
delete this.edges[id2][id1];
},
/*
Method: hasNode
Returns a boolean indicating if the node belongs to the <Graph> or not.
Parameters:
id - (string) Node id.
*/
hasNode: function(id) {
return id in this.nodes;
},
/*
Method: empty
Empties the Graph
*/
empty: function() { this.nodes = {}; this.edges = {}; }
};
/*
Class: Graph.Node
A <Graph> node.
Implements:
<Accessors> methods.
The following <Graph.Util> methods are implemented by <Graph.Node>
- <Graph.Util.eachEdge>
- <Graph.Util.eachLevel>
- <Graph.Util.eachSubgraph>
- <Graph.Util.eachSubnode>
- <Graph.Util.anySubnode>
- <Graph.Util.getSubnodes>
- <Graph.Util.getParents>
- <Graph.Util.isDescendantOf>
*/
Graph.Node = function(opt) {
var innerOptions = {
'id': '',
'name': '',
'data': {},
'adjacencies': {}
};
extend(this, merge(innerOptions, opt));
};
Graph.Node.fromJSON = function(json) {
return new Graph.Node(json);
};
Graph.Node.prototype = {
toJSON: function() {
return {
id: this.id,
name: this.name,
data: this.data,
adjacencies: this.adjacencies
};
},
/*
Method: adjacentTo
Indicates if the node is adjacent to the node specified by id
Parameters:
id - (string) A node id.
Example:
(start code js)
node.adjacentTo('nodeId') == true;
(end code)
*/
adjacentTo: function(node) {
return node.id in this.adjacencies;
},
/*
Method: getAdjacency
Returns a <Graph.Edge> object connecting the current <Graph.Node> and the node having *id* as id.
Parameters:
id - (string) A node id.
*/
getEdge: function(id) {
return this.adjacencies[id];
},
/*
Method: toString
Returns a String with information on the Node.
*/
toString: function() {
return 'Node(' + JSON.stringify([this.id, this.name, this.data, this.adjacencies]) + ')';
}
};
/*
Class: Graph.Edge
A <Graph> adjacence (or edge) connecting two <Graph.Nodes>.
Implements:
<Accessors> methods.
See also:
<Graph>, <Graph.Node>
Properties:
nodeFrom - A <Graph.Node> connected by this edge.
nodeTo - Another <Graph.Node> connected by this edge.
data - Node data property containing a hash (i.e {}) with custom options.
*/
Graph.Edge = function(nodeFrom, nodeTo, data) {
this.nodeFrom = nodeFrom;
this.nodeTo = nodeTo;
this.data = data || {};
};
Graph.Edge.fromJSON = function(graph, edgeJSON) {
return new Graph.Edge(graph.get(edgeJSON.nodeFrom),
graph.get(edgeJSON.nodeTo),
edgeJSON.data);
};
Graph.Edge.prototype.toJSON = function() {
return {
nodeFrom: this.nodeFrom.id,
nodeTo: this.nodeTo.id,
data: this.data
};
};
/*
Object: Graph.Util
<Graph> traversal and processing utility object.
Note:
For your convenience some of these methods have also been appended to <Graph> and <Graph.Node> classes.
*/
Graph.Util = {
/*
filter
For internal use only. Provides a filtering function based on flags.
*/
filter: function(param) {
if(!param || !(typeof param == 'string')) return function() { return true; };
var props = param.split(" ");
return function(elem) {
for(var i=0; i<props.length; i++) {
if(elem[props[i]]) {
return false;
}
}
return true;
};
},
/*
Method: getNode
Returns a <Graph.Node> by *id*.
Also implemented by:
<Graph>
Parameters:
graph - (object) A <Graph> instance.
id - (string) A <Graph.Node> id.
Example:
(start code js)
$jit.Graph.Util.getNode(graph, 'nodeid');
//or...
graph.getNode('nodeid');
(end code)
*/
getNode: function(graph, id) {
return graph.nodes[id];
},
/*
Method: eachNode
Iterates over <Graph> nodes performing an *action*.
Also implemented by:
<Graph>.
Parameters:
graph - (object) A <Graph> instance.
action - (function) A callback function having a <Graph.Node> as first formal parameter.
Example:
(start code js)
$jit.Graph.Util.eachNode(graph, function(node) {
alert(node.name);
});
//or...
graph.eachNode(function(node) {
alert(node.name);
});
(end code)
*/
eachNode: function(graph, action, flags) {
var filter = this.filter(flags);
for(var i in graph.nodes) {
if(filter(graph.nodes[i])) action(graph.nodes[i]);
}
},
/*
Method: each
Iterates over <Graph> nodes performing an *action*. It's an alias for <Graph.Util.eachNode>.
Also implemented by:
<Graph>.
Parameters:
graph - (object) A <Graph> instance.
action - (function) A callback function having a <Graph.Node> as first formal parameter.
Example:
(start code js)
$jit.Graph.Util.each(graph, function(node) {
alert(node.name);
});
//or...
graph.each(function(node) {
alert(node.name);
});
(end code)
*/
each: function(graph, action, flags) {
this.eachNode(graph, action, flags);
},
/*
Method: eachEdge
Iterates over <Graph.Node> adjacencies applying the *action* function.
Also implemented by:
<Graph.Node>.
Parameters:
node - (object) A <Graph.Node>.
action - (function) A callback function having <Graph.Edge> as first formal parameter.
Example:
(start code js)
$jit.Graph.Util.eachEdge(node, function(adj) {
alert(adj.nodeTo.name);
});
//or...
node.eachEdge(function(adj) {
alert(adj.nodeTo.name);
});
(end code)
*/
eachEdge: function(node, action, flags) {
var adj = node.adjacencies, filter = this.filter(flags);
for(var id in adj) {
var a = adj[id];
if(filter(a)) {
if(a.nodeFrom != node) {
var tmp = a.nodeFrom;
a.nodeFrom = a.nodeTo;
a.nodeTo = tmp;
}
action(a, id);
}
}
},
/*
Method: computeLevels
Performs a BFS traversal setting the correct depth for each node.
Also implemented by:
<Graph>.
Note:
The depth of each node can then be accessed by
>node.depth
Parameters:
graph - (object) A <Graph>.
id - (string) A starting node id for the BFS traversal.
startDepth - (optional|number) A minimum depth value. Default's 0.
*/
computeLevels: function(graph, id, startDepth, flags) {
startDepth = startDepth || 0;
var filter = this.filter(flags);
this.eachNode(graph, function(elem) {
elem._flag = false;
elem.depth = -1;
}, flags);
var root = graph.getNode(id);
root.depth = startDepth;
var queue = [root];
while(queue.length != 0) {
var node = queue.pop();
node._flag = true;
this.eachEdge(node, function(adj) {
var n = adj.nodeTo;
if(n._flag == false && filter(n) && !adj._hiding) {
if(n.depth < 0) n.depth = node.depth + 1 + startDepth;
queue.unshift(n);
}
}, flags);
}
},
/*
Method: eachBFS
Performs a BFS traversal applying *action* to each <Graph.Node>.
Also implemented by:
<Graph>.
Parameters:
graph - (object) A <Graph>.
id - (string) A starting node id for the BFS traversal.
action - (function) A callback function having a <Graph.Node> as first formal parameter.
Example:
(start code js)
$jit.Graph.Util.eachBFS(graph, 'mynodeid', function(node) {
alert(node.name);
});
//or...
graph.eachBFS('mynodeid', function(node) {
alert(node.name);
});
(end code)
*/
eachBFS: function(graph, id, action, flags) {
var filter = this.filter(flags);
this.clean(graph);
var queue = [graph.getNode(id)];
while(queue.length != 0) {
var node = queue.pop();
if (!node) return;
node._flag = true;
action(node, node.depth);
this.eachEdge(node, function(adj) {
var n = adj.nodeTo;
if(n._flag == false && filter(n) && !adj._hiding) {
n._flag = true;
queue.unshift(n);
}
}, flags);
}
},
/*
Method: eachLevel
Iterates over a node's subgraph applying *action* to the nodes of relative depth between *levelBegin* and *levelEnd*.
In case you need to break the iteration, *action* should return false.
Also implemented by:
<Graph.Node>.
Parameters:
node - (object) A <Graph.Node>.
levelBegin - (number) A relative level value.
levelEnd - (number) A relative level value.
action - (function) A callback function having a <Graph.Node> as first formal parameter.
*/
eachLevel: function(node, levelBegin, levelEnd, action, flags) {
var d = node.depth, filter = this.filter(flags), that = this, shouldContinue = true;
levelEnd = levelEnd === false? Number.MAX_VALUE -d : levelEnd;
(function loopLevel(node, levelBegin, levelEnd) {
if(!shouldContinue) return;
var d = node.depth, ret;
if(d >= levelBegin && d <= levelEnd && filter(node)) ret = action(node, d);
if(typeof ret !== "undefined") shouldContinue = ret;
if(shouldContinue && d < levelEnd) {
that.eachEdge(node, function(adj) {
var n = adj.nodeTo;
if(n.depth > d) loopLevel(n, levelBegin, levelEnd);
});
}
})(node, levelBegin + d, levelEnd + d);
},
/*
Method: eachSubgraph
Iterates over a node's children recursively.
Also implemented by:
<Graph.Node>.
Parameters:
node - (object) A <Graph.Node>.
action - (function) A callback function having a <Graph.Node> as first formal parameter.
Example:
(start code js)
$jit.Graph.Util.eachSubgraph(node, function(node) {
alert(node.name);
});
//or...
node.eachSubgraph(function(node) {
alert(node.name);
});
(end code)
*/
eachSubgraph: function(node, action, flags) {
this.eachLevel(node, 0, false, action, flags);
},
/*
Method: eachSubnode
Iterates over a node's children (without deeper recursion).
Also implemented by:
<Graph.Node>.
Parameters:
node - (object) A <Graph.Node>.
action - (function) A callback function having a <Graph.Node> as first formal parameter.
Example:
(start code js)
$jit.Graph.Util.eachSubnode(node, function(node) {
alert(node.name);
});
//or...
node.eachSubnode(function(node) {
alert(node.name);
});
(end code)
*/
eachSubnode: function(node, action, flags) {
this.eachLevel(node, 1, 1, action, flags);
},
/*
Method: anySubnode
Returns *true* if any subnode matches the given condition.
Also implemented by:
<Graph.Node>.
Parameters:
node - (object) A <Graph.Node>.
cond - (function) A callback function returning a Boolean instance. This function has as first formal parameter a <Graph.Node>.
Example:
(start code js)
$jit.Graph.Util.anySubnode(node, function(node) { return node.name == "mynodename"; });
//or...
node.anySubnode(function(node) { return node.name == 'mynodename'; });
(end code)
*/
anySubnode: function(node, cond, flags) {
var flag = false;
cond = cond || function() { return true; };
var c = typeof cond == 'string'? function(n) { return n[cond]; } : cond;
this.eachSubnode(node, function(elem) {
if(c(elem)) flag = true;
}, flags);
return flag;
},
/*
Method: getSubnodes
Collects all subnodes for a specified node.
The *level* parameter filters nodes having relative depth of *level* from the root node.
Also implemented by:
<Graph.Node>.
Parameters:
node - (object) A <Graph.Node>.
level - (optional|number) Default's *0*. A starting relative depth for collecting nodes.
Returns:
An array of nodes.
*/
getSubnodes: function(node, level, flags) {
var ans = [], that = this;
level = level || 0;
var levelStart, levelEnd;
if(Array.isArray(level) == 'array') {
levelStart = level[0];
levelEnd = level[1];
} else {
levelStart = level;
levelEnd = Number.MAX_VALUE - node.depth;
}
this.eachLevel(node, levelStart, levelEnd, function(n) {
ans.push(n);
}, flags);
return ans;
},
/*
Method: getParents
Returns an Array of <Graph.Nodes> which are parents of the given node.
Also implemented by:
<Graph.Node>.
Parameters:
node - (object) A <Graph.Node>.
Returns:
An Array of <Graph.Nodes>.
Example:
(start code js)
var pars = $jit.Graph.Util.getParents(node);
//or...
var pars = node.getParents();
if(pars.length > 0) {
//do stuff with parents
}
(end code)
*/
getParents: function(node) {
var ans = [];
this.eachEdge(node, function(adj) {
var n = adj.nodeTo;
if(n.depth < node.depth) ans.push(n);
});
return ans;
},
/*
Method: isDescendantOf
Returns a boolean indicating if some node is descendant of the node with the given id.
Also implemented by:
<Graph.Node>.
Parameters:
node - (object) A <Graph.Node>.
id - (string) A <Graph.Node> id.
Example:
(start code js)
$jit.Graph.Util.isDescendantOf(node, "nodeid"); //true|false
//or...
node.isDescendantOf('nodeid');//true|false
(end code)
*/
isDescendantOf: function(node, id) {
if(node.id == id) return true;
var pars = this.getParents(node), ans = false;
for ( var i = 0; !ans && i < pars.length; i++) {
ans = ans || this.isDescendantOf(pars[i], id);
}
return ans;
},
/*
Method: clean
Cleans flags from nodes.
Also implemented by:
<Graph>.
Parameters:
graph - A <Graph> instance.
*/
clean: function(graph) { this.eachNode(graph, function(elem) { elem._flag = false; }); }
};
//Append graph methods to <Graph>
['get', 'getNode', 'each', 'eachNode', 'computeLevels', 'eachBFS', 'clean'].forEach(function(m) {
Graph.prototype[m] = function() {
return Graph.Util[m].apply(Graph.Util, [this].concat(Array.prototype.slice.call(arguments)));
};
});
//Append node methods to <Graph.Node>
['eachEdge', 'eachLevel', 'eachSubgraph', 'eachSubnode', 'anySubnode', 'getSubnodes', 'getParents', 'isDescendantOf'].forEach(function(m) {
Graph.Node.prototype[m] = function() {
return Graph.Util[m].apply(Graph.Util, [this].concat(Array.prototype.slice.call(arguments)));
};
});
this.Graph = Graph;
})();