-
Notifications
You must be signed in to change notification settings - Fork 7
/
vis.js
1192 lines (1025 loc) · 42.1 KB
/
vis.js
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Based on simple canvas network visualization by Mike Bostock
// source: https://bl.ocks.org/mbostock/ad70335eeef6d167bc36fd3c04378048
function vis(new_controls) {
// Context //
// ------- //
var isLocal = window.location['href'].includes("http://localhost");
var isWeb = window.location['href'].includes("https://ulfaslak");
var isTest = window.location['href'].includes("pytest");
// if this is a test, call the postData function after 5 seconds
if (isTest)
d3.timeout(postData, 5000);
// Canvas //
// ------ //
var canvas = document.querySelector("canvas");
var parentdiv = document.getElementsByClassName("canvas_container")[0];
canvas.width = parentdiv.offsetWidth;
canvas.height = parentdiv.offsetHeight;
window.onresize = function() {
canvasOffsetX = canvas.getBoundingClientRect().x;
canvasOffsetY = canvas.getBoundingClientRect().y;
}
window.onresize()
let context = canvas.getContext("2d");
let width = canvas.width;
let height = canvas.height;
// Retina canvas rendering
var devicePixelRatio = window.devicePixelRatio || 1
d3.select(canvas)
.attr("width", width * devicePixelRatio)
.attr("height", height * devicePixelRatio)
.style("width", width + "px")
.style("height", height + "px").node()
context.scale(devicePixelRatio, devicePixelRatio)
// Input/Output //
// ------------ //
// Download figure function (must be defined before control variables)
var download = function() {
var link = document.createElement('a');
link.download = 'network.png';
link.href = document.getElementById('canvas').toDataURL();
link.click();
}
// Upload dataset button
function uploadEvent() {
var fileInput = document.getElementById('upload');
fileInput.addEventListener("change", function() {
var file = fileInput.files[0];
var reader = new FileReader();
if (file.name.endsWith(".json")) {
reader.onload = function(e) {
restartIfValidJSON(JSON.parse(reader.result));
}
} else if (file.name.endsWith(".csv")) {
reader.onload = function(e) {
restartIfValidCSV(reader.result)
}
} else {
Swal.fire({ text: "File not supported", type: "error" })
return false
}
reader.readAsText(file);
});
}
// Upload network
var uploadFile = function() {
var uploader = document.getElementById('upload');
uploader.click()
uploadEvent();
}
// Post data back to Python
function postData() {
let nw_prop = get_network_properties();
let controls_copy = {};
for (let prop in controls){
if (
(controls.hasOwnProperty(prop)) &&
(prop != 'file_path') &&
(prop != 'post_to_python') &&
(prop != 'download_figure')
){
controls_copy[prop] = controls[prop];
}
}
post_json(nw_prop, controls_copy, canvas, function(){
Swal.fire({
//type: "success",
title: "Success!",
text: "Closes automatically after 3 seconds.",
type: "success",
timer: 3000,
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'OK',
}).then((willDelete) => {
if (!willDelete) {
} else {
post_stop();
}
});
});
}
// Simulation //
// ---------- //
// Control variables
window.controls = {
// Input/output
'file_path': "",
'download_figure': download,
'zoom': 1.5,
// Physics
'node_charge': -30,
'node_gravity': 0.1,
'link_distance': 10,
'link_distance_variation': 0,
'node_collision': false,
'wiggle_nodes': false,
'freeze_nodes': false,
// Nodes
'node_fill_color': '#16a085',
'node_stroke_color': '#000000',
'node_label_color': '#000000',
'display_node_labels': false,
'scale_node_size_by_strength': false,
'node_size': 10,
'node_stroke_width': 0.5,
'node_size_variation': 0.5,
// Links
'link_color': '#7c7c7c',
'link_width': 5,
'link_alpha': 0.5,
'link_width_variation': 0.5,
// Thresholding
'display_singleton_nodes': true,
'min_link_weight_percentile': 0.0,
'max_link_weight_percentile': 1.0
};
// Context dependent keys
if (isLocal) controls['post_to_python'] = postData;
if (isWeb) controls['upload_file'] = uploadFile;
// Overwrite default controls with inputted controls
d3.keys(new_controls).forEach(key => {
controls[key] = new_controls[key];
});
if (controls['file_path'] == "") controls['file_path'] = "https://gist.githubusercontent.com/ulfaslak/6be66de1ac3288d5c1d9452570cbba5a/raw/0b9595c09b9f70a77ee05ca16d5a8b42a9130c9e/miserables.json";
// Force layout
var simulation = d3.forceSimulation()
.force("link", d3.forceLink()
.id(d => d.id)
.distance(controls['link_distance'])
)
.force("charge", d3.forceManyBody().strength(+controls['node_charge']))
.force("center", d3.forceCenter(width / 2, height / 2))
.force("collide", d3.forceCollide(0).radius(d => controls['node_collision'] * computeNodeRadii(d)))
.force("x", d3.forceX(width / 2)).force("y", d3.forceY(height / 2));
simulation.force("x").strength(+controls['node_gravity']);
simulation.force("y").strength(+controls['node_gravity']);
// Start
handleURL(controls['file_path']);
uploadEvent();
function ticked() {
// draw
context.clearRect(0, 0, width, height);
context.strokeStyle = controls['link_color'];
context.globalAlpha = controls['link_alpha'];
context.globalCompositeOperation = "destination-over";
graph.links.forEach(drawLink);
context.globalAlpha = 1.0
context.strokeStyle = controls['node_stroke_color'];
context.lineWidth = controls['node_stroke_width'] < 1e-3 ? 1e-9 : controls['node_stroke_width'] * controls['zoom'];
context.globalCompositeOperation = "source-over";
graph.nodes.forEach(drawNode);
graph.nodes.forEach(drawText);
}
// Restart simulation
function restart() {
// Start simulation
simulation
.nodes(graph.nodes)
.on("tick", ticked);
simulation.force("link")
.links(graph.links);
d3.select(canvas)
.call(d3.drag()
.container(canvas)
.subject(dragsubject)
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
if (nodePositions || controls['freeze_nodes']) {
simulation.alpha(0).restart();
} else {
simulation.alpha(1).restart();
}
}
function simulationSoftRestart(){
if (!controls['freeze_nodes']){
simulation.restart();
} else {
ticked();
}
}
// Network functions
// -----------------
function dragsubject() {
return simulation.find(zoomScaler.invert(d3.event.x), zoomScaler.invert(d3.event.y), 20);
}
function dragstarted() {
console.log("dragstarted")
if (!controls['freeze_nodes']) simulation.alphaTarget(0.3);
simulation.restart();
d3.event.subject.fx = d3.event.subject.x;
d3.event.subject.fy = d3.event.subject.y;
}
function dragged() {
console.log("dragged")
d3.event.subject.fx = zoomScaler.invert(event.clientX - canvasOffsetX);
d3.event.subject.fy = zoomScaler.invert(event.clientY - canvasOffsetY);
if (controls['freeze_nodes']) simulation.restart();
}
function dragended() {
console.log("dragended")
if (!controls['freeze_nodes']) simulation.alphaTarget(0);
d3.event.subject.fx = null;
d3.event.subject.fy = null;
}
function drawLink(d) {
var thisLinkWidth = valIfValid(d.weight, 1) ** (controls['link_width_variation']) * linkWidthNorm * controls['link_width'];
context.beginPath();
context.moveTo(zoomScaler(d.source.x), zoomScaler(d.source.y));
context.lineTo(zoomScaler(d.target.x), zoomScaler(d.target.y));
context.lineWidth = thisLinkWidth * controls['zoom'];
context.stroke();
}
function drawNode(d) {
// Node
var thisNodeSize = valIfValid(d.size, 1) ** (controls['node_size_variation']) * nodeSizeNorm * controls['node_size'];
context.beginPath();
context.moveTo(zoomScaler(d.x) + thisNodeSize * (controls['zoom'] + (controls['zoom'] - 1)), zoomScaler(d.y));
context.arc(zoomScaler(d.x), zoomScaler(d.y), thisNodeSize * (controls['zoom'] + (controls['zoom'] - 1)), 0, 2 * Math.PI);
context.fillStyle = computeNodeColor(d);
context.fill();
context.stroke();
}
function drawText(d) {
if (controls['display_node_labels'] || d.id == hoveredNode || selectedNodes.includes(d.id)) {
var thisNodeSize = valIfValid(d.size, 1) ** (controls['node_size_variation']) * nodeSizeNorm * controls['node_size'];
context.font = clip(thisNodeSize * controls['zoom'] * 2, 10, 20) + "px Helvetica"
context.fillStyle = controls['node_label_color']
context.fillText(d.id, zoomScaler(d.x), zoomScaler(d.y))
}
}
// Key events //
// ---------- //
var shiftDown = false
window.onkeydown = function() {
if (window.event.keyCode == 16) {
shiftDown = true;
}
}
window.onkeyup = function() {
shiftDown = false;
}
var hoveredNode;
var selectedNodes = [];
var xy;
d3.select(canvas).on("mousemove", function() {
if (!controls['display_node_labels']) {
xy = d3.mouse(this)
hoveredNode = simulation.find(zoomScaler.invert(xy[0]), zoomScaler.invert(xy[1]), 20)
if (typeof (hoveredNode) != 'undefined') {
hoveredNode = hoveredNode.id;
}
simulation.restart();
}
})
window.addEventListener("mousedown", function() {
if (typeof (hoveredNode) != 'undefined') {
if (selectedNodes.includes(hoveredNode)) {
selectedNodes.splice(selectedNodes.indexOf(hoveredNode), 1)
} else {
selectedNodes.push(hoveredNode)
}
simulation.restart();
}
}, true)
// Parameter controls //
// ------------------ //
// Hack to enable titles (https://stackoverflow.com/a/29563786/3986879)
var eachController = function(fnc) {
for (var controllerName in dat.controllers) {
if (dat.controllers.hasOwnProperty(controllerName)) {
fnc(dat.controllers[controllerName]);
}
}
}
var setTitle = function(v) {
// __li is the root dom element of each controller
if (v) {
this.__li.setAttribute('title', v);
} else {
this.__li.removeAttribute('title')
}
return this;
};
eachController(function(controller) {
if (!controller.prototype.hasOwnProperty('title')) {
controller.prototype.title = setTitle;
}
});
// Titles
var title1_1 = "Path to file: URL of eligible file in either JSON or CSV format"
var title1_2 = "Upload file: Upload a network from your computer in either JSON or CSV format"
var title1_3 = "Download figure: Download the network as a PNG image"
var title1_4 = "Post to Python: Post all calculated node and link properties and image (optional) back to Python.";
var title1_5 = "Zoom: Zoom in or out"
var title2_1 = "Charge: Each node has negative charge and thus repel one another (like electrons). The more negative this charge is, the greater the repulsion"
var title2_2 = "Gravity: Push the nodes more or less towards the center of the canvas"
var title2_3 = "Link distance: The optimal link distance that the force layout algorithm will try to achieve for each link"
var title2_4 = "Link distance variation: Tweak the link distance scaling function. Increase to contract strong links. Most effectful when 'Link distance' is large."
var title2_5 = "Collision: Make it harder for nodes to overlap"
var title2_6 = "Wiggle: Increase the force layout algorithm temperature to make the nodes wiggle. Useful for big networks that need some time for the nodes to settle in the right positions"
var title2_7 = "Freeze: Set force layout algorithm temperature to zero, causing the nodes to freeze in their position."
var title3_1 = 'Fill: Node color(s). If nodes have "group" attributes (unless groups are named after colors) each group is given a random color. Changing "Fill color" will continuously change the color of all groups'
var title3_2 = "Stroke: The color of the ring around nodes"
var title3_3 = "Label color: The color of node labels"
var title3_4 = "Display labels: Whether to show labels or not"
var title3_5 = "Size by strength: Rescale the size of each node relative to their strength (weighted degree)"
var title3_6 = "Size: Change the size of all nodes"
var title3_7 = "Stroke width: Change the width of the ring around nodes"
var title3_8 = "Size variation: Tweak the node size scaling function. Increase to make big nodes bigger and small nodes smaller. Useful for highlighting densely connected nodes."
var title4_1 = "Color: The color of links"
var title4_2 = "Width: Change the width of all links"
var title4_3 = "Alpha: How transparent links should be. Useful in large dense networks"
var title4_4 = "Width variation: Tweak the link width scaling function. Increase to make wide links wider and narrow links narrower. Useful for highlighting strong connections"
var title5_1 = "Singleton nodes: Whether or not to show links that have zero degree"
var title5_2 = "Min. link percentile: Lower percentile threshold on link weight"
var title5_3 = "Max. link percentile: Upper percentile threshold on link weight"
// Control panel
var gui = new dat.GUI({ autoPlace: false });
var customContainer = document.getElementsByClassName('controls_container')[0];
gui.width = customContainer.offsetWidth;
gui.closed = false;
customContainer.appendChild(gui.domElement);
gui.remember(controls);
// Input/Output
var f1 = gui.addFolder('Input/output'); f1.open();
if (isWeb) f1.add(controls, 'file_path', controls['file_path']).name('Path to file').onFinishChange(function(v) { handleURL(v) }).title(title1_1);
if (isWeb) f1.add(controls, 'upload_file').name('Upload file').title(title1_2);
f1.add(controls, 'download_figure').name('Download figure').title(title1_3);
if (isLocal) f1.add(controls, 'post_to_python').name('Post to Python').title(title1_4);
f1.add(controls, 'zoom', 0.6, 5).name('Zoom').onChange(function(v) { inputtedZoom(v) }).title(title1_5);
// Physics
var f2 = gui.addFolder('Physics'); f2.open();
f2.add(controls, 'node_charge', -100, 0).name('Charge').onChange(function(v) { inputtedCharge(v) }).title(title2_1);
f2.add(controls, 'node_gravity', 0, 1).name('Gravity').onChange(function(v) { inputtedGravity(v) }).title(title2_2);
f2.add(controls, 'link_distance', 0.1, 50).name('Link distance').onChange(function(v) { inputtedDistance(v) }).title(title2_3);
f2.add(controls, 'link_distance_variation', 0, 1).name('Link distance variation').step(0.01).onChange(function(v) { inputtedDistanceScaling(v) }).title(title2_4);
f2.add(controls, 'node_collision', false).name('Collision').onChange(function(v) { inputtedCollision(v) }).title(title2_5);
f2.add(controls, 'wiggle_nodes', false).name('Wiggle').onChange(function(v) { inputtedReheat(v) }).listen().title(title2_6);
f2.add(controls, 'freeze_nodes', false).name('Freeze').onChange(function(v) { inputtedFreeze(v) }).listen().title(title2_7);
// Nodes
var f3 = gui.addFolder('Nodes'); f3.open();
f3.addColor(controls, 'node_fill_color', controls['node_fill_color']).name('Fill').onChange(function(v) { inputtedNodeFill(v) }).title(title3_1);
f3.addColor(controls, 'node_stroke_color', controls['node_stroke_color']).name('Stroke').onChange(function(v) { inputtedNodeStroke(v) }).title(title3_2);
f3.addColor(controls, 'node_label_color', controls['node_label_color']).name('Label color').onChange(function(v) { inputtedTextStroke(v) }).title(title3_3);
f3.add(controls, 'node_size', 0, 50).name('Size').onChange(function(v) { inputtedNodeSize(v) }).title(title3_6);
f3.add(controls, 'node_stroke_width', 0, 10).name('Stroke width').onChange(function(v) { inputtedNodeStrokeSize(v) }).title(title3_7);
f3.add(controls, 'node_size_variation', 0., 3.).name('Size variation').onChange(function(v) { inputtedNodeSizeExponent(v) }).title(title3_8);
f3.add(controls, 'display_node_labels', false).name('Display labels').onChange(function(v) { inputtedShowLabels(v) }).title(title3_4);
f3.add(controls, 'scale_node_size_by_strength', false).name('Size by strength').onChange(function(v) { inputtedNodeSizeByStrength(v) }).title(title3_5);
// Links
var f4 = gui.addFolder('Links'); f4.open();
f4.addColor(controls, 'link_color', controls['link_color']).name('Color').onChange(function(v) { inputtedLinkStroke(v) }).title(title4_1);
f4.add(controls, 'link_width', 0.01, 30).name('Width').onChange(function(v) { inputtedLinkWidth(v) }).title(title4_2);
f4.add(controls, 'link_alpha', 0, 1).name('Alpha').onChange(function(v) { inputtedLinkAlpha(v) }).title(title4_3);
f4.add(controls, 'link_width_variation', 0., 3.).name('Width variation').onChange(function(v) { inputtedLinkWidthExponent(v) }).title(title4_4);
// Thresholding
var f5 = gui.addFolder('Thresholding'); f5.close();
f5.add(controls, 'display_singleton_nodes', true).name('Singleton nodes').onChange(function(v) { inputtedShowSingletonNodes(v) }).title(title5_1);
f5.add(controls, 'min_link_weight_percentile', 0, 0.99).name('Min. link percentile').step(0.01).onChange(function(v) { inputtedMinLinkWeight(v) }).listen().title(title5_2);
f5.add(controls, 'max_link_weight_percentile', 0.01, 1).name('Max. link percentile').step(0.01).onChange(function(v) { inputtedMaxLinkWeight(v) }).listen().title(title5_3);
// Utility functions //
// ----------------- //
// The zoomScaler converts a simulation coordinate (what we don't see) to a
// canvas coordinate (what we do see), and zoomScaler.invert does the opposite.
zoomScaler = d3.scaleLinear().domain([0, width]).range([width * (1 - controls['zoom']), controls['zoom'] * width])
function computeNodeRadii(d) {
var thisNodeSize = nodeSizeNorm * controls['node_size'];
if (d.size) {
thisNodeSize *= (d.size) ** (controls['node_size_variation']);
}
return thisNodeSize
}
function computeNodeColor(d) {
if (d.color) {
return d.color;
} else if (d.group) {
return activeSwatch[d.group];
} else {
return controls['node_fill_color'];
}
}
// Handle parameter updates //
// ------------------------ //
// Physics
function inputtedCharge(v) {
simulation.force("charge").strength(+v);
simulation.alpha(1).restart();
if (controls['freeze_nodes']) controls['freeze_nodes'] = false;
}
function inputtedGravity(v) {
simulation.force("x").strength(+v);
simulation.force("y").strength(+v);
simulation.alpha(1).restart();
if (controls['freeze_nodes']) controls['freeze_nodes'] = false;
}
function inputtedDistance(v) {
if (isWeighted && linkWeightOrder.length > 1 && controls['link_distance_variation'] > 0) {
simulation.force("link").distance(d => {
return (1 - getPercentile(d.weight, linkWeightOrder)) ** controls['link_distance_variation'] * v
});
} else {
simulation.force("link").distance(v);
}
simulation.alpha(1).restart();
if (controls['freeze_nodes']) controls['freeze_nodes'] = false;
}
function inputtedDistanceScaling(v) {
if (isWeighted && linkWeightOrder.length > 1) {
simulation.force("link").distance(d => {
return (1 - getPercentile(d.weight, linkWeightOrder)) ** v * controls['link_distance']
});
simulation.alpha(1).restart();
if (controls['freeze_nodes']) controls['freeze_nodes'] = false;
}
}
function inputtedCollision(v) {
simulation.force("collide").radius(function(d) { return controls['node_collision'] * computeNodeRadii(d) });
if (!controls['freeze_nodes'])
simulation.alpha(1)
simulationSoftRestart();
}
function inputtedReheat(v) {
simulation.alpha(0.5);
simulation.alphaTarget(v).restart();
if (v) controls['freeze_nodes'] = !v;
}
function inputtedFreeze(v) {
if (v) {
controls['wiggle_nodes'] = !v
simulation.alpha(0);
} else {
simulation.alpha(0.3).alphaTarget(0).restart();
nodePositions = false;
}
}
// Styling
function inputtedNodeFill(v) {
var dr = hexToInt(v.slice(1, 3)) - hexToInt(referenceColor.slice(1, 3))
var dg = hexToInt(v.slice(3, 5)) - hexToInt(referenceColor.slice(3, 5))
var db = hexToInt(v.slice(5, 7)) - hexToInt(referenceColor.slice(5, 7))
for (var g of d3.keys(activeSwatch)) {
var r_ = bounceModulus(parseInt(referenceSwatch[g].slice(1, 3), 16) + dr, 0, 255);
var g_ = bounceModulus(parseInt(referenceSwatch[g].slice(3, 5), 16) + dg, 0, 255);
var b_ = bounceModulus(parseInt(referenceSwatch[g].slice(5, 7), 16) + db, 0, 255);
activeSwatch[g] = '#' + toHex(r_) + toHex(g_) + toHex(b_);
}
simulationSoftRestart();
}
function inputtedNodeStroke(v) {
simulationSoftRestart();
}
function inputtedLinkStroke(v) {
simulationSoftRestart();
}
function inputtedTextStroke(v) {
simulationSoftRestart();
}
function inputtedShowLabels(v) {
selectedNodes = [];
simulationSoftRestart();
}
function inputtedShowSingletonNodes(v) {
if (v) {
graph['nodes'].push(...negativeGraph.nodes)
negativeGraph['nodes'] = []
} else if (!v) {
graph['nodes'] = graph.nodes.filter(n => {
var keepNode = nodeStrengths[n.id] >= minLinkWeight;
if (!keepNode) negativeGraph['nodes'].push(n);
return keepNode;
})
}
restart();
simulationSoftRestart();
}
function inputtedNodeSizeByStrength(v) {
recomputeNodeNorms();
if (v) {
if (controls['display_singleton_nodes']){
graph.nodes.forEach(n => { n.size = nodeStrengths[n.id] > 0.0 ? nodeStrengths[n.id] : minNonzeroNodeSize })
negativeGraph.nodes.forEach(n => { n.size = nodeStrengths[n.id] > 0.0 ? nodeStrengths[n.id] : minNonzeroNodeSize })
} else {
graph.nodes.forEach(n => { n.size = nodeStrengths[n.id] })
negativeGraph.nodes.forEach(n => { n.size = nodeStrengths[n.id] })
}
} else if (!v) {
graph.nodes.forEach(n => { n.size = valIfValid(findNode(masterGraph, n).size, 1) })
negativeGraph.nodes.forEach(n => { n.size = valIfValid(findNode(masterGraph, n).size, 1) })
}
simulationSoftRestart();
}
function inputtedLinkWidth(v) {
simulationSoftRestart();
}
function inputtedLinkAlpha(v) {
simulationSoftRestart();
}
function inputtedNodeSize(v) {
if (controls['node_collision']) {
simulation.force("collide").radius(function(d) { return computeNodeRadii(d) })
if (!controls['freeze_nodes'])
simulation.alpha(1);
}
simulationSoftRestart();
}
function inputtedNodeStrokeSize(v) {
simulationSoftRestart();
}
function inputtedNodeSizeExponent(v) {
nodeSizeNorm = 1 / maxNodeSize ** (controls['node_size_variation'])
if (controls['node_collision']) {
simulation.force("collide").radius(function(d) { return computeNodeRadii(d) })
if (!controls['freeze_nodes'])
simulation.alpha(1);
}
simulationSoftRestart();
}
function inputtedLinkWidthExponent(v) {
linkWidthNorm = 1 / maxLinkWeight ** (controls['link_width_variation'])
simulationSoftRestart();
}
function inputtedZoom(v) {
zoomScaler = d3.scaleLinear().domain([0, width]).range([width * (1 - controls['zoom']), controls['zoom'] * width])
simulationSoftRestart();
}
var vMinPrev = 0;
var dvMin = 0;
function inputtedMinLinkWeight(v) {
dvMin = v - vMinPrev
if (shiftDown) {
controls['max_link_weight_percentile'] = d3.min([1, controls['max_link_weight_percentile'] + dvMin])
} else {
controls['max_link_weight_percentile'] = d3.max([controls['max_link_weight_percentile'], v + 0.01])
}
dvMax = controls['max_link_weight_percentile'] - vMaxPrev
vMinPrev = v
vMaxPrev = controls['max_link_weight_percentile']
shave(); restart();
}
var vMaxPrev = 1;
var dvMax = 0;
function inputtedMaxLinkWeight(v) {
dvMax = v - vMaxPrev
if (shiftDown) {
controls['min_link_weight_percentile'] = d3.max([0, controls['min_link_weight_percentile'] + dvMax])
} else {
controls['min_link_weight_percentile'] = d3.min([controls['min_link_weight_percentile'], v - 0.01])
}
dvMin = controls['min_link_weight_percentile'] - vMinPrev
vMinPrev = controls['min_link_weight_percentile']
vMaxPrev = v
shave(); restart();
}
// Handle input data //
// ----------------- //
function handleURL() {
if (controls['file_path'].endsWith(".json")) {
d3.json(controls['file_path'], function(error, _graph) {
if (error) {
Swal.fire({ text: "File not found", type: "error" })
return false
}
restartIfValidJSON(_graph);
})
} else if (controls['file_path'].endsWith(".csv")) {
try {
fetch(controls['file_path']).then(r => r.text()).then(r => restartIfValidCSV(r));
} catch (error) {
throw error;
Swal.fire({ text: "File not found", type: "error" })
}
}
}
function restartIfValidJSON(masterGraph) {
// Check for 'nodes' and 'links' lists
if (!masterGraph.nodes || masterGraph.nodes.length == 0) {
Swal.fire({ text: "Dataset does not have a key 'nodes'", type: "error" })
return false
}
if (!masterGraph.links) {
Swal.fire({ text: "Dataset does not have a key 'links'", type: "warning" })
}
// Check that node and link objects are formatted right
for (var d of masterGraph.links) {
if (!d3.keys(d).includes("source") || !d3.keys(d).includes("target")) {
Swal.fire({ text: "Found objects in 'links' without 'source' or 'target' key.", type: "error" });
return false;
}
}
// Check that 'links' and 'nodes' data are congruent
var nodesNodes = masterGraph.nodes.map(d => { return d.id });
var nodesNodesSet = new Set(nodesNodes)
var linksNodesSet = new Set()
masterGraph.links.forEach(l => {
linksNodesSet.add(l.source); linksNodesSet.add(l.source.id) // Either l.source or l.source.id will be null
linksNodesSet.add(l.target); linksNodesSet.add(l.target.id) // so just add both and remove null later (same for target)
}); linksNodesSet.delete(undefined)
if (nodesNodesSet.size == 0) {
Swal.fire({ text: "No nodes found.", type: "error" })
return false;
}
if (nodesNodes.includes(null)) {
Swal.fire({ text: "Found items in node list without 'id' key.", type: "error" });
return false;
}
if (nodesNodes.length != nodesNodesSet.size) {
Swal.fire({ text: "Found multiple nodes with the same id.", type: "error" });
return false;
}
if (nodesNodesSet.size < linksNodesSet.size) {
Swal.fire({ text: "Found nodes referenced in 'links' which are not in 'nodes'.", type: "error" });
return false;
}
// Check that attributes are indicated consistently in both nodes and links
countWeight = masterGraph.links.filter(n => { return 'weight' in n }).length
if (0 < countWeight & countWeight < masterGraph.links.length) {
Swal.fire({ text: "Found links with and links without 'weight' attribute", type: "error" });
return false;
} else if (countWeight == 0) {
masterGraph.links.forEach(l => { l.weight = 1; })
}
var countGroup = masterGraph.nodes.filter(n => { return 'group' in n }).length
if (0 < countGroup & countGroup < masterGraph.nodes.length) {
Swal.fire({ text: "Found nodes with and nodes without 'group' attribute", type: "error" });
return false;
}
countSize = masterGraph.nodes.filter(n => { return 'size' in n }).length
if (0 < countSize & countSize < masterGraph.nodes.length) {
Swal.fire({ text: "Found nodes with and nodes without 'size' attribute", type: "error" });
return false;
}
else if (countSize == 0) {
masterGraph.nodes.forEach(n => { n.size = 1; })
}
// Reference graph (is never changed)
window.masterGraph = masterGraph
// Size and weight norms, colors and degrees
computeMasterGraphGlobals();
console.log("minNonzeroNodeSize = "+minNonzeroNodeSize);
// Check for really weak links
if (minLinkWeight < 1e-9) {
Swal.fire({ text: "Found links with weight < 1e-9. This may cause trouble with precision.", type: "warning" });
}
// Active graph that d3 operates on
window.graph = _.cloneDeep(masterGraph)
// Container for part of the network which are not in `graph` (for faster thresholding)
window.negativeGraph = { 'nodes': [], 'links': [] }
// If 'display_singleton_nodes' is untoggled then the graph should be updated
inputtedShowSingletonNodes(controls['display_singleton_nodes'])
inputtedNodeSizeByStrength(controls['scale_node_size_by_strength'])
// If 'scale_node_size_by_strength' is toggled, then node sizes need to follow computed degrees
if (controls['scale_node_size_by_strength']) {
if (controls['display_singleton_nodes']){
graph.nodes.forEach(n => { n.size = nodeStrengths[n.id] > 0.0 ? nodeStrengths[n.id] : minNonzeroNodeSize })
} else {
graph.nodes.forEach(n => { n.size = nodeStrengths[n.id] })
}
}
// Reset all thresholds ...
// commented this out because it overwrites the predefined values in `config`
// controls["min_link_weight_percentile"] = 0
// controls["max_link_weight_percentile"] = 1
// Run the restart if all of this was OK
restart();
}
function restartIfValidCSV(rawInput) {
// Assume hsleader is "source,target(,weight)"
var nodes = new Set();
var links = d3.csvParse(rawInput).map(l => {
nodes.add(l.source); nodes.add(l.target);
return { 'source': l.source, 'target': l.target, 'weight': +valIfValid(l.weight, 1) }
})
// Warn against zero links
var zeroLinksCount = 0
links = links.filter(l => {
if (l.weight == 0) {
zeroLinksCount += 1;
} else {
return l;
}
})
if (zeroLinksCount > 0) {
Swal.fire({ text: "Removed " + zeroLinksCount + " links with weight 0", type: "warning" })
}
// Reference graph (is never changed)
window.masterGraph = {
'nodes': Array.from(nodes).map(n => { return { 'id': n, 'size': 1 } }),
'links': links
}
// Size and weight norms, colors and degrees
computeMasterGraphGlobals();
console.log("minNonzeroNodeSize = "+minNonzeroNodeSize);
// Check for really weak links
if (minLinkWeight < 1e-9) {
Swal.fire({ text: "Found links with weight < 1e-9. This may cause trouble with precision.", type: "warning" });
}
// Active graph that d3 operates on
window.graph = _.cloneDeep(masterGraph)
// If 'display_singleton_nodes' is untoggled then the graph should be updated
inputtedShowSingletonNodes(controls['display_singleton_nodes'])
inputtedNodeSizeByStrength(controls['scale_node_size_by_strength'])
// If 'scale_node_size_by_strength' is toggled, then node sizes need to follow computed degrees
if (controls['scale_node_size_by_strength']) {
if (controls['display_singleton_nodes']){
graph.nodes.forEach(n => { n.size = nodeStrengths[n.id] > 0.0 ? nodeStrengths[n.id] : minNonzeroNodeSize })
} else {
graph.nodes.forEach(n => { n.size = nodeStrengths[n.id] })
}
}
// Container for part of the network which are not in `graph` (for faster thresholding)
window.negativeGraph = { 'nodes': [], 'links': [] }
// Reset all thresholds ...
// commented this out because it overwrites the predefined values in `config`
// controls["min_link_weight_percentile"] = 0
// controls["max_link_weight_percentile"] = 1
restart();
}
// Various utilities
// -----------------
function findNode(_graph, n) {
for (let _n of _graph.nodes) {
if (_n.id == valIfValid(n.id, n)) {
return _n;
}
}
return undefined;
}
function findLink(_graph, l) {
for (let _l of _graph.links) {
if (_l.source.id == l.source && _l.target.id == l.target) {
return _l;
}
}
return undefined;
}
function computeMasterGraphGlobals() {
// Check for initial node positions
nodePositions = true
for (var d of masterGraph.nodes) {
if (!d3.keys(d).includes("x") && !d3.keys(d).includes("y")) {
nodePositions = false; break;
}
}
if (nodePositions) {
// Rescale node positions to fit nicely inside of canvas depending on xlim or rescale properties.
if (masterGraph.rescale || ((!masterGraph.hasOwnProperty('rescale') && !masterGraph.hasOwnProperty('xlim')))) {
let xVals = []; let yVals = [];
masterGraph.nodes.forEach(d => { xVals.push(d.x); yVals.push(d.y) })
let domainScalerX = d3.scaleLinear().domain([d3.min(xVals), d3.max(xVals)]).range([width * 0.15, width * (1 - 0.15)])
let domainScalerY = d3.scaleLinear().domain([d3.min(yVals), d3.max(yVals)]).range([width * 0.15, width * (1 - 0.15)])
masterGraph.nodes.forEach((d, i) => {
d['x'] = zoomScaler.invert(domainScalerX(d.x))
d['y'] = zoomScaler.invert(domainScalerY(d.y))
})
}
controls['freeze_nodes'] = true;
}
// Check to see if it is weighted
isWeighted = countWeight > 0
// Sort out node colors
var nodeGroups = new Set(masterGraph.nodes.filter(n => 'group' in n).map(n => { return n.group }))
activeSwatch = {};
for (let g of nodeGroups) {
if (validColor(g)) {
activeSwatch[g] = getHexColor(g);
} else {
activeSwatch[g] = randomColor();
}
}
window.referenceSwatch = _.cloneDeep(activeSwatch)
window.referenceColor = controls['node_fill_color']
// Immutable node degree (unless strength is toggled)
masterNodeStrengths = {}; masterGraph.nodes.map(n => masterNodeStrengths[n.id] = 0)
masterNodeDegrees = {}; masterGraph.nodes.map(n => masterNodeDegrees[n.id] = 0)
masterGraph.links.forEach(l => {
masterNodeStrengths[l.source] += valIfValid(l.weight, 1);
masterNodeStrengths[l.target] += valIfValid(l.weight, 1);
masterNodeDegrees[l.source] += 1;
masterNodeDegrees[l.target] += 1;
});
// Degree dicrionary to keep track of ACTIVE degrees after thresholds are applied
nodeStrengths = _.cloneDeep(masterNodeStrengths)
// Compute node size and link width norms
recomputeNodeNorms();
recomputeLinkNorms();
}
function recomputeNodeNorms() {
// Compute node size norms
if (controls['scale_node_size_by_strength']) {
maxNodeSize = d3.max(d3.values(masterNodeStrengths))
let all_strengths = d3.values(masterNodeStrengths)
all_strengths.sort();
let i = -1;
do {
++i;
} while (all_strengths[i] == 0.0);
minNonzeroNodeSize = all_strengths[i];
} else {
maxNodeSize = d3.max(masterGraph.nodes.map(n => valIfValid(n.size, 0))); // Nodes are given size if they don't have size on load
minNonzeroNodeSize = maxNodeSize;
}
nodeSizeNorm = 1 / maxNodeSize ** (controls['node_size_variation'])
}
function recomputeLinkNorms() {
linkWeightOrder = removeConsecutiveDuplicates(masterGraph.links.map(l => valIfValid(l.weight, 1)).sort((a, b) => a - b))
minLinkWeight = linkWeightOrder[0]
maxLinkWeight = linkWeightOrder[linkWeightOrder.length - 1]
linkWidthNorm = 1 / maxLinkWeight ** controls['link_width_variation']
}
function shave() {
// MIN SLIDER MOVES RIGHT or MAX SLIDER MOVES LEFT
if (dvMin > 0 || dvMax < 0) {
// Remove links and update `nodeStrengths
graph['links'] = graph.links.filter(l => {
let withinThreshold = (controls['min_link_weight_percentile'] <= getPercentile(l.weight, linkWeightOrder)) && (getPercentile(l.weight, linkWeightOrder) <= controls['max_link_weight_percentile'])
if (!withinThreshold) {
nodeStrengths[l.source.id] -= valIfValid(l.weight, 1);
nodeStrengths[l.target.id] -= valIfValid(l.weight, 1);
negativeGraph.links.push(l);
}
return withinThreshold
})
// Remove singleton nodes
if (!controls['display_singleton_nodes']) {
graph['nodes'] = graph.nodes.filter(n => {
let keepNode = nodeStrengths[n.id] >= minLinkWeight;
if (!keepNode) {
negativeGraph.nodes.push(n)
}
return keepNode;
})
}