-
Notifications
You must be signed in to change notification settings - Fork 17
/
app_ddi.js
3136 lines (2603 loc) · 116 KB
/
app_ddi.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
//////////
// Globals
// hostname default - the app will use it to obtain the variable metadata
// (ddi) and pre-processed data info if the file id is supplied as an
// argument (for ex., gui.html?dfId=17), but hostname isn't.
// Edit it to suit your installation.
// (NOTE that if the file id isn't supplied, the app will default to the
// local files specified below!)
// NEW: it is also possible now to supply complete urls for the ddi and
// the tab-delimited data file; the parameters are ddiurl and dataurl.
// These new parameters are optional. If they are not supplied, the app
// will go the old route - will try to cook standard dataverse urls
// for both the data and metadata, if the file id is supplied; or the
// local files if nothing is supplied.
// -- L.A.
var production=false;
var private=false;
if(production && fileid=="") {
alert("Error: No fileid has been provided.");
throw new Error("Error: No fileid has been provided.");
}
var dataverseurl="";
if (hostname) {
dataverseurl="https://"+hostname;
} else {
if (production) {
dataverseurl="%PRODUCTION_DATAVERSE_URL%";
} else {
dataverseurl="http://localhost:8080";
}
}
if (fileid && !dataurl) {
// file id supplied; we are going to assume that we are dealing with
// a dataverse and cook a standard dataverse data access url,
// with the fileid supplied and the hostname we have
// either supplied or configured:
dataurl = dataverseurl+"/api/access/datafile/"+fileid;
dataurl = dataurl+"?key="+apikey;
// (it is also possible to supply dataurl to the script directly,
// as an argument -- L.A.)
}
if (!production) {
// base URL for the R apps:
var rappURL = "http://0.0.0.0:8000/custom/";
} else {
var rappURL = "https://beta.dataverse.org/custom/"; //this will change when/if the production host changes
}
// space index
var myspace = 0;
var svg = d3.select("#main.left div.carousel-inner").attr('id', 'innercarousel')
.append('div').attr('class', 'item active').attr('id', 'm0').append('svg').attr('id', 'whitespace');
var logArray = [];
//.attr('width', width)
//.attr('height', height);
var tempWidth = d3.select("#main.left").style("width")
var width = tempWidth.substring(0,(tempWidth.length-2));
/*var tempHeight = d3.select("#main.left").style("height")
var height = tempHeight.substring(0,(tempHeight.length-2));*/
var height = $(window).height() -120; // Hard coding for header and footer and bottom margin.
var forcetoggle=["true"];
var estimated=false;
var estimateLadda = Ladda.create(document.getElementById("btnEstimate"));
var selectLadda = Ladda.create(document.getElementById("btnSelect"));
var rightClickLast = false;
// this is the initial color scale that is used to establish the initial colors of the nodes. allNodes.push() below establishes a field for the master node array allNodes called "nodeCol" and assigns a color from this scale to that field. everything there after should refer to the nodeCol and not the color scale, this enables us to update colors and pass the variable type to R based on its coloring
var colors = d3.scale.category20();
var colorTime=false;
var timeColor = '#2d6ca2';
var colorCS=false;
var csColor = '#419641';
var depVar=false;
var dvColor = '#28a4c9';
var nomColor = '#ff6600';
var subsetdiv=false;
var setxdiv=false;
var varColor = '#f0f8ff'; //d3.rgb("aliceblue");
var selVarColor = '#fa8072'; //d3.rgb("salmon");
var taggedColor = '#f5f5f5'; //d3.rgb("whitesmoke");
var d3Color = '#1f77b4'; // d3's default blue
var grayColor = '#c0c0c0';
var lefttab = "tab1"; //global for current tab in left panel
var righttab = "btnModels"; // global for current tab in right panel
var zparams = { zdata:[], zedges:[], ztime:[], znom:[], zcross:[], zmodel:"", zvars:[], zdv:[], zdataurl:"", zsubset:[], zsetx:[], zmodelcount:0, zplot:[], zsessionid:"", zdatacite:""};
// Radius of circle
var allR = 40;
//Width and height for histgrams
var barwidth = 1.3*allR;
var barheight = 0.5*allR;
var barPadding = 0.35;
var barnumber =7;
var arc0 = d3.svg.arc()
.innerRadius(allR + 5)
.outerRadius(allR + 20)
.startAngle(0)
.endAngle(3.2);
var arc1 = d3.svg.arc()
.innerRadius(allR + 5)
.outerRadius(allR + 20)
.startAngle(0)
.endAngle(1);
var arc2 = d3.svg.arc()
.innerRadius(allR + 5)
.outerRadius(allR + 20)
.startAngle(1.1)
.endAngle(2.2);
var arc3 = d3.svg.arc()
.innerRadius(allR + 5)
.outerRadius(allR + 20)
.startAngle(2.3)
.endAngle(3.3);
var arc4 = d3.svg.arc()
.innerRadius(allR + 5)
.outerRadius(allR + 20)
.startAngle(4.3)
.endAngle(5.3);
// From .csv
var dataset2 = [];
var valueKey = [];
var lablArray = [];
var hold = [];
var allNodes = [];
var allResults = [];
var subsetNodes = [];
var links = [];
var nodes = [];
var transformVar = "";
var summaryHold = false;
var selInteract = false;
var modelCount = 0;
var callHistory = []; // unique to the space. saves transform and subset calls.
var citetoggle = false;
// transformation toolbar options
var transformList = ["log(d)", "exp(d)", "d^2", "sqrt(d)", "interact(d,e)"];
// arry of objects containing allNode, zparams, transform vars
var spaces = [];
var trans = []; //var list for each space contain variables in original data plus trans in that space
// end of (most) global declarations (minus functions)
// collapsable user log
$('#collapseLog').on('shown.bs.collapse', function () {
d3.select("#collapseLog div.panel-body").selectAll("p")
.data(logArray)
.enter()
.append("p")
.text(function(d){
return d;
});
//$("#logicon").removeClass("glyphicon-chevron-up").addClass("glyphicon-chevron-down");
});
$('#collapseLog').on('hidden.bs.collapse', function () {
d3.select("#collapseLog div.panel-body").selectAll("p")
.remove();
//$("#logicon").removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up");
});
// text for the about box
// note that .textContent is the new way to write text to a div
$('#about div.panel-body').text('TwoRavens v0.1 "Dallas" -- The Norse god Odin had two talking ravens as advisors, who would fly out into the world and report back all they observed. In the Norse, their names were "Thought" and "Memory". In our coming release, our thought-raven automatically advises on statistical model selection, while our memory-raven accumulates previous statistical models from Dataverse, to provide cummulative guidance and meta-analysis.'); //This is the first public release of a new, interactive Web application to explore data, view descriptive statistics, and estimate statistical models.";
//
// read DDI metadata with d3:
var metadataurl = "";
if (ddiurl) {
// a complete ddiurl is supplied:
metadataurl=ddiurl;
} else if (fileid) {
// file id supplied; we're going to cook a standard dataverse
// metadata url, with the file id provided and the hostname
// supplied or configured:
metadataurl=dataverseurl+"/api/meta/datafile/"+fileid;
} else {
// neither a full ddi url, nor file id supplied; use one of the sample DDIs that come with
// the app, in the data directory:
// metadataurl="data/qog137.xml"; // quality of government
//metadataurl="data/fearonLaitin.xml"; // This is Fearon Laitin
metadataurl="data/PUMS5small-ddi.xml"; // This is California PUMS subset
//metadataurl="data/BP.formatted-ddi.xml";
//metadataurl="data/FL_insurance_sample-ddi.xml";
//metadataurl="data/strezhnev_voeten_2013.xml"; // This is Strezhnev Voeten
//metadataurl="data/19.xml"; // Fearon from DVN Demo
//metadataurl="data/76.xml"; // Collier from DVN Demo
//metadataurl="data/79.xml"; // two vars from DVN Demo
//metadataurl="data/000.xml"; // one var in metadata
//metadataurl="data/0000.xml"; // zero vars in metadata
}
// Reading the pre-processed metadata:
// Pre-processed data:
var pURL = "";
if (dataurl) {
// data url is supplied
pURL = dataurl+"&format=prep";
} else {
// no dataurl/file id supplied; use one of the sample data files distributed with the
// app in the "data" directory:
//pURL = "data/preprocess2429360.txt"; // This is the Strezhnev Voeten JSON data
// pURL = "data/fearonLaitin.json"; // This is the Fearon Laitin JSON data
//pURL = "data/fearonLaitinNewPreprocess3long.json"; // This is the revised (May 29, 2015) Fearon Laitin JSON data
pURL = "data/preprocessPUMS5small.json"; // This is California PUMS subset
//pURL = "data/FL_insurance_sample.tab.json";
// pURL = "data/qog_pp.json"; // This is Qual of Gov
}
var preprocess = {};
var mods = new Object;
// this is the function and callback routine that loads all external data: metadata (DVN's ddi), preprocessed (for plotting distributions), and zeligmodels (produced by Zelig) and initiates the data download to the server
readPreprocess(url=pURL, p=preprocess, v=null, callback=function(){
d3.xml(metadataurl, "application/xml", function(xml) {
var vars = xml.documentElement.getElementsByTagName("var");
var temp = xml.documentElement.getElementsByTagName("fileName");
zparams.zdata = temp[0].childNodes[0].nodeValue;
// function to clean the citation so that the POST is valid json
function cleanstring(s) {
s=s.replace(/\&/g, "and");
s=s.replace(/\;/g, ",");
s=s.replace(/\%/g, "-");
return s;
}
var cite = xml.documentElement.getElementsByTagName("biblCit");
zparams.zdatacite=cite[0].childNodes[0].nodeValue;
zparams.zdatacite=cleanstring(zparams.zdatacite);
// dataset name trimmed to 12 chars
var dataname = zparams.zdata.replace( /\.(.*)/, "") ; // regular expression to drop any file extension
// Put dataset name, from meta-data, into top panel
d3.select("#dataName")
.html(dataname);
$('#cite div.panel-body').text(zparams.zdatacite);
// Put dataset name, from meta-data, into page title
d3.select("title").html("TwoRavens " +dataname)
//d3.select("#title").html("blah");
// temporary values for hold that correspond to histogram bins
hold = [.6, .2, .9, .8, .1, .3, .4];
var myvalues = [0, 0, 0, 0, 0];
// console.log("GOT HERE A");
// console.log(vars);
for (i=0;i<vars.length;i++) {
valueKey[i] = vars[i].attributes.name.nodeValue;
if(vars[i].getElementsByTagName("labl").length === 0) {lablArray[i]="no label";}
else {lablArray[i] = vars[i].getElementsByTagName("labl")[0].childNodes[0].nodeValue;}
var datasetcount = d3.layout.histogram()
.bins(barnumber).frequency(false)
(myvalues);
// this creates an object to be pushed to allNodes. this contains all the preprocessed data we have for the variable, as well as UI data pertinent to that variable, such as setx values (if the user has selected them) and pebble coordinates
var obj1 = {id:i, reflexive: false, "name": valueKey[i], "labl": lablArray[i], data: [5,15,20,0,5,15,20], count: hold, "nodeCol":colors(i), "baseCol":colors(i), "strokeColor":selVarColor, "strokeWidth":"1", "subsetplot":false, "subsetrange":["", ""],"setxplot":false, "setxvals":["", ""], "grayout":false};
jQuery.extend(true, obj1, preprocess[valueKey[i]]);
// console.log(vars[i].childNodes[4].attributes.type.ownerElement.firstChild.data);
allNodes.push(obj1);
};
// Reading the zelig models and populating the model list in the right panel.
d3.json("data/zelig5models.json", function(error, json) {
if (error) return console.warn(error);
var jsondata = json;
console.log("zelig models json: ", jsondata);
for(var key in jsondata.zelig5models) {
if(jsondata.zelig5models.hasOwnProperty(key)) {
mods[jsondata.zelig5models[key].name[0]] = jsondata.zelig5models[key].description[0];
}
}
d3.json("data/zelig5choicemodels.json", function(error, json) {
if (error) return console.warn(error);
var jsondata = json;
console.log("zelig choice models json: ", jsondata);
for(var key in jsondata.zelig5choicemodels) {
if(jsondata.zelig5choicemodels.hasOwnProperty(key)) {
mods[jsondata.zelig5choicemodels[key].name[0]] = jsondata.zelig5choicemodels[key].description[0];
}
}
scaffolding(callback=layout);
dataDownload();
});
});
});
});
////////////////////////////////////////////
// everything below this point is a function
// scaffolding is called after all external data are guaranteed to have been read to completion. this populates the left panel with variable names, the right panel with model names, the transformation tool, an the associated mouseovers. its callback is layout(), which initializes the modeling space
function scaffolding(callback) {
// establishing the transformation element
d3.select("#transformations")
.append("input")
.attr("id", "tInput")
.attr("class", "form-control")
.attr("type", "text")
.attr("value", "Variable transformation");
// the variable dropdown
d3.select("#transformations")
.append("ul")
.attr("id", "transSel")
.style("display", "none")
.style("background-color", varColor)
.selectAll('li')
.data(["a", "b"]) //set to variables in model space as they're added
.enter()
.append("li")
.text(function(d) {return d; });
// the function dropdown
d3.select("#transformations")
.append("ul")
.attr("id", "transList")
.style("display", "none")
.style("background-color", varColor)
.selectAll('li')
.data(transformList)
.enter()
.append("li")
.text(function(d) {return d; });
//jquery does this well
$('#tInput').click(function() {
var t = document.getElementById('transSel').style.display;
if(t !== "none") { // if variable list is displayed when input is clicked...
$('#transSel').fadeOut(100);
return false;
}
var t1 = document.getElementById('transList').style.display;
if(t1 !== "none") { // if function list is displayed when input is clicked...
$('#transList').fadeOut(100);
return false;
}
// highlight the text
$(this).select();
var pos = $('#tInput').offset();
pos.top += $('#tInput').width();
$('#transSel').fadeIn(100);
return false;
});
$('#tInput').keyup(function(event) {
var t = document.getElementById('transSel').style.display;
var t1 = document.getElementById('transList').style.display;
if(t !== "none") {
$('#transSel').fadeOut(100);
} else if(t1 !== "none") {
$('#transList').fadeOut(100);
}
if(event.keyCode == 13){ // keyup on "Enter"
var n = $('#tInput').val();
var t = transParse(n=n);
if(t === null) {return;}
// console.log(t);
// console.log(t.slice(0, t.length-1));
// console.log(t[t.length-1]);
transform(n=t.slice(0, t.length-1), t=t[t.length-1], typeTransform=false);
}
});
$('#transList li').click(function(event) {
var tvar = $('#tInput').val();
// if interact is selected, show variable list again
if($(this).text() === "interact(d,e)") {
$('#tInput').val(tvar.concat('*'));
selInteract = true;
$(this).parent().fadeOut(100);
$('#transSel').fadeIn(100);
event.stopPropagation();
return;
}
var tfunc = $(this).text().replace("d", "_transvar0");
var tcall = $(this).text().replace("d", tvar);
$('#tInput').val(tcall);
$(this).parent().fadeOut(100);
event.stopPropagation();
transform(n=tvar, t=tfunc, typeTransform=false);
});
// populating the variable list in the left panel
d3.select("#tab1").selectAll("p")
.data(valueKey)
.enter()
.append("p")
.attr("id",function(d){
return d.replace(/\W/g, "_"); // replace non-alphanumerics for selection purposes
}) // perhapse ensure this id is unique by adding '_' to the front?
.text(function(d){return d;})
.style('background-color',function(d) {
if(findNodeIndex(d) > 2) {return varColor;}
else {return hexToRgba(selVarColor);}
})
.attr("data-container", "body")
.attr("data-toggle", "popover")
.attr("data-trigger", "hover")
.attr("data-placement", "right")
.attr("data-html", "true")
.attr("onmouseover", "$(this).popover('toggle');")
.attr("onmouseout", "$(this).popover('toggle');")
.attr("data-original-title", "Summary Statistics");
d3.select("#models")
.style('height', 2000)
.style('overfill', 'scroll');
var modellist = Object.keys(mods);
d3.select("#models").selectAll("p")
.data(modellist)
.enter()
.append("p")
.attr("id", function(d){
return "_model_".concat(d);
})
.text(function(d){return d;})
.style('background-color',function(d) {
return varColor;
})
.attr("data-container", "body")
.attr("data-toggle", "popover")
.attr("data-trigger", "hover")
.attr("data-placement", "top")
.attr("data-html", "true")
.attr("onmouseover", "$(this).popover('toggle');")
.attr("onmouseout", "$(this).popover('toggle');")
.attr("data-original-title", "Model Description")
.attr("data-content", function(d){
return mods[d];
});
if(typeof callback === "function") {
callback(); // this calls layout() because at this point all scaffolding is up and ready
}
}
function layout(v) {
var myValues=[];
nodes = [];
links = [];
if(v === "add" | v === "move") {
d3.select("#tab1").selectAll("p").style('background-color',varColor);
for(var j =0; j < zparams.zvars.length; j++ ) {
var ii = findNodeIndex(zparams.zvars[j]);
if(allNodes[ii].grayout) {continue;}
nodes.push(allNodes[ii]);
var selectMe = zparams.zvars[j].replace(/\W/g, "_");
selectMe = "#".concat(selectMe);
d3.select(selectMe).style('background-color',function(){
return hexToRgba(nodes[j].strokeColor);
});
}
for(var j=0; j < zparams.zedges.length; j++) {
var mysrc = nodeIndex(zparams.zedges[j][0]);
var mytgt = nodeIndex(zparams.zedges[j][1]);
links.push({source:nodes[mysrc], target:nodes[mytgt], left:false, right:true});
}
}
else {
if(allNodes.length > 2) {
nodes = [allNodes[0], allNodes[1], allNodes[2]];
links = [
{source: nodes[1], target: nodes[0], left: false, right: true },
{source: nodes[0], target: nodes[2], left: false, right: true }
];
}
else if(allNodes.length === 2) {
nodes = [allNodes[0], allNodes[1]];
links = [{source: nodes[1], target: nodes[0], left: false, right: true }];
}
else if(allNodes.length === 1){
nodes = [allNodes[0]];
}
else {
alert("There are zero variables in the metadata.");
return;
}
}
panelPlots(); // after nodes is populated, add subset and setx panels
populatePopover(); // pipes in the summary stats shown on mouseovers
// init D3 force layout
var force = d3.layout.force()
.nodes(nodes)
.links(links)
.size([width, height])
.linkDistance(150)
.charge(-800)
.on('tick',tick); // .start() is important to initialize the layout
// define arrow markers for graph links
svg.append('svg:defs').append('svg:marker')
.attr('id', 'end-arrow')
.attr('viewBox', '0 -5 10 10')
.attr('refX', 6)
.attr('markerWidth', 3)
.attr('markerHeight', 3)
.attr('orient', 'auto')
.append('svg:path')
.attr('d', 'M0,-5L10,0L0,5')
.style('fill', '#000');
svg.append('svg:defs').append('svg:marker')
.attr('id', 'start-arrow')
.attr('viewBox', '0 -5 10 10')
.attr('refX', 4)
.attr('markerWidth', 3)
.attr('markerHeight', 3)
.attr('orient', 'auto')
.append('svg:path')
.attr('d', 'M10,-5L0,0L10,5')
.style('fill', '#000');
// line displayed when dragging new nodes
var drag_line = svg.append('svg:path')
.attr('class', 'link dragline hidden')
.attr('d', 'M0,0L0,0');
// handles to link and node element groups
var path = svg.append('svg:g').selectAll('path'),
circle = svg.append('svg:g').selectAll('g');
// mouse event vars
var selected_node = null,
selected_link = null,
mousedown_link = null,
mousedown_node = null,
mouseup_node = null;
function resetMouseVars() {
mousedown_node = null;
mouseup_node = null;
mousedown_link = null;
}
// update force layout (called automatically each iteration)
function tick() {
// draw directed edges with proper padding from node centers
path.attr('d', function(d) {
var deltaX = d.target.x - d.source.x,
deltaY = d.target.y - d.source.y,
dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY),
normX = deltaX / dist,
normY = deltaY / dist,
sourcePadding = d.left ? allR+5 : allR,
targetPadding = d.right ? allR+5 : allR,
sourceX = d.source.x + (sourcePadding * normX),
sourceY = d.source.y + (sourcePadding * normY),
targetX = d.target.x - (targetPadding * normX),
targetY = d.target.y - (targetPadding * normY);
return 'M' + sourceX + ',' + sourceY + 'L' + targetX + ',' + targetY;
});
// if(forcetoggle){
circle.attr('transform', function(d) {
return 'translate(' + d.x + ',' + d.y + ')';
});
// };
}
// add listeners to leftpanel.left. every time a variable is clicked, nodes updates and background color changes. mouseover shows summary stats or model description.
d3.select("#tab1").selectAll("p")
.on("mouseover", function(d) {
// REMOVED THIS TOOLTIP CODE AND MADE A BOOTSTRAP POPOVER COMPONENT
$("body div.popover")
.addClass("variables");
$("body div.popover div.popover-content")
.addClass("form-horizontal");
})
.on("mouseout", function() {
//Remove the tooltip
//d3.select("#tooltip").style("display", "none");
})
.on("click", function varClick(){
if(allNodes[findNodeIndex(this.id)].grayout) {return null;}
d3.select(this)
.style('background-color',function(d) {
var myText = d3.select(this).text();
var myColor = d3.select(this).style('background-color');
var mySC = allNodes[findNodeIndex(myText)].strokeColor;
zparams.zvars = []; //empty the zvars array
if(d3.rgb(myColor).toString() === varColor.toString()) { // we are adding a var
if(nodes.length==0) {
nodes.push(findNode(myText));
nodes[0].reflexive=true;
}
else {nodes.push(findNode(myText));}
return hexToRgba(selVarColor);
}
else { // dropping a variable
nodes.splice(findNode(myText)["index"], 1);
spliceLinksForNode(findNode(myText));
if(mySC==dvColor) {
var dvIndex = zparams.zdv.indexOf(myText);
if (dvIndex > -1) { zparams.zdv.splice(dvIndex, 1); }
//zparams.zdv="";
}
else if(mySC==csColor) {
var csIndex = zparams.zcross.indexOf(myText);
if (csIndex > -1) { zparams.zcross.splice(csIndex, 1); }
}
else if(mySC==timeColor) {
var timeIndex = zparams.ztime.indexOf(myText);
if (timeIndex > -1) { zparams.ztime.splice(timeIndex, 1); }
}
else if(mySC==nomColor) {
var nomIndex = zparams.znom.indexOf(myText);
if (nomIndex > -1) { zparams.znom.splice(dvIndex, 1); }
}
nodeReset(allNodes[findNodeIndex(myText)]);
borderState();
legend();
return varColor;
}
});
panelPlots();
restart();
});
d3.select("#models").selectAll("p") // models tab
.on("mouseover", function(d) {
// REMOVED THIS TOOLTIP CODE AND MADE A BOOTSTRAP POPOVER COMPONENT
})
.on("mouseout", function() {
//Remove the tooltip
//d3.select("#tooltip").style("display", "none");
})
// d3.select("#Display_content")
.on("click", function(){
var myColor = d3.select(this).style('background-color');
d3.select("#models").selectAll("p")
.style('background-color',varColor);
d3.select(this)
.style('background-color',function(d) {
if(d3.rgb(myColor).toString() === varColor.toString()) {
zparams.zmodel = d.toString();
return hexToRgba(selVarColor);
}
else {
zparams.zmodel = "";
return varColor;
}
});
restart();
});
// update graph (called when needed)
function restart() {
// nodes.id is pegged to allNodes, i.e. the order in which variables are read in
// nodes.index is floating and depends on updates to nodes. a variables index changes when new variables are added.
circle.call(force.drag);
if(forcetoggle[0]==="true")
{
force.gravity(0.1);
force.charge(-800);
force.linkStrength(1);
// force.resume();
// circle
// .on('mousedown.drag', null)
// .on('touchstart.drag', null);
}
else
{
force.gravity(0);
force.charge(0);
force.linkStrength(0);
//force.stop();
// force.resume();
}
force.resume();
// path (link) group
path = path.data(links);
// update existing links
// VJD: dashed links between pebbles are "selected". this is disabled for now
path.classed('selected', function(d) { return;})//return d === selected_link; })
.style('marker-start', function(d) { return d.left ? 'url(#start-arrow)' : ''; })
.style('marker-end', function(d) { return d.right ? 'url(#end-arrow)' : ''; });
// add new links
path.enter().append('svg:path')
.attr('class', 'link')
.classed('selected', function(d) { return;})//return d === selected_link; })
.style('marker-start', function(d) { return d.left ? 'url(#start-arrow)' : ''; })
.style('marker-end', function(d) { return d.right ? 'url(#end-arrow)' : ''; })
.on('mousedown', function(d) { // do we ever need to select a link? make it delete..
var obj1 = JSON.stringify(d);
for(var j =0; j < links.length; j++) {
if(obj1 === JSON.stringify(links[j])) {
links.splice(j,1);
}
}
});
// remove old links
path.exit().remove();
// circle (node) group
circle = circle.data(nodes, function(d) {return d.id; });
// update existing nodes (reflexive & selected visual states)
//d3.rgb is the function adjusting the color here.
circle.selectAll('circle')
.classed('reflexive', function(d) { return d.reflexive; })
.style('fill', function(d){
return d3.rgb(d.nodeCol);
//return (d === selected_node) ? d3.rgb(d.nodeCol).brighter() : d3.rgb(d.nodeCol); // IF d is equal to selected_node return brighter color ELSE return normal color
})
.style('stroke', function(d){
return (d3.rgb(d.strokeColor));
})
.style('stroke-width', function(d){
return (d.strokeWidth);
});
// add new nodes
var g = circle.enter()
.append('svg:g')
.attr("id", function(d) {
var myname = d.name+"biggroup";
return (myname);
});
// add plot
g.each(function(d) {
d3.select(this);
if(d.plottype === "continuous") {
densityNode(d, obj=this);
}
else if (d.plottype === "bar") {
barsNode(d, obj=this);
}
});
// add arc tags
// NOTE: this block of code has been commented out to remove the "cross section" and "time series" arc tags. These tags are functioning as intended, but they do not, at present, do anything to change the statistical model or variables. To avoid confusion when using TwoRavens, they have been dropped. To add them back in, simply uncomment the block below.
/*
g.append("path")
.attr("d", arc1)
.attr("id", function(d){
return "timeArc".concat(d.id);
})
.style("fill", "yellow")
.attr("fill-opacity", 0)
.on('mouseover', function(d){
d3.select(this).transition() .attr("fill-opacity", .3)
.delay(0)
.duration(100); //.attr('transform', 'scale(2)');
d3.select("#timeText".concat(d.id)).transition()
.attr("fill-opacity", .9)
.delay(0)
.duration(100);
})
.on('mouseout', function(d){
d3.select(this).transition()
.attr("fill-opacity", 0)
.delay(100)
.duration(500);
d3.select("#timeText".concat(d.id)).transition()
.attr("fill-opacity", 0)
.delay(100)
.duration(500);
})
.on('click', function(d){
setColors(d, timeColor);
legend(timeColor);
restart();
});
g.append("text")
.attr("id", function(d){
return "timeText".concat(d.id);
})
.attr("x", 6)
.attr("dy", 11.5)
.attr("fill-opacity", 0)
.append("textPath")
.attr("xlink:href", function(d){
return "#timeArc".concat(d.id);
})
.text("Time");
g.append("path")
.attr("id", function(d){
return "csArc".concat(d.id);
})
.attr("d", arc2)
.style("fill", csColor)
.attr("fill-opacity", 0)
.on('mouseover', function(d){
d3.select(this).transition()
.attr("fill-opacity", .3)
.delay(0)
.duration(100);
d3.select("#csText".concat(d.id)).transition()
.attr("fill-opacity", .9)
.delay(0)
.duration(100);
})
.on('mouseout', function(d){
d3.select(this).transition()
.attr("fill-opacity", 0)
.delay(100)
.duration(500);
d3.select("#csText".concat(d.id)).transition()
.attr("fill-opacity", 0)
.delay(100)
.duration(500);
})
.on('click', function(d){
setColors(d, csColor);
legend(csColor);
restart();
});
g.append("text")
.attr("id", function(d){
return "csText".concat(d.id);
})
.attr("x", 6)
.attr("dy", 11.5)
.attr("fill-opacity", 0)
.append("textPath")
.attr("xlink:href", function(d){
return "#csArc".concat(d.id);
})
.text("Cross Sec");
*/
g.append("path")
.attr("id", function(d){
return "dvArc".concat(d.id);
})
.attr("d", arc3)
.style("fill", dvColor)
.attr("fill-opacity", 0)
.on('mouseover', function(d){
d3.select(this).transition() .attr("fill-opacity", .3)
.delay(0)
.duration(100);
d3.select("#dvText".concat(d.id)).transition() .attr("fill-opacity", .9)
.delay(0)
.duration(100);
})
.on('mouseout', function(d){
d3.select(this).transition() .attr("fill-opacity", 0)
.delay(100)
.duration(500);
d3.select("#dvText".concat(d.id)).transition() .attr("fill-opacity", 0)
.delay(100)
.duration(500);
})
.on('click', function(d){
setColors(d, dvColor);
legend(dvColor);
restart();
});
g.append("text")
.attr("id", function(d){
return "dvText".concat(d.id);
})
.attr("x", 6)
.attr("dy", 11.5)
.attr("fill-opacity", 0)
.append("textPath")
.attr("xlink:href", function(d){
return "#dvArc".concat(d.id);
})
.text("Dep Var");
g.append("path")
.attr("id", function(d){
return "nomArc".concat(d.id);
})
.attr("d", arc4)
.style("fill", nomColor)
.attr("fill-opacity", 0)
.on('mouseover', function(d){
if(d.defaultNumchar=="character") {return;}
d3.select(this).transition() .attr("fill-opacity", .3)
.delay(0)
.duration(100);
d3.select("#nomText".concat(d.id)).transition() .attr("fill-opacity", .9)
.delay(0)
.duration(100);
})
.on('mouseout', function(d){
if(d.defaultNumchar=="character") {return;}
d3.select(this).transition() .attr("fill-opacity", 0)
.delay(100)
.duration(500);
d3.select("#nomText".concat(d.id)).transition() .attr("fill-opacity", 0)
.delay(100)
.duration(500);
})
.on('click', function(d){
if(d.defaultNumchar=="character") {return;}
setColors(d, nomColor);
legend(nomColor);
restart();
});
g.append("text")
.attr("id", function(d){
return "nomText".concat(d.id);
})
.attr("x", 6)
.attr("dy", 11.5)
.attr("fill-opacity", 0)
.append("textPath")
.attr("xlink:href", function(d){
return "#nomArc".concat(d.id);
})
.text("Nominal");