-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathddg_viz.html
590 lines (476 loc) · 18.9 KB
/
ddg_viz.html
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
<!DOCTYPE html>
<meta charset="utf-8">
<!-- <script src="https://d3js.org/d3.v2.min.js?2.9.3"></script>-->
<script src="https://d3js.org/d3.v5.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@100;400;600;700;900&display=swap" rel="stylesheet">
<style>
h1 {
font-family:"Raleway";
color:#565656;
}
body {
font-family:"Raleway";
background-color:#E3F0F2;
}
#pagetitle {
position:absolute;
left:2%;
top:0%;
}
.link {
stroke: #aaa;
}
.nodelabel {
pointer-events: none;
font-family: "Raleway";
font-size: 12px;
fill: #555;
}
.typelabel {
pointer-events: none;
font-family: "Raleway";
font-size: 20px;
font-weight: 700;
/*fill: #555;*/
}
.demand {
stroke:#CFAA95;
fill:#CFAA95;
}
.metric {
stroke:#CFB995;
fill:#CFB995;
}
.element {
stroke:#657588;
fill:#657588;
}
.dataset {
stroke:#7D6288;
fill:#7D6288;
}
.source {
stroke:#62887D;
fill:#62887D;
}
.faded {
opacity:0.15;
}
.highlighted {
stroke: #000;
stroke-width:2px;
}
.tooltip {
position: absolute;
text-align: left;
width: 200px;
min-height: 100px;
padding: 10px;
font: 12px sans-serif;
background: white;
border: 1px dotted #ccc;
border-radius: 8px;
pointer-events: none;
}
#viewport {
position:absolute;
top:10%;
left:0;
width:100%;
height:90%;
background-color:#fcfcfc;
margin:0px;
padding:0px;
}
#logo {
position:absolute;
top:2%;
right:2%;
width:200px;
height:auto;
}
#logo_image {
flex-shrink: 0;
width: 100%;
height: 100%
}
</style>
<body>
<div id="page-container">
<div id="logo">
<img src="brighthive_logo.png" id="logo_image">
</div>
<h1 id="pagetitle">Data Dependency Graph Explorer</h1>
<div id="viewport"></div>
</div>
<script>
///////////////////////////////////////////////
////////////////// Setup /////////////////////
///////////////////////////////////////////////
// Toggles and stuff
var pinnings = false; // Toggle: Have any nodes have been pinned?
var reverseToggle = false; // Toggle: Has the user pressed "r" to reverse the chain of highlighted nodes?
var focused = null; // ID of currently mouseover'd node
// get dimensions of viewport div, set d3 width and height variables
var viewport_bounds = document.getElementById("viewport").getBoundingClientRect();
var width = viewport_bounds.width;
var height = viewport_bounds.height;
// There are (currently) five node types. We space them evenly across the width of the viewport.
var x_positions = {"demand":width/6,"metric":2*width/6,"element":3*width/6, "dataset":4*width/6, "source":5*width/6};
// Append SVG
var svg = d3.select("#viewport").append("svg")
.attr("width", width)
.attr("height", height);
var node_radii = {'demand':25,'metric':15,'element':10,'dataset':8,'source':5};
///////////////////////////////////////////////
///////// Main promise on JSON load ///////////
///////////////////////////////////////////////
// Here: Everything after graph file is reading. Everything inside .then() follows reading the JSON
d3.json("edgelist.json").then(function(graph) {
////////////////////////////////////////////////
/// Set up node radii and link directories ///
///////////////////////////////////////////////
nodes_list_full = graph.nodes;
console.log(nodes_list_full.filter(function(x) { return(x.id=="element_1")}));
links_list_full = graph.links;
// Get node radii based on how many nodes there are of each type
// Loop over node types. Send along the list of nodes to calculateForces and then set the radius according to how many there are.
/*for (var type in node_radii) {
node_radii[type] = calculateForces(nodes_list_full.filter(function(x) { return(x.type == type) }).length, height);
}*/
// Set up these dictionaries: they will store children and parent nodes (respectively) of mouseover'd nodes
// These are first-degree connections only; we do a search on mouseover instead of building out all paths at load time
children_directory = {}; // right now this is just first degree connections
parents_directory = {};
// create children and parents directories
links_list_full.forEach(function (d) {
// create children dictionary
if(typeof children_directory[d.source] === 'undefined') {
children_directory[d.source] = [d.target];
} else {
children_directory[d.source].push(d.target);
}
// create parents dictionary
if(typeof parents_directory[d.target] === 'undefined') {
parents_directory[d.target] = [d.source];
} else {
parents_directory[d.target].push(d.source);
}
});
// initial -- demand nodes only
//var manual_start_nodes = ['question_9','question_23','question_29'];
var manual_start_nodes = ['question_19','question_22','question_23']
var start_node_ids = []
//var nodes_list_start = nodes_list_full.filter(function (x) { if(x.type == "demand") { start_node_ids.push(x['id']) } ;return (x.type == "demand")});
var nodes_list_start = nodes_list_full.filter(function(x) { return(manual_start_nodes.includes(x['id']))});
var links_list_start = []
///////////////////////////////////////////////
///////// Add type labels /////////
///////////////////////////////////////////////
// this, below, is the worst code I have ever written
svg
.selectAll(".typelabel")
.data(['Demand','Metric','Element','Dataset','Source'])
.enter()
.append("text")
.attr("class","typelabel")
.text(function(x) { return(x)})
.attr('x', function(d) { return(x_positions[d.toLowerCase()] - this.getBBox().width/2)}) // text is written from left to right -- move it back left by half its width to center it
.attr('y', '10%')
.style('fill',function(d) { return({"demand":"#CFAA95","metric":"#CFB995","element":"#657588","dataset":"#7D6288","source":"#62887D"}[d.toLowerCase()]); });
///////////////////////////////////////////////
///////// Start simulation /////////
///////////////////////////////////////////////
simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function(d) { return d.id; }).strength(0.1))
.force("collide", d3.forceCollide(function(d) { return node_radii[d.type] + 5; }).strength(0.9))
.force("centerline", d3.forceY(height/2).strength(0.5))
.force("column", d3.forceX(function (d) { return(x_positions[d.type]); }).strength(2))
.force("charge", d3.forceManyBody().strength(-300))
.on("tick", ticked);
// set up nodes list
nodes_list = []
links_list = []
///////////////////////////////////////////////
///////// Append nodes, links, labels /////////
///////////////////////////////////////////////
// add first elements
addElements(nodes_list_start, links_list_start, children_directory, parents_directory);
});
////////////////////////////
// //\\ //
// // \\ //
// // \\ //
// // \\ //
// ============ //
// | | //
// | | //
// | | //
// | | //
// === //
// This is the end of the//
// JSON promise! //
////////////////////////////
// THIS IS A VERY LONG FUNCTION
function addElements(new_nodes, new_links, children_directory, parents_directory) {
nodes_list = nodes_list.concat(new_nodes)
links_list = links_list.concat(new_links)
////// Links ///////
link = svg.selectAll('.link').data(links_list, function(d) { return d.target.id }); ///////
link.exit().remove()
linkEnter = link.enter().append("line")
.attr("class", "link")
.attr("stroke-width", function(d) { return Math.sqrt(d.value); })
.attr('marker-end',function(m) { return('url(#arrowhead)') });
link = linkEnter.merge(link);
////// Links: arrowheads ///////
// these need to be resized according to node radius
svg.append('defs').append('marker')
.attr("id",'arrowhead')
.attr('viewBox','-0 -5 10 10') //the bound of the SVG viewport for the current SVG fragment. defines a coordinate system 10 wide and 10 high starting on (0,-5)
.attr('refX', 10) // x coordinate for the reference point of the marker. If circle is bigger, this need to be bigger.
.attr('refY',0)
.attr('orient','auto')
.attr('markerWidth',13)
.attr('markerHeight',13)
.attr('xoverflow','visible')
.append('svg:path')
.attr('d', 'M 0,-3 L 6 ,0 L 0,3')
.attr('fill', '#999')
.style('stroke','none');
/////// Nodes: g Objects /////////
// Append node objects -- these contain both circles and text
node = svg.selectAll('.node').data(nodes_list, function(d) { return(d.id) });
node.exit().remove()
var nodeEnter = node.enter().append("g").attr("class","node");//.attr('id', function(d) { return(d.id)});
/////// Nodes: Circles //////
// Append circle to node object--this is graphically the node
circle = nodeEnter.append("circle")
.attr("class", function(d) { return d.type; })
.attr("r", function(d) { return node_radii[d.type]; })
.classed('pinned',false)
.attr('expanded',false)
.on("mouseover", function(d) {
focused = this; // set this global variable as soon as there's a mouseover
// fading and highlighting
if (reverseToggle === false) {
current_fadechain = getChildren(d.id, children_directory);
} else {
// for parents instead of children
current_fadechain = getChildren(d.id, parents_directory); // need to change source to target for links below!
}
if (pinnings == false) {
d3.selectAll("circle").classed("faded", true);
link.classed("faded", true);
d3.selectAll("circle").filter(function(f) { return(current_fadechain.includes(f.id)) }).classed("faded", false).classed("highlighted",true);
link.filter(function(f) { return(current_fadechain.includes(reverseToggle == false ? f.source.id : f.target.id)) }).classed("faded", false);
} else { // e.g. some nodes have been pinned
//circle.classed("faded", false);
//link.classed("faded", false);
d3.selectAll("circle").filter(function(f) { return(current_fadechain.includes(f.id)) }).classed("faded", false).classed("highlighted",true);
link.filter(function(f) { return(current_fadechain.includes(reverseToggle == false ? f.source.id : f.target.id)) }).classed("faded", false);
}
// show tooltip
tooltip
.style("opacity",0.7)
.style('left', d3.event.pageX + 20 + 'px')
.style('top', d3.event.pageY - 120 + 'px')
.html(tooltip_fill(d));
})
.on('mouseout', function (d) {
// fading and highlighting
if (pinnings == false) {
d3.selectAll("circle").classed("faded", false);
link.classed("faded", false);
d3.selectAll("circle").classed("highlighted",function(f) { return(d3.select(this).classed('pinned') === true ? true : false)} );
} else {
d3.selectAll("circle").classed("faded", function(f) { return(d3.select(this).classed('pinned') === true ? false : true)});
link.classed("faded", function(f) { return(d3.select(this).classed('pinned') === true ? false : true)});
d3.selectAll("circle").classed("highlighted",function(f) { return(d3.select(this).classed('pinned') === true ? true : false)} );
}
focused = null; // unset this variable
tooltip.style('opacity',0); // fade out tooltip
})
.on('click', function(d) {
// class current chain
// don't pin if it's a demand node...?
// FIX HIGHLIGHTING!
if (d.expanded == true) {
pinnings = true;
d3.selectAll("circle").filter(function(f) { return(current_fadechain.includes(f.id)) }).classed("pinned", true).style('opacity',1);
link.filter(function(f) { return(current_fadechain.includes(reverseToggle == false ? f.source.id : f.target.id)) }).classed("pinned", true).style('opacity',1);
//label.remove(); // remove labels
}
d3.event.stopPropagation();
console.log(nodes_list_full);
var new_nodes = nodes_list_full.filter(function(x) { return(current_fadechain.includes(x['id']))});
var new_links = links_list_full.filter(function(x) { return(current_fadechain.includes(x.source)); } );
d.expanded = true;
addElements(new_nodes, new_links, children_directory, parents_directory);
var evt = new MouseEvent("mouseout");
tooltip.style('opacity',0); // fade out tooltip
d3.selectAll('.nodelabel').remove();
});
/////// Nodes: Labels //////
label = nodeEnter.append("text")
.attr('class','nodelabel')
.text(function(d) { if (d.type == "demand") { return(d.label) } })
.attr('dx','30px')
.attr('dy', '0px');
node = nodeEnter.merge(node);
///////////////////////////////////////////////
///////// Append Tooltip and Typelabels /////////
///////////////////////////////////////////////
////// Tooltip ///////
var tooltip = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
simulation.nodes(nodes_list);
simulation.force("link").links(links_list);
restartSimulation();
} // END ADDELEMENTS FUNCTION
///////////////////////////////////////////////
///////////////// Listeners //////////////////
///////////////////////////////////////////////
// keydown handlers
d3.select("body")
.on("keydown", function() {
if(d3.event.keyCode === 82){ // "r"
reverseToggle = true;
var evt = new MouseEvent("mouseover");
focused.dispatchEvent(evt);
}
})
.on("keyup", function() {
if(d3.event.keyCode === 82){
reverseToggle = false;
var evt = new MouseEvent("mouseout");
focused.dispatchEvent(evt);
}
});
// listen for click on background
svg
.on('click', function(d) {
pinnings = false;
circle.classed("faded", false);
link.classed("faded", false);
circle.classed("pinned", false);
link.classed("pinned", false);
circle.classed("highlighted", false);
})
d3.select(window).on("resize", function() {resize()});
///////////////////////////////////////////////
///////////////// Functions //////////////////
///////////////////////////////////////////////
// Reposition nodes on tick of force simulation
function ticked() {
/* We use translate here instead of x,y attributes because nodes with labels are now g objects (as opposed to the above). From a StackOverflow answer:
"When node is a single shape element, we just adjust its positional attributes in the tick function. For eg. if it is a circle, we update its cx and cy attributes.
....The positional attribute of g element is transform". Constraint added here to keep nodes within window. */
node.each(function(d) { if(d.type == "demand") { d.x = x_positions[d.type]; }}); // we pin demand nodes to the same x-coordinate
node
.attr("transform", function(d) {
if (d.type != "demand") {
return "translate(" + d.x + "," + Math.max(10, Math.min(height - 10, d.y)) + ")";
} else {
d.x = x_positions['demand']
return "translate(" + x_positions['demand'] + "," + Math.max(10, Math.min(height - 10, d.y)) + ")";
}
});
link
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
}
// Fill infobox with info
function tooltip_fill(node) {
filler = "<b>" + node.label + "</b><p>";// + node.description + "</p>"
return(filler)
}
// reposition nodes and labels and restart simulation on window
function resize() {
viewport_bounds = document.getElementById("viewport").getBoundingClientRect();
width = viewport_bounds.width;
height = viewport_bounds.height;
svg.attr("width", width).attr("height", height); // reset svg width and height
x_positions = {"demand":width/6,"metric":2*width/6,"element":3*width/6, "dataset":4*width/6, "source":5*width/6}; // reset node type columns
// restart simulation
restartSimulation();
// replace node type labels
// replace node column labels
svg
.selectAll(".typelabel")
.attr('x', function(d) { return(x_positions[d.toLowerCase()])})//; x_positions[d.toLowerCase()]; })
}
function restartSimulation() {
simulation
.force("link", d3.forceLink().id(function(d) { return d.id; }).strength(0.1))
.force("collide", d3.forceCollide(function(d) { return node_radii[d.type] + 5; }).strength(0.7))
.force("centerline", d3.forceY(height/2).strength(0.5))
.force("column", d3.forceX(function (d) { return(x_positions[d.type]); }).strength(5))
.alpha(0.1)
.restart();
}
/* We want to be able to fit as many nodes vertically in the window as we can as long as they're >2px in radius
and as long as they have >2px between them. So we size nodes according to the number of nodes. */
function calculateForces(num_nodes, window_height) {
//var size_hierarchy = ['Demand','Metric','Element','Dataset','Source'];
var min_radius = 2;
var max_radius = 20;
var min_gap = 2;
var min_diameter = 2 * min_radius;
var node_size = 3*window_height/((num_nodes * (min_diameter + min_gap)))
return(Math.min(node_size,max_radius));
}
/* For a given node, and a dictionaruy giving first-degree targets for all nodes,
this function will find all downstream nodes. It's basically a kind of hacky depth-first search. */
/*function getChildren(parent_node_name, children_directory) {
var tocheck = [parent_node_name];
var checked = [];
var all_children = [];
for (i = 0; i <= tocheck.length; i++) {
var item = tocheck[i];
var children = children_directory[item];
if (typeof children == 'undefined') {
children = [];
}
var unchecked = children.filter(function(x) { return(!tocheck.includes(x))});
all_children = all_children.concat(unchecked);
tocheck = tocheck.concat(unchecked);
}
return(all_children);
}*/
function getChildren(parent_node_name, children_directory) {
var current_children = [parent_node_name];
for (var i = 0; i < current_children.length; i++) {
var new_children = children_directory[current_children[i]];
if (typeof new_children != 'undefined') {
var actually_new = new_children.filter(function(x) { return(!current_children.includes(x))});
current_children = current_children.concat(actually_new);
} else {
current_children = current_children;
}
}
return(current_children)
}
/*
// drag events not currently used
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = null;
d.fy = null;
}
*/
</script>
</body>
</html>