Debian Codegraph @

lib/order/cross-count.js

raw symbols SCIP
1 "use strict";
2
3 var _ = require("../lodash");
4
5 module.exports = crossCount;
6
7 /*
8 * A function that takes a layering (an array of layers, each with an array of
9 * ordererd nodes) and a graph and returns a weighted crossing count.
10 *
11 * Pre-conditions:
12 *
13 * 1. Input graph must be simple (not a multigraph), directed, and include
14 * only simple edges.
15 * 2. Edges in the input graph must have assigned weights.
16 *
17 * Post-conditions:
18 *
19 * 1. The graph and layering matrix are left unchanged.
20 *
21 * This algorithm is derived from Barth, et al., "Bilayer Cross Counting."
22 */
23 function crossCount(g, layering) {
24 var cc = 0;
25 for (var i = 1; i < layering.length; ++i) {
26 cc += twoLayerCrossCount(g, layering[i-1], layering[i]);
27 }
28 return cc;
29 }
30
31 function twoLayerCrossCount(g, northLayer, southLayer) {
32 // Sort all of the edges between the north and south layers by their position
33 // in the north layer and then the south. Map these edges to the position of
34 // their head in the south layer.
35 var southPos = _.zipObject(southLayer,
36 _.map(southLayer, function (v, i) { return i; }));
37 var southEntries = _.flatten(_.map(northLayer, function(v) {
38 return _.sortBy(_.map(g.outEdges(v), function(e) {
39 return { pos: southPos[e.w], weight: g.edge(e).weight };
40 }), "pos");
41 }), true);
42
43 // Build the accumulator tree
44 var firstIndex = 1;
45 while (firstIndex < southLayer.length) firstIndex <<= 1;
46 var treeSize = 2 * firstIndex - 1;
47 firstIndex -= 1;
48 var tree = _.map(new Array(treeSize), function() { return 0; });
49
50 // Calculate the weighted crossings
51 var cc = 0;
52 _.forEach(southEntries.forEach(function(entry) {
53 var index = entry.pos + firstIndex;
54 tree[index] += entry.weight;
55 var weightSum = 0;
56 while (index > 0) {
57 if (index % 2) {
58 weightSum += tree[index + 1];
59 }
60 index = (index - 1) >> 1;
61 tree[index] += entry.weight;
62 }
63 cc += entry.weight * weightSum;
64 }));
65
66 return cc;
67 }