-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
dagre.js
2291 lines (2229 loc) · 101 KB
/
dagre.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
var dagre = dagre || {};
// Dagre graph layout
// https://github.com/dagrejs/dagre
// https://github.com/dagrejs/graphlib
dagre.layout = (graph, options) => {
options = options || {};
// options.time = true;
const time = (name, callback) => {
const start = Date.now();
const result = callback();
const duration = Date.now() - start;
if (options.time) {
/* eslint-disable */
console.log(name + ': ' + duration + 'ms');
/* eslint-enable */
}
return result;
};
// Constructs a new graph from the input graph, which can be used for layout.
// This process copies only whitelisted attributes from the input graph to the
// layout graph. Thus this function serves as a good place to determine what
// attributes can influence layout.
const buildLayoutGraph = (graph) => {
const g = new dagre.Graph({ compound: true });
g.setGraph(Object.assign({}, { ranksep: 50, edgesep: 20, nodesep: 50, rankdir: 'tb' }, graph.graph()));
for (const node of graph.nodes.values()) {
const v = node.v;
const label = node.label;
g.setNode(v, {
width: label.width || 0,
height: label.height || 0
});
g.setParent(v, graph.parent(v));
}
for (const e of graph.edges.values()) {
const edge = e.label;
g.setEdge(e.v, e.w, {
minlen: edge.minlen || 1,
weight: edge.weight || 1,
width: edge.width || 0,
height: edge.height || 0,
labeloffset: edge.labeloffset || 10,
labelpos: edge.labelpos || 'r'
});
}
return g;
};
const runLayout = (g, time) => {
let uniqueIdCounter = 0;
const uniqueId = (prefix) => {
const id = ++uniqueIdCounter;
return prefix + id;
};
const flat = (list) => {
if (Array.isArray(list) && list.every((item) => !Array.isArray(item))) {
return list;
}
const target = [];
for (const item of list) {
if (!Array.isArray(item)) {
target.push(item);
continue;
}
for (const entry of item) {
target.push(entry);
}
}
return target;
};
// Adds a dummy node to the graph and return v.
const addDummyNode = (g, type, label, name) => {
let v;
do {
v = uniqueId(name);
} while (g.hasNode(v));
label.dummy = type;
g.setNode(v, label);
return v;
};
const asNonCompoundGraph = (g) => {
const graph = new dagre.Graph({});
graph.setGraph(g.graph());
for (const node of g.nodes.values()) {
const v = node.v;
if (g.children(v).length === 0) {
graph.setNode(v, node.label);
}
}
for (const e of g.edges.values()) {
graph.setEdge(e.v, e.w, e.label);
}
return graph;
};
const maxRank = (g) => {
let rank = Number.NEGATIVE_INFINITY;
for (const node of g.nodes.values()) {
const x = node.label.rank;
if (x !== undefined && x > rank) {
rank = x;
}
}
return rank === Number.NEGATIVE_INFINITY ? undefined : rank;
};
// Given a DAG with each node assigned 'rank' and 'order' properties, this function will produce a matrix with the ids of each node.
const buildLayerMatrix = (g) => {
const rank = maxRank(g);
const length = rank === undefined ? 0 : rank + 1;
const layering = Array.from(new Array(length), () => []);
for (const node of g.nodes.values()) {
const label = node.label;
const rank = label.rank;
if (rank !== undefined) {
layering[rank][label.order] = node.v;
}
}
return layering;
};
// This idea comes from the Gansner paper: to account for edge labels in our layout we split each rank in half by doubling minlen and halving ranksep.
// Then we can place labels at these mid-points between nodes.
// We also add some minimal padding to the width to push the label for the edge away from the edge itself a bit.
const makeSpaceForEdgeLabels = (g) => {
const graph = g.graph();
graph.ranksep /= 2;
for (const e of g.edges.values()) {
const edge = e.label;
edge.minlen *= 2;
if (edge.labelpos.toLowerCase() !== 'c') {
if (graph.rankdir === 'TB' || graph.rankdir === 'BT') {
edge.width += edge.labeloffset;
}
else {
edge.height += edge.labeloffset;
}
}
}
};
// A helper that preforms a pre- or post-order traversal on the input graph and returns the nodes in the order they were visited.
// If the graph is undirected then this algorithm will navigate using neighbors.
// If the graph is directed then this algorithm will navigate using successors.
// Order must be one of 'pre' or 'post'.
const dfs = (g, vs, postorder) => {
const doDfs = (g, v, postorder, visited, navigation, acc) => {
if (!visited.has(v)) {
visited.add(v);
if (!postorder) {
acc.push(v);
}
for (const w of navigation(v)) {
doDfs(g, w, postorder, visited, navigation, acc);
}
if (postorder) {
acc.push(v);
}
}
};
if (!Array.isArray(vs)) {
vs = [ vs ];
}
const navigation = (g.isDirected() ? g.successors : g.neighbors).bind(g);
const acc = [];
const visited = new Set();
for (const v of vs) {
if (!g.hasNode(v)) {
throw new Error('Graph does not have node: ' + v);
}
doDfs(g, v, postorder, visited, navigation, acc);
}
return acc;
};
const postorder = (g, vs) => {
return dfs(g, vs, true);
};
const preorder = (g, vs) => {
return dfs(g, vs, false);
};
const removeSelfEdges = (g) => {
for (const e of g.edges.values()) {
if (e.v === e.w) {
const label = g.node(e.v).label;
if (!label.selfEdges) {
label.selfEdges = [];
}
label.selfEdges.push({ e: e, label: e.label });
g.removeEdge(e);
}
}
};
const acyclic_run = (g) => {
const dfsFAS = (g) => {
const fas = [];
const stack = new Set();
const visited = new Set();
const dfs = (v) => {
if (!visited.has(v)) {
visited.add(v);
stack.add(v);
for (const e of g.node(v).out) {
if (stack.has(e.w)) {
fas.push(e);
}
else {
dfs(e.w);
}
}
stack.delete(v);
}
};
for (const v of g.nodes.keys()) {
dfs(v);
}
return fas;
};
for (const e of dfsFAS(g)) {
const label = e.label;
g.removeEdge(e);
label.forwardName = e.name;
label.reversed = true;
g.setEdge(e.w, e.v, label, uniqueId('rev'));
}
};
const acyclic_undo = (g) => {
for (const e of g.edges.values()) {
const edge = e.label;
if (edge.reversed) {
edge.points.reverse();
g.removeEdge(e);
const forwardName = edge.forwardName;
delete edge.reversed;
delete edge.forwardName;
g.setEdge(e.w, e.v, edge, forwardName);
}
}
};
// Returns the amount of slack for the given edge.
// The slack is defined as the difference between the length of the edge and its minimum length.
const slack = (g, e) => {
return g.node(e.w).label.rank - g.node(e.v).label.rank - e.label.minlen;
};
// Assigns a rank to each node in the input graph that respects the 'minlen' constraint specified on edges between nodes.
// This basic structure is derived from Gansner, et al., 'A Technique for Drawing Directed Graphs.'
//
// Pre-conditions:
// 1. Graph must be a connected DAG
// 2. Graph nodes must be objects
// 3. Graph edges must have 'weight' and 'minlen' attributes
//
// Post-conditions:
// 1. Graph nodes will have a 'rank' attribute based on the results of the
// algorithm. Ranks can start at any index (including negative), we'll
// fix them up later.
const rank = (g) => {
// Constructs a spanning tree with tight edges and adjusted the input node's ranks to achieve this.
// A tight edge is one that is has a length that matches its 'minlen' attribute.
// The basic structure for this function is derived from Gansner, et al., 'A Technique for Drawing Directed Graphs.'
//
// Pre-conditions:
// 1. Graph must be a DAG.
// 2. Graph must be connected.
// 3. Graph must have at least one node.
// 5. Graph nodes must have been previously assigned a 'rank' property that respects the 'minlen' property of incident edges.
// 6. Graph edges must have a 'minlen' property.
//
// Post-conditions:
// - Graph nodes will have their rank adjusted to ensure that all edges are tight.
//
// Returns a tree (undirected graph) that is constructed using only 'tight' edges.
const feasibleTree = (g) => {
const t = new dagre.Graph({ directed: false });
// Choose arbitrary node from which to start our tree
const start = g.nodes.keys().next().value;
const size = g.nodes.size;
t.setNode(start, {});
// Finds the edge with the smallest slack that is incident on tree and returns it.
const findMinSlackEdge = (t, g) => {
let minKey = Number.MAX_SAFE_INTEGER;
let minValue = undefined;
for (const e of g.edges.values()) {
if (t.hasNode(e.v) !== t.hasNode(e.w)) {
const key = slack(g, e);
if (key < minKey) {
minKey = key;
minValue = e;
}
}
}
return minValue;
};
// Finds a maximal tree of tight edges and returns the number of nodes in the tree.
const tightTree = (t, g) => {
const stack = Array.from(t.nodes.keys()).reverse();
while (stack.length > 0) {
const v = stack.pop();
const node = g.node(v);
for (const e of node.in.concat(node.out)) {
const edgeV = e.v;
const w = (v === edgeV) ? e.w : edgeV;
if (!t.hasNode(w) && !slack(g, e)) {
t.setNode(w, {});
t.setEdge(v, w, {});
stack.push(w);
}
}
}
return t.nodes.size;
};
while (tightTree(t, g) < size) {
const edge = findMinSlackEdge(t, g);
const delta = t.hasNode(edge.v) ? slack(g, edge) : -slack(g, edge);
for (const v of t.nodes.keys()) {
g.node(v).label.rank += delta;
}
}
return t;
};
// Initializes ranks for the input graph using the longest path algorithm. This
// algorithm scales well and is fast in practice, it yields rather poor
// solutions. Nodes are pushed to the lowest layer possible, leaving the bottom
// ranks wide and leaving edges longer than necessary. However, due to its
// speed, this algorithm is good for getting an initial ranking that can be fed
// into other algorithms.
//
// This algorithm does not normalize layers because it will be used by other
// algorithms in most cases. If using this algorithm directly, be sure to
// run normalize at the end.
//
// Pre-conditions:
// 1. Input graph is a DAG.
// 2. Input graph node labels can be assigned properties.
//
// Post-conditions:
// 1. Each node will be assign an (unnormalized) 'rank' property.
const longestPath = (g) => {
const visited = new Set();
const dfs = (v) => {
const node = g.node(v);
if (visited.has(v)) {
return node.label.rank;
}
visited.add(v);
let rank = Number.MAX_SAFE_INTEGER;
for (const e of node.out) {
rank = Math.min(rank, dfs(e.w) - e.label.minlen);
}
if (rank === Number.MAX_SAFE_INTEGER) {
rank = 0;
}
node.label.rank = rank;
return rank;
};
for (const node of g.nodes.values()) {
if (node.in.length === 0) {
dfs(node.v);
}
}
};
// The network simplex algorithm assigns ranks to each node in the input graph
// and iteratively improves the ranking to reduce the length of edges.
//
// Preconditions:
// 1. The input graph must be a DAG.
// 2. All nodes in the graph must have an object value.
// 3. All edges in the graph must have 'minlen' and 'weight' attributes.
//
// Postconditions:
// 1. All nodes in the graph will have an assigned 'rank' attribute that has
// been optimized by the network simplex algorithm. Ranks start at 0.
//
// A rough sketch of the algorithm is as follows:
// 1. Assign initial ranks to each node. We use the longest path algorithm,
// which assigns ranks to the lowest position possible. In general this
// leads to very wide bottom ranks and unnecessarily long edges.
// 2. Construct a feasible tight tree. A tight tree is one such that all
// edges in the tree have no slack (difference between length of edge
// and minlen for the edge). This by itself greatly improves the assigned
// rankings by shorting edges.
// 3. Iteratively find edges that have negative cut values. Generally a
// negative cut value indicates that the edge could be removed and a new
// tree edge could be added to produce a more compact graph.
//
// Much of the algorithms here are derived from Gansner, et al., 'A Technique
// for Drawing Directed Graphs.' The structure of the file roughly follows the
// structure of the overall algorithm.
const networkSimplex = (g) => {
// Returns a new graph with only simple edges. Handles aggregation of data associated with multi-edges.
const simplify = (g) => {
const graph = new dagre.Graph();
graph.setGraph(g.graph());
for (const node of g.nodes.values()) {
graph.setNode(node.v, node.label);
}
for (const e of g.edges.values()) {
const simpleEdge = graph.edge(e.v, e.w);
const simpleLabel = simpleEdge ? simpleEdge.label : { weight: 0, minlen: 1 };
const label = e.label;
graph.setEdge(e.v, e.w, {
weight: simpleLabel.weight + label.weight,
minlen: Math.max(simpleLabel.minlen, label.minlen)
});
}
return graph;
};
const initLowLimValues = (tree, root) => {
const dfs = (tree, visited, nextLim, v, parent) => {
const low = nextLim;
const label = tree.node(v).label;
visited.add(v);
for (const w of tree.neighbors(v)) {
if (!visited.has(w)) {
nextLim = dfs(tree, visited, nextLim, w, v);
}
}
label.low = low;
label.lim = nextLim++;
if (parent) {
label.parent = parent;
}
else {
// TODO should be able to remove this when we incrementally update low lim
delete label.parent;
}
return nextLim;
};
root = tree.nodes.keys().next().value;
const visited = new Set();
dfs(tree, visited, 1, root);
};
// Initializes cut values for all edges in the tree.
const initCutValues = (t, g) => {
// Given the tight tree, its graph, and a child in the graph calculate and
// return the cut value for the edge between the child and its parent.
const calcCutValue = (t, g, child) => {
const childLabel = t.node(child).label;
const parent = childLabel.parent;
// The graph's view of the tree edge we're inspecting
const edge = g.edge(child, parent);
// True if the child is on the tail end of the edge in the directed graph
const childIsTail = edge ? true : false;
// The accumulated cut value for the edge between this node and its parent
const graphEdge = edge ? edge.label : g.edge(parent, child).label;
let cutValue = graphEdge.weight;
const node = g.node(child);
for (const e of node.in.concat(node.out)) {
const isOutEdge = e.v === child;
const other = isOutEdge ? e.w : e.v;
if (other !== parent) {
const pointsToHead = isOutEdge === childIsTail;
const otherWeight = e.label.weight;
cutValue += pointsToHead ? otherWeight : -otherWeight;
const edge = t.edge(child, other);
if (edge) {
const otherCutValue = edge.label.cutvalue;
cutValue += pointsToHead ? -otherCutValue : otherCutValue;
}
}
}
return cutValue;
};
const assignCutValue = (t, g, child) => {
const childLabel = t.node(child).label;
const parent = childLabel.parent;
t.edge(child, parent).label.cutvalue = calcCutValue(t, g, child);
};
let vs = postorder(t, Array.from(t.nodes.keys()));
vs = vs.slice(0, vs.length - 1);
for (const v of vs) {
assignCutValue(t, g, v);
}
};
const leaveEdge = (tree) => {
return Array.from(tree.edges.values()).find((e) => e.label.cutvalue < 0);
};
const enterEdge = (t, g, edge) => {
let v = edge.v;
let w = edge.w;
// For the rest of this function we assume that v is the tail and w is the
// head, so if we don't have this edge in the graph we should flip it to
// match the correct orientation.
if (!g.edge(v, w)) {
v = edge.w;
w = edge.v;
}
const vLabel = t.node(v).label;
const wLabel = t.node(w).label;
let tailLabel = vLabel;
let flip = false;
// If the root is in the tail of the edge then we need to flip the logic that
// checks for the head and tail nodes in the candidates function below.
if (vLabel.lim > wLabel.lim) {
tailLabel = wLabel;
flip = true;
}
// Returns true if the specified node is descendant of the root node per the assigned low and lim attributes in the tree.
const isDescendant = (vLabel, rootLabel) => {
return rootLabel.low <= vLabel.lim && vLabel.lim <= rootLabel.lim;
};
let minKey = Number.POSITIVE_INFINITY;
let minValue = undefined;
for (const edge of g.edges.values()) {
if (flip === isDescendant(t.node(edge.v).label, tailLabel) &&
flip !== isDescendant(t.node(edge.w).label, tailLabel)) {
const key = slack(g, edge);
if (key < minKey) {
minKey = key;
minValue = edge;
}
}
}
return minValue;
};
const exchangeEdges = (t, g, e, f) => {
t.removeEdge(e);
t.setEdge(f.v, f.w, {});
initLowLimValues(t);
initCutValues(t, g);
// update ranks
const root = Array.from(t.nodes.keys()).find((v) => !g.node(v).label.parent);
let vs = preorder(t, root);
vs = vs.slice(1);
for (const v of vs) {
const parent = t.node(v).label.parent;
let edge = g.edge(v, parent);
let flipped = false;
if (!edge) {
edge = g.edge(parent, v);
flipped = true;
}
g.node(v).label.rank = g.node(parent).label.rank + (flipped ? edge.label.minlen : -edge.label.minlen);
}
};
g = simplify(g);
longestPath(g);
const t = feasibleTree(g);
initLowLimValues(t);
initCutValues(t, g);
let e;
let f;
while ((e = leaveEdge(t))) {
f = enterEdge(t, g, e);
exchangeEdges(t, g, e, f);
}
};
switch(g.graph().ranker) {
case 'tight-tree': {
longestPath(g);
feasibleTree(g);
break;
}
case 'longest-path': {
longestPath(g);
break;
}
default: {
networkSimplex(g);
break;
}
}
};
// Creates temporary dummy nodes that capture the rank in which each edge's label is going to, if it has one of non-zero width and height.
// We do this so that we can safely remove empty ranks while preserving balance for the label's position.
const injectEdgeLabelProxies = (g) => {
for (const e of g.edges.values()) {
const edge = e.label;
if (edge.width && edge.height) {
const v = g.node(e.v).label;
const w = g.node(e.w).label;
addDummyNode(g, 'edge-proxy', { rank: (w.rank - v.rank) / 2 + v.rank, e: e }, '_ep');
}
}
};
const removeEmptyRanks = (g) => {
// Ranks may not start at 0, so we need to offset them
if (g.nodes.size > 0) {
let minRank = Number.MAX_SAFE_INTEGER;
let maxRank = Number.MIN_SAFE_INTEGER;
const nodes = Array.from(g.nodes.values());
for (const node of nodes) {
const label = node.label;
if (label.rank !== undefined) {
minRank = Math.min(minRank, label.rank);
maxRank = Math.max(maxRank, label.rank);
}
}
const size = maxRank - minRank;
if (size > 0) {
const layers = new Array(size);
for (const node of nodes) {
const label = node.label;
if (label.rank !== undefined) {
const rank = label.rank - minRank;
if (!layers[rank]) {
layers[rank] = [];
}
layers[rank].push(node.v);
}
}
let delta = 0;
const nodeRankFactor = g.graph().nodeRankFactor;
for (let i = 0; i < layers.length; i++) {
const vs = layers[i];
if (vs === undefined && i % nodeRankFactor !== 0) {
delta--;
}
else if (delta && vs) {
for (const v of vs) {
g.node(v).label.rank += delta;
}
}
}
}
}
};
// A nesting graph creates dummy nodes for the tops and bottoms of subgraphs,
// adds appropriate edges to ensure that all cluster nodes are placed between
// these boundries, and ensures that the graph is connected.
// In addition we ensure, through the use of the minlen property, that nodes
// and subgraph border nodes do not end up on the same rank.
//
// Preconditions:
// 1. Input graph is a DAG
// 2. Nodes in the input graph has a minlen attribute
//
// Postconditions:
// 1. Input graph is connected.
// 2. Dummy nodes are added for the tops and bottoms of subgraphs.
// 3. The minlen attribute for nodes is adjusted to ensure nodes do not
// get placed on the same rank as subgraph border nodes.
//
// The nesting graph idea comes from Sander, 'Layout of Compound Directed Graphs.'
const nestingGraph_run = (g) => {
const root = addDummyNode(g, 'root', {}, '_root');
const treeDepths = (g) => {
const depths = {};
const dfs = (v, depth) => {
const children = g.children(v);
if (children && children.length > 0) {
for (const child of children) {
dfs(child, depth + 1);
}
}
depths[v] = depth;
};
for (const v of g.children()) {
dfs(v, 1);
}
return depths;
};
const dfs = (g, root, nodeSep, weight, height, depths, v) => {
const children = g.children(v);
if (!children.length) {
if (v !== root) {
g.setEdge(root, v, { weight: 0, minlen: nodeSep });
}
return;
}
const top = addDummyNode(g, 'border', { width: 0, height: 0 }, '_bt');
const bottom = addDummyNode(g, 'border', { width: 0, height: 0 }, '_bb');
const label = g.node(v).label;
g.setParent(top, v);
label.borderTop = top;
g.setParent(bottom, v);
label.borderBottom = bottom;
for (const child of children) {
dfs(g, root, nodeSep, weight, height, depths, child);
const childNode = g.node(child).label;
const childTop = childNode.borderTop ? childNode.borderTop : child;
const childBottom = childNode.borderBottom ? childNode.borderBottom : child;
const thisWeight = childNode.borderTop ? weight : 2 * weight;
const minlen = childTop !== childBottom ? 1 : height - depths[v] + 1;
g.setEdge(top, childTop, { weight: thisWeight, minlen: minlen, nestingEdge: true });
g.setEdge(childBottom, bottom, { weight: thisWeight, minlen: minlen, nestingEdge: true });
}
if (!g.parent(v)) {
g.setEdge(root, top, { weight: 0, minlen: height + depths[v] });
}
};
const depths = treeDepths(g);
const height = Math.max(...Object.values(depths)) - 1; // Note: depths is an Object not an array
const nodeSep = 2 * height + 1;
g.graph().nestingRoot = root;
// Multiply minlen by nodeSep to align nodes on non-border ranks.
for (const e of g.edges.values()) {
e.label.minlen *= nodeSep;
}
// Calculate a weight that is sufficient to keep subgraphs vertically compact
const weight = Array.from(g.edges.values()).reduce((acc, e) => acc + e.label.weight, 0) + 1;
// Create border nodes and link them up
for (const child of g.children()) {
dfs(g, root, nodeSep, weight, height, depths, child);
}
// Save the multiplier for node layers for later removal of empty border layers.
g.graph().nodeRankFactor = nodeSep;
};
const nestingGraph_cleanup = (g) => {
const graphLabel = g.graph();
g.removeNode(graphLabel.nestingRoot);
delete graphLabel.nestingRoot;
for (const e of g.edges.values()) {
if (e.label.nestingEdge) {
g.removeEdge(e);
}
}
};
const assignRankMinMax = (g) => {
// Adjusts the ranks for all nodes in the graph such that all nodes v have rank(v) >= 0 and at least one node w has rank(w) = 0.
let min = Number.POSITIVE_INFINITY;
for (const node of g.nodes.values()) {
const rank = node.label.rank;
if (rank !== undefined && rank < min) {
min = rank;
}
}
for (const node of g.nodes.values()) {
const label = node.label;
if (label.rank !== undefined) {
label.rank -= min;
}
}
let maxRank = 0;
for (const node of g.nodes.values()) {
const label = node.label;
if (label.borderTop) {
label.minRank = g.node(label.borderTop).label.rank;
label.maxRank = g.node(label.borderBottom).label.rank;
maxRank = Math.max(maxRank, label.maxRank);
}
}
g.graph().maxRank = maxRank;
};
// Breaks any long edges in the graph into short segments that span 1 layer each.
// This operation is undoable with the denormalize function.
//
// Pre-conditions:
// 1. The input graph is a DAG.
// 2. Each node in the graph has a 'rank' property.
//
// Post-condition:
// 1. All edges in the graph have a length of 1.
// 2. Dummy nodes are added where edges have been split into segments.
// 3. The graph is augmented with a 'dummyChains' attribute which contains
// the first dummy in each chain of dummy nodes produced.
const normalize = (g) => {
g.graph().dummyChains = [];
for (const e of g.edges.values()) {
let v = e.v;
const w = e.w;
const name = e.name;
const edgeLabel = e.label;
const labelRank = edgeLabel.labelRank;
let vRank = g.node(v).label.rank;
const wRank = g.node(w).label.rank;
if (wRank !== vRank + 1) {
g.removeEdge(e);
let first = true;
vRank++;
while (vRank < wRank) {
edgeLabel.points = [];
delete e.key;
const attrs = {
width: 0, height: 0,
edgeLabel: edgeLabel,
edgeObj: e,
rank: vRank
};
const dummy = addDummyNode(g, 'edge', attrs, '_d');
if (vRank === labelRank) {
attrs.width = edgeLabel.width;
attrs.height = edgeLabel.height;
attrs.dummy = 'edge-label';
attrs.labelpos = edgeLabel.labelpos;
}
g.setEdge(v, dummy, { weight: edgeLabel.weight }, name);
if (first) {
g.graph().dummyChains.push(dummy);
first = false;
}
v = dummy;
vRank++;
}
g.setEdge(v, w, { weight: edgeLabel.weight }, name);
}
}
};
const denormalize = (g) => {
for (let v of g.graph().dummyChains) {
let label = g.node(v).label;
const edgeLabel = label.edgeLabel;
const e = label.edgeObj;
g.setEdge(e.v, e.w, edgeLabel, e.name);
while (label.dummy) {
const w = g.successors(v)[0];
g.removeNode(v);
edgeLabel.points.push({ x: label.x, y: label.y });
if (label.dummy === 'edge-label') {
edgeLabel.x = label.x;
edgeLabel.y = label.y;
edgeLabel.width = label.width;
edgeLabel.height = label.height;
}
v = w;
label = g.node(v).label;
}
}
};
const removeEdgeLabelProxies = (g) => {
for (const node of g.nodes.values()) {
const label = node.label;
if (label.dummy === 'edge-proxy') {
label.e.label.labelRank = label.rank;
g.removeNode(node.v);
}
}
};
const parentDummyChains = (g) => {
// Find a path from v to w through the lowest common ancestor (LCA). Return the full path and the LCA.
const findPath = (g, postorderNums, v, w) => {
const vPath = [];
const wPath = [];
const low = Math.min(postorderNums[v].low, postorderNums[w].low);
const lim = Math.max(postorderNums[v].lim, postorderNums[w].lim);
// Traverse up from v to find the LCA
let parent = v;
do {
parent = g.parent(parent);
vPath.push(parent);
}
while (parent && (postorderNums[parent].low > low || lim > postorderNums[parent].lim));
const lca = parent;
// Traverse from w to LCA
parent = w;
while ((parent = g.parent(parent)) !== lca) {
wPath.push(parent);
}
return { path: vPath.concat(wPath.reverse()), lca: lca };
};
const postorder = (g) => {
const result = {};
let lim = 0;
const dfs = (v) => {
const low = lim;
for (const u of g.children(v)) {
dfs(u);
}
result[v] = { low: low, lim: lim++ };
};
for (const v of g.children()) {
dfs(v);
}
return result;
};
const postorderNums = postorder(g);
for (let v of g.graph().dummyChains || []) {
const node = g.node(v).label;
const edgeObj = node.edgeObj;
const pathData = findPath(g, postorderNums, edgeObj.v, edgeObj.w);
const path = pathData.path;
const lca = pathData.lca;
let pathIdx = 0;
let pathV = path[pathIdx];
let ascending = true;
while (v !== edgeObj.w) {
const node = g.node(v).label;
if (ascending) {
while ((pathV = path[pathIdx]) !== lca && g.node(pathV).label.maxRank < node.rank) {
pathIdx++;
}
if (pathV === lca) {
ascending = false;
}
}
if (!ascending) {
while (pathIdx < path.length - 1 && g.node(pathV = path[pathIdx + 1]).label.minRank <= node.rank) {
pathIdx++;
}
pathV = path[pathIdx];
}
g.setParent(v, pathV);
v = g.successors(v)[0];
}
}
};
const addBorderSegments = (g) => {
const addBorderNode = (g, prop, prefix, sg, sgNode, rank) => {
const label = { width: 0, height: 0, rank: rank, borderType: prop };
const prev = sgNode[prop][rank - 1];
const curr = addDummyNode(g, 'border', label, prefix);
sgNode[prop][rank] = curr;
g.setParent(curr, sg);
if (prev) {
g.setEdge(prev, curr, { weight: 1 });
}
};
const dfs = (v) => {
const children = g.children(v);
const node = g.node(v).label;
if (children.length) {
for (const v of children) {
dfs(v);
}
}
if ('minRank' in node) {
node.borderLeft = [];
node.borderRight = [];
const maxRank = node.maxRank + 1;
for (let rank = node.minRank; rank < maxRank; rank++) {
addBorderNode(g, 'borderLeft', '_bl', v, node, rank);
addBorderNode(g, 'borderRight', '_br', v, node, rank);
}
}
};
for (const v of g.children()) {
dfs(v);
}
};
// Applies heuristics to minimize edge crossings in the graph and sets the best order solution as an order attribute on each node.
//
// Pre-conditions:
// 1. Graph must be DAG
// 2. Graph nodes must have the 'rank' attribute
// 3. Graph edges must have the 'weight' attribute
//
// Post-conditions:
// 1. Graph nodes will have an 'order' attribute based on the results of the algorithm.
const order = (g) => {
const sortSubgraph = (g, v, cg, biasRight) => {
// Given a list of entries of the form {v, barycenter, weight} and a constraint graph this function will resolve any conflicts between the constraint graph and the barycenters for the entries.
// If the barycenters for an entry would violate a constraint in the constraint graph then we coalesce the nodes in the conflict into a new node that respects the contraint and aggregates barycenter and weight information.
// This implementation is based on the description in Forster, 'A Fast and Simple Hueristic for Constrained Two-Level Crossing Reduction,' thought it differs in some specific details.
//
// Pre-conditions:
// 1. Each entry has the form {v, barycenter, weight}, or if the node has no barycenter, then {v}.
//
// Returns:
// A new list of entries of the form {vs, i, barycenter, weight}.
// The list `vs` may either be a singleton or it may be an aggregation of nodes ordered such that they do not violate constraints from the constraint graph.
// The property `i` is the lowest original index of any of the elements in `vs`.
const resolveConflicts = (entries, cg) => {
const mappedEntries = new Map();
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
const tmp = { indegree: 0, 'in': [], out: [], vs: [ entry.v ], i: i };
if (entry.barycenter !== undefined) {
tmp.barycenter = entry.barycenter;
tmp.weight = entry.weight;
}
mappedEntries.set(entry.v, tmp);
}
for (const e of cg.edges.values()) {
const entryV = mappedEntries.get(e.v);
const entryW = mappedEntries.get(e.w);
if (entryV && entryW) {
entryW.indegree++;
entryV.out.push(entryW);
}
}
const sourceSet = Array.from(mappedEntries.values()).filter((entry) => !entry.indegree);
const results = [];
function handleIn(vEntry) {
return function(uEntry) {
if (uEntry.merged) {
return;
}
if (uEntry.barycenter === undefined || vEntry.barycenter === undefined || uEntry.barycenter >= vEntry.barycenter) {
let sum = 0;
let weight = 0;
if (vEntry.weight) {
sum += vEntry.barycenter * vEntry.weight;
weight += vEntry.weight;
}
if (uEntry.weight) {
sum += uEntry.barycenter * uEntry.weight;
weight += uEntry.weight;
}
vEntry.vs = uEntry.vs.concat(vEntry.vs);
vEntry.barycenter = sum / weight;