| 1 | var _ = require("../lodash"); |
| 2 | var Graph = require("../graphlib").Graph; |
| 3 | |
| 4 | module.exports = buildLayerGraph; |
| 5 | |
| 6 | /* |
| 7 | * Constructs a graph that can be used to sort a layer of nodes. The graph will |
| 8 | * contain all base and subgraph nodes from the request layer in their original |
| 9 | * hierarchy and any edges that are incident on these nodes and are of the type |
| 10 | * requested by the "relationship" parameter. |
| 11 | * |
| 12 | * Nodes from the requested rank that do not have parents are assigned a root |
| 13 | * node in the output graph, which is set in the root graph attribute. This |
| 14 | * makes it easy to walk the hierarchy of movable nodes during ordering. |
| 15 | * |
| 16 | * Pre-conditions: |
| 17 | * |
| 18 | * 1. Input graph is a DAG |
| 19 | * 2. Base nodes in the input graph have a rank attribute |
| 20 | * 3. Subgraph nodes in the input graph has minRank and maxRank attributes |
| 21 | * 4. Edges have an assigned weight |
| 22 | * |
| 23 | * Post-conditions: |
| 24 | * |
| 25 | * 1. Output graph has all nodes in the movable rank with preserved |
| 26 | * hierarchy. |
| 27 | * 2. Root nodes in the movable layer are made children of the node |
| 28 | * indicated by the root attribute of the graph. |
| 29 | * 3. Non-movable nodes incident on movable nodes, selected by the |
| 30 | * relationship parameter, are included in the graph (without hierarchy). |
| 31 | * 4. Edges incident on movable nodes, selected by the relationship |
| 32 | * parameter, are added to the output graph. |
| 33 | * 5. The weights for copied edges are aggregated as need, since the output |
| 34 | * graph is not a multi-graph. |
| 35 | */ |
| 36 | function buildLayerGraph(g, rank, relationship) { |
| 37 | var root = createRootNode(g), |
| 38 | result = new Graph({ compound: true }).setGraph({ root: root }) |
| 39 | .setDefaultNodeLabel(function(v) { return g.node(v); }); |
| 40 | |
| 41 | _.forEach(g.nodes(), function(v) { |
| 42 | var node = g.node(v), |
| 43 | parent = g.parent(v); |
| 44 | |
| 45 | if (node.rank === rank || node.minRank <= rank && rank <= node.maxRank) { |
| 46 | result.setNode(v); |
| 47 | result.setParent(v, parent || root); |
| 48 | |
| 49 | // This assumes we have only short edges! |
| 50 | _.forEach(g[relationship](v), function(e) { |
| 51 | var u = e.v === v ? e.w : e.v, |
| 52 | edge = result.edge(u, v), |
| 53 | weight = !_.isUndefined(edge) ? edge.weight : 0; |
| 54 | result.setEdge(u, v, { weight: g.edge(e).weight + weight }); |
| 55 | }); |
| 56 | |
| 57 | if (_.has(node, "minRank")) { |
| 58 | result.setNode(v, { |
| 59 | borderLeft: node.borderLeft[rank], |
| 60 | borderRight: node.borderRight[rank] |
| 61 | }); |
| 62 | } |
| 63 | } |
| 64 | }); |
| 65 | |
| 66 | return result; |
| 67 | } |
| 68 | |
| 69 | function createRootNode(g) { |
| 70 | var v; |
| 71 | while (g.hasNode((v = _.uniqueId("_root")))); |
| 72 | return v; |
| 73 | } |