Debian Codegraph @

lib/position/bk.js

raw symbols SCIP
1 "use strict";
2
3 var _ = require("../lodash");
4 var Graph = require("../graphlib").Graph;
5 var util = require("../util");
6
7 /*
8 * This module provides coordinate assignment based on Brandes and Köpf, "Fast
9 * and Simple Horizontal Coordinate Assignment."
10 */
11
12 module.exports = {
13 positionX: positionX,
14 findType1Conflicts: findType1Conflicts,
15 findType2Conflicts: findType2Conflicts,
16 addConflict: addConflict,
17 hasConflict: hasConflict,
18 verticalAlignment: verticalAlignment,
19 horizontalCompaction: horizontalCompaction,
20 alignCoordinates: alignCoordinates,
21 findSmallestWidthAlignment: findSmallestWidthAlignment,
22 balance: balance
23 };
24
25 /*
26 * Marks all edges in the graph with a type-1 conflict with the "type1Conflict"
27 * property. A type-1 conflict is one where a non-inner segment crosses an
28 * inner segment. An inner segment is an edge with both incident nodes marked
29 * with the "dummy" property.
30 *
31 * This algorithm scans layer by layer, starting with the second, for type-1
32 * conflicts between the current layer and the previous layer. For each layer
33 * it scans the nodes from left to right until it reaches one that is incident
34 * on an inner segment. It then scans predecessors to determine if they have
35 * edges that cross that inner segment. At the end a final scan is done for all
36 * nodes on the current rank to see if they cross the last visited inner
37 * segment.
38 *
39 * This algorithm (safely) assumes that a dummy node will only be incident on a
40 * single node in the layers being scanned.
41 */
42 function findType1Conflicts(g, layering) {
43 var conflicts = {};
44
45 function visitLayer(prevLayer, layer) {
46 var
47 // last visited node in the previous layer that is incident on an inner
48 // segment.
49 k0 = 0,
50 // Tracks the last node in this layer scanned for crossings with a type-1
51 // segment.
52 scanPos = 0,
53 prevLayerLength = prevLayer.length,
54 lastNode = _.last(layer);
55
56 _.forEach(layer, function(v, i) {
57 var w = findOtherInnerSegmentNode(g, v),
58 k1 = w ? g.node(w).order : prevLayerLength;
59
60 if (w || v === lastNode) {
61 _.forEach(layer.slice(scanPos, i +1), function(scanNode) {
62 _.forEach(g.predecessors(scanNode), function(u) {
63 var uLabel = g.node(u),
64 uPos = uLabel.order;
65 if ((uPos < k0 || k1 < uPos) &&
66 !(uLabel.dummy && g.node(scanNode).dummy)) {
67 addConflict(conflicts, u, scanNode);
68 }
69 });
70 });
71 scanPos = i + 1;
72 k0 = k1;
73 }
74 });
75
76 return layer;
77 }
78
79 _.reduce(layering, visitLayer);
80 return conflicts;
81 }
82
83 function findType2Conflicts(g, layering) {
84 var conflicts = {};
85
86 function scan(south, southPos, southEnd, prevNorthBorder, nextNorthBorder) {
87 var v;
88 _.forEach(_.range(southPos, southEnd), function(i) {
89 v = south[i];
90 if (g.node(v).dummy) {
91 _.forEach(g.predecessors(v), function(u) {
92 var uNode = g.node(u);
93 if (uNode.dummy &&
94 (uNode.order < prevNorthBorder || uNode.order > nextNorthBorder)) {
95 addConflict(conflicts, u, v);
96 }
97 });
98 }
99 });
100 }
101
102
103 function visitLayer(north, south) {
104 var prevNorthPos = -1,
105 nextNorthPos,
106 southPos = 0;
107
108 _.forEach(south, function(v, southLookahead) {
109 if (g.node(v).dummy === "border") {
110 var predecessors = g.predecessors(v);
111 if (predecessors.length) {
112 nextNorthPos = g.node(predecessors[0]).order;
113 scan(south, southPos, southLookahead, prevNorthPos, nextNorthPos);
114 southPos = southLookahead;
115 prevNorthPos = nextNorthPos;
116 }
117 }
118 scan(south, southPos, south.length, nextNorthPos, north.length);
119 });
120
121 return south;
122 }
123
124 _.reduce(layering, visitLayer);
125 return conflicts;
126 }
127
128 function findOtherInnerSegmentNode(g, v) {
129 if (g.node(v).dummy) {
130 return _.find(g.predecessors(v), function(u) {
131 return g.node(u).dummy;
132 });
133 }
134 }
135
136 function addConflict(conflicts, v, w) {
137 if (v > w) {
138 var tmp = v;
139 v = w;
140 w = tmp;
141 }
142
143 var conflictsV = conflicts[v];
144 if (!conflictsV) {
145 conflicts[v] = conflictsV = {};
146 }
147 conflictsV[w] = true;
148 }
149
150 function hasConflict(conflicts, v, w) {
151 if (v > w) {
152 var tmp = v;
153 v = w;
154 w = tmp;
155 }
156 return _.has(conflicts[v], w);
157 }
158
159 /*
160 * Try to align nodes into vertical "blocks" where possible. This algorithm
161 * attempts to align a node with one of its median neighbors. If the edge
162 * connecting a neighbor is a type-1 conflict then we ignore that possibility.
163 * If a previous node has already formed a block with a node after the node
164 * we're trying to form a block with, we also ignore that possibility - our
165 * blocks would be split in that scenario.
166 */
167 function verticalAlignment(g, layering, conflicts, neighborFn) {
168 var root = {},
169 align = {},
170 pos = {};
171
172 // We cache the position here based on the layering because the graph and
173 // layering may be out of sync. The layering matrix is manipulated to
174 // generate different extreme alignments.
175 _.forEach(layering, function(layer) {
176 _.forEach(layer, function(v, order) {
177 root[v] = v;
178 align[v] = v;
179 pos[v] = order;
180 });
181 });
182
183 _.forEach(layering, function(layer) {
184 var prevIdx = -1;
185 _.forEach(layer, function(v) {
186 var ws = neighborFn(v);
187 if (ws.length) {
188 ws = _.sortBy(ws, function(w) { return pos[w]; });
189 var mp = (ws.length - 1) / 2;
190 for (var i = Math.floor(mp), il = Math.ceil(mp); i <= il; ++i) {
191 var w = ws[i];
192 if (align[v] === v &&
193 prevIdx < pos[w] &&
194 !hasConflict(conflicts, v, w)) {
195 align[w] = v;
196 align[v] = root[v] = root[w];
197 prevIdx = pos[w];
198 }
199 }
200 }
201 });
202 });
203
204 return { root: root, align: align };
205 }
206
207 function horizontalCompaction(g, layering, root, align, reverseSep) {
208 // This portion of the algorithm differs from BK due to a number of problems.
209 // Instead of their algorithm we construct a new block graph and do two
210 // sweeps. The first sweep places blocks with the smallest possible
211 // coordinates. The second sweep removes unused space by moving blocks to the
212 // greatest coordinates without violating separation.
213 var xs = {},
214 blockG = buildBlockGraph(g, layering, root, reverseSep),
215 borderType = reverseSep ? "borderLeft" : "borderRight";
216
217 function iterate(setXsFunc, nextNodesFunc) {
218 var stack = blockG.nodes();
219 var elem = stack.pop();
220 var visited = {};
221 while (elem) {
222 if (visited[elem]) {
223 setXsFunc(elem);
224 } else {
225 visited[elem] = true;
226 stack.push(elem);
227 stack = stack.concat(nextNodesFunc(elem));
228 }
229
230 elem = stack.pop();
231 }
232 }
233
234 // First pass, assign smallest coordinates
235 function pass1(elem) {
236 xs[elem] = blockG.inEdges(elem).reduce(function(acc, e) {
237 return Math.max(acc, xs[e.v] + blockG.edge(e));
238 }, 0);
239 }
240
241 // Second pass, assign greatest coordinates
242 function pass2(elem) {
243 var min = blockG.outEdges(elem).reduce(function(acc, e) {
244 return Math.min(acc, xs[e.w] - blockG.edge(e));
245 }, Number.POSITIVE_INFINITY);
246
247 var node = g.node(elem);
248 if (min !== Number.POSITIVE_INFINITY && node.borderType !== borderType) {
249 xs[elem] = Math.max(xs[elem], min);
250 }
251 }
252
253 iterate(pass1, blockG.predecessors.bind(blockG));
254 iterate(pass2, blockG.successors.bind(blockG));
255
256 // Assign x coordinates to all nodes
257 _.forEach(align, function(v) {
258 xs[v] = xs[root[v]];
259 });
260
261 return xs;
262 }
263
264
265 function buildBlockGraph(g, layering, root, reverseSep) {
266 var blockGraph = new Graph(),
267 graphLabel = g.graph(),
268 sepFn = sep(graphLabel.nodesep, graphLabel.edgesep, reverseSep);
269
270 _.forEach(layering, function(layer) {
271 var u;
272 _.forEach(layer, function(v) {
273 var vRoot = root[v];
274 blockGraph.setNode(vRoot);
275 if (u) {
276 var uRoot = root[u],
277 prevMax = blockGraph.edge(uRoot, vRoot);
278 blockGraph.setEdge(uRoot, vRoot, Math.max(sepFn(g, v, u), prevMax || 0));
279 }
280 u = v;
281 });
282 });
283
284 return blockGraph;
285 }
286
287 /*
288 * Returns the alignment that has the smallest width of the given alignments.
289 */
290 function findSmallestWidthAlignment(g, xss) {
291 return _.minBy(_.values(xss), function (xs) {
292 var max = Number.NEGATIVE_INFINITY;
293 var min = Number.POSITIVE_INFINITY;
294
295 _.forIn(xs, function (x, v) {
296 var halfWidth = width(g, v) / 2;
297
298 max = Math.max(x + halfWidth, max);
299 min = Math.min(x - halfWidth, min);
300 });
301
302 return max - min;
303 });
304 }
305
306 /*
307 * Align the coordinates of each of the layout alignments such that
308 * left-biased alignments have their minimum coordinate at the same point as
309 * the minimum coordinate of the smallest width alignment and right-biased
310 * alignments have their maximum coordinate at the same point as the maximum
311 * coordinate of the smallest width alignment.
312 */
313 function alignCoordinates(xss, alignTo) {
314 var alignToVals = _.values(alignTo),
315 alignToMin = _.min(alignToVals),
316 alignToMax = _.max(alignToVals);
317
318 _.forEach(["u", "d"], function(vert) {
319 _.forEach(["l", "r"], function(horiz) {
320 var alignment = vert + horiz,
321 xs = xss[alignment],
322 delta;
323 if (xs === alignTo) return;
324
325 var xsVals = _.values(xs);
326 delta = horiz === "l" ? alignToMin - _.min(xsVals) : alignToMax - _.max(xsVals);
327
328 if (delta) {
329 xss[alignment] = _.mapValues(xs, function(x) { return x + delta; });
330 }
331 });
332 });
333 }
334
335 function balance(xss, align) {
336 return _.mapValues(xss.ul, function(ignore, v) {
337 if (align) {
338 return xss[align.toLowerCase()][v];
339 } else {
340 var xs = _.sortBy(_.map(xss, v));
341 return (xs[1] + xs[2]) / 2;
342 }
343 });
344 }
345
346 function positionX(g) {
347 var layering = util.buildLayerMatrix(g);
348 var conflicts = _.merge(
349 findType1Conflicts(g, layering),
350 findType2Conflicts(g, layering));
351
352 var xss = {};
353 var adjustedLayering;
354 _.forEach(["u", "d"], function(vert) {
355 adjustedLayering = vert === "u" ? layering : _.values(layering).reverse();
356 _.forEach(["l", "r"], function(horiz) {
357 if (horiz === "r") {
358 adjustedLayering = _.map(adjustedLayering, function(inner) {
359 return _.values(inner).reverse();
360 });
361 }
362
363 var neighborFn = (vert === "u" ? g.predecessors : g.successors).bind(g);
364 var align = verticalAlignment(g, adjustedLayering, conflicts, neighborFn);
365 var xs = horizontalCompaction(g, adjustedLayering,
366 align.root, align.align, horiz === "r");
367 if (horiz === "r") {
368 xs = _.mapValues(xs, function(x) { return -x; });
369 }
370 xss[vert + horiz] = xs;
371 });
372 });
373
374 var smallestWidth = findSmallestWidthAlignment(g, xss);
375 alignCoordinates(xss, smallestWidth);
376 return balance(xss, g.graph().align);
377 }
378
379 function sep(nodeSep, edgeSep, reverseSep) {
380 return function(g, v, w) {
381 var vLabel = g.node(v);
382 var wLabel = g.node(w);
383 var sum = 0;
384 var delta;
385
386 sum += vLabel.width / 2;
387 if (_.has(vLabel, "labelpos")) {
388 switch (vLabel.labelpos.toLowerCase()) {
389 case "l": delta = -vLabel.width / 2; break;
390 case "r": delta = vLabel.width / 2; break;
391 }
392 }
393 if (delta) {
394 sum += reverseSep ? delta : -delta;
395 }
396 delta = 0;
397
398 sum += (vLabel.dummy ? edgeSep : nodeSep) / 2;
399 sum += (wLabel.dummy ? edgeSep : nodeSep) / 2;
400
401 sum += wLabel.width / 2;
402 if (_.has(wLabel, "labelpos")) {
403 switch (wLabel.labelpos.toLowerCase()) {
404 case "l": delta = wLabel.width / 2; break;
405 case "r": delta = -wLabel.width / 2; break;
406 }
407 }
408 if (delta) {
409 sum += reverseSep ? delta : -delta;
410 }
411 delta = 0;
412
413 return sum;
414 };
415 }
416
417 function width(g, v) {
418 return g.node(v).width;
419 }