Repository navigation
Expand file tree
/
Copy pathnetworkGeneration.js
More file actions
2217 lines (1981 loc) · 70.2 KB
/
Copy pathnetworkGeneration.js
File metadata and controls
2217 lines (1981 loc) · 70.2 KB
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
/*
* author: Max Ohn
* project: Software Praktikum SS18
* faculty: CCSH RWTH Aachen
*
*/
//
// ----------------------------< HTML page building >----------------------------
//
d3.selectAll("html body").style("height", "98vh");
d3.select("body").append("div").attr("id", "container").style("position", "relative")
.append("div")
.attr("id", "divNetwork")
.styles({width: "51%", height: "100%", float: "left"});
d3.select("#container")
.styles({width: "99%", height: "98%", overflow: "hidden", position: "absolute"})
.append("div").attr("id", "divChart")
.styles({width: "48%", height: "100%"});;
// Network dropdown button
let networkDropdown = d3.select("#divNetwork")
.append("div")
.attr("id", "networkDropdown")
.styles({float: "left", position: "relative", display: "inline-block"});
networkDropdown.append("button")
.attrs({id: "networkDropdownButton", onclick: "toggleDropdown(\"network\")"})
.text("Model type")
.styles({"background-color": "#0000FF", color: "white", padding: "16px", "font-size": "16px", border: "none", cursor: "pointer"})
.on("mouseover", d => { d3.select("#networkDropdownButton").style("background-color", "#000080"); })
.on("mouseout", d => {
if (d3.select("#networkDropdownMenu").style("display") == "none") {
d3.select("#networkDropdownButton").style("background-color", "#0000FF");
}
});
// Network dropdown menu and items
networkDropdown.append("div")
.attr("id", "networkDropdownMenu")
.styles({ display: "none", position: "absolute", overflow: "auto", right: 0, "z-index": 3,
"min-width": "120px", "background-color": "#f1f1f1", "box-shadow": "0px 8px 16px 0px rgba(0,0,0,0.2)"})
.selectAll("a")
.data([ {type: "Barabasi", onclick: "changeToBarab()"},
{type: "Minority", onclick: "changeToMinor()"},
{type: "Gilbert", onclick: "changeToGilbert()"},
{type: "Watts-Alpha", onclick: "changeToWattsA()"},
{type: "Watts-Beta", onclick: "changeToWattsB()"},
{type: "Common-friends", onclick: "changeToCF()"}
]).enter()
.append("a")
.attrs({id: d => { return "networkDropdownItem" + d.type; }, onclick: d => { return d.onclick; }})
.text(d => { return d.type; })
.styles({display: "block", padding: "12px 16px", cursor: "context-menu"})
.on("mouseover", d => { d3.select("#networkDropdownItem" + d.type).style("background-color", "#ddd") })
.on("mouseout", d => { d3.select("#networkDropdownItem" + d.type).style("background-color", "#f1f1f1") });
// Padding between networkDropdownButton and setparamsButton
d3.select("#divNetwork")
.append("div")
.styles({float: "left", position: "relative", display: "inline-block", height: "1px", width: "10px"})
// Parameter customization
d3.select("#divNetwork")
.append("div")
.styles({float: "left", position: "relative", display: "inline-block"})
.append("button")
.attrs({id: "setParamsButton", onclick: "setParameters()"})
.text("Set parameters")
.styles({"background-color": "#0000FF", color: "white", padding: "16px", "font-size": "16px", border: "none", cursor: "pointer"})
.on("mouseover", d => { d3.select("#setParamsButton").style("background-color", "#000080"); })
.on("mouseout", d => {
d3.select("#setParamsButton").style("background-color", "#0000FF");
});
// Prepare chart box
let chartDropdown = d3.select("#divChart").styles({width: "48%", height: "100%", overflow: "hidden", float: "right"})
// Chart dropdown button
.append("div")
.attr("id", "chartDropdown")
.styles({float: "right", position: "relative", display: "inline-block"});
chartDropdown.append("button")
.attrs({id: "chartDropdownButton", onclick: "toggleDropdown(\"chart\")"})
.text("Chart type")
.styles({"background-color": "#0000FF", color: "white", padding: "16px", "font-size": "16px", border: "none", cursor: "pointer"})
.on("mouseover", d => { d3.select("#chartDropdownButton").style("background-color", "#000080"); })
.on("mouseout", d => {
if (d3.select("#chartDropdownMenu").style("display") == "none") {
d3.select("#chartDropdownButton").style("background-color", "#0000FF");
}
});
// Chart dropdown menu and items
chartDropdown.append("div")
.attr("id", "chartDropdownMenu")
.styles({ display: "none", position: "absolute", overflow: "auto", right: 0, "z-index": 3,
"min-width": "120px", "background-color": "#f1f1f1", "box-shadow": "0px 8px 16px 0px rgba(0,0,0,0.2)"})
.selectAll("a")
.data([ {type: "Bar", onclick: "changeToBar()"},
{type: "Scatter", onclick: "changeToScatter()"},
{type: "AvgPathLength", onclick: "changeToAPL()"}
]).enter()
.append("a")
.attrs({id: d => { return "chartDropdownItem" + d.type; }, onclick: d => { return d.onclick; }})
.text(d => { return d.type; })
.styles({display: "block", padding: "12px 16px", cursor: "context-menu"})
.on("mouseover", d => { d3.select("#chartDropdownItem" + d.type).style("background-color", "#ddd") })
.on("mouseout", d => { d3.select("#chartDropdownItem" + d.type).style("background-color", "#f1f1f1") });
// Radio buttons for x scale
d3.select("#divChart").append("div").attr("id", "chartParams").append("div").attr("id", "xScaleRadio").append("label").text("x: ")
let xScaleRadio = d3.select("#xScaleRadio").selectAll("span")
.data([{v: "Lin", f: "changeToLin(\"x\")"}, {v: "Log", f: "changeToLog(\"x\")"}])
.enter().append("span")
xScaleRadio.append("input")
.attrs({type: "radio", name: "xScaleRadio", value: d => { return d.v.toLowerCase(); }, onchange: d => { return d.f}})
.property("checked", d => { return d.v === "Lin"})
xScaleRadio.append("label").text(d => { return d.v; })
// Radio buttons for y scale
d3.select("#chartParams").append("div").attr("id", "yScaleRadio").append("label").text("y: ")
let yScaleRadio = d3.select("#yScaleRadio").selectAll("span").data([
{v: "Lin", f: "changeToLin(\"y\")"},
{v: "Log", f: "changeToLog(\"y\")"},
{v: "Abs", f: "changeToActual()"}
]).enter().append("span")
yScaleRadio.append("input")
.attrs({type: "radio", name: "yScaleRadio", value: d => { return d.v.toLowerCase(); }, onchange: d => { return d.f}})
.property("checked", d => { return d.v === "Lin"})
yScaleRadio.append("label").text(d => { return d.v; })
// svg containing the network (left)
const svgNetwork = d3.select("#divNetwork").append("svg")
.attrs({id: "networkCanvas", width: "90%", height: "90%"})
.styles({overflow: "hidden", border: "3px solid black", margin: "auto", cursor: "pointer"});
// svg containing the chart (right)
const svgChart = d3.select("#divChart").append("svg")
.attrs({width: "90%", height: "85%"})
.styles({overflow: "visible", float: "right", margin: "auto", cursor: "pointer"});
// "Watermark"
d3.select("#container").append("div")
.styles({position: "absolute", bottom: 0})
.append("text")
.text("Created by Max Ohn in 2018's \"Forschungspraktikum\" course at RWTH Aachen")
.styles({"font-size": "12px", "font-family": "sans-serif"});
//
// --------------------------- </ HTML page building >---------------------------
//
//
// -----------------------------< Global variables >-----------------------------
//
let network = []; // Adjacency matrix of the network
let initNodes = 5; // Amount of initial nodes
let maxNodes = 512; // Maximal amount of nodes
const radius = d => { // Radius of nodes depends on node degree
if (typeof d === "number") {
return 1.2*d+2;
}
return 1.2*d.deg+2;
};
let model = "barab"; // Current model generating new edges
let initProb = 0.3; // Probability that an edge in the initial graph exists
let initPartners = 1; // Determines to how many nodes each new node will connect
let minorityPercentage = 0.2; // Minority percentage for minority model
let homophily = 0.8; // Factor deciding whether nodes of the same groups want to connect
// (1-homophily for nodes of different groups)
let nodePairs; // Contains all node pairs upon initialization, removes them step-by-step
let initDegree = 4; // Degree of nodes in regular network (watts)
let rewireProb = 0.5; // Probability that an edge gets rewired (wattsB)
let globalIter; // Keeps track of a variable with global scope
let alphaFactor = 1; // wattsA variable to regulate between caveman vs solaria propensities
let finalAvgDegree = 5; // wattsA halts as soon as this average degree is reached
let friendProb = 0.4; // Probability to connect to nodes neighbor (comFr)
let color; // Color scale for nodes and chart bars
let chartType = "bar"; // Type of chart (bar, scatter, apl)
let xScaleType = "lin"; // Scale of x-Axis (lin or log)
let yScaleType = "lin"; // Scale of y-Axis (lin, log or abs)
let twSize = -1; // Determines how many time steps of the past we save for avgPathLength
let aplTimeWindow; // Keeps track of previous avgPathLength's
let isFirstStep = true; // Removes aplTimeWindow's first entry upon starting to generate (else is double)
let go = false; // Adding nodes in progress
let refreshRate = 200; // Amount of milliseconds until the next node comes
let runstatus; // Interval running after refreshRate (generates nodes)
let finished = false; // true if no further node/edge can be added
let nodes=[], links=[]; // Current nodes and edges
let oldNodes; // Saving last interations nodes for visual transition purposes
let node; // Visuals of nodes
let link; // Visuals of edges
let counter; // AvgDegree / Node / Link display
// Saving widths and heights for later use
const widthNetwork = document.getElementById("networkCanvas").clientWidth;
const heightNetwork = Math.round(svgNetwork.style("height").replace("px", ""));
const widthChart = Math.round(svgChart.style("width").replace("px", ""));
const heightChart = Math.round(svgChart.style("height").replace("px", ""));
// Force initialization
const force = d3.forceSimulation()
.on("tick", tick) // Applies tick function
.force("x", d3.forceX(widthNetwork/2)) // Pulling towards horizontal center
.force("y", d3.forceY(heightNetwork/2)) // Pulling towards vertical center
.force("charge", d3.forceManyBody().strength(d => { // Repelling from other nodes
return Math.min(-70, -490/radius(d)); // The smaller the node, the more it repels others
}))
.force("link", d3.forceLink() // Pulling towards connected nodes
.strength(0.1).distance(d => { // Depends on node degrees and avg node degree of network
return (radius(d.source) + radius(d.target) + Math.min(100, Math.max(40, 600/(d.source.deg + d.target.deg))))*(avgDegree()/2);
})) // And the more nodes, the longer the links
.force("collision", d3.forceCollide().radius(d => { return radius(d)+5; })) // Avoid node overlapping
;
//
// -----------------------------</ Global variables >-----------------------------
//
//
// -----------------------------< Helper functions >-----------------------------
//
/*
* Function that returns an array of numbers
* The number at the i-th index indicates the amount of nodes with degree i
*
*/
function allDegrees() {
let degrees = new Array(d3.max(nodes.map(d => d.deg))+1).fill(0);
nodes.forEach(d => {
degrees[d.deg]++;
});
return degrees;
}
/*
* Function that gives the angle (rad) between two points with
* pair: has form {source: {x: a, y: b, ...}, target: {x: c, y: d, ...}, ...} i.e. points (a,b) and (c,b) are compared
* swap: if 1 then calculate angle for source point, if -1 then calculate angle for target point
* Used in tick() to draw links from edge of node to edge of node instead of center of node to center of node
*
*/
function angle(pair, swap=1) {
return Math.atan2(swap*(pair.target.y - pair.source.y), swap*(pair.target.x - pair.source.x));
}
/*
* Function called in setParameters()
* For some reason this functionality (specifically the "d3.select(this)")
* did not work without defining a special function for it.
* d3.select(this) are cells in an HTML table and d contains the data for the cells
* d has the form {column: c, value: v} with
* c is either "text", "range" or "value"
* v is an object of the form {"text": t, "id": id, "min": min, "max": max, "value": v}
*
*/
function fillParameterCell(d) {
switch(d.column) {
// The descriptive text is just plain text
case "text":
d3.select(this).append("text").html(d.value.text).styles({"margin-left": "1em", cursor: "context-menu"})
// Description setup
.on("mouseover", () => {
return d3.select("#" + d.value.id + "Descr").style("visibility", "visible");
})
.on("mousemove", () => {
return d3.select("#" + d.value.id + "Descr")
.style("top", (d3.event.pageY - document.getElementById("paramsDiv").getBoundingClientRect().y + 10)+"px")
.style("left", (d3.mouse(this)[0]+10)+"px");
})
.on("mouseout", () => {
return d3.select("#" + d.value.id + "Descr").style("visibility", "hidden");
});
// Add description for mouseover
d3.select(this).append("div")
.attr("id", "" + d.value.id + "Descr")
.styles({ visibility: "hidden", "background-color": "lightgrey", border: "2px solid black", padding: "5px",
"border-radius": "6px", position: "absolute", "z-index": 2
}).text(d.value.descr);
break;
// The range bar is an input element with type range
case "range":
d3.select(this).append("input")
.attrs({id: "" + d.value.id + "Range", type: "range", min: d.value.min, max: d.value.max, value: d.value.value})
.attr("onchange", () => {
if (d.value.id == "initProb" ||
d.value.id == "minorityPercentage" ||
d.value.id == "homophily" ||
d.value.id == "rewireProb" ||
d.value.id == "friendProb") {
return "updateText(\"" + d.value.id + "Text\", this.value/100)";
} else {
return "updateText(\"" + d.value.id + "Text\", this.value)";
}
});
d3.select(this).select("#initDegreeRange").attr("step", 2);
break;
// The range value is an input element with type text
case "value":
d3.select(this).append("input")
.attrs({id: "" + d.value.id + "Text", type: "text", size: 3})
.attr("value", () => {
if (d.value.id == "initProb" ||
d.value.id == "minorityPercentage" ||
d.value.id == "homophily" ||
d.value.id == "rewireProb" ||
d.value.id == "friendProb") {
return d.value.value/100;
} else {
return d.value.value;
}
})
.style("margin-left", "1em");
break;
default:
console.log("Wrong d.column in toggleRunning: " + d.column)
break;
}
}
/*
* Given an array of probabilities, return a random index of this array based on the probabilities
*
*/
function randomChoice(probs) {
let randVal = d3.sum(probs)*Math.random();
return probs.findIndex(a => (randVal -= a) < 0 );
}
/*
* Stop the running process
*
*/
function stop() {
clearInterval(runstatus);
go = false;
}
/*
* Given node d, return the amount of nodes of group minor with the same degree
*
*/
function minorsWithSameDegree(d) {
let deg = typeof d === "number" ? d : d.deg;
return nodes.filter(n => { return n.group == "minor" && n.deg == deg; }).length;
}
/*
* Instead of letting the force decide the node positions,
* nodes are evenly distributed on a circle and don't move.
* This function returns the coordinates for the nodes in an array.
*
*/
function nodePosInCircle() {
const cx = widthNetwork/2;
const cy = heightNetwork/2;
const r = Math.min(widthNetwork/3, heightNetwork/3)
let coords = [];
for (let i = 0, l = nodes.length; i < l; i++) {
const rads = (270+360*i/nodes.length)*Math.PI/180;
coords.push([cx + r*Math.cos(rads), cy + r*Math.sin(rads)]);
}
return coords;
}
/*
* Return an array of node indices representing n's neighbors
*
*/
function getNeighbors(n) {
return network[n].map((d, i) => { return d ? i : -1}).filter(d => { return d != -1});
}
/*
* Reinitialize aplTimeWindow i.e. on the first use or on global resets
*
*/
function resetTimeWindow() {
if (twSize > 0) {
aplTimeWindow = Array(twSize).fill(0);
} else {
aplTimeWindow = [];
}
}
/*
* Given two node indices s and t, return the shortest amount of hops to reach one from the other (Breath-First-Search)
*
*/
function shortestPath(s, t) {
let queue = [{node: s, pathLength: 0}];
let visited = {s: true};
let tail = 0;
while (tail < queue.length) {
const u = queue[tail].node;
let count = queue[tail++].pathLength;
const nbs = getNeighbors(u);
for (let i = 0, l = nbs.length; i < l; i++) {
if (nbs[i] == t) {
return count + 1;
}
if (!visited[nbs[i]]) {
visited[nbs[i]] = true;
queue.push({node: nbs[i], pathLength: count + 1});
}
}
}
throw -1;
}
/*
* Return the average path length
* i.e. the sum of all shortest path between any two nodes devided by the amount of paths in total
*
*/
function avgPathLength() {
let shortestPathSum = 0;
let l = nodes.length;
for (let i = 0; i < l; i++) {
for (let j = 0 ; j < l; j++) {
try {
shortestPathSum += i != j ? shortestPath(i, j) : 0;
} catch (e) {
return e;
}
}
}
return (1/(nodes.length*(nodes.length - 1)))*shortestPathSum;
}
/*
* Return the average degree
* i.e. the sum of all node degrees divided by the amount of nodes
*
*/
function avgDegree() {
return preciseRound(d3.sum(nodes.map(d => { return d.deg; }))/nodes.length, 2);
}
/*
* Recalculate avgPathLength every timestep
*
*/
function updateAplTimeWindow() {
if (twSize > 0) {
aplTimeWindow.shift();
}
// Pop first element in the first step to avoid having it as duplicate
if (isFirstStep && aplTimeWindow.filter(d => { return d == 0; }).length == aplTimeWindow.length - 1) {
isFirstStep = false;
aplTimeWindow.pop();
}
aplTimeWindow.push(avgPathLength())
}
/*
* n is an array of pairs of node indices
* Returns an object {0: a, 1: b, 2: c, ...} where
* the keys are indices of the given array n and
* a, b, c, ... are arrays containing node indices representing nodes that are connected to both nodes in the pair
*
*/
function commonNeighbors(n) {
let commonNeighbors = {};
for (let i = 0; i < n.length; i++) {
commonNeighbors[i] = getNeighbors(n[i][0]).filter(d => -1 !== getNeighbors(n[i][1]).indexOf(d));
}
return commonNeighbors;
}
/*
* Check the nLastLinks elements of the links array and update the network adjacency matrix accordingly
*
*/
function updateAdjMatrix(nLastLinks=links.length) {
for (let i = links.length-nLastLinks, l = links.length; i < l; i++) {
addLinkToNetwork(links[i].source.index, links[i].target.index);
}
}
/*
* Add row and column to network matrix for new node
*
*/
function extendMatrix() {
network.push(Array(nodes.length).fill(false))
for (let i = 0, l = nodes.length-1; i < l; i++) {
network[i].push(false);
}
}
/*
* Add specific link to network matrix
*
*/
function addLinkToNetwork(n1, n2) {
network[n1][n2] = true;
network[n2][n1] = true;
}
/*
* Remove specific link to network matrix
*
*/
function removeLinkFromNetwork(n1, n2) {
network[n1][n2] = false;
network[n2][n1] = false;
}
/*
* Round num to have decimals many decimal points
*
*/
function preciseRound(num, decimals) {
const t = Math.pow(10, decimals);
return (Math.round((num*t) + (decimals > 0 ? 1 : 0) * (Math.sign(num) * (10/Math.pow(100, decimals))))/t).toFixed(decimals);
}
//
// -----------------------------</ Helper functions >-----------------------------
//
//
// -------------------------------< Initialization >-------------------------------
//
// Event if mouse is being clicked inside svg's or spacebar is being pressed
svgNetwork.on("mousedown", toggleRunning);
svgChart.on("mousedown", toggleRunning);
d3.select("html").on("keydown", () => { if (d3.event.code == "Space") toggleRunning(); })
// Close chart dropdown if it is open and the button is not being clicked
window.onclick = event => {
if (event.target.id != "chartDropdownButton" && d3.select("#chartDropdownMenu").style("display") == "block") {
d3.select("#chartDropdownMenu").style("display", "none");
d3.select("#chartDropdownButton").style("background-color", "#0000CD");
} else if (event.target.id != "networkDropdownButton" && d3.select("#networkDropdownMenu").style("display") == "block") {
d3.select("#networkDropdownMenu").style("display", "none");
d3.select("#networkDropdownButton").style("background-color", "#0000CD");
}
};
setup();
/*
* Initial generation of nodes, edges and chart elements
* + all of their visuals
*
*/
function setup() {
// Generate initial nodes of the form {x: a, y: b, deg: c, index: i} with
// a = random value for the nodes initial horizontal position
// b = random value for the nodes initial vertical position
// c = 0 because no edges have been set yet, hence degree of zero
nodes = d3.range(initNodes).map((d, i) => {
return {x: Math.random()*widthNetwork, y: Math.random()*heightNetwork, deg: 0, index: i};
});
network = Array(initNodes).fill().map(() => Array(initNodes).fill(false));
// If the minority model gets simulated, all nodes are assigned to either the majority or minority group
if (model == "minor") {
let amountMinorNodes = Math.floor(minorityPercentage*nodes.length);
nodes.forEach((d, i) => {
d.group = --amountMinorNodes < 0 ? "major" : "minor";
});
}
switch(model) {
// Generate random edges between initial nodes
case "comFr":
case "minor":
case "barab":
links = randomNetwork();
break;
// Set the "to check" nodes to the first two nodes
case "gilbert":
nodePairs = [];
for (let i = 0; i < initNodes; i++) {
for (let j = 0; j < initNodes; j++) {
if (i != j) {
nodePairs.push([i, j]);
}
}
}
break;
// Generate a regular network
case "wattsA":
case "wattsB":
const nodeCoords = nodePosInCircle();
nodes.forEach((d, i) => {
d.x = nodeCoords[i][0];
d.y = nodeCoords[i][1];
d.vx = 0;
d.vy = 0;
})
globalIter = 0;
links = regularNetwork(initDegree);
break;
default:
console.log("Wrong model in setup: " + model)
break;
}
// Clone nodes (for transition purposes in redraw())
oldNodes = nodes.map(d => Object.assign({}, d));
// Initialize visuals
node = svgNetwork.selectAll(".node");
link = svgNetwork.selectAll(".link");
counter = svgNetwork.selectAll(".counter");
// Update adjacency matrix according to links
updateAdjMatrix();
// Initial defining of color scale for nodes and chart bars
setColorScale();
// Keep track of average path length
resetTimeWindow();
// Draw paper text
showPaper();
// Draw everything
redraw();
}
//
// -------------------------------</ Initialization >-------------------------------
//
//
// -----------------------------< Event functions >-----------------------------
//
/*
* Changes applied by the force i.e. node and edge visuals get relocated
*
*/
function tick() {
node.attrs({cx: d => { return d.x; }, cy: d => { return d.y; }});
link.attrs({x1: d => { return d.source.x + radius(d.source)*Math.cos(angle(d)); },
y1: d => { return d.source.y + radius(d.source)*Math.sin(angle(d)); },
x2: d => { return d.target.x + radius(d.target)*Math.cos(angle(d,-1)); },
y2: d => { return d.target.y + radius(d.target)*Math.sin(angle(d,-1)); }});
}
/*
* Action on mouse click
* If shift is being held aswell, delete current progress and start anew
* Otherwise if progression is currently stopped, continue it
* i.e. add new node, new edges and update chart
* If progression runs, stop it
*
*/
function toggleRunning(){
go = !go;
// If shift is pressed, remove everything and start anew
if (d3.event.shiftKey){
reset();
};
// Start adding nodes and edges
if (go){
runstatus = setInterval(
// Applied every refreshRate amount of milliseconds
() => {
// If no further nodes/edges can be generated
if (finished) {
return;
}
switch(model) {
case "comFr":
case "barab":
case "minor":
// If maximum amount nodes not yet reached and no custom network is being created
if (nodes.length < maxNodes) {
// Create new node at random location
const newNode = {x: Math.random()*widthNetwork, y: Math.random()*heightNetwork, deg: 0, index: nodes.length};
// Determine nodes connected to the new node
let targets;
// Check which model to use to generate new edges
switch(model) {
case "barab":
targets = barabasiAlbert();
break;
case "minor":
newNode.group = Math.random() < minorityPercentage ? "minor" : "major";
targets = minorities(newNode);
break;
case "comFr":
targets = commonFriends();
// Required for link visualization and coloring
globalIter = targets.length;
break;
default:
console.log("Wrong model in toggleRunning: " + model)
break;
}
targets.forEach(d => {
links.push({source: newNode, target: d});
});
newNode.deg = targets.length;
nodes.push(newNode);
// Update network matrix
extendMatrix();
updateAdjMatrix(targets.length);
} else {
finished = true;
stop();
}
break;
case "gilbert":
let foundEdge = false;
// Finding new edge
while (!foundEdge && nodePairs.length > 0) {
// Check for next node pair
const pair = nodePairs.splice(nodePairs.length*Math.random() | 0, 1)[0]
// Add edge
if (Math.random() < initProb) {
foundEdge = true;
links.push({source: nodes[pair[0]], target: nodes[pair[1]]});
nodes[pair[0]].deg++;
nodes[pair[1]].deg++;
addLinkToNetwork(pair[0], pair[1]);
}
}
// All edges checked
if (nodePairs.length == 0) {
finished = true;
stop();
}
break;
case "wattsA":
let searchingNewEdge = true;
let timeout = 100;
// Try to create an edge
while (searchingNewEdge) {
timeout--;
if (timeout < 0) {
stop();
alert("Could not add edge.")
return;
}
let newTarget;
try {
newTarget = randomChoice(wattsPropensity(globalIter));
// propensityVector threw an error which means that there was no node to connect
} catch(e) {
globalIter++; // Represents nodes indices
continue;
}
// Found matching target -> add edge
searchingNewEdge = false;
links.push({source: nodes[globalIter], target: nodes[newTarget]});
addLinkToNetwork(globalIter, newTarget);
nodes[globalIter].deg++;
nodes[newTarget].deg++;
globalIter = (globalIter + 1) % nodes.length;
}
// Finished generating as soon as desired avgDegree is reached
if (avgDegree() >= finalAvgDegree) {
finished = true;
stop();
}
break;
case "wattsB":
let edgeRewired = false;
// Try until every link has been checked for rewiring
while(!edgeRewired && globalIter < links.length) {
// If the probability decides for true
if (Math.random() < rewireProb) {
edgeRewired = true;
let foundEdge = false;
let timeout = 100;
// Keep trying to rewire the edge
while (!foundEdge) {
let rewireTarget = Math.floor(Math.random()*nodes.length);
// If the new edge fits i.e. it's a new connection, update edge target and node degrees
if (links[globalIter].source.index != rewireTarget && !network[links[globalIter].source.index][rewireTarget]) {
console.log("" + links[globalIter].source.index + ", " + rewireTarget)
foundEdge = true;
removeLinkFromNetwork(links[globalIter].source.index, links[globalIter].target.index);
links[globalIter].target.deg--;
nodes[rewireTarget].deg++;
links[globalIter].target = nodes[rewireTarget];
addLinkToNetwork(links[globalIter].source.index, rewireTarget);
}
timeout--;
if (timeout < 0) {
stop();
alert("Could not rewire edge.")
return;
}
}
}
globalIter++; // Represents links indices
}
if (globalIter == links.length) {
finished = true;
stop();
}
break;
default:
console.log("Wrong model in toggleRunning: " + model)
break;
}
// Add new info to the visuals i.e. draw new node and edges + update the chart
redraw();
}, refreshRate);
} else {
clearInterval(runstatus);
}
}
//
// -----------------------------</ Event functions >-----------------------------
//
//
// -----------------------------< Network generation >-----------------------------
//
/*
* Gilbert-Model (Random network)
* Given the initial nodes, determine which ones are connected
* Generation of edge depends on variable initProb
* If mustConnect is true, each node must have at least one edge
*
*/
function randomNetwork(mustConnect=true) {
let isConnected;
let randLinks = [];
let l = nodes.length;
for (let i = 0; i < l-1; i++) {
isConnected = false;
for (let j = i+1; j < l; j++) {
if (Math.random() < initProb) {
nodes[i].deg++;
nodes[j].deg++;
randLinks.push({source: nodes[i], target: nodes[j]});
isConnected = true;
}
}
// If each node should have an edge but some node has no adjacent node yet, iterate again
if (mustConnect && !isConnected) {
i--;
}
}
return randLinks;
}
/*
* Barabasi-Albert-Model (https://arxiv.org/pdf/cond-mat/9910332.pdf)
* Generation of edge depends on amount of edges already adjacent to a node
*
*/
function barabasiAlbert() {
let targets = []; // Contains nodes to which the new node will connect
// Contains probabilities for the new node to connect to the corresponding existing node
let probs = nodes.map(d => { return d.deg/d3.sum(nodes.map(d => d.deg)); })
let timeout = 100;
// Find exactly initPartners many nodes
while (targets.length < initPartners) {
// Given the probabilities, choose a random node
const randNode = randomChoice(probs);
// If it hasnt been chosen before by this new node, add it as target
if (!targets.includes(randNode)) {
nodes[randNode].deg++;
targets.push(nodes[randNode]);
timeout++;
}
timeout--;
if (timeout < 0) {
stop();
alert("New node could only connect to " + targets.length + " out of " + initPartners + " necessary nodes.")
break;
}
}
return targets;
}
/*
* Minority-Model based on Barabasi-Albert (https://arxiv.org/pdf/1702.00150.pdf)
* Nodes are assigned to a group. Edges to the new node depend on its group and the Barabasi-Albert-Model
*
*/
function minorities(newNode) {
let targets = []; // Contains nodes to which the new node will connect
// Calculate common divisor for all elements
let divisor = 0;
nodes.forEach(d => { divisor += d.group == newNode.group ? homophily*d.deg : (1-homophily)*d.deg; });
// Contains probabilities for the new node to connect to the corresponding existing node (also depending on the node's group)
let probs = nodes.map(d => {
return d.group == newNode.group ? homophily*d.deg/divisor : (1-homophily)*d.deg/divisor;
});
let timeout = 100;
// Find exactly initPartners many nodes
while (targets.length < initPartners) {
// Given the probabilities, choose a random node
const randNode = randomChoice(probs);
// If it hasnt been chosen before by this new node, add it as target
if (!targets.includes(nodes[randNode])) {
nodes[randNode].deg++;
targets.push(nodes[randNode]);
timeout++;
}
timeout--;
if (timeout < 0) {
stop();
alert("New node could only connect to " + targets.length + " out of " + initPartners + " necessary nodes.")
break;
}
}
return targets;
}
/*
* Returns links of a regular network with the size of nodes
* degree parameter must be even and smaller than nodes.length-1
*
*/
function regularNetwork(degree) {
let regularLinks = [];
for (let currStep = 1, maxPartners = degree/2; currStep <= maxPartners; currStep++) {
for (let i = 0, l = nodes.length; i < l; i++) {
regularLinks.push({source: nodes[i], target: nodes[(i+currStep)%nodes.length]})
nodes[i].deg++;
nodes[(i+currStep)%nodes.length].deg++;
}
}
return regularLinks;
}
/*
* Return an array containing probabilities to connect node n to its neighbors
*