summaryrefslogtreecommitdiff
path: root/bubble.js
blob: fd59b326bf244fcd97b11388ae483cdee94bd5cb (plain)
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
/* jshint devel:true, browser:true */
/* global d3, collisionTick */
'use strict';

/* settings */
// whether to enable expensive features
var I_GOT_MONEY = 0;
// whether to ignore lonely users
var KILL_LONERS = true;
// if true, enable sticky nodes unless Ctrl is held. If false, stick only if
// ctrl is held (the inverse).
var STICKY_DEFAULT = true;


/* functions */

function getEdgesNodes(nodesCsv, edgesCsv, completeCallback) {
    var results = {};
    var checker = function (what) {
        return function (error, rows) {
            if (error) {
                console.log('Cannot complete requests!', error);
                return;
            }
            results[what] = rows;
            // all data available, call callback function
            if (results.nodes && results.edges) {
                completeCallback(results);
            }
        };
    };
    // fetch both files, asynchronously.
    nodesCsv.get(checker('nodes'));
    edgesCsv.get(checker('edges'));
}

function preprocess(data) {
    // map userID to nodes
    var users = {};
    data.nodes.forEach(function (user, i) {
        users[user.group] = user;
    });
    console.log('Initial nodes count:', data.nodes.length);
    console.log('Initial edges count:', data.edges.length);

    var ratelimit_count = 0, ratelimit_max = 10;
    function ratelimit() {
        return ratelimit_count <= ratelimit_max;
    }
    // filter away invalid edges
    data.edges = data.edges.filter(function (link, i) {
        var invalid = false;
        if (!(link.source in users)) {
            if (ratelimit()) console.warn('Dropping invalid source user',
                link.source, 'at line', (i + 1), link);
            invalid = true;
        }
        if (!(link.target in users)) {
            if (ratelimit()) console.warn('Dropping invalid target user',
                link.target, 'at line', (i + 1), link);
            invalid = true;
        }
        if (link.source === link.target) {
            if (ratelimit()) console.warn('Dropping self-referencing user',
                link.target, 'at line', (i + 1), link);
            invalid = true;
        }
        return !invalid;
    });
    if (ratelimit_count > ratelimit_max) {
        console.log('Supressed', ratelimit_count, 'messages');
    }
    console.log('Valid edges count:', data.edges.length);

    // find all related users by userID
    var hasRelations = {};
    data.edges.forEach(function (link) {
        hasRelations[link.target] = 1;
        hasRelations[link.source] = 1;
    });

    if (KILL_LONERS) {
        var hasRelated = {};
        data.nodes = data.nodes.filter(function (d) {
            return d.group in hasRelations;
        });
        console.log('Nodes count (after dropping loners):', data.nodes.length);
    }

    // prepare data for force layout: map user IDs to indices
    var userIds_indices = {};
    data.nodes.forEach(function (user, i) {
        users[user.group] = user;
        userIds_indices[user.group] = i;
    });
    console.log('UserID to index map:', userIds_indices);

    // change userID of relation edges to indices
    data.edges.map(function (link) {
        link.source = userIds_indices[link.source];
        link.target = userIds_indices[link.target];
    });
}

function initForce(width, height) {
    console.log('Initing force with dimensions', width, height);
    var force = d3.layout.force()
        .charge(-10) // default -30
        //.linkDistance(20) // default 20
        .size([width, height]);

    // sticky positions after dragging if CTRL is held down
    function sticky() {
        return STICKY_DEFAULT ^ d3.event.sourceEvent.ctrlKey;
    }
    force.drag()
        .on('dragstart', function (d) {
            // if ctrl is pressed, sticky...
            if (sticky()) {
                d.fixed = true;
            }
        })
        .on('dragend', function (d) {
            // release if not sticky, otherwise keep sticky
            d.fixed = sticky();
        });

    return force;
}

function initZoom(svg) {
    var zoomBehavior = d3.behavior.zoom()
        .scaleExtent([0.1, 10]) // min/max zoom
        .on('zoomstart', zoomStart)
        .on('zoom', zoom);
    var container = svg
        .call(zoomBehavior)
        .on('dblclick.zoom', null)
        // the zoom transformations apply here.
        .append('g');
    var zoomInfo = d3.select('#infobox .zoom-level');
    zoomInfo.text('100');

    var oldTranslation, oldScale, panAllowed = false;
    // pan is only allowed if the source is not an element
    function zoomStart() {
        var ev = d3.event.sourceEvent;
        panAllowed = ev.target === svg.node();
        oldTranslation = zoomBehavior.translate();
        oldScale = zoomBehavior.scale();
    }
    function zoom() {
        // disallow pan only if not zooming
        if (!panAllowed && d3.event.scale === oldScale) {
            d3.event.translate = oldTranslation;
            zoomBehavior.translate(oldTranslation);
        }
        container.attr('transform',
            'translate(' + d3.event.translate + ')' +
                'scale(' + d3.event.scale + ')');
        // save old translation for later restore if disabled.
        oldTranslation = d3.event.translate;
        oldScale = d3.event.scale;
        zoomInfo.text(Math.floor(100 * oldScale));
    }
    return container;
}

// contents holds the actual nodes and edges and exists to allow pan/zoom
var contents;
// force layout configuration
var force;

function initSvg() {
    var svg = d3.select('#map').append('svg');
    contents = initZoom(svg);

    svg.append('defs')
        // definition for an arrow head. Note: affected by stroke width of the path
        .append('marker')
            .attr('id', 'arrow')
            .attr('markerWidth', 6)
            .attr('markerHeight', 6)
            .attr('orient', 'auto')
            // make dimensions relative to this box instead of absolute pixels
            // NOTE: capital 'B'!!! view *B* ox!!! Spent two hours on that...
            // viewBox="x y width height"
            .attr('viewBox', '-10 -5 10 10')
            .attr('markerUnits', 'userSpaceOnUse')
        .append('path')
            .attr('class', 'arrow-head')
            // M x,y - absolute moveTo
            // L x,y - relative lineTo
            // arrow head '>' as in: (edge) --- '>' o (node)
            .attr('d', 'M-10,-5 L0,0 L-10,5');

    // default the space of the force layout to the svg canvas dimension. If you
    // want to allow pan / zoom with more data out of view, multiply this by
    // some factor.
    var dim = d3.select('#map').node().getBoundingClientRect();
    // begin simulation
    force = initForce(dim.width, dim.height);
}

function processData(data) {
    var infoPane = d3.select('#infobox');

    preprocess(data);
    infoPane.select('.node-count').text(data.nodes.length);
    infoPane.select('.edge-count').text(data.edges.length);
    force.nodes(data.nodes)
        .links(data.edges)
        .start();

    // element 'g' groups SVG elements, useful to apply a single transf. to all
    /* edges */
    var link = contents.append('g').selectAll('path')
        .data(force.links())
        .enter().append('path')
            .attr('class', 'link')
            .attr('marker-end', 'url(#arrow)')
            .style('stroke-width', function (d) {
                return Math.sqrt(d.value);
            });
    link.append('title')
        .text(function (d) {
            return d.value;
        });

    /* nodes */
    var node = contents.append('g').selectAll('circle')
        .data(force.nodes())
        .enter().append('circle')
            .attr('class', function (d) {
                return 'node ' + (d.isSpam ? 'spam' : 'ham');
            })
            .attr('r', function (d) {
                return d.radius;
            })
            .call(force.drag);
    node.append('title')
        .text(function (d) {
            return d.name;
        });

    var infoBox = d3.select('#infobox');
    var selectedNode = null;
    node.on('dblclick', function (d) {
            if (selectedNode === d) {
                // no update needed, unmark for dynamic update
                selectedNode = null;
                d3.select(this).classed('selected', false);
            } else {
                selectedNode = d;
                updateInfobox(d, this);
            }
            console.log(selectedNode, d);
            infoBox.classed('user-locked', selectedNode === d);
        })
        .on('mouseover', function (d) {
            // only update on hover if no node is selected
            if (selectedNode === null) {
                updateInfobox(d, this);
            }
        });

    // info panel for each user node
    var userInfo = infoPane.select('.user-info');
    function updateInfobox(d, nodeElm) {
        // unselect other nodes, mark self as selected.
        contents.select('.node.selected').classed('selected', false);
        d3.select(nodeElm).classed('selected', true);

        // display user block
        userInfo.style('display', 'block');

        userInfo.select('.name')
            .text(d.name);
        userInfo.select('.tweet-count')
            .text(d.tweetCount);
        userInfo.select('.spam-status')
            .text(d.isSpam ? 'SPAM' : 'ham');

        var selfId = d.index;
        var links = [];
        force.links().forEach(function (edge) {
            // insert related elements, assuming no self-references
            if (edge.source.index === selfId) {
                links.push({
                    direction: 'to',
                    node: edge.target
                });
            } else if (edge.target.index === selfId) {
                links.push({
                    direction: 'from',
                    node: edge.source
                });
            }
        });
        userInfo.select('.relations-count')
            .text(links.length);
        var relations = userInfo.select('.relations')
            .selectAll('li')
            .data(links, function (d) {
                // unique keys to group by direction and node (index)
                return d.direction + ' ' + d.node.index;
            });
        relations.enter().append('li')
            .text(function (d) {
                return d.direction + ' ' + d.node.name;
            });
        relations.exit().remove();
    }

    force.on('tick', function() {
        // based on http://bl.ocks.org/mbostock/1153292
        link.attr('d', function force_tick(d) {
            // https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths#Arcs
            // A rx ry x-axis-rotation large-arc-flag sweep-flag x y
            // a rx ry x-axis-rotation large-arc-flag sweep-flag dx dy
            // rx and ry are the offsets from the center between current
            // position and (last-x, last-y)
            // large-arc-flag 0 means draw the arc on the angle < 180 degree
            var dx = d.target.x - d.source.x,
                dy = d.target.y - d.source.y,
                r = Math.sqrt(dx * dx + dy * dy),
                // curve radius is based on two circles, with their radius being
                // an offset from the center between the start and end point
                cr = r;
            // remove the radius such that the arrow head just hits the node
            var ratio = (r - d.target.radius) / r;
            dx *= ratio;
            dy *= ratio;
            return 'M' + d.source.x + ',' + d.source.y + ' ' +
                   'a' + cr + ',' + cr + ' 0 0 0 ' +
                   dx + ',' + dy;
        });

        // warning: expensive!
        if (I_GOT_MONEY) {
            collisionTick(force.nodes());
        }

        node.attr('cx', function(d) { return d.x; })
            .attr('cy', function(d) { return d.y; });
        // PROFILE
        ticks++;
    });
}

// initialize information panel
(function () {
    var infoPane = d3.select('#infobox');
    // SHIT: d3js cannot handle drag with nested elements --> stutter!
    // BREAKS TEXT SELECTION :(
    infoPane //.select('.draggable')
        .call(d3.behavior.drag()
            .on('drag', function () {
                var changes = {
                    'left': d3.event.dx,
                    'top': d3.event.dy
                };
                // add the differences to the old positions
                for (var name in changes) {
                    var newValue = parseInt(infoPane.style(name));
                    newValue += changes[name];
                    infoPane.style(name, newValue + 'px');
                }
            }));
}());

function run() {
    /* fetch CSV files and render the result */
    getEdgesNodes(
        // userid,name,tweetCount
        d3.csv('users.csv')
            .row(function (d) {
                return {
                    name: d.name,
                    group: +d.userid,
                    tweetCount: d.tweetcount,
                    radius: Math.sqrt(d.tweetcount),
                    isSpam: +d.isspam,
                    related: [] // nodes that link to this
                };
            }),
        // source,target,value
        d3.csv('links.csv')
            .row(function (d) {
                return {
                    source: +d.source,
                    target: +d.target,
                    value: +d.value
                };
            }),
        processData /* callback function when data is ready */
    );
}

// initialize SVG element and force
initSvg();

// Set PROFILE=1 to enable profiling when using the button.
var ticks = 0, PROFILE = 1;
if (/no-auto/.test(location.search)) {
    // advanced stuff here: profiling!
    d3.select('body').append('button')
        .style('position', 'absolute')
        .style('z-index', 2)
        .style('font-size', '20em')
        .text('RUN')
        .on('click', function () {
            d3.select(this).remove();
            if (PROFILE) {
                ticks = 0;
                console.time('Run');
                console.timeline('Run');
                console.profile('Run');
            }
            run();
            if (PROFILE) {
                setTimeout(function () {
                    console.log('Ticks:', ticks);
                    console.timelineEnd('Run');
                    console.profileEnd('Run');
                    console.timeEnd('Run');
                }, 30000);
            }
        });
/* notes
X 30 ticks, firefox
X 66 ticks, chromium
X disabled edge positioning, 84 ticks, chromium

70 ticks in 31.3s, chromium (disabled title elements) [69,30.3]
73 ticks in 30.8s, chromium (title elements enabled) [68,30.4]
62 ticks in 30.2s, chromium (removed 2x 'g' elements) [60,31.8]
 */
} else {
    run();
}