forked from ciena-blueplanet/dagre
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dagre.es6.js
2656 lines (2334 loc) · 71.4 KB
/
dagre.es6.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 = (function (exports,_,graphlib) {
'use strict';
_ = _ && _.hasOwnProperty('default') ? _['default'] : _;
var graphlib__default = 'default' in graphlib ? graphlib['default'] : graphlib;
/*
* Adds a dummy node to the graph and return v.
*/
function addDummyNode (g, type, attrs, name) {
var v;
do {
v = _.uniqueId(name);
} while (g.hasNode(v))
attrs.dummy = type;
g.setNode(v, attrs);
return v
}
/*
* Returns a new graph with only simple edges. Handles aggregation of data
* associated with multi-edges.
*/
function simplify (g) {
var simplified = new graphlib.Graph().setGraph(g.graph());
_.forEach(g.nodes(), function (v) { simplified.setNode(v, g.node(v)); });
_.forEach(g.edges(), function (e) {
var simpleLabel = simplified.edge(e.v, e.w) || { weight: 0, minlen: 1 };
var label = g.edge(e);
simplified.setEdge(e.v, e.w, {
weight: simpleLabel.weight + label.weight,
minlen: Math.max(simpleLabel.minlen, label.minlen)
});
});
return simplified
}
function asNonCompoundGraph (g) {
var simplified = new graphlib.Graph({ multigraph: g.isMultigraph() }).setGraph(g.graph());
_.forEach(g.nodes(), function (v) {
if (!g.children(v).length) {
simplified.setNode(v, g.node(v));
}
});
_.forEach(g.edges(), function (e) {
simplified.setEdge(e, g.edge(e));
});
return simplified
}
function successorWeights (g) {
var weightMap = _.map(g.nodes(), function (v) {
var sucs = {};
_.forEach(g.outEdges(v), function (e) {
sucs[e.w] = (sucs[e.w] || 0) + g.edge(e).weight;
});
return sucs
});
return _.zipObject(g.nodes(), weightMap)
}
function predecessorWeights (g) {
var weightMap = _.map(g.nodes(), function (v) {
var preds = {};
_.forEach(g.inEdges(v), function (e) {
preds[e.v] = (preds[e.v] || 0) + g.edge(e).weight;
});
return preds
});
return _.zipObject(g.nodes(), weightMap)
}
/*
* Finds where a line starting at point ({x, y}) would intersect a rectangle
* ({x, y, width, height}) if it were pointing at the rectangle's center.
*/
function intersectRect (rect, point) {
var x = rect.x;
var y = rect.y;
// Rectangle intersection algorithm from:
// http://math.stackexchange.com/questions/108113/find-edge-between-two-boxes
var dx = point.x - x;
var dy = point.y - y;
var w = rect.width / 2;
var h = rect.height / 2;
if (!dx && !dy) {
throw new Error('Not possible to find intersection inside of the rectangle')
}
var sx, sy;
if (Math.abs(dy) * w > Math.abs(dx) * h) {
// Intersection is top or bottom of rect.
if (dy < 0) {
h = -h;
}
sx = h * dx / dy;
sy = h;
} else {
// Intersection is left or right of rect.
if (dx < 0) {
w = -w;
}
sx = w;
sy = w * dy / dx;
}
return { x: x + sx, y: y + sy }
}
/*
* Given a DAG with each node assigned "rank" and "order" properties, this
* function will produce a matrix with the ids of each node.
*/
function buildLayerMatrix (g) {
var layering = _.map(_.range(maxRank(g) + 1), function () { return [] });
_.forEach(g.nodes(), function (v) {
var node = g.node(v);
var rank = node.rank;
if (!_.isUndefined(rank)) {
layering[rank][node.order] = v;
}
});
return layering
}
/*
* 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.
*/
function normalizeRanks (g) {
var min = _.min(_.map(g.nodes(), function (v) { return g.node(v).rank }));
_.forEach(g.nodes(), function (v) {
var node = g.node(v);
if (_.has(node, 'rank')) {
node.rank -= min;
}
});
}
function removeEmptyRanks (g) {
// Ranks may not start at 0, so we need to offset them
var offset = _.min(_.map(g.nodes(), function (v) { return g.node(v).rank }));
var layers = [];
_.forEach(g.nodes(), function (v) {
var rank = g.node(v).rank - offset;
if (!layers[rank]) {
layers[rank] = [];
}
layers[rank].push(v);
});
var delta = 0;
var nodeRankFactor = g.graph().nodeRankFactor;
_.forEach(layers, function (vs, i) {
if (_.isUndefined(vs) && i % nodeRankFactor !== 0) {
--delta;
} else if (delta) {
_.forEach(vs, function (v) { g.node(v).rank += delta; });
}
});
}
function addBorderNode (g, prefix, rank, order) {
var node = {
width: 0,
height: 0
};
if (arguments.length >= 4) {
node.rank = rank;
node.order = order;
}
return addDummyNode(g, 'border', node, prefix)
}
function maxRank (g) {
return _.max(_.map(g.nodes(), function (v) {
var rank = g.node(v).rank;
if (!_.isUndefined(rank)) {
return rank
}
}))
}
/*
* Partition a collection into two groups: `lhs` and `rhs`. If the supplied
* function returns true for an entry it goes into `lhs`. Otherwise it goes
* into `rhs.
*/
function partition (collection, fn) {
var result = { lhs: [], rhs: [] };
_.forEach(collection, function (value) {
if (fn(value)) {
result.lhs.push(value);
} else {
result.rhs.push(value);
}
});
return result
}
/*
* Returns a new function that wraps `fn` with a timer. The wrapper logs the
* time it takes to execute the function.
*/
function time (name, fn) {
var start = _.now();
try {
return fn()
} finally {
console.log(name + ' time: ' + (_.now() - start) + 'ms');
}
}
function notime (name, fn) {
return fn()
}
var util = {
addBorderNode,
addDummyNode,
asNonCompoundGraph,
buildLayerMatrix,
intersectRect,
maxRank,
partition,
predecessorWeights,
normalizeRanks,
notime,
removeEmptyRanks,
simplify,
successorWeights,
time
};
function debugOrdering (g) {
var layerMatrix = buildLayerMatrix(g);
var h = new graphlib.Graph({ compound: true, multigraph: true }).setGraph({});
_.forEach(g.nodes(), function (v) {
h.setNode(v, { label: v });
h.setParent(v, 'layer' + g.node(v).rank);
});
_.forEach(g.edges(), function (e) {
h.setEdge(e.v, e.w, {}, e.name);
});
_.forEach(layerMatrix, function (layer, i) {
var layerV = 'layer' + i;
h.setNode(layerV, { rank: 'same' });
_.reduce(layer, function (u, v) {
h.setEdge(u, v, { style: 'invis' });
return v
});
});
return h
}
/*
* Simple doubly linked list implementation derived from Cormen, et al.,
* "Introduction to Algorithms".
*/
function List () {
var sentinel = {};
sentinel._next = sentinel._prev = sentinel;
this._sentinel = sentinel;
}
List.prototype.dequeue = function () {
var sentinel = this._sentinel;
var entry = sentinel._prev;
if (entry !== sentinel) {
unlink(entry);
return entry
}
};
List.prototype.enqueue = function (entry) {
var sentinel = this._sentinel;
if (entry._prev && entry._next) {
unlink(entry);
}
entry._next = sentinel._next;
sentinel._next._prev = entry;
sentinel._next = entry;
entry._prev = sentinel;
};
List.prototype.toString = function () {
var strs = [];
var sentinel = this._sentinel;
var curr = sentinel._prev;
while (curr !== sentinel) {
strs.push(JSON.stringify(curr, filterOutLinks));
curr = curr._prev;
}
return '[' + strs.join(', ') + ']'
};
function unlink (entry) {
entry._prev._next = entry._next;
entry._next._prev = entry._prev;
delete entry._next;
delete entry._prev;
}
function filterOutLinks (k, v) {
if (k !== '_next' && k !== '_prev') {
return v
}
}
var DEFAULT_WEIGHT_FN = _.constant(1);
function doGreedyFAS (g, buckets, zeroIdx) {
var results = [];
var sources = buckets[buckets.length - 1];
var sinks = buckets[0];
var entry;
while (g.nodeCount()) {
while ((entry = sinks.dequeue())) { removeNode(g, buckets, zeroIdx, entry); }
while ((entry = sources.dequeue())) { removeNode(g, buckets, zeroIdx, entry); }
if (g.nodeCount()) {
for (var i = buckets.length - 2; i > 0; --i) {
entry = buckets[i].dequeue();
if (entry) {
results = results.concat(removeNode(g, buckets, zeroIdx, entry, true));
break
}
}
}
}
return results
}
function removeNode (g, buckets, zeroIdx, entry, collectPredecessors) {
var results = collectPredecessors ? [] : undefined;
_.forEach(g.inEdges(entry.v), function (edge) {
var weight = g.edge(edge);
var uEntry = g.node(edge.v);
if (collectPredecessors) {
results.push({ v: edge.v, w: edge.w });
}
uEntry.out -= weight;
assignBucket(buckets, zeroIdx, uEntry);
});
_.forEach(g.outEdges(entry.v), function (edge) {
var weight = g.edge(edge);
var w = edge.w;
var wEntry = g.node(w);
wEntry['in'] -= weight;
assignBucket(buckets, zeroIdx, wEntry);
});
g.removeNode(entry.v);
return results
}
function buildState (g, weightFn) {
var fasGraph = new graphlib.Graph();
var maxIn = 0;
var maxOut = 0;
_.forEach(g.nodes(), function (v) {
fasGraph.setNode(v, { v: v, 'in': 0, out: 0 });
});
// Aggregate weights on nodes, but also sum the weights across multi-edges
// into a single edge for the fasGraph.
_.forEach(g.edges(), function (e) {
var prevWeight = fasGraph.edge(e.v, e.w) || 0;
var weight = weightFn(e);
var edgeWeight = prevWeight + weight;
fasGraph.setEdge(e.v, e.w, edgeWeight);
maxOut = Math.max(maxOut, fasGraph.node(e.v).out += weight);
maxIn = Math.max(maxIn, fasGraph.node(e.w)['in'] += weight);
});
var buckets = _.range(maxOut + maxIn + 3).map(function () { return new List() });
var zeroIdx = maxIn + 1;
_.forEach(fasGraph.nodes(), function (v) {
assignBucket(buckets, zeroIdx, fasGraph.node(v));
});
return { graph: fasGraph, buckets: buckets, zeroIdx: zeroIdx }
}
function assignBucket (buckets, zeroIdx, entry) {
if (!entry.out) {
buckets[0].enqueue(entry);
} else if (!entry['in']) {
buckets[buckets.length - 1].enqueue(entry);
} else {
buckets[entry.out - entry['in'] + zeroIdx].enqueue(entry);
}
}
/*
* A greedy heuristic for finding a feedback arc set for a graph. A feedback
* arc set is a set of edges that can be removed to make a graph acyclic.
* The algorithm comes from: P. Eades, X. Lin, and W. F. Smyth, "A fast and
* effective heuristic for the feedback arc set problem." This implementation
* adjusts that from the paper to allow for weighted edges.
*/
var greedyFAS = function (g, weightFn) {
if (g.nodeCount() <= 1) {
return []
}
var state = buildState(g, weightFn || DEFAULT_WEIGHT_FN);
var results = doGreedyFAS(state.graph, state.buckets, state.zeroIdx);
// Expand multi-edges
return _.flatten(_.map(results, function (e) {
return g.outEdges(e.v, e.w)
}), true)
};
function dfsFAS (g) {
var fas = [];
var stack = {};
var visited = {};
function dfs (v) {
if (_.has(visited, v)) {
return
}
visited[v] = true;
stack[v] = true;
_.forEach(g.outEdges(v), function (e) {
if (_.has(stack, e.w)) {
fas.push(e);
} else {
dfs(e.w);
}
});
delete stack[v];
}
_.forEach(g.nodes(), dfs);
return fas
}
function undo (g) {
_.forEach(g.edges(), function (e) {
var label = g.edge(e);
if (label.reversed) {
g.removeEdge(e);
var forwardName = label.forwardName;
delete label.reversed;
delete label.forwardName;
g.setEdge(e.w, e.v, label, forwardName);
}
});
}
function run (g) {
var fas = (g.graph().acyclicer === 'greedy'
? greedyFAS(g, weightFn(g))
: dfsFAS(g));
_.forEach(fas, function (e) {
var label = g.edge(e);
g.removeEdge(e);
label.forwardName = e.name;
label.reversed = true;
g.setEdge(e.w, e.v, label, _.uniqueId('rev'));
});
function weightFn (g) {
return function (e) {
return g.edge(e).weight
}
}
}
function normalizeEdge (g, e) {
var v = e.v;
var vRank = g.node(v).rank;
var w = e.w;
var wRank = g.node(w).rank;
var name = e.name;
var edgeLabel = g.edge(e);
var labelRank = edgeLabel.labelRank;
if (wRank === vRank + 1) return
g.removeEdge(e);
var dummy, attrs, i;
for (i = 0, ++vRank; vRank < wRank; ++i, ++vRank) {
edgeLabel.points = [];
attrs = {
width: 0,
height: 0,
edgeLabel: edgeLabel,
edgeObj: e,
rank: vRank
};
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 (i === 0) {
g.graph().dummyChains.push(dummy);
}
v = dummy;
}
g.setEdge(v, w, { weight: edgeLabel.weight }, name);
}
/*
* 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.
*/
function run$1 (g) {
g.graph().dummyChains = [];
_.forEach(g.edges(), function (edge) { normalizeEdge(g, edge); });
}
function undo$1 (g) {
_.forEach(g.graph().dummyChains, function (v) {
var node = g.node(v);
var origLabel = node.edgeLabel;
var w;
g.setEdge(node.edgeObj, origLabel);
while (node.dummy) {
w = g.successors(v)[0];
g.removeNode(v);
origLabel.points.push({ x: node.x, y: node.y });
if (node.dummy === 'edge-label') {
origLabel.x = node.x;
origLabel.y = node.y;
origLabel.width = node.width;
origLabel.height = node.height;
}
v = w;
node = g.node(v);
}
});
}
/*
* 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.
*/
function longestPath (g) {
var visited = {};
function dfs (v) {
var label = g.node(v);
if (_.has(visited, v)) {
return label.rank
}
visited[v] = true;
var rank = _.min(_.map(g.outEdges(v), function (e) {
return dfs(e.w) - g.edge(e).minlen
}));
if (
rank === Number.POSITIVE_INFINITY || // return value of _.map([]) for Lodash 3
rank === undefined || // return value of _.map([]) for Lodash 4
rank === null // return value of _.map([null])
) {
rank = 0;
}
return (label.rank = rank)
}
_.forEach(g.sources(), dfs);
}
/*
* 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.
*/
function slack (g, e) {
return g.node(e.w).rank - g.node(e.v).rank - g.edge(e).minlen
}
/*
* Finds a maximal tree of tight edges and returns the number of nodes in the
* tree.
*/
function tightTree (t, g) {
function dfs (v) {
_.forEach(g.nodeEdges(v), function (e) {
var edgeV = e.v;
var w = (v === edgeV) ? e.w : edgeV;
if (!t.hasNode(w) && !slack(g, e)) {
t.setNode(w, {});
t.setEdge(v, w, {});
dfs(w);
}
});
}
_.forEach(t.nodes(), dfs);
return t.nodeCount()
}
/*
* Finds the edge with the smallest slack that is incident on tree and returns
* it.
*/
function findMinSlackEdge (t, g) {
return _.minBy(g.edges(), function (e) {
if (t.hasNode(e.v) !== t.hasNode(e.w)) {
return slack(g, e)
}
})
}
function shiftRanks (t, g, delta) {
_.forEach(t.nodes(), function (v) {
g.node(v).rank += delta;
});
}
/*
* 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.
*/
function feasibleTree (g) {
var t = new graphlib.Graph({ directed: false });
// Choose arbitrary node from which to start our tree
var start = g.nodes()[0];
var size = g.nodeCount();
t.setNode(start, {});
var edge, delta;
while (tightTree(t, g) < size) {
edge = findMinSlackEdge(t, g);
delta = t.hasNode(edge.v) ? slack(g, edge) : -slack(g, edge);
shiftRanks(t, g, delta);
}
return t
}
const {preorder, postorder} = graphlib.alg;
// Expose some internals for testing purposes
networkSimplex.initLowLimValues = initLowLimValues;
networkSimplex.initCutValues = initCutValues;
networkSimplex.calcCutValue = calcCutValue;
networkSimplex.leaveEdge = leaveEdge;
networkSimplex.enterEdge = enterEdge;
networkSimplex.exchangeEdges = exchangeEdges;
/*
* Initializes cut values for all edges in the tree.
*/
function initCutValues (t, g) {
var vs = postorder(t, t.nodes());
vs = vs.slice(0, vs.length - 1);
_.forEach(vs, function (v) {
assignCutValue(t, g, v);
});
}
function assignCutValue (t, g, child) {
var childLab = t.node(child);
var parent = childLab.parent;
t.edge(child, parent).cutvalue = calcCutValue(t, g, child);
}
/*
* 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.
*/
function calcCutValue (t, g, child) {
var childLab = t.node(child);
var parent = childLab.parent;
// True if the child is on the tail end of the edge in the directed graph
var childIsTail = true;
// The graph's view of the tree edge we're inspecting
var graphEdge = g.edge(child, parent);
// The accumulated cut value for the edge between this node and its parent
var cutValue = 0;
if (!graphEdge) {
childIsTail = false;
graphEdge = g.edge(parent, child);
}
cutValue = graphEdge.weight;
_.forEach(g.nodeEdges(child), function (e) {
var isOutEdge = e.v === child;
var other = isOutEdge ? e.w : e.v;
if (other !== parent) {
var pointsToHead = isOutEdge === childIsTail;
var otherWeight = g.edge(e).weight;
cutValue += pointsToHead ? otherWeight : -otherWeight;
if (isTreeEdge(t, child, other)) {
var otherCutValue = t.edge(child, other).cutvalue;
cutValue += pointsToHead ? -otherCutValue : otherCutValue;
}
}
});
return cutValue
}
function initLowLimValues (tree, root) {
if (arguments.length < 2) {
root = tree.nodes()[0];
}
dfsAssignLowLim(tree, {}, 1, root);
}
function dfsAssignLowLim (tree, visited, nextLim, v, parent) {
var low = nextLim;
var label = tree.node(v);
visited[v] = true;
_.forEach(tree.neighbors(v), function (w) {
if (!_.has(visited, w)) {
nextLim = dfsAssignLowLim(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
}
function leaveEdge (tree) {
return _.find(tree.edges(), function (e) {
return tree.edge(e).cutvalue < 0
})
}
function enterEdge (t, g, edge) {
var v = edge.v;
var 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.hasEdge(v, w)) {
v = edge.w;
w = edge.v;
}
var vLabel = t.node(v);
var wLabel = t.node(w);
var tailLabel = vLabel;
var 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;
}
var candidates = _.filter(g.edges(), function (edge) {
return flip === isDescendant(t, t.node(edge.v), tailLabel) &&
flip !== isDescendant(t, t.node(edge.w), tailLabel)
});
return _.minBy(candidates, function (edge) { return slack(g, edge) })
}
function exchangeEdges (t, g, e, f) {
var v = e.v;
var w = e.w;
t.removeEdge(v, w);
t.setEdge(f.v, f.w, {});
initLowLimValues(t);
initCutValues(t, g);
updateRanks(t, g);
}
function updateRanks (t, g) {
var root = _.find(t.nodes(), function (v) { return !g.node(v).parent });
var vs = preorder(t, root);
vs = vs.slice(1);
_.forEach(vs, function (v) {
var parent = t.node(v).parent;
var edge = g.edge(v, parent);
var flipped = false;
if (!edge) {
edge = g.edge(parent, v);
flipped = true;
}
g.node(v).rank = g.node(parent).rank + (flipped ? edge.minlen : -edge.minlen);
});
}
/*
* Returns true if the edge is in the tree.
*/
function isTreeEdge (tree, u, v) {
return tree.hasEdge(u, v)
}
/*
* Returns true if the specified node is descendant of the root node per the
* assigned low and lim attributes in the tree.
*/
function isDescendant (tree, vLabel, rootLabel) {
return rootLabel.low <= vLabel.lim && vLabel.lim <= rootLabel.lim
}
/*
* 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.
*/
function networkSimplex (g) {
g = simplify(g);
longestPath(g);
var t = feasibleTree(g);
initLowLimValues(t);
initCutValues(t, g);
var e, f;
while ((e = leaveEdge(t))) {
f = enterEdge(t, g, e);
exchangeEdges(t, g, e, f);
}
}
// A fast and simple ranker, but results are far from optimal.
var longestPathRanker = longestPath;
function tightTreeRanker (g) {
longestPath(g);
feasibleTree(g);
}
function networkSimplexRanker (g) {
networkSimplex(g);
}
/*
* 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.
*/
function rank (g) {
switch (g.graph().ranker) {
case 'network-simplex': networkSimplexRanker(g); break
case 'tight-tree': tightTreeRanker(g); break
case 'longest-path': longestPathRanker(g); break
default: networkSimplexRanker(g);
}
}
// Find a path from v to w through the lowest common ancestor (LCA). Return the
// full path and the LCA.
function findPath (g, postorderNums, v, w) {
var vPath = [];
var wPath = [];
var low = Math.min(postorderNums[v].low, postorderNums[w].low);
var lim = Math.max(postorderNums[v].lim, postorderNums[w].lim);
var parent;
var lca;
// Traverse up from v to find the LCA
parent = v;
do {
parent = g.parent(parent);
vPath.push(parent);
} while (parent &&
(postorderNums[parent].low > low || lim > postorderNums[parent].lim))
lca = parent;
// Traverse from w to LCA
parent = w;
while ((parent = g.parent(parent)) !== lca) {
wPath.push(parent);