import * as _ from 'lodash-es';
export { crossCount };
function crossCount(g, layering) {
var cc = 0;
for (var i = 1; i < layering.length; ++i) {
cc += twoLayerCrossCount(g, layering[i - 1], layering[i]);
}
return cc;
}
function twoLayerCrossCount(g, northLayer, southLayer) {
var southPos = _.zipObject(
southLayer,
_.map(southLayer, function (v, i) {
return i;
})
);
var southEntries = _.flatten(
_.map(northLayer, function (v) {
return _.sortBy(
_.map(g.outEdges(v), function (e) {
return { pos: southPos[e.w], weight: g.edge(e).weight };
}),
'pos'
);
})
);
var firstIndex = 1;
while (firstIndex < southLayer.length) firstIndex <<= 1;
var treeSize = 2 * firstIndex - 1;
firstIndex -= 1;
var tree = _.map(new Array(treeSize), function () {
return 0;
});
var cc = 0;
_.forEach(
southEntries.forEach(function (entry) {
var index = entry.pos + firstIndex;
tree[index] += entry.weight;
var weightSum = 0;
while (index > 0) {
if (index % 2) {
weightSum += tree[index + 1];
}
index = (index - 1) >> 1;
tree[index] += entry.weight;
}
cc += entry.weight * weightSum;
})
);
return cc;
}