dragnn_layout.js 7.6 KB
Newer Older
Ivan Bogatyy's avatar
Ivan Bogatyy committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248

/**
 * @fileoverview Cytoscape layout function for DRAGNN graphs.
 *
 * Currently, the algorithm has 3 stages:
 *
 *   1. Initial layout
 *   2. Spring-based resolution
 *   3. Re-layout based on component order and direction
 *
 * In the future, if we propagated a few more pieces of information, we could
 * probably skip the spring-based step altogether.
 */
'use strict';

const _ = require('lodash');

// default layout options
const defaults = {
  horizontal: true,
  ready() {},  // on layoutready
  stop() {},   // on layoutstop
};

/**
 * Partitions nodes into component nodes and step nodes.
 *
 * @param {!Array} nodes Nodes to partition.
 * @return {!Object<string, Object>} dictionary with two keys, 'component' and
 *     'step', both of which are list of Cytoscape nodes.
 */
function partitionNodes(nodes) {
  // Split nodes into components and steps per component.
  const partition = {component: [], step: []};
  _.each(nodes, function(node) {
    partition[node.hasClass('step') ? 'step' : 'component'].push(node);
  });
  return partition;
}

/**
 * Partitions step nodes by their component name.
 *
 * @param {!Array} nodes Nodes to partition.
 * @return {!Object<string, Object>} dictionary keys as component names,
 *     values as children of that component.
 */
function partitionStepNodes(nodes) {
  const partition = {};
  _.each(nodes, (node) => {
    const key = node.data('parent');
    if (partition[key] === undefined) {
      partition[key] = [node];
    } else {
      partition[key].push(node);
    }
  });
  return partition;
}

/**
 * Initializes the custom Cytoscape layout. This needs to be an old-style class,
 * because of how it's called in Cytoscape.
 *
 * @param {!Object} options Options to initialize with. These will be passed
 *     through to the intermediate "cose" layout.
 */
function DragnnLayout(options) {
  this.options = _.extend({}, defaults, options);
  this.horizontal = this.options.horizontal;
}

/**
 * Calculates the step position, given an effective component index, and step
 * index.
 *
 * @param {number} componentIdx Zero-based (display) index of the component.
 * @param {number} stepIdx Zero-based (display) index of the step.
 * @return {!Object<string, number>} Position dictionary (x and y)
 */
DragnnLayout.prototype.stepPosition = function(componentIdx, stepIdx) {
  return (
      this.horizontal ? {'x': stepIdx * 30, 'y': 220 * componentIdx} :
                        {'x': 320 * componentIdx, 'y': stepIdx * 30});
};

/**
 * The main method for our DRAGNN-specific layout. See module docstring.
 *
 * Cytoscape automatically injects `this.trigger` methods and `options.cy`,
 * `options.eles` variables.
 *
 * @return {DragnnLayout} `this`, for chaining.
 */
DragnnLayout.prototype.run = function() {
  const eles = this.options.eles;  // elements to consider in the layout
  const cy = this.options.cy;

  this.trigger('layoutstart');

  const visible = _.filter(eles.nodes(), function(n) {
    return n.visible();
  });
  const partition = partitionNodes(visible);
  const stepPartition = partitionStepNodes(partition.step);

  // Initialize components as horizontal or vertical "strips".
  _.each(stepPartition, (stepNodes) => {
    _.each(stepNodes, (node, idx) => {
      node.position(this.stepPosition(node.data('componentIdx'), idx));
    });
  });

  // Next do a cose layout, and then run finalLayout().
  cy.layout(_.extend({}, this.options, {
    name: 'cose',
    animate: false,
    ready: this.finalLayout.bind(this, partition, stepPartition, cy)
  }));

  return this;
};

/**
 * Gets a list of components, by their current visual position.
 *
 * @param {!Array} componentNodes Cytoscape component nodes.
 * @return {!Array<string, Object>} List of (componentName, position dict)
 *     pairs.
 */
DragnnLayout.prototype.sortedComponents = function(componentNodes) {
  // Position dictionaries are mutable, so copy them to avoid confusion.
  const copyPosition = (pos) => {
    return {x: pos.x, y: pos.y};
  };

  const componentPositions = _.map(componentNodes, (node) => {
    return [node.id(), copyPosition(node.position())];
  });

  return _.sortBy(componentPositions, (x) => {
    return this.horizontal ? x[1].y : x[1].x;
  });
};

/**
 * Computes the final, fancy layout. This will use two components from the
 * spring model,
 *
 *  - the order of components
 *  - directionality within components
 *
 * and redo layout in a way that's visually appealing (but may not be minimizing
 * distance).
 *
 * @param {!Object<string, Object>} partition Result of partitionNodes().
 * @param {!Object<string, Object>} stepPartition Result of
 *     partitionStepNodes().
 * @param {!Object} cy Cytoscape controller.
 */
DragnnLayout.prototype.finalLayout = function(partition, stepPartition, cy) {
  // Helper to abstract the horizontal vs. vertical layout.
  const compDim = this.horizontal ? 'y' : 'x';
  const stepDim = this.horizontal ? 'x' : 'y';

  const sorted = this.sortedComponents(partition.component);

  // Computes dictionaries from old --> new component positions.
  const newCompPos = _.fromPairs(_.map(sorted, (x, i) => {
    return [x[0], this.stepPosition(i, 0)];
  }));

  // Component --> slope for "step index --> position" function.
  const nodesPerComponent = {};
  const stepSlope = {};

  _.each(stepPartition, (stepNodes) => {
    const nodeOffset = (node) => {
      return node.relativePosition()[stepDim];
    };

    const name = _.head(stepNodes).data('parent');
    const slope =
        (nodeOffset(_.last(stepNodes)) - nodeOffset(_.head(stepNodes))) /
        stepNodes.length;

    nodesPerComponent[name] = stepNodes.length;
    stepSlope[name] =
        Math.sign(slope) * Math.min(300, Math.max(100, Math.abs(slope)));
  });

  // Set new node positions. As before, component nodes auto-size to fit.
  _.each(stepPartition, (stepNodes) => {
    const component = _.head(stepNodes).data('parent');
    const newPos = newCompPos[component];

    _.each(stepNodes, function(node, i) {
      // Keep things near the component centers.
      const x = i - (nodesPerComponent[component] / 2);

      const offset = {};
      offset[compDim] = 40 * Math.log(1.1 + (i % 5)) * (1 - 2 * (i % 2));
      offset[stepDim] = stepSlope[component] * x / 2;

      node.position({'x': newPos.x + offset.x, 'y': newPos.y + offset.y});
    });
  });

  // Set the curvature of edges. For now, we only bend edges within components,
  // by bending them away from the component center.
  _.each(this.options.eles.edges().filter(':visible'), function(edge) {
    const src = edge.source();
    const dst = edge.target();
    const srcPos = src.position();
    const dstPos = dst.position();
    const stepDiff = dstPos[stepDim] - srcPos[stepDim];

    if (src.data('componentIdx') == dst.data('componentIdx')) {
      const avgRelPosition =
          (src.relativePosition()[compDim] + dst.relativePosition()[compDim]);

      // Only bend longer edges.
      if (Math.abs(stepDiff) > 250) {
        const amount = stepDiff / 10;
        const direction = Math.sign(avgRelPosition + 0.001);
        edge.data('curvature', direction * amount);
      }
    }
  });

  // trigger layoutready when each node has had its position set at least once
  this.one('layoutready', this.options.ready);
  this.trigger('layoutready');

  // trigger layoutstop when the layout stops (e.g. finishes)
  this.one('layoutstop', this.options.stop);
  this.trigger('layoutstop');

  // For some reason (not sure yet), this needs to happen on the next tick.
  // (It's not that the component nodes need to resize--that happens even if
  // the selection is limited to node.step).
  setTimeout(() => {
    cy.fit(cy.$('node:visible'), 30);
  }, 10);
};

module.exports = DragnnLayout;