-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.html
executable file
·1450 lines (1237 loc) · 61.3 KB
/
main.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
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
<!-- <!DOCTYPE html> -->
<html>
<head>
<title>The Networks of War</title>
<!-- subtitle: Network Analysis Between Countries at War -->
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link href='https://fonts.googleapis.com/css2?family=Libre+Franklin:wght@100;400&display=swap' rel='stylesheet'>
<style>
@media (max-width:750px){
#war_network_analysis_graph {
display: none;
}
#war_menu {
display: none;
}
#war_network_analysis_graph {
display: none;
}
#message {
display: none;
}
#list_of_data_sources {
display: none;
}
}
@media (min-width:750px){
#hidden_project_explained {
display: none;
}
}
/* svg {
border: 1px solid #000;
} */
svg text {
/* font-family: 'Libre Franklin', sans-serif; */
stroke: black;
fill: black;
background: white;
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
/* pointer-events: none; */
}
div.tooltip {
/* position: absolute; */
text-align: left;
align: left;
padding: 10px;
/* font-family: 'Libre Franklin', sans-serif; */
font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 15px;
stroke: black;
background: white;
border: solid;
border-width: 1px;
border-radius: 5px;
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
pointer-events: none;
}
</style>
</head>
<body>
<!-- <div id='war_choice_menu'>
document.getElementById('war_choice_menu').style.display = 'none';
document.getElementById('war_choice_menu').style.display = 'block';
<p align='center'>Choose a War Type</p>
<div class='center'>
<div class='btn-group'>
<a onclick=''><button class='button'>Inter-State</button></a>
<a onclick='' ><button class='button'>Intra-State</button></a>
</div>
</div>
<div class='center' style='margin-top:20px; margin-bottom:40px;'>
<div class='btn-group'>
<a onclick='' ><button class='button'>Extra-State</button></a>
<a onclick='' ><button class='button'>Non-State</button></a>
</div>
</div>
</div> -->
<div id='hidden_project_explained' align='left' style='margin-bottom:15px;'>
<p>While I'm flattered you came to check out my project, it has several interactive features that work best on desktop. So, grab a computer and come back soon!</p>
</div>
<div id='message'>
<p>Hey there! I'm developing a tool to analyze the networks between countries at war, using data provided by <a href='https://correlatesofwar.org/' target='_blank'>The Correlates of War Project</a>. This project is currently in progress. Stay tuned soon for more updates.</p>
</div>
<div id='war_menu' align='center' style='margin-bottom:15px;'></div>
<script src='https://unpkg.com/[email protected]/dist/d3-simple-slider.min.js'></script>
<div id='war_network_analysis_graph' align='center' style='margin-bottom:10px;'></div>
<div id='list_of_data_sources' align='left' style='margin-bottom:15px;'>
<p>All data has been obtained from the <a href='https://correlatesofwar.org/' target='_blank'>Correlates of War Project</a>, using all of the following files in some capacity:
<ul>
<li>COW Country Codes: COW country codes.csv</li>
<li>COW War Data, 1816 - 2007</li>
<ul>
<li>Inter-StateWarData_v4.0.csv</li>
<li>INTRA-STATE_State_participants v5.1.csv</li>
<li>Extra-StateWarData_v4.0.csv</li>
<li>directed_dyadic_war.csv</li>
</ul>
<li>Colonial/Dependency Contiguity: contcold.csv</li>
<li>Direct Contiguity: contdird.csv</li>
<li>Defense Cooperation Agreement Dataset: DCAD-v1.0-dyadic.csv</li>
<li>Diplomatic Exchange: Diplomatic_Exchange_2006v1.csv</li>
<li>Formal Alliances: alliance_v4.1_by_dyad_yearly.csv</li>
<li>Militarized Interstate Disputes: dyadic MIDs 3.1.csv</li>
<li>National Material Capabilities: NMC_5_0-wsupplementary.csv</li>
<li>Intergovernmental Organizations: dyadic_formatv3.csv</li>
<li>Territorial Change: tc2018.csv</li>
<li>Trade: Dyadic_COW_4.0.csv</li>
</ul>
</p>
</div>
<!-- Load d3.js -->
<script src='https://d3js.org/d3.v5.min.js'></script>
<script src='https://d3js.org/d3-time.v2.min.js'></script>
<script>
function getTextWidth(svgInput, textInput, fontSize) {
// obtaining length of any textinput (based on default font size and font family)
textWidthArray = [];
svgInput.append('g')
.selectAll('.dummyText')
.data([textInput])
.enter().append('text')
.attr('pointer-events', 'none')
// .attr('font-family', 'sans-serif')
.attr('font-size', fontSize)
.text(function(d) { return d; })
.each(function(d, i) {
thisWidth = this.getComputedTextLength();
textWidthArray.push(thisWidth);
this.remove();
});
textWidth = textWidthArray.reduce((a, b) => a + b, 0);
return textWidth;
};
// returning the max value from any array
function maxFromArray(array) {
maxValue = array.reduce(function(a, b) { return Math.max(a, b); });
return maxValue;
};
// returning the min value from any array
function minFromArray(array) {
minValue = array.reduce(function(a, b) { return Math.min(a, b); });
return minValue;
};
// returning average overall value across all numbers in an array.
function arrayAverage(array) {
// Find the sum
sumOfAllItems = 0;
for ( i in array )
{ sumOfAllItems+=array[i]; }
// get the length of the array
totalItems = array.length;
// return the average
return sumOfAllItems/totalItems;
};
// unique values from array part 1
Array.prototype.contains = function(v) {
for ( var i = 0; i < this.length; i++ ) {
if ( this[i]===v )
{ return true; }
else
{ return false; }
}
};
// unique values from array part 2
// returning all non null values from an array with no duplicates
Array.prototype.uniqueNonNull = function() {
array = [];
for ( var i = 0; i < this.length; i++ ) {
// not adding any values to the array that have already been added
// not adding any null values to the array
if ( !array.contains(this[i]) && isNaN(this[i])==false )
{ array.push(this[i]) }
}
return array;
};
function addStdText(svgInput, classInput, idInput, textX, textY, fontSize, strokeWidth, textInput) {
svgInput.append('text')
.attr('class', classInput)
.attr('id', idInput)
.attr('x', textX)
.attr('y', textY)
.attr('pointer-events', 'none')
.text(textInput)
.style('fill', 'black')
.style('font-size', fontSize)
.style('stroke-width', strokeWidth)
.style('stroke', function(d) {
if ( strokeWidth==0 )
{ return 'transparent'; }
else
{ return 'black'; }
});
};
function addStdRect(svgInput, classInput, idInput, rectX, rectY, rectWidth, rectHeight, rectStroke, rectStrokeWidth, rectStrokeOpacity, rectFill, rectFillOpacity, rMO, rML, rClick) {
svgInput.append('rect')
.attr('class', classInput)
.attr('id', idInput)
.attr('x', rectX)
.attr('y', rectY)
.attr('width', rectWidth)
.attr('height', rectHeight)
.style('stroke', rectStroke)
.style('stroke-width', rectStrokeWidth)
.attr('stroke-opacity', rectStrokeOpacity)
.style('fill', rectFill)
.attr('fill-opacity', rectFillOpacity)
.on('mouseover', rMO)
.on('mouseleave', rML)
.on('click', rClick);
};
function addStdSVG(svgName, divInput, widthInput, heightInput, marginLeftInput, marginTopInput, cursorInput) {
window[svgName] = d3.select('#' + divInput)
.append('svg')
.attr('width', widthInput)
.attr('height', heightInput)
.attr('transform', 'translate(' + marginLeftInput + ',' + marginTopInput + ')')
.style('cursor', cursorInput);
};
function defineTooltip(divInput, idInput, leftLoc, topLoc, divWidth, divHeight, textInput) {
d3.select('#' + divInput)
.append('div')
.attr('pointer-events', 'none')
.attr('class', 'tooltip')
.attr('id', idInput)
.style('width', divWidth)
.style('height', divHeight)
.style('left', leftLoc)
.style('top', topLoc)
.style('bottom', '0px')
.style('opacity', 0)
.html(textInput);
};
function addTooltipSymbol(svgInput, idInput, circX, circY, textX, textY, textRotate) {
svgInput.append("circle")
.attr("pointer-events", "none")
.attr("id", idInput + "Circle")
.attr("cx", circX)
.attr("cy", circY)
.attr('r', 7.5)
.style('fill', "rgb(0,122,255)")
.style('opacity', 0.9)
.style("stroke-width", 2)
.style("stroke", "transparent");
svgInput.append("text")
.attr("pointer-events", "none")
.attr("id", idInput + "Text")
.attr("transform", textRotate)
.attr("x", textX)
.attr("y", textY)
.text("i")
.style('fill', "white")
.style('stroke', "white")
.style('font-size', "11.5px")
.style('font-weight', 500);
};
var generalRectMO = function(d) {
// this will be used as a decorator to other mouseover functions
d3.select(this)
.style('stroke-width', 2)
.style('cursor', 'pointer');
},
generalRectML = function(d) {
// this will be used as a decorator to other mouseleave
d3.select(this)
.style('stroke-width', 1);
};
// reading in the data to create the war menu
d3.csv('../assets/csv/the_networks_of_war/war_file_list.csv').then(function(data) {
parseTime = d3.timeParse('%Y-%m-%d');
warPageURL = window.location.href,
warPageType = warPageURL.split('the_networks_of_war_')[1].split('s/')[0],
warNameLengths = [],
// creating a dummy svg so that the gettextwidth function can be used before any 'real' svgs are defined
svgDummy = d3.select('#war_menu').append('svg').attr('width', 0).attr('height', 0),
fileDic = {
'file_name' : [],
'war_name': [],
'start_year': [],
'end_year': [],
'start_date': [],
'end_date': [],
'war_type': [],
'war_sub_type': [],
'ongoing_war': [],
'start_date_estimated': [],
'end_date_estimated': [],
'total_days_in_war': [],
'total_participants': []
};
data.forEach(function(d) {
// determining the war type for each row in the file.
fileWarType = d.war_type.toLowerCase().replace('-', '_').replace(' ', '_');
// performing the following actions if the war type in the file matches the war type for the page.
if ( warPageType==fileWarType )
{ warNameLengths.push(getTextWidth(svgDummy, d.war_name, '14px'));
fileDic['file_name'].push(d.file_name),
fileDic['war_name'].push(d.war_name),
fileDic['start_year'].push(parseInt(d.start_year)),
fileDic['end_year'].push(parseInt(d.end_year)),
fileDic['start_date'].push(parseTime(d.start_date)),
fileDic['end_date'].push(parseTime(d.end_date)),
fileDic['war_type'].push(d.war_type),
fileDic['war_sub_type'].push(d.war_sub_type),
fileDic['ongoing_war'].push(parseInt(d.ongoing_war)),
fileDic['start_date_estimated'].push(parseInt(d.start_date_estimated)),
fileDic['end_date_estimated'].push(parseInt(d.end_date_estimated)),
fileDic['total_participants'].push(parseInt(d.total_participants));
if ( parseInt(d.start_date_estimated)==1 || parseInt(d.end_date_estimated)==1 )
{ estimationFlag = ' *' }
else
{ estimationFlag = '' }
if ( parseInt(d.ongoing_war)==1 )
{ fileDic['total_days_in_war'].push((d3.timeDay.count(parseTime(d.start_date), new Date()) + 1).toLocaleString() + estimationFlag); }
else
{ fileDic['total_days_in_war'].push(parseInt(d.total_days_in_war).toLocaleString() + estimationFlag); }
}
});
// removing all svgs to this point (only includes dummy svg)
d3.selectAll('svg').remove();
warNameMaxLength = maxFromArray(warNameLengths);
// new code section: start of code for svg1
// adding createMenu function here so that the as much can be pre-defined as possible.
// this will reduce runtime needed to re-execute the menu upon returning
function createMenu() {
// set the dimensions and margins of the menu
margin = {top: 0, bottom: 15, left: 0, right: 0},
width = warNameMaxLength + 500,
height = (Object.keys(fileDic['file_name']).length+2) * 30;
// setting a text sizes for all menu items
menuTextSize = '14px';
addStdSVG('svg1', 'war_menu', width, height, margin.left, margin.top, 'pointer');
// first rect is an outline for the entire menu
// shifting width (width-2) to allow for stroke to be seen (same reason for adjusting the height)
addStdRect(svg1, null, null, 1, 1, width-2, ((Object.keys(fileDic['file_name']).length+1) * 30) + 10 - 1, 'black', 1, null, 'transparent', null, null, null, null);
// creating the labels for the menu (everything in the top row)
addStdRect(svg1, null, null, 0, 0, width, 40, 'black', 1, 0.15, 'black', 0.075, null, null, null);
addStdText(svg1, null, null, 10, 25, '14px', 0.75, 'Name');
addStdText(svg1, null, null, warNameMaxLength + 65, 25, menuTextSize, 0.75, 'Timeframe');
addStdText(svg1, null, null, warNameMaxLength + 200, 25, menuTextSize, 0.75, 'Length in Days');
addStdText(svg1, null, null, warNameMaxLength + 340, 25, menuTextSize, 0.75, 'Total Participants');
// Three function that change the tooltip when user hover / move / leave a rectangle on the menu
var mainMenuMouseOver = function(d) {
d3.select(this)
.style('stroke-width', 2)
.style('stroke-opacity', 0.75)
.style('fill', 'rgb(26,188,156)')
.style('fill-opacity', 0.20);
},
mainMenuMouseLeave = function(d) {
d3.select(this)
.style('stroke-width', 1)
.style('stroke-opacity', 0.15)
.style('fill', 'black')
.style('fill-opacity', 0.075);
},
mainMenuClick = function(d) {
// removing all current svgs
// the manue is no longer needed once a selection has been made.
selectedWarID = d3.select(this).attr('id');
d3.selectAll('svg').remove();
createNetworkGraph(selectedWarID);
window.scrollTo(0, 325);
};
for ( var i = 0; i <= Object.keys(fileDic['file_name']).length-1; i++ ) {
addStdRect(svg1, null, fileDic['file_name'][i], 0, (30*(i+1))+10, width, 30, 'black', 1, 0.15, 'black', 0.075, mainMenuMouseOver, mainMenuMouseLeave, mainMenuClick);
addStdText(svg1, null, null, 10, 30*(i+2), menuTextSize, 0, fileDic['war_name'][i]);
// calculating days since war began if the war is ongoing
if ( fileDic['ongoing_war'][i]==1 )
{ addStdText(svg1, null, null, warNameMaxLength + 55, 30*(i+2), menuTextSize, 0, fileDic['start_year'][i] + ' - Present'); }
else if ( fileDic['start_year'][i]==fileDic['end_year'][i] )
{ addStdText(svg1, null, null, warNameMaxLength + 55, 30*(i+2), menuTextSize, 0, fileDic['start_year'][i]); }
else
{ addStdText(svg1, null, null, warNameMaxLength + 55, 30*(i+2), menuTextSize, 0, fileDic['start_year'][i] + ' - ' + fileDic['end_year'][i]); }
addStdText(svg1, null, null, warNameMaxLength + 230, 30*(i+2), menuTextSize, 0, fileDic['total_days_in_war'][i].toLocaleString());
addStdText(svg1, null, null, warNameMaxLength + 395, 30*(i+2), menuTextSize, 0, fileDic['total_participants'][i].toLocaleString());
};
};
// calling the war menu function upon page load
createMenu();
function createNetworkGraph(fileName) {
// new code section: start of code for svg2
// reading in the data to create the network graph
d3.json('../assets/json/the_networks_of_war/' + fileName).then(function(graph) {
// creating a color scale to color the side of each war.
color = d3.scaleLinear().domain([1, 2]).range(['lightgreen', 'violet']);
// set the dimensions and margins of the graph
margin = {top: 0, bottom: 15, left: 0, right: 0},
width = 750,
height = 900;
// setting a text sizes for all graph items
graphTextSize = '14px',
graphMenuTextSize = '15px';
// defining svg for the graph,
// includes area for descriptive statistics to be activated upon hovering nodes.
addStdSVG('svg2', 'war_network_analysis_graph', width, height, margin.left, margin.top, null);
// defining a mouseover function for the svg
var svg2BodyMO = function(d) {
svg2.selectAll('.link_descriptor_dropdowns').remove();
svg2.selectAll('.node_descriptor_dropdowns').remove();
};
addStdRect(svg2, null, 'svg2_rect_outline', 0, 0, width, height, 'black', 1, null, 'transparent', null, svg2BodyMO, null, null);
// this will send you back to choose a new war (of the same type)
var backToMenuClick = function(d) {
// removing all current svgs
// the graph is no longer needed once the user chooses to leave it.
d3.selectAll('svg').remove();
// removing all current tooltips
d3.selectAll('.tooltip').remove();
createMenu();
};
// creating a rect for a back to menu button
addStdRect(svg2, null, 'back_to_menu', 1, 10, 70, 30, 'black', 1, null, 'transparent', null, generalRectMO, generalRectML, backToMenuClick);
addStdText(svg2, null, null, 6, 31.5, graphMenuTextSize, 0, '↖ Menu');
// obtaining array for all war fields in the json file
// these will be iterated through to fill the warDic dictionary
warFields = Object.keys(graph.war[0]).sort();
warDic = {};
// obtaining all values from war json dictionary (originally war_df)
for ( var i = 0; i <= warFields.length-1; i++ )
{ warDic[warFields[i]] = graph.war[0][warFields[i]]; };
if ( warDic['start_year']==warDic['end_year'] ) {
warDic['single_year_war'] = true,
warDic['timeFrame'] = warDic['start_year'];
}
else {
warDic['single_year_war'] = false,
warDic['timeFrame'] = warDic['start_year'] + '-' + warDic['end_year'];
}
addStdText(svg2, null, null, 0, 85, graphMenuTextSize, 0, warDic['war_name']);
addStdText(svg2, null, null, 0, 102.5, graphMenuTextSize, 0, warDic['timeFrame']);
if ( warDic['single_year_war']==false ) {
sliderDefined = true,
sliderData = [0, 1, 2],
sliderDataLabels = {0: 'First Year', 1: 'Last Year', 2: 'All Years'},
yearSlider = d3.sliderBottom()
.min(d3.min(sliderData))
.max(d3.max(sliderData))
.width(130)
.step(1)
.ticks(3)
.default(d3.max(sliderData))
.tickValues(sliderData)
.tickFormat(function(d, i) { return sliderDataLabels[i]; })
.on('onchange', val => {
timeFrame = val;
// keeping current dropdown selection for links/nodes if they appear in the newly selected timeframe.
if ( Object.keys(descriptiveFields['link'][timeFrame]).includes(linkDescriptorSelected.substring(0, linkDescriptorSelected.length-2).concat(descriptiveTags[sliderDataLabels[timeFrame]])) )
{ linkDescriptorSelected = linkDescriptorSelected.substring(0, linkDescriptorSelected.length-2).concat(descriptiveTags[sliderDataLabels[timeFrame]]) }
else
{ linkDescriptorSelected = defaultValues['link'][timeFrame] }
if ( Object.keys(descriptiveFields['node'][timeFrame]).includes(nodeDescriptorSelected.substring(0, nodeDescriptorSelected.length-2).concat(descriptiveTags[sliderDataLabels[timeFrame]])) )
{ nodeDescriptorSelected = nodeDescriptorSelected.substring(0, nodeDescriptorSelected.length-2).concat(descriptiveTags[sliderDataLabels[timeFrame]]); }
else
{ nodeDescriptorSelected = defaultValues['node'][timeFrame]; }
descriptiveMenuClick('link', linkDescriptorSelected, linkMenuMouseOver, 0);
descriptiveMenuClick('node', nodeDescriptorSelected, nodeMenuMouseOver, yAdjustment);
});
svg2.append('g')
.attr('id', 'timeframe_slider')
.attr('transform', 'translate(200,200)')
.call(yearSlider);
svg2.select('#timeframe_slider').attr('transform', 'translate(200,20)');
timeFrame = yearSlider.value();
}
else {
sliderDefined = false;
timeFrame = 2;
};
// overriding feature in built-in function that makes current selection invisible
d3.selectAll('.axis .tick text').style('stroke-width', 0).attr('font-size', '12px').style('opacity', 1);
// making ticks on axis black
d3.selectAll('.axis line').style('stroke', 'black');
// var linkNodes = [];
//
// graph.links.forEach(function(link) {
//
// linkNodes.push({
// source: graph.nodes[link.source],
// target: graph.nodes[link.target]
// });
// });
// obtaining arrays of all participant/link fields in the json file.
// these will be used to fill the descriptiveFields and descriptorNameLengths arrays.
oppositeGroupings = {
'node': 'link',
'link': 'node'
},
allPartFields = Object.keys(graph.nodes[0]).sort(),
allLinkFields = Object.keys(graph.links[0]).sort(),
descriptiveFields = {
'node': {
0: {}, 1: {}, 2: {}
},
'link': {
0: {}, 1: {}, 2: {}
}
},
descriptorNameLengths = {
'node': [],
'link': []
},
defaultValues = {
'node': {},
'link': {}
},
// integers refer to options on the slider
descriptiveTags = {
'_x': 0,
'_y': 1,
'_z': 2,
'First Year': '_x',
'Last Year': '_y',
'All Years': '_z'
};
function defaultSelectorCheck(groupingType, dropdownSelectedInput) {
if ( defaultValues[groupingType][timeFrame].includes(dropdownSelectedInput) )
{ return true; }
else
{ return false; }
};
function getNodeDescriptiveValues(sizeField) {
nodeDescriptiveValues = [],
// this will become the sum of all inputs to the radius function
maxDomain = 0,
// this will be used to count the total nodes with null radius sizes.
nullRadiusNodes = 0;
// first defining the data that will ifnnfluence how the svg is defnined
graph.nodes.forEach(function(d) {
// determining totalCasualties across all countries as maxRadiusSize.
// this will make larger numbers proportional to the total across all countries.
// checking for null input or null value in field
if ( isNaN(parseFloat(d[sizeField])) ) {
nullRadiusNodes+=1
nodeDescriptiveValues.push(NaN);
}
else {
// cannot be a negative value
// the plus may need to be removed here
{ maxDomain+=Math.max(0, parseFloat(d[sizeField])) }
// cannot be a negative value
// the plus may need to be removed here
nodeDescriptiveValues.push(Math.max(0, parseFloat(d[sizeField])));
}
});
totalNodes = nodeDescriptiveValues.length;
if ( nullRadiusNodes!=totalNodes ) {
// stdNullRadiusSize is the average of non-null inputs for node size
stdNullRadiusSize = maxDomain/(totalNodes - nullRadiusNodes);
maxDomain+=(stdNullRadiusSize * nullRadiusNodes);
}
else {
maxDomain = 2;
stdNullRadiusSize = maxDomain/totalNodes;
}
return [nodeDescriptiveValues, maxDomain, stdNullRadiusSize, nullRadiusNodes];
};
function getLinkDescriptiveValues(linkDescriptorName) {
// will need to return this array to make it global
linkDescriptiveValues = [];
graph.links.forEach(function(d) {
// returning an array filled with zeros if the selection is 'None'
if ( isNaN(parseFloat(d[linkDescriptorName])) )
{ linkDescriptiveValues.push(0); }
else if ( parseFloat(d[linkDescriptorName]) > 0 )
{ linkDescriptiveValues.push(1); }
else
{ linkDescriptiveValues.push(0); }
});
return linkDescriptiveValues;
};
// the following functions are for both dyadic and participant descriptive fields
function getDefaultSelectors(defaultValues, timeFrameInput, grouping) {
// creating a value for a default descriptor for when no descriptive fields exist
if ( Object.keys(descriptiveFields[grouping][timeFrameInput]).length==0 )
// filling no selection with the default empty value ('None Available') if there are none to choose from.
{ textLabel = 'None Available'; }
// filling no selection with the default empty value ('None selected') if none have been chosen.
else
{ textLabel = 'None Selected'; }
defaultValues[grouping][timeFrameInput] = textLabel;
descriptorNameLengths[grouping].push(getTextWidth(svg2, textLabel, graphMenuTextSize));
return [defaultValues, descriptorNameLengths];
};
for ( var i = 0; i <= allLinkFields.length-1; i++ ) {
// getting an array of all descriptive dyadic fields that have at least one record > 0 (binary yes)
// only pushing first year links if the start year equals the end year
if ( Object.keys(descriptiveTags).includes(allLinkFields[i].slice(-2))==false ) {}
else if ( d3.max(graph.links, function(d) { return d[allLinkFields[i]]; })!=1 ) {}
else {
// nonDescriptiveField = false;
timeFrameInt = descriptiveTags[allLinkFields[i].slice(-2)];
descriptiveFields['link'][timeFrameInt][allLinkFields[i]] = {'values': getLinkDescriptiveValues(allLinkFields[i]) };
// getting an array of name lengths for all items added
descriptorNameLengths['link'].push(getTextWidth(svg2, allLinkFields[i], graphMenuTextSize));
}
};
for ( var i = 0; i <= allPartFields.length-1; i++ ) {
// not including any field in nonDescriptivePartFields (text fields or just fields that don't need to be filtered on)
// not including any field with incomplete data (only zeros or null values)
// getNodeDescriptiveValues will need to be called twice to weed out the nonDescriptiveField tag
if ( Object.keys(descriptiveTags).includes(allPartFields[i].slice(-2))==false )
{ nonDescriptiveField = true; }
else {
nonDescriptiveField = false;
nodeDescriptiveValuesOutput = getNodeDescriptiveValues(allPartFields[i]);
nodeDescriptiveValues = nodeDescriptiveValuesOutput[0];
nullRadiusNodes = nodeDescriptiveValuesOutput[3];
// accounting for when all values in array are zeros
// assuming that any network with all zeros should actually be all nulls
// could happen when descriptive data years do not cover war years
uniqueNodeDescriptiveValues = nodeDescriptiveValues.uniqueNonNull();
}
// flagging all fields that will be removed from analysis due to incomplete or non-applicable data
// flagging all fields that will be removed from analysis due to incomplete or non-applicable data
if ( nonDescriptiveField ) {}
else if ( uniqueNodeDescriptiveValues.length==0 ) {}
// nodeDescriptiveValues only contains zeros
else if ( uniqueNodeDescriptiveValues.length==1 && uniqueNodeDescriptiveValues[0]==0 ) {}
// must have greater than (or equal to) 50% non-null nodes.
// this will prevent improper size comparisons.
else if ( nullRadiusNodes/(nodeDescriptiveValues.length - nullRadiusNodes) >= 0.5 ) {}
// all participants were in the war for the same number of days.
// nothing to compare if all the values are the same (for the same reason).
else if ( allPartFields[i]=='days_at_war_z' && uniqueNodeDescriptiveValues.length==1 ) {}
else {
timeFrameInt = descriptiveTags[allPartFields[i].slice(-2)];
descriptiveFields['node'][timeFrameInt][allPartFields[i]] = {
'values': nodeDescriptiveValues,
'max_domain': nodeDescriptiveValuesOutput[1],
'std_node_size': nodeDescriptiveValuesOutput[2]
};
// getting an array of name lengths for all items added
descriptorNameLengths['node'].push(getTextWidth(svg2, allPartFields[i], graphMenuTextSize));
}
};
function adjustForOneYearWars(groupingType, fieldName, overAllFields) {
newFieldName = fieldName.split('_x')[0] + '_z';
if ( overAllFields.includes(newFieldName)==false ) {
descriptiveFields[groupingType][descriptiveTags['_z']][newFieldName] = descriptiveFields[groupingType][descriptiveTags['_x']][fieldName]
// getting an array of name lengths for all items added
descriptorNameLengths[groupingType].push(getTextWidth(svg2, newFieldName, graphMenuTextSize));
}
return [descriptiveFields, descriptorNameLengths]
};
if ( warDic['single_year_war'] ) {
for ( var i = 0; i <= Object.keys(descriptiveFields['node'][0]).length-1; i++ ) {
adjustForOneYearWarsOutput = adjustForOneYearWars('node', Object.keys(descriptiveFields['node'][0])[i], Object.keys(descriptiveFields['node'][2]));
descriptiveFields = adjustForOneYearWarsOutput[0];
descriptorNameLengths = adjustForOneYearWarsOutput[1];
};
for ( var i = 0; i <= Object.keys(descriptiveFields['link'][0]).length-1; i++ ) {
adjustForOneYearWarsOutput = adjustForOneYearWars('link', Object.keys(descriptiveFields['link'][0])[i], Object.keys(descriptiveFields['link'][2]));
descriptiveFields = adjustForOneYearWarsOutput[0];
descriptorNameLengths = adjustForOneYearWarsOutput[1];
};
};
for ( var i = 0; i <= 2; i++ ) {
linkNullDescriptiveOutput = getDefaultSelectors(defaultValues, i, 'link'),
defaultValues = linkNullDescriptiveOutput[0],
descriptorNameLengths = linkNullDescriptiveOutput[1],
linkDescriptorSelected = defaultValues['link'][timeFrame],
partNullDescriptiveOutput = getDefaultSelectors(defaultValues, i, 'node'),
defaultValues = partNullDescriptiveOutput[0],
descriptorNameLengths = partNullDescriptiveOutput[1],
nodeDescriptorSelected = defaultValues['node'][timeFrame];
};
function nameFitsInNode(svgInput, nodeRadius, nameInput, textSize) {
// adjusting text position when it does not fit inside the node
if ( nodeRadius * 2 > getTextWidth(svgInput, nameInput, textSize) + 15 )
{ return true; }
else
{ return false; }
};
function nameVerticalShift(svgInput, nodeRadius, participantName, textSize) {
// adjusting text position when it does not fit inside the node
if ( nameFitsInNode(svgInput, nodeRadius, participantName, textSize)==false )
{ return nodeRadius + 25; }
else
{ return 5; }
};
function nameHorizontalShift(svgInput, nodeRadius, participantName, textSize) {
// adjusting text position when it does not fit inside the node
if ( nameFitsInNode(svgInput, nodeRadius, participantName, textSize)==false )
{ return 20; }
else
{ return 0; }
};
function getNodeMargins(nodeDescriptiveValues, maxDomain, stdNullRadiusSize) {
minRadiusSize = 1,
maxRadiusSize = 150,
radius = d3.scaleLinear().domain([0, maxDomain]).range([minRadiusSize, maxRadiusSize]),
// addedMarginSize = 5 + linkNodeSize,
addedMarginSize = 5,
// dic for size of all the participant nodes, and size needed around them according to borders and text adjustments
nodeMargins = {
'name': {},
'radius_size': {},
// dic for vertical distance each text label needs to be shifted
'vertical_name_shift': {},
'name_fits_in_node': {},
// dic for horizontal distance each text label needs to be shifted
'horizontal_name_shift': {},
// dic for the lengths of the names of all the participant names on the screen
'name_lengths': {},
// creating four dics to define values that will prevent any nodes, lines, or text from leaving/being cut off from the svg2.
'added_top_margin': {},
'added_bottom_margin': {},
'added_left_margin': {},
'added_right_margin': {}
},
// creating a dummy svg so that the gettextwidth function can be used before any 'real' svgs are defined
svgDummy = d3.select('#war_menu').append('svg').attr('width', 0).attr('height', 0);
// now going through the iterations that needed radius to already be defined
graph.nodes.forEach(function(d) {
// determining totalCasualties across all countries as maxRadiusSize.
// this will make larger numbers proportional to the total across all countries.
// setting a minimum for radius so the node will never completely disappear.
if ( isNaN(parseFloat(nodeDescriptiveValues[d.id])) )
{ currentRadiusSize = radius(stdNullRadiusSize); }
else
{ currentRadiusSize = radius(nodeDescriptiveValues[d.id]); }
nodeMargins['radius_size'][d.id] = currentRadiusSize,
nodeMargins['name'][d.id] = d.participant,
currentNameLength = getTextWidth(svgDummy, d.participant, graphTextSize),
currentNameLengthHalf = currentNameLength/2,
nodeMargins['name_lengths'][d.id] = currentNameLength,
currentVerticalShift = nameVerticalShift(svgDummy, currentRadiusSize, d.participant, graphTextSize),
currentHorizontalShift = nameHorizontalShift(svgDummy, currentRadiusSize, d.participant, graphTextSize),
nodeMargins['vertical_name_shift'][d.id] = currentVerticalShift,
nameFitsInNodeBool = nameFitsInNode(svgDummy, currentRadiusSize, d.participant, graphTextSize),
nodeMargins['name_fits_in_node'][d.id] = nameFitsInNodeBool,
nodeMargins['horizontal_name_shift'][d.id] = currentHorizontalShift;
if ( nameFitsInNodeBool==false ) {
// name vertical shift (which includes nodesize), plus the height of the text, plus a little extra
// text is only a factor for the literal height of the letters
nodeMargins['added_top_margin'][d.id] = currentVerticalShift + parseInt(graphTextSize) + addedMarginSize;
// name vertical shift (which includes nodesize), plus the height of the text, plus a little extra
// don't need to add the text size for bottom margin
nodeMargins['added_bottom_margin'][d.id] = currentVerticalShift + parseInt(graphTextSize) + addedMarginSize;
// plus half the length of the name on the screen, plus horizontal shift, plus a little extra
// without the addedMarginSize, this is the distance from the middle of the node to the left
// not including the radius because that's overlap
nodeMargins['added_left_margin'][d.id] = currentNameLengthHalf + currentHorizontalShift + addedMarginSize;
// plus half the length of the name on the screen, plus horizontal shift, plus a little extra
// without the addedMarginSize, this is the distance from the middle of the node to the right
// not including the radius because that's overlap
nodeMargins['added_right_margin'][d.id] = currentNameLengthHalf + currentHorizontalShift + addedMarginSize;
}
else {
// text is not a factor on the right if the above does not apply
// the node plus a little extra
nodeMargins['added_top_margin'][d.id] = currentRadiusSize + addedMarginSize;
// the node plusd a little extra
nodeMargins['added_bottom_margin'][d.id] = currentRadiusSize + addedMarginSize;
// the node plus a little extra
// text is not a factor on the left if the above does not apply
// don't need to adjust for the name if it is inside the node
nodeMargins['added_left_margin'][d.id] = currentRadiusSize + addedMarginSize;
// the node plus a little extra
// text is not a factor on the right if the above does not apply
// don't need to adjust for the name if it is inside the node
nodeMargins['added_right_margin'][d.id] = currentRadiusSize + addedMarginSize;
}
});
return nodeMargins;
};
getNodeDescriptiveValuesOutput = getNodeDescriptiveValues(null),
nodeDescriptiveValues = getNodeDescriptiveValuesOutput[0],
maxDomain = getNodeDescriptiveValuesOutput[1],
stdNullRadiusSize = getNodeDescriptiveValuesOutput[2],
// base value that will be used to calculate the values appended to the arrays above.
nodeMargins = getNodeMargins(nodeDescriptiveValues, maxDomain, stdNullRadiusSize);
// // base value that will be used to calculate the values appended to the arrays above.
// // including linkNodeSize inside of addedMarginSize.
// var linkNodeSize = 10;
function OnlyOnePrimaryNodeCheck() {
// creating an array of all links by node id
// determining if all links involve the same node.
// using this to evaluate whether there is one, or more than one center node in the network
linkCombinations = [];
graph.links.forEach(function(link) {
linkCombinations.push(Array(parseInt(graph.nodes[link.source].id), parseInt(graph.nodes[link.target].id)).sort());
});
// evaluating all links, starting with the first link defined (could be any)
// this affect aggect the graph layout
nodeID1 = linkCombinations[0][0],
nodeID2 = linkCombinations[0][1],
nodeID1Count = 0,
nodeID2Count = 0,
totalLinks = linkCombinations.length;
// iterating over the first link in the network.
// checking to see if all links contain the same node.
for ( var i = 0; i <= totalLinks-1; i++ ) {
if ( linkCombinations[i].includes(nodeID1) )
{ nodeID1Count+=1 }
if ( linkCombinations[i].includes(nodeID2) )
{ nodeID2Count+=1 }
};
if ( nodeID1Count==totalLinks | nodeID2Count==totalLinks )
{ return true; }
else
{ return false; }
};
onlyOnePrimaryNode = OnlyOnePrimaryNodeCheck();
function createGraphLayout() {
// var graphLayout = d3.forceSimulation(graph.nodes.concat(linkNodes))
graphLayout = d3.forceSimulation(graph.nodes)
.force('charge', d3.forceManyBody().strength(-5000))
.force('center', d3.forceCenter(width/2, (height/3) * 2))
.force('x', d3.forceX(width/2).strength(0.50))
.force('y', d3.forceY((height/3) * 2).strength(0.75))
.force('collision', d3.forceCollide().radius(function(d) { return Math.max(nodeMargins['radius_size'][d.id] + nodeMargins['horizontal_name_shift'][d.id] + 20,
arrayAverage(Object.values(nodeMargins['radius_size'])) + arrayAverage(Object.values(nodeMargins['horizontal_name_shift'])) + 20,
// linkNodeSize,
30); }).strength(1))
// creating conditional rules for defining link distance based on how many primary nodes are in the network.
// link distance can be much greater if there is only one primary node.
.force('link', d3.forceLink(graph.links).id(function(d) { return parseInt(d.id); }).distance(function(d) { if ( onlyOnePrimaryNode )
{ return Math.max(((nodeMargins['radius_size'][d.source.id] + nodeMargins['radius_size'][d.target.id]) * 2) + 125, 200); }
else
{ return Math.max(((nodeMargins['radius_size'][d.source.id] + nodeMargins['radius_size'][d.target.id]) * 2), 100); }
}).strength(0.25))
// linkNodeSize + 20,
.on('tick', ticked);
return graphLayout;
};
// defining graph layout with nodeMargins dictionary
graphLayout = createGraphLayout();
link = svg2.selectAll().append('g')
.data(graph.links)
.enter();
// creating an array that checks whether each node is part of the selected node's primary network.
// I have no idea why but this line doesn't work if I move it anywhere else.
firstDegreeLinks = [];
graph.links.forEach(function(d) {
firstDegreeLinks[d.source.index + '-' + d.target.index] = true;
firstDegreeLinks[d.target.index + '-' + d.source.index] = true;
});
// this function will be used to check if a given link is in the array firstDegreeLinks
function firstDegreeCheck(a, b) {
return a==b || firstDegreeLinks[a + '-' + b];
};
linkStrokeWidth = 1,
nodeStrokeWidth = 1,
linkDashStrokeWidth = 3;