Debian Codegraph @

lib/order/index.js

raw symbols SCIP
1 "use strict";
2
3 var _ = require("../lodash");
4 var initOrder = require("./init-order");
5 var crossCount = require("./cross-count");
6 var sortSubgraph = require("./sort-subgraph");
7 var buildLayerGraph = require("./build-layer-graph");
8 var addSubgraphConstraints = require("./add-subgraph-constraints");
9 var Graph = require("../graphlib").Graph;
10 var util = require("../util");
11
12 module.exports = order;
13
14 /*
15 * Applies heuristics to minimize edge crossings in the graph and sets the best
16 * order solution as an order attribute on each node.
17 *
18 * Pre-conditions:
19 *
20 * 1. Graph must be DAG
21 * 2. Graph nodes must be objects with a "rank" attribute
22 * 3. Graph edges must have the "weight" attribute
23 *
24 * Post-conditions:
25 *
26 * 1. Graph nodes will have an "order" attribute based on the results of the
27 * algorithm.
28 */
29 function order(g) {
30 var maxRank = util.maxRank(g),
31 downLayerGraphs = buildLayerGraphs(g, _.range(1, maxRank + 1), "inEdges"),
32 upLayerGraphs = buildLayerGraphs(g, _.range(maxRank - 1, -1, -1), "outEdges");
33
34 var layering = initOrder(g);
35 assignOrder(g, layering);
36
37 var bestCC = Number.POSITIVE_INFINITY,
38 best;
39
40 for (var i = 0, lastBest = 0; lastBest < 4; ++i, ++lastBest) {
41 sweepLayerGraphs(i % 2 ? downLayerGraphs : upLayerGraphs, i % 4 >= 2);
42
43 layering = util.buildLayerMatrix(g);
44 var cc = crossCount(g, layering);
45 if (cc < bestCC) {
46 lastBest = 0;
47 best = _.cloneDeep(layering);
48 bestCC = cc;
49 }
50 }
51
52 assignOrder(g, best);
53 }
54
55 function buildLayerGraphs(g, ranks, relationship) {
56 return _.map(ranks, function(rank) {
57 return buildLayerGraph(g, rank, relationship);
58 });
59 }
60
61 function sweepLayerGraphs(layerGraphs, biasRight) {
62 var cg = new Graph();
63 _.forEach(layerGraphs, function(lg) {
64 var root = lg.graph().root;
65 var sorted = sortSubgraph(lg, root, cg, biasRight);
66 _.forEach(sorted.vs, function(v, i) {
67 lg.node(v).order = i;
68 });
69 addSubgraphConstraints(lg, cg, sorted.vs);
70 });
71 }
72
73 function assignOrder(g, layering) {
74 _.forEach(layering, function(layer) {
75 _.forEach(layer, function(v, i) {
76 g.node(v).order = i;
77 });
78 });
79 }