Debian Codegraph @

lib/rank/feasible-tree.js

raw symbols SCIP
1 "use strict";
2
3 var _ = require("../lodash");
4 var Graph = require("../graphlib").Graph;
5 var slack = require("./util").slack;
6
7 module.exports = feasibleTree;
8
9 /*
10 * Constructs a spanning tree with tight edges and adjusted the input node's
11 * ranks to achieve this. A tight edge is one that is has a length that matches
12 * its "minlen" attribute.
13 *
14 * The basic structure for this function is derived from Gansner, et al., "A
15 * Technique for Drawing Directed Graphs."
16 *
17 * Pre-conditions:
18 *
19 * 1. Graph must be a DAG.
20 * 2. Graph must be connected.
21 * 3. Graph must have at least one node.
22 * 5. Graph nodes must have been previously assigned a "rank" property that
23 * respects the "minlen" property of incident edges.
24 * 6. Graph edges must have a "minlen" property.
25 *
26 * Post-conditions:
27 *
28 * - Graph nodes will have their rank adjusted to ensure that all edges are
29 * tight.
30 *
31 * Returns a tree (undirected graph) that is constructed using only "tight"
32 * edges.
33 */
34 function feasibleTree(g) {
35 var t = new Graph({ directed: false });
36
37 // Choose arbitrary node from which to start our tree
38 var start = g.nodes()[0];
39 var size = g.nodeCount();
40 t.setNode(start, {});
41
42 var edge, delta;
43 while (tightTree(t, g) < size) {
44 edge = findMinSlackEdge(t, g);
45 delta = t.hasNode(edge.v) ? slack(g, edge) : -slack(g, edge);
46 shiftRanks(t, g, delta);
47 }
48
49 return t;
50 }
51
52 /*
53 * Finds a maximal tree of tight edges and returns the number of nodes in the
54 * tree.
55 */
56 function tightTree(t, g) {
57 function dfs(v) {
58 _.forEach(g.nodeEdges(v), function(e) {
59 var edgeV = e.v,
60 w = (v === edgeV) ? e.w : edgeV;
61 if (!t.hasNode(w) && !slack(g, e)) {
62 t.setNode(w, {});
63 t.setEdge(v, w, {});
64 dfs(w);
65 }
66 });
67 }
68
69 _.forEach(t.nodes(), dfs);
70 return t.nodeCount();
71 }
72
73 /*
74 * Finds the edge with the smallest slack that is incident on tree and returns
75 * it.
76 */
77 function findMinSlackEdge(t, g) {
78 return _.minBy(g.edges(), function(e) {
79 if (t.hasNode(e.v) !== t.hasNode(e.w)) {
80 return slack(g, e);
81 }
82 });
83 }
84
85 function shiftRanks(t, g, delta) {
86 _.forEach(t.nodes(), function(v) {
87 g.node(v).rank += delta;
88 });
89 }