| 1 | "use strict"; |
| 2 | |
| 3 | var _ = require("../lodash"); |
| 4 | |
| 5 | module.exports = { |
| 6 | longestPath: longestPath, |
| 7 | slack: slack |
| 8 | }; |
| 9 | |
| 10 | /* |
| 11 | * Initializes ranks for the input graph using the longest path algorithm. This |
| 12 | * algorithm scales well and is fast in practice, it yields rather poor |
| 13 | * solutions. Nodes are pushed to the lowest layer possible, leaving the bottom |
| 14 | * ranks wide and leaving edges longer than necessary. However, due to its |
| 15 | * speed, this algorithm is good for getting an initial ranking that can be fed |
| 16 | * into other algorithms. |
| 17 | * |
| 18 | * This algorithm does not normalize layers because it will be used by other |
| 19 | * algorithms in most cases. If using this algorithm directly, be sure to |
| 20 | * run normalize at the end. |
| 21 | * |
| 22 | * Pre-conditions: |
| 23 | * |
| 24 | * 1. Input graph is a DAG. |
| 25 | * 2. Input graph node labels can be assigned properties. |
| 26 | * |
| 27 | * Post-conditions: |
| 28 | * |
| 29 | * 1. Each node will be assign an (unnormalized) "rank" property. |
| 30 | */ |
| 31 | function longestPath(g) { |
| 32 | var visited = {}; |
| 33 | |
| 34 | function dfs(v) { |
| 35 | var label = g.node(v); |
| 36 | if (_.has(visited, v)) { |
| 37 | return label.rank; |
| 38 | } |
| 39 | visited[v] = true; |
| 40 | |
| 41 | var rank = _.min(_.map(g.outEdges(v), function(e) { |
| 42 | return dfs(e.w) - g.edge(e).minlen; |
| 43 | })); |
| 44 | |
| 45 | if (rank === Number.POSITIVE_INFINITY || // return value of _.map([]) for Lodash 3 |
| 46 | rank === undefined || // return value of _.map([]) for Lodash 4 |
| 47 | rank === null) { // return value of _.map([null]) |
| 48 | rank = 0; |
| 49 | } |
| 50 | |
| 51 | return (label.rank = rank); |
| 52 | } |
| 53 | |
| 54 | _.forEach(g.sources(), dfs); |
| 55 | } |
| 56 | |
| 57 | /* |
| 58 | * Returns the amount of slack for the given edge. The slack is defined as the |
| 59 | * difference between the length of the edge and its minimum length. |
| 60 | */ |
| 61 | function slack(g, e) { |
| 62 | return g.node(e.w).rank - g.node(e.v).rank - g.edge(e).minlen; |
| 63 | } |