-
-
Notifications
You must be signed in to change notification settings - Fork 362
/
LayoutEngine.js
1720 lines (1509 loc) · 54.1 KB
/
LayoutEngine.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
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* There's a mix-up with terms in the code. Following are the formal definitions:
*
* tree - a strict hierarchical network, i.e. every node has at most one parent
* forest - a collection of trees. These distinct trees are thus not connected.
*
* So:
* - in a network that is not a tree, there exist nodes with multiple parents.
* - a network consisting of unconnected sub-networks, of which at least one
* is not a tree, is not a forest.
*
* In the code, the definitions are:
*
* tree - any disconnected sub-network, strict hierarchical or not.
* forest - a bunch of these sub-networks
*
* The difference between tree and not-tree is important in the code, notably within
* to the block-shifting algorithm. The algorithm assumes formal trees and fails
* for not-trees, often in a spectacular manner (search for 'exploding network' in the issues).
*
* In order to distinguish the definitions in the following code, the adjective 'formal' is
* used. If 'formal' is absent, you must assume the non-formal definition.
*
* ----------------------------------------------------------------------------------
* NOTES
* =====
*
* A hierarchical layout is a different thing from a hierarchical network.
* The layout is a way to arrange the nodes in the view; this can be done
* on non-hierarchical networks as well. The converse is also possible.
*/
'use strict';
import TimSort from 'timsort';
import * as util from 'vis-util';
import NetworkUtil from '../NetworkUtil';
import { HorizontalStrategy, VerticalStrategy } from './components/DirectionStrategy.js';
import {
fillLevelsByDirectionLeaves,
fillLevelsByDirectionRoots
} from "./layout-engine";
/**
* Container for derived data on current network, relating to hierarchy.
*
* @private
*/
class HierarchicalStatus {
/**
* @ignore
*/
constructor() {
this.childrenReference = {}; // child id's per node id
this.parentReference = {}; // parent id's per node id
this.trees = {}; // tree id per node id; i.e. to which tree does given node id belong
this.distributionOrdering = {}; // The nodes per level, in the display order
this.levels = {}; // hierarchy level per node id
this.distributionIndex = {}; // The position of the node in the level sorting order, per node id.
this.isTree = false; // True if current network is a formal tree
this.treeIndex = -1; // Highest tree id in current network.
}
/**
* Add the relation between given nodes to the current state.
*
* @param {Node.id} parentNodeId
* @param {Node.id} childNodeId
*/
addRelation(parentNodeId, childNodeId) {
if (this.childrenReference[parentNodeId] === undefined) {
this.childrenReference[parentNodeId] = [];
}
this.childrenReference[parentNodeId].push(childNodeId);
if (this.parentReference[childNodeId] === undefined) {
this.parentReference[childNodeId] = [];
}
this.parentReference[childNodeId].push(parentNodeId);
}
/**
* Check if the current state is for a formal tree or formal forest.
*
* This is the case if every node has at most one parent.
*
* Pre: parentReference init'ed properly for current network
*/
checkIfTree() {
for (let i in this.parentReference) {
if (this.parentReference[i].length > 1) {
this.isTree = false;
return;
}
}
this.isTree = true;
}
/**
* Return the number of separate trees in the current network.
* @returns {number}
*/
numTrees() {
return (this.treeIndex + 1); // This assumes the indexes are assigned consecitively
}
/**
* Assign a tree id to a node
* @param {Node} node
* @param {string|number} treeId
*/
setTreeIndex(node, treeId) {
if (treeId === undefined) return; // Don't bother
if (this.trees[node.id] === undefined) {
this.trees[node.id] = treeId;
this.treeIndex = Math.max(treeId, this.treeIndex);
}
}
/**
* Ensure level for given id is defined.
*
* Sets level to zero for given node id if not already present
*
* @param {Node.id} nodeId
*/
ensureLevel(nodeId) {
if (this.levels[nodeId] === undefined) {
this.levels[nodeId] = 0;
}
}
/**
* get the maximum level of a branch.
*
* TODO: Never entered; find a test case to test this!
* @param {Node.id} nodeId
* @returns {number}
*/
getMaxLevel(nodeId) {
let accumulator = {};
let _getMaxLevel = (nodeId) => {
if (accumulator[nodeId] !== undefined) {
return accumulator[nodeId];
}
let level = this.levels[nodeId];
if (this.childrenReference[nodeId]) {
let children = this.childrenReference[nodeId];
if (children.length > 0) {
for (let i = 0; i < children.length; i++) {
level = Math.max(level,_getMaxLevel(children[i]));
}
}
}
accumulator[nodeId] = level;
return level;
};
return _getMaxLevel(nodeId);
}
/**
*
* @param {Node} nodeA
* @param {Node} nodeB
*/
levelDownstream(nodeA, nodeB) {
if (this.levels[nodeB.id] === undefined) {
// set initial level
if (this.levels[nodeA.id] === undefined) {
this.levels[nodeA.id] = 0;
}
// set level
this.levels[nodeB.id] = this.levels[nodeA.id] + 1;
}
}
/**
* Small util method to set the minimum levels of the nodes to zero.
*
* @param {Array.<Node>} nodes
*/
setMinLevelToZero(nodes) {
let minLevel = 1e9;
// get the minimum level
for (let nodeId in nodes) {
if (nodes.hasOwnProperty(nodeId)) {
if (this.levels[nodeId] !== undefined) {
minLevel = Math.min(this.levels[nodeId], minLevel);
}
}
}
// subtract the minimum from the set so we have a range starting from 0
for (let nodeId in nodes) {
if (nodes.hasOwnProperty(nodeId)) {
if (this.levels[nodeId] !== undefined) {
this.levels[nodeId] -= minLevel;
}
}
}
}
/**
* Get the min and max xy-coordinates of a given tree
*
* @param {Array.<Node>} nodes
* @param {number} index
* @returns {{min_x: number, max_x: number, min_y: number, max_y: number}}
*/
getTreeSize(nodes, index) {
let min_x = 1e9;
let max_x = -1e9;
let min_y = 1e9;
let max_y = -1e9;
for (let nodeId in this.trees) {
if (this.trees.hasOwnProperty(nodeId)) {
if (this.trees[nodeId] === index) {
let node = nodes[nodeId];
min_x = Math.min(node.x, min_x);
max_x = Math.max(node.x, max_x);
min_y = Math.min(node.y, min_y);
max_y = Math.max(node.y, max_y);
}
}
}
return {
min_x: min_x,
max_x: max_x,
min_y: min_y,
max_y: max_y
};
}
/**
* Check if two nodes have the same parent(s)
*
* @param {Node} node1
* @param {Node} node2
* @return {boolean} true if the two nodes have a same ancestor node, false otherwise
*/
hasSameParent(node1, node2) {
let parents1 = this.parentReference[node1.id];
let parents2 = this.parentReference[node2.id];
if (parents1 === undefined || parents2 === undefined) {
return false;
}
for (let i = 0; i < parents1.length; i++) {
for (let j = 0; j < parents2.length; j++) {
if (parents1[i] == parents2[j]) {
return true;
}
}
}
return false;
}
/**
* Check if two nodes are in the same tree.
*
* @param {Node} node1
* @param {Node} node2
* @return {Boolean} true if this is so, false otherwise
*/
inSameSubNetwork(node1, node2) {
return (this.trees[node1.id] === this.trees[node2.id]);
}
/**
* Get a list of the distinct levels in the current network
*
* @returns {Array}
*/
getLevels() {
return Object.keys(this.distributionOrdering);
}
/**
* Add a node to the ordering per level
*
* @param {Node} node
* @param {number} level
*/
addToOrdering(node, level) {
if (this.distributionOrdering[level] === undefined) {
this.distributionOrdering[level] = [];
}
var isPresent = false;
var curLevel = this.distributionOrdering[level];
for (var n in curLevel) {
//if (curLevel[n].id === node.id) {
if (curLevel[n] === node) {
isPresent = true;
break;
}
}
if (!isPresent) {
this.distributionOrdering[level].push(node);
this.distributionIndex[node.id] = this.distributionOrdering[level].length - 1;
}
}
}
/**
* The Layout Engine
*/
class LayoutEngine {
/**
* @param {Object} body
*/
constructor(body) {
this.body = body;
this.initialRandomSeed = Math.round(Math.random() * 1000000);
this.randomSeed = this.initialRandomSeed;
this.setPhysics = false;
this.options = {};
this.optionsBackup = {physics:{}};
this.defaultOptions = {
randomSeed: undefined,
improvedLayout: true,
clusterThreshold: 150,
hierarchical: {
enabled:false,
levelSeparation: 150,
nodeSpacing: 100,
treeSpacing: 200,
blockShifting: true,
edgeMinimization: true,
parentCentralization: true,
direction: 'UD', // UD, DU, LR, RL
sortMethod: 'hubsize' // hubsize, directed
}
};
util.extend(this.options, this.defaultOptions);
this.bindEventListeners();
}
/**
* Binds event listeners
*/
bindEventListeners() {
this.body.emitter.on('_dataChanged', () => {
this.setupHierarchicalLayout();
});
this.body.emitter.on('_dataLoaded', () => {
this.layoutNetwork();
});
this.body.emitter.on('_resetHierarchicalLayout', () => {
this.setupHierarchicalLayout();
});
this.body.emitter.on('_adjustEdgesForHierarchicalLayout', () => {
if (this.options.hierarchical.enabled !== true) {
return;
}
// get the type of static smooth curve in case it is required
let type = this.direction.curveType();
// force all edges into static smooth curves.
this.body.emitter.emit('_forceDisableDynamicCurves', type, false);
});
}
/**
*
* @param {Object} options
* @param {Object} allOptions
* @returns {Object}
*/
setOptions(options, allOptions) {
if (options !== undefined) {
let hierarchical = this.options.hierarchical;
let prevHierarchicalState = hierarchical.enabled;
util.selectiveDeepExtend(["randomSeed", "improvedLayout", "clusterThreshold"],this.options, options);
util.mergeOptions(this.options, options, 'hierarchical');
if (options.randomSeed !== undefined) {this.initialRandomSeed = options.randomSeed;}
if (hierarchical.enabled === true) {
if (prevHierarchicalState === true) {
// refresh the overridden options for nodes and edges.
this.body.emitter.emit('refresh', true);
}
// make sure the level separation is the right way up
if (hierarchical.direction === 'RL' || hierarchical.direction === 'DU') {
if (hierarchical.levelSeparation > 0) {
hierarchical.levelSeparation *= -1;
}
}
else {
if (hierarchical.levelSeparation < 0) {
hierarchical.levelSeparation *= -1;
}
}
this.setDirectionStrategy();
this.body.emitter.emit('_resetHierarchicalLayout');
// because the hierarchical system needs it's own physics and smooth curve settings,
// we adapt the other options if needed.
return this.adaptAllOptionsForHierarchicalLayout(allOptions);
}
else {
if (prevHierarchicalState === true) {
// refresh the overridden options for nodes and edges.
this.body.emitter.emit('refresh');
return util.deepExtend(allOptions,this.optionsBackup);
}
}
}
return allOptions;
}
/**
*
* @param {Object} allOptions
* @returns {Object}
*/
adaptAllOptionsForHierarchicalLayout(allOptions) {
if (this.options.hierarchical.enabled === true) {
let backupPhysics = this.optionsBackup.physics;
// set the physics
if (allOptions.physics === undefined || allOptions.physics === true) {
allOptions.physics = {
enabled: backupPhysics.enabled === undefined ? true : backupPhysics.enabled,
solver :'hierarchicalRepulsion'
};
backupPhysics.enabled = backupPhysics.enabled === undefined ? true : backupPhysics.enabled;
backupPhysics.solver = backupPhysics.solver || 'barnesHut';
}
else if (typeof allOptions.physics === 'object') {
backupPhysics.enabled = allOptions.physics.enabled === undefined ? true : allOptions.physics.enabled;
backupPhysics.solver = allOptions.physics.solver || 'barnesHut';
allOptions.physics.solver = 'hierarchicalRepulsion';
}
else if (allOptions.physics !== false) {
backupPhysics.solver ='barnesHut';
allOptions.physics = {solver:'hierarchicalRepulsion'};
}
// get the type of static smooth curve in case it is required
let type = this.direction.curveType();
// disable smooth curves if nothing is defined. If smooth curves have been turned on,
// turn them into static smooth curves.
if (allOptions.edges === undefined) {
this.optionsBackup.edges = {smooth:{enabled:true, type:'dynamic'}};
allOptions.edges = {smooth: false};
}
else if (allOptions.edges.smooth === undefined) {
this.optionsBackup.edges = {smooth:{enabled:true, type:'dynamic'}};
allOptions.edges.smooth = false;
}
else {
if (typeof allOptions.edges.smooth === 'boolean') {
this.optionsBackup.edges = {smooth:allOptions.edges.smooth};
allOptions.edges.smooth = {enabled: allOptions.edges.smooth, type:type}
}
else {
let smooth = allOptions.edges.smooth;
// allow custom types except for dynamic
if (smooth.type !== undefined && smooth.type !== 'dynamic') {
type = smooth.type;
}
// TODO: this is options merging; see if the standard routines can be used here.
this.optionsBackup.edges = {
smooth : smooth.enabled === undefined ? true : smooth.enabled,
type : smooth.type === undefined ? 'dynamic': smooth.type,
roundness : smooth.roundness === undefined ? 0.5 : smooth.roundness,
forceDirection: smooth.forceDirection === undefined ? false : smooth.forceDirection
};
// NOTE: Copying an object to self; this is basically setting defaults for undefined variables
allOptions.edges.smooth = {
enabled : smooth.enabled === undefined ? true : smooth.enabled,
type : type,
roundness : smooth.roundness === undefined ? 0.5 : smooth.roundness,
forceDirection: smooth.forceDirection === undefined ? false: smooth.forceDirection
}
}
}
// Force all edges into static smooth curves.
// Only applies to edges that do not use the global options for smooth.
this.body.emitter.emit('_forceDisableDynamicCurves', type);
}
return allOptions;
}
/**
*
* @returns {number}
*/
seededRandom() {
let x = Math.sin(this.randomSeed++) * 10000;
return x - Math.floor(x);
}
/**
*
* @param {Array.<Node>} nodesArray
*/
positionInitially(nodesArray) {
if (this.options.hierarchical.enabled !== true) {
this.randomSeed = this.initialRandomSeed;
let radius = nodesArray.length + 50;
for (let i = 0; i < nodesArray.length; i++) {
let node = nodesArray[i];
let angle = 2 * Math.PI * this.seededRandom();
if (node.x === undefined) {
node.x = radius * Math.cos(angle);
}
if (node.y === undefined) {
node.y = radius * Math.sin(angle);
}
}
}
}
/**
* Use Kamada Kawai to position nodes. This is quite a heavy algorithm so if there are a lot of nodes we
* cluster them first to reduce the amount.
*/
layoutNetwork() {
if (this.options.hierarchical.enabled !== true && this.options.improvedLayout === true) {
let indices = this.body.nodeIndices;
// first check if we should Kamada Kawai to layout. The threshold is if less than half of the visible
// nodes have predefined positions we use this.
let positionDefined = 0;
for (let i = 0; i < indices.length; i++) {
let node = this.body.nodes[indices[i]];
if (node.predefinedPosition === true) {
positionDefined += 1;
}
}
// if less than half of the nodes have a predefined position we continue
if (positionDefined < 0.5 * indices.length) {
let MAX_LEVELS = 10;
let level = 0;
let clusterThreshold = this.options.clusterThreshold;
//
// Define the options for the hidden cluster nodes
// These options don't propagate outside the clustering phase.
//
// Some options are explicitly disabled, because they may be set in group or default node options.
// The clusters are never displayed, so most explicit settings here serve as performance optimizations.
//
// The explicit setting of 'shape' is to avoid `shape: 'image'`; images are not passed to the hidden
// cluster nodes, leading to an exception on creation.
//
// All settings here are performance related, except when noted otherwise.
//
let clusterOptions = {
clusterNodeProperties:{
shape: 'ellipse', // Bugfix: avoid type 'image', no images supplied
label: '', // avoid label handling
group: '', // avoid group handling
font: {multi: false}, // avoid font propagation
},
clusterEdgeProperties:{
label: '', // avoid label handling
font: {multi: false}, // avoid font propagation
smooth: {
enabled: false // avoid drawing penalty for complex edges
}
}
};
// if there are a lot of nodes, we cluster before we run the algorithm.
// NOTE: this part fails to find clusters for large scale-free networks, which should
// be easily clusterable.
// TODO: examine why this is so
if (indices.length > clusterThreshold) {
let startLength = indices.length;
while (indices.length > clusterThreshold && level <= MAX_LEVELS) {
//console.time("clustering")
level += 1;
let before = indices.length;
// if there are many nodes we do a hubsize cluster
if (level % 3 === 0) {
this.body.modules.clustering.clusterBridges(clusterOptions);
}
else {
this.body.modules.clustering.clusterOutliers(clusterOptions);
}
let after = indices.length;
if (before == after && level % 3 !== 0) {
this._declusterAll();
this.body.emitter.emit("_layoutFailed");
console.info("This network could not be positioned by this version of the improved layout algorithm."
+ " Please disable improvedLayout for better performance.");
return;
}
//console.timeEnd("clustering")
//console.log(before,level,after);
}
// increase the size of the edges
this.body.modules.kamadaKawai.setOptions({springLength: Math.max(150, 2 * startLength)})
}
if (level > MAX_LEVELS){
console.info("The clustering didn't succeed within the amount of interations allowed,"
+ " progressing with partial result.");
}
// position the system for these nodes and edges
this.body.modules.kamadaKawai.solve(indices, this.body.edgeIndices, true);
// shift to center point
this._shiftToCenter();
// perturb the nodes a little bit to force the physics to kick in
let offset = 70;
for (let i = 0; i < indices.length; i++) {
// Only perturb the nodes that aren't fixed
let node = this.body.nodes[indices[i]];
if (node.predefinedPosition === false) {
node.x += (0.5 - this.seededRandom())*offset;
node.y += (0.5 - this.seededRandom())*offset;
}
}
// uncluster all clusters
this._declusterAll();
// reposition all bezier nodes.
this.body.emitter.emit("_repositionBezierNodes");
}
}
}
/**
* Move all the nodes towards to the center so gravitational pull wil not move the nodes away from view
* @private
*/
_shiftToCenter() {
let range = NetworkUtil.getRangeCore(this.body.nodes, this.body.nodeIndices);
let center = NetworkUtil.findCenter(range);
for (let i = 0; i < this.body.nodeIndices.length; i++) {
let node = this.body.nodes[this.body.nodeIndices[i]];
node.x -= center.x;
node.y -= center.y;
}
}
/**
* Expands all clusters
* @private
*/
_declusterAll() {
let clustersPresent = true;
while (clustersPresent === true) {
clustersPresent = false;
for (let i = 0; i < this.body.nodeIndices.length; i++) {
if (this.body.nodes[this.body.nodeIndices[i]].isCluster === true) {
clustersPresent = true;
this.body.modules.clustering.openCluster(this.body.nodeIndices[i], {}, false);
}
}
if (clustersPresent === true) {
this.body.emitter.emit('_dataChanged');
}
}
}
/**
*
* @returns {number|*}
*/
getSeed() {
return this.initialRandomSeed;
}
/**
* This is the main function to layout the nodes in a hierarchical way.
* It checks if the node details are supplied correctly
*
* @private
*/
setupHierarchicalLayout() {
if (this.options.hierarchical.enabled === true && this.body.nodeIndices.length > 0) {
// get the size of the largest hubs and check if the user has defined a level for a node.
let node, nodeId;
let definedLevel = false;
let undefinedLevel = false;
this.lastNodeOnLevel = {};
this.hierarchical = new HierarchicalStatus();
for (nodeId in this.body.nodes) {
if (this.body.nodes.hasOwnProperty(nodeId)) {
node = this.body.nodes[nodeId];
if (node.options.level !== undefined) {
definedLevel = true;
this.hierarchical.levels[nodeId] = node.options.level;
}
else {
undefinedLevel = true;
}
}
}
// if the user defined some levels but not all, alert and run without hierarchical layout
if (undefinedLevel === true && definedLevel === true) {
throw new Error('To use the hierarchical layout, nodes require either no predefined levels'
+ ' or levels have to be defined for all nodes.');
}
else {
// define levels if undefined by the users. Based on hubsize.
if (undefinedLevel === true) {
let sortMethod = this.options.hierarchical.sortMethod;
if (sortMethod === 'hubsize') {
this._determineLevelsByHubsize();
}
else if (sortMethod === 'directed') {
this._determineLevelsDirected();
}
else if (sortMethod === 'custom') {
this._determineLevelsCustomCallback();
}
}
// fallback for cases where there are nodes but no edges
for (let nodeId in this.body.nodes) {
if (this.body.nodes.hasOwnProperty(nodeId)) {
this.hierarchical.ensureLevel(nodeId);
}
}
// check the distribution of the nodes per level.
let distribution = this._getDistribution();
// get the parent children relations.
this._generateMap();
// place the nodes on the canvas.
this._placeNodesByHierarchy(distribution);
// condense the whitespace.
this._condenseHierarchy();
// shift to center so gravity does not have to do much
this._shiftToCenter();
}
}
}
/**
* @private
*/
_condenseHierarchy() {
// Global var in this scope to define when the movement has stopped.
let stillShifting = false;
let branches = {};
// first we have some methods to help shifting trees around.
// the main method to shift the trees
let shiftTrees = () => {
let treeSizes = getTreeSizes();
let shiftBy = 0;
for (let i = 0; i < treeSizes.length - 1; i++) {
let diff = treeSizes[i].max - treeSizes[i+1].min;
shiftBy += diff + this.options.hierarchical.treeSpacing;
shiftTree(i + 1, shiftBy);
}
};
// shift a single tree by an offset
let shiftTree = (index, offset) => {
let trees = this.hierarchical.trees;
for (let nodeId in trees) {
if (trees.hasOwnProperty(nodeId)) {
if (trees[nodeId] === index) {
this.direction.shift(nodeId, offset);
}
}
}
};
// get the width of all trees
let getTreeSizes = () => {
let treeWidths = [];
for (let i = 0; i < this.hierarchical.numTrees(); i++) {
treeWidths.push(this.direction.getTreeSize(i));
}
return treeWidths;
};
// get a map of all nodes in this branch
let getBranchNodes = (source, map) => {
if (map[source.id]) {
return;
}
map[source.id] = true;
if (this.hierarchical.childrenReference[source.id]) {
let children = this.hierarchical.childrenReference[source.id];
if (children.length > 0) {
for (let i = 0; i < children.length; i++) {
getBranchNodes(this.body.nodes[children[i]], map);
}
}
}
};
// get a min max width as well as the maximum movement space it has on either sides
// we use min max terminology because width and height can interchange depending on the direction of the layout
let getBranchBoundary = (branchMap, maxLevel = 1e9) => {
let minSpace = 1e9;
let maxSpace = 1e9;
let min = 1e9;
let max = -1e9;
for (let branchNode in branchMap) {
if (branchMap.hasOwnProperty(branchNode)) {
let node = this.body.nodes[branchNode];
let level = this.hierarchical.levels[node.id];
let position = this.direction.getPosition(node);
// get the space around the node.
let [minSpaceNode, maxSpaceNode] = this._getSpaceAroundNode(node,branchMap);
minSpace = Math.min(minSpaceNode, minSpace);
maxSpace = Math.min(maxSpaceNode, maxSpace);
// the width is only relevant for the levels two nodes have in common. This is why we filter on this.
if (level <= maxLevel) {
min = Math.min(position, min);
max = Math.max(position, max);
}
}
}
return [min, max, minSpace, maxSpace];
}
// check what the maximum level is these nodes have in common.
let getCollisionLevel = (node1, node2) => {
let maxLevel1 = this.hierarchical.getMaxLevel(node1.id);
let maxLevel2 = this.hierarchical.getMaxLevel(node2.id);
return Math.min(maxLevel1, maxLevel2);
};
/**
* Condense elements. These can be nodes or branches depending on the callback.
*
* @param {function} callback
* @param {Array.<number>} levels
* @param {*} centerParents
*/
let shiftElementsCloser = (callback, levels, centerParents) => {
let hier = this.hierarchical;
for (let i = 0; i < levels.length; i++) {
let level = levels[i];
let levelNodes = hier.distributionOrdering[level];
if (levelNodes.length > 1) {
for (let j = 0; j < levelNodes.length - 1; j++) {
let node1 = levelNodes[j];
let node2 = levelNodes[j+1];
// NOTE: logic maintained as it was; if nodes have same ancestor,
// then of course they are in the same sub-network.
if (hier.hasSameParent(node1, node2) && hier.inSameSubNetwork(node1, node2) ) {
callback(node1, node2, centerParents);
}
}
}
}
};
// callback for shifting branches
let branchShiftCallback = (node1, node2, centerParent = false) => {
//window.CALLBACKS.push(() => {
let pos1 = this.direction.getPosition(node1);
let pos2 = this.direction.getPosition(node2);
let diffAbs = Math.abs(pos2 - pos1);
let nodeSpacing = this.options.hierarchical.nodeSpacing;
//console.log("NOW CHECKING:", node1.id, node2.id, diffAbs);
if (diffAbs > nodeSpacing) {
let branchNodes1 = {};
let branchNodes2 = {};
getBranchNodes(node1, branchNodes1);
getBranchNodes(node2, branchNodes2);
// check the largest distance between the branches
let maxLevel = getCollisionLevel(node1, node2);
let branchNodeBoundary1 = getBranchBoundary(branchNodes1, maxLevel);
let branchNodeBoundary2 = getBranchBoundary(branchNodes2, maxLevel);
let max1 = branchNodeBoundary1[1];
let min2 = branchNodeBoundary2[0];
let minSpace2 = branchNodeBoundary2[2];
//console.log(node1.id, getBranchBoundary(branchNodes1, maxLevel), node2.id,
// getBranchBoundary(branchNodes2, maxLevel), maxLevel);
let diffBranch = Math.abs(max1 - min2);
if (diffBranch > nodeSpacing) {
let offset = max1 - min2 + nodeSpacing;
if (offset < -minSpace2 + nodeSpacing) {
offset = -minSpace2 + nodeSpacing;
//console.log("RESETTING OFFSET", max1 - min2 + this.options.hierarchical.nodeSpacing, -minSpace2, offset);
}
if (offset < 0) {
//console.log("SHIFTING", node2.id, offset);
this._shiftBlock(node2.id, offset);
stillShifting = true;
if (centerParent === true)
this._centerParent(node2);
}
}
}
//this.body.emitter.emit("_redraw");})
};
let minimizeEdgeLength = (iterations, node) => {
//window.CALLBACKS.push(() => {
// console.log("ts",node.id);
let nodeId = node.id;
let allEdges = node.edges;
let nodeLevel = this.hierarchical.levels[node.id];
// gather constants
let C2 = this.options.hierarchical.levelSeparation * this.options.hierarchical.levelSeparation;
let referenceNodes = {};
let aboveEdges = [];
for (let i = 0; i < allEdges.length; i++) {
let edge = allEdges[i];
if (edge.toId != edge.fromId) {
let otherNode = edge.toId == nodeId ? edge.from : edge.to;
referenceNodes[allEdges[i].id] = otherNode;
if (this.hierarchical.levels[otherNode.id] < nodeLevel) {
aboveEdges.push(edge);
}
}
}
// differentiated sum of lengths based on only moving one node over one axis
let getFx = (point, edges) => {
let sum = 0;
for (let i = 0; i < edges.length; i++) {
if (referenceNodes[edges[i].id] !== undefined) {
let a = this.direction.getPosition(referenceNodes[edges[i].id]) - point;
sum += a / Math.sqrt(a * a + C2);
}
}
return sum;
};
// doubly differentiated sum of lengths based on only moving one node over one axis
let getDFx = (point, edges) => {
let sum = 0;
for (let i = 0; i < edges.length; i++) {
if (referenceNodes[edges[i].id] !== undefined) {
let a = this.direction.getPosition(referenceNodes[edges[i].id]) - point;
sum -= (C2 * Math.pow(a * a + C2, -1.5));
}
}
return sum;
};
let getGuess = (iterations, edges) => {
let guess = this.direction.getPosition(node);
// Newton's method for optimization
let guessMap = {};
for (let i = 0; i < iterations; i++) {
let fx = getFx(guess, edges);
let dfx = getDFx(guess, edges);