-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiacollo.js
More file actions
2634 lines (2340 loc) · 84.3 KB
/
diacollo.js
File metadata and controls
2634 lines (2340 loc) · 84.3 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
//-*- Mode: Javascript; coding: utf-8; -*-
//
// File: diacollo.js
// Author: Bryan Jurish <moocow@cpan.org>
// Description: client-side diacollo callbacks & visualization routines
//
// WARNING
// The following code is hacky, messy, sloppy, ugly, and otherwise generally sub-optimal.
// Patches & improvements welcome.
// Continue at your own risk.
//
//-- user query params
var user_query = {};
var user_format = null; //-- save format request, e.g. for motion-charts
var qinfo = null; //-- query info, set e.g. by html mode
var responseData = null; //-- cached response data, for browser-friendly 'save as'
//-- timing
var ttk_elapsed = 0;
var dcp_t0 = 0;
//----------------------------------------------------------------------
// profile queries params
var dcp_url_base = ".";
var dcp_url_local = "./profile.perl";
var dcp_params_default = {
"query" : null,
"date" : null,
"slice" : null,
"score" : null,
"kbest" : null,
"cutoff" : null,
"diff" : null,
"global" : null,
"onepass" : null,
"profile" : null,
"format" : "text",
"debug" : 0,
"groupby": null,
"eps" : 0
};
var dynformats = {
"gmotion" : true,
"hichart" : true,
"bubble" : true,
"cloud": true
};
var scoreNames = {
'f': 'Frequency',
'fm': 'Frequency per Million',
'lf': 'log Frequency',
'lfm': 'log Frequency per Million',
'milf': 'Pointwise Mutual Information * log Frequency',
'mi1': 'Pointwise Mutual Information',
'mi3': 'Mutual Information^3',
'ld': 'log Dice',
'll': 'log Likelihood'
};
//----------------------------------------------------------------------
function dqReady(ddc_url='') {
//-- set preliminary timing info
ddc_url_root = ddc_url
$(".elapsed").text("~" + String(ttk_elapsed) + "\u00a0sec");
//-- setup submit-on-enter for IE
$("#dqForm input[type='text']").keypress(function(e) {
if (e.which==13) { $("#dqForm").submit() }
});
//-- set default query parameters
profileSelectChange();
var param = user_query;
keys(dcp_params_default).forEach(function(k) {
if (param[k] == null) { param[k] = dcp_params_default[k]; }
if (param[k] == null) { delete param[k]; }
if (param[k] == "") { delete param[k]; }
});
if (!param.profile.match(/^diff-/)) {
["query","date","slice"].forEach(function(k) {
delete param["a"+k];
delete param["b"+k];
});
}
if (param.query == null) {
dcpInfoMsg("No 'query' parameter specified - please enter a query.");
return;
}
//-- save and tweak format request
user_format = param.format;
if (Boolean(dynformats[user_format])) {
param.format = "json"; //-- dynamic chart: google motion chart or highcharts 2d plot: query json
}
//-- ui tweaks and timing
dcpStatusMsg("loading","Querying...");
dcp_t0 = $.now();
//-- setup raw link url
var uparam = $.param(param);
var uhref = dcp_url_base + "?" + uparam;
$("#rawLink").prop("href",uhref).text(uhref).show();
//-- setup initial debug table
setupDebugTable({});
//-- check for pre-fetched data (--> loading from local file exported by browser "Save As" function)
if (dcpData != null) {
$("#profileDataD3").hide();
$("#dqForm td label").addClass("disabled");
$("#dqForm").on('submit',function() {
alert("You cannot submit queries from an offline data set!");
return false;
});
document.title += " [exported]";
$(".headers h1").append(" [exported]");
//$("#dqForm, #dqForm input, #dqForm select").prop("disabled",true);
dcpOnComplete(null,"success");
dcpOnSuccess(dcpData,"success",{"responseText":dcpData});
} else {
//-- send request
$.ajax({
type: "GET",
url: dcp_url_local+'?'+uparam,
dataType: "text",
success: dcpOnSuccess,
error: dcpOnError,
complete: dcpOnComplete
})
}
}
//----------------------------------------------------------------------
function setupDebugTable(qinfo = null) {
//-- populate
if (qinfo) {
$("#debug_qcanon").text(qinfo.qcanon ? qinfo.qcanon : "(not available)")
$("#debug_qtemplate").text(qinfo.qtemplate ? qinfo.qtemplate : "(not available)")
}
//-- show/hide
if ($("#in_debug").prop('checked')) {
$(".debugInfo").show();
} else {
$(".debugInfo").hide();
}
}
//----------------------------------------------------------------------
// jqStatusSelection = dcpStatusMsg(cls,msg)
function dcpStatusMsg(cls,msg) {
var st = $("#status");
st.on("click", function() { st.fadeOut(); });
st.attr("class","status "+cls).find(".msg").text(msg);
return st;
}
// dcpErrorMsg(msg)
function dcpErrorMsg(msg,time) { return dcpStatusMsg("error",msg).fadeIn(Number(time)); }
function dcpWarnMsg(msg,time) { return dcpStatusMsg("warning",msg).fadeIn(Number(time)); }
function dcpInfoMsg(msg,time) { return dcpStatusMsg("info",msg).fadeIn(Number(time)); }
function dcpHintMsg(msg,time) { return dcpStatusMsg("info hint",msg).fadeIn(Number(time)); }
function dcpClearMsg(time) { return dcpStatusMsg("","").fadeOut(Number(time)); };
function dcpShowPrefetchHint() {
if (dcpData) {
dcpInfoMsg("Cached result data: you will be unable to submit new queries.").fadeOut(5000);
}
}
function dcpCacheData(data) {
if (dcpData == null) {
$("#diacolloResponseData").text('dcpData = ' + JSON.stringify(data).replace(/</g,'\\u003c').replace(/>/g,'\\u003e') + ';');
}
}
//----------------------------------------------------------------------
var isDiff;
var isAbsDiff;
function dcpOnSuccess(data,textStatus,jqXHR) {
dcpClearMsg();
isDiff = Boolean(user_query.profile.match(/^diff-/));
isAbsDiff = Boolean(isDiff && user_query.diff.match(/^adiff/)); //|min
//-- cache response if appropriate
if (dcpData==null) {
dcpCacheData(jqXHR.responseText);
}
//-- format dispatch
if (user_format == "html" || jqXHR.responseText.match(/<html\b/i)) {
//-- response: html
dcpFormatHtml(data, jqXHR);
}
else if (user_format == "gmotion") {
//-- response: gmotion (google motion chart)
dcpFormatGMotion(data, jqXHR);
}
else if (user_format == "hichart") {
//-- response: hichart (highcharts 2d plot)
dcpFormatHiChart(data, jqXHR);
}
else if (user_format == "bubble") {
//-- response: bubble (d3 bubble chart)
dcpFormatBubble(data, jqXHR);
}
else if (user_format == "cloud") {
//-- response: cloud (d3 cloud)
dcpFormatCloud(data, jqXHR);
}
else {
//-- response: other (treat as text data)
if (user_format == "json") {
var jdata = (data instanceof Object) ? data : $.parseJSON(data);
qinfo = jdata.qinfo;
} else {
qinfo = {};
}
setupDebugTable(qinfo);
$("#profileDataText").text(data).fadeIn();
}
}
//----------------------------------------------------------------------
function dcpOnError(jqXHR, textStatus, errorMsg) {
dcpErrorMsg(textStatus + ": " + errorMsg);
if (textStatus == "error" && jqXHR.responseText.match(/<html\b/i)) {
if (jqXHR.responseText.match(/<h1\b/i)) { dcpClearMsg(); }
$("#errorDiv")
.addClass("error")
.append( $.parseHTML(jqXHR.responseText, document, false) )
.find("h1")
.prepend($("#status .icon").clone());
$("#errorDiv").show();
}
}
//----------------------------------------------------------------------
function dcpOnComplete(jqXHR, textStatus) {
var dcp_t1 = $.now();
var elapsed = (ttk_elapsed + (dcp_t1-dcp_t0)/1000.0);
elapsed = Math.floor(elapsed*10000)/10000.0;
$(".elapsed").hide().text(String(elapsed) + "\u00a0sec").fadeIn();
}
//----------------------------------------------------------------------
function dcpFormatHtml(data, jqXHR) {
//-- parse response
$("#profileDataHtml").empty().append( $.parseHTML(jqXHR.responseText, document, true) );
$("#profileDataHtml").find("table").addClass("dbViewTable dcpTable " + (isDiff ? "diffTable" : "prfTable"));
if ($("#profileDataHtml td").size()==0) {
dcpErrorMsg("Error: no data to display!");
return;
}
$("#profileDataHtml").fadeIn();
//-- setup debug debug
setupDebugTable(qinfo);
//-- parse headers
var cols = [];
$("#profileDataHtml tr:first-child th").each(function(i,th) {
cols.push($(th).text());
});
var ilabel = cols.indexOf("label");
var iscore = cols.indexOf(isDiff ? "diff" : "score");
//-- setup label-change classes
var plabel = '';
$("#profileDataHtml tr:not(:first-child)").each(function(i,tr) {
var label = $(tr).find(":nth-child("+(ilabel+1)+")").text();
if (label != plabel) {
$(tr).addClass("newlabel").attr("id",label);
plabel = label;
}
});
//-- setup ddc kwic links
if (ilabel != -1 && Boolean(ddc_url_root)) {
console.log("enabling kwic in diacollo.js: ddc_url_root -> ", ddc_url_root);
var qtemplate = (qinfo.qtemplate!=null ? qinfo.qtemplate : qinfo.aqtemplate);
$("#profileDataHtml tr:first-child").append("<th/>");
$("#profileDataHtml tr:not(:first-child)").each(function(i,tr) {
var linkhtml;
if (isDiff) {
linkhtml = (kwiclink({"tr":tr,"ilabel":ilabel,
"qtemplate":qinfo.aqtemplate,"text":"KWIC:A","dtrim":/[^0-9].*$/,"dslice":user_query.slice,
"title":"DDC KWIC search for row pairs (QUERY)"
})
+ " "
+ kwiclink({"tr":tr,"ilabel":ilabel,
"qtemplate":qinfo.bqtemplate,"text":"KWIC:B","dtrim":/^.*[^0-9]/,"dslice":user_query.bslice,
"title":"DDC KWIC search for row pairs (~QUERY)"
}));
} else {
linkhtml = kwiclink({"tr":tr,"ilabel":ilabel,"qtemplate":qinfo.qtemplate,"text":"KWIC",
"title":"DDC KWIC search for row pairs"
});
}
$(tr).append('<td class="links">'+linkhtml+'</td>');
});
}
//-- setup score colors
if (true) {
//-- get min, max score values
var max;
$("#profileDataHtml tr:not(:first-child)").find(":nth-child("+(iscore+1)+")").each(function(i,td) {
var val = Number($(td).text());
if (max==null || Math.abs(val) > max) {
max = Math.abs(val);
}
});
//-- insert header
$("#profileDataHtml tr:first-child").append("<th/>");
//-- map to colors
var min = (isAbsDiff || user_query.score == "mi" ? -max : 0);
var ctitle = (isAbsDiff
? "Color-coded association preference (red:a .. blue:b)"
: "Color-coded association preference (red:attract..blue:repel)");
$("#profileDataHtml tr:not(:first-child)").each(function(i,tr) {
$(tr).append('<td title="'+ctitle+'" class="diffColor"><span> </span></td>');
var val = Number($(tr).find("td:nth-child("+(iscore+1)+")").text());
var st = $(tr).find(".diffColor span");
var sz = st.height()+"px";
st.css({"background-color":heatcolorv(val, min, max), width:sz, height:sz});
});
}
//-- jump to fragment if specified
var fragment = locFragment(window.location);
if (fragment != "") {
window.location.hash = '';
window.location.hash = '#'+fragment;
}
}
//----------------------------------------------------------------------
function dcpFormatGMotion(data, jqXHR) {
//-- parse data
data = $.parseJSON(data);
qinfo = data.qinfo;
setupDebugTable(qinfo);
if (data.profiles.length == 0) {
dcpErrorMsg("Error: no data to display!");
return;
}
//-- setup plot area
$(".rawURL").hide();
$("#profileDataChart").addClass("gmChart").fadeIn();
//-- setup chart data
var cstate = '{}'; //-- chart state
var cdata = new google.visualization.DataTable();
cdata.addColumn('string', data.titles.join('/')); //-- 1st column must be item type
cdata.addColumn('number', 'year'); //-- 2nd column must be date ('number' => year)
if (isDiff) {
//-- motion chart: diff
cdata.addColumn('number', 'ascore');
cdata.addColumn('number', 'bscore');
cdata.addColumn('number', 'diff');
data.profiles.forEach(function(p) {
var year = Number(String(p.label).replace(/^0-/,'').replace(/-.*$/,''));
var scoref = p.score;
for (var key in p[scoref]) {
var item = key.replace(/\t/g,'/');
cdata.addRow([item, year, p.prf1[scoref][key], p.prf2[scoref][key], p[scoref][key]]);
}
});
cstate = '{"showTrails":false}';
}
else {
//-- motion chart: profile
cdata.addColumn('number', 'f2');
cdata.addColumn('number', 'f12');
cdata.addColumn('number', 'score');
data.profiles.forEach(function(p) {
var year = Number(p.label);
var scoref = p.score;
for (var key in p[scoref]) {
var item = key.replace(/\t/g,'/');
cdata.addRow([item, year, p.f2[key], p.f12[key], p[scoref][key]]);
}
});
cstate = '{"showTrails":false,"xLambda":0,"yLambda":0}';
}
//-- plot the chart
var chart = new google.visualization.MotionChart(document.getElementById('profileDataChart'));
chart.draw(cdata, {width:600, height:480, state:cstate});
}
//----------------------------------------------------------------------
var hitem2key = {};
function dcpFormatHiChart(data, jqXHR) {
//-- parse data
//data = $.parseJSON(data);
//qinfo = data.qinfo;
if ( !(data = dcpParseFlat(data,{mode:"bubble"})) ) { return; }
if (data.profiles.length == 0) {
dcpErrorMsg("Error: no data to display!");
return;
}
dcpStatusMsg("loading","Rendering...");
//-- hichart: enable "download" icon
$("#d3icons > a").hide();
$("#profileDataD3, #d3icons, #exportBtn").fadeIn();
//-- setup plot data
var cdata = { //-- chart data
chart: {
type: (user_query.debug ? 'line' : 'spline'),
zoomType: 'x'
},
credits: {
enabled: false
},
title: {
text:"DiaCollo Profile"+(isDiff ? " Diff" : "")
},
subtitle: {
text: (isDiff ? (chartTitleString('',1)+' - '+chartTitleString('b',1)) : chartTitleString())
},
xAxis: {
title: { text: 'Date (slice)' },
},
yAxis: {
title: { text: 'Score'+(isDiff ? (' Diff ('+user_query.diff+')') : '')+' ('+scoreNames[user_query.score]+')' }
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0,
padding: 5
//,itemStyle: { "color": "#333333", "cursor": "pointer", "fontSize": "12px", "fontWeight": "normal" }
},
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function (e) {
dcur = dlabels.indexOf(String(this.label).replace(/\./g,"-"));
var idata = items[ itemid[this.series.name.replace(/\//g,"\t")] ];
var dopts = {};
if (!$("#profileDataPopup").is(":visible")) {
dopts.position = {at:"center", of:e}
}
d3InfoPopup(idata, dopts);
}
}
},
marker: {
lineWidth: 1
}
}
},
series: []
};
//-- create hicharts series
var item, di, score;
items.forEach(function(item) {
item.hiseries = { name:item.label, data:[] };
for (var di in dlabels) {
score = item.score[di];
item.hiseries.data.push({x:Number(String(dlabels[di]).replace(/-/g,".")), y:(score==null ? null : score), label:dlabels[di]});
}
cdata.series.push(item.hiseries);
});
//-- setup plot area
$(".rawURL").hide();
$("#profileDataChart").addClass("hcParent").show();
//-- plot the chart
$("#profileDataChart").addClass("hcChart").highcharts(cdata).show();
dcpClearMsg();
}
//----------------------------------------------------------------------
// str = chartTitleString(prefix,parens)
function chartTitleString(prefix,parens) {
if (prefix==null) { prefix = ''; }
var q = user_query[prefix+'query'];
var title = q;
/*
var d = user_query[prefix+'date'];
if (d != null && d != '') {
title += ' ['+d.replace(/:/,'-')+']';
}
var s = user_query[prefix+'slice'];
if (s != null && s != '') {
title += ' /'+s;
}
*/
return Boolean(parens) ? ('('+title+')') : title;
}
//----------------------------------------------------------------------
// d3: common variables & utilities
var dforce, dcloud, dcur, dsnapto, dkeys, dlabels, itemid, items;
var dcpScoreRange; //-- [minScore,maxScore]
var dcpValueNull; //-- null value
var dcpSizeRange; //-- [minSize,maxSize]
var dcpItemSize; //-- interpolating accessor for item size (cloud:font-size, bubble:radius)
var d3InfoCur; //-- currently selected info-popup data
var brushInterp; //-- function variable for brush interpolation
var brushSnap; //-- function variable for brush snap
// data = dcpParseFlat(dataStr,opts)
// + parses profile data into flat d3-friendly format
// + returns true on success; sets $("#status .msg").text() and returns false on error
// + sets globals:
// qinfo = data.qinfo
// dkeys = [$date0,...] (slice key-strings, raw, e.g. "1900-1900" or "0-1750")
// dlabels = [$date0,...] (slice key-strings, trimmed, e.g. "1900" or "1750")
// items = [$itemData0,...]
// itemid = {$itemKey0:$itemId0, ...}
// dcur = $currentSliceIndex //-- may be fractional if inbetween slices
// dcpScoreRange = [min,max]
// dcpSizeRange = [min,max]
// dcpItemSize = function(d,dcur) { ... }
// dcpDateInterp = function(dcur) { ... }
// + where items[itemId] =
// item = {id:$itemId, item:$itemKey, label:$itemLabel, score:[...], value:[...], avalue:[...], sizes:[...], opacity:[...], maxSize:maxSize?}
// + array-valued item data keys are indexed by dlabels[] index
// + calls setupDebugTable() after parsing qinfo()
// + options:
// mode: MODE, //-- parse mode (known values: "bubble", "cloud")
var d3data = null;
function dcpParseFlat(data,opts) {
//-- status message
dcpStatusMsg("loading","Parsing...");
//-- parse JSON data
if (!(data instanceof Object)) { data = $.parseJSON(data); }
d3data = data;
qinfo = data.qinfo;
setupDebugTable(qinfo);
if (data.profiles.length == 0) {
dcpErrorMsg("Error: no data to display!");
return null;
}
//-- options
if (opts==null) { opts={}; }
if (opts.mode==null) { opts.mode="bubble"; }
var isBubble = opts.mode == "bubble";
var isCloud = opts.mode == "cloud";
//-- initialize
dkeys = [];
dlabels = [];
itemid = {};
items = [];
dcur = 0; //-- current subprofile index
//-- get data range
data.profiles.forEach(function (p) { p.range = d3.extent(d3.values(p[p.score])); });
var smin = d3.min(data.profiles, function(p) { return p.range[0]; });
var smax = d3.max(data.profiles, function(p) { return p.range[1]; });
if (smin > 0) { smin = 0; }
if (smax < smin) { smax = smin; }
if (smin==smax) { smin -= 1e-5; smax += 1e-5; }
var amax = Math.max(Math.abs(smin),Math.abs(smax));
dcpScoreRange = [smin,smax];
dcpValueNull = dcpScoreValue(0);
//-- setup scales: size/radius ("sizes" key)
dcpSizeRange = (isBubble
? [8,56] //-- bubble: radius range
: [12,78] //-- cloud: font-size range (in pixels)
);
dcpItemSize = (isAbsDiff
? function(item,pos) { return dcpSizeRange[0] + linterp(item.avalue,pos)*(dcpSizeRange[1]-dcpSizeRange[0]); }
: function(item,pos) { return dcpSizeRange[0] + linterp(item.value,pos) *(dcpSizeRange[1]-dcpSizeRange[0]); }
);
//-- setup formatters (for details popup)
var ffmt = d3.format(",r");
var sfmt = d3.format(user_query.score=="ld" ? ".4r"
: (user_query.score=="f" ? ",r"
: ".4s"));
//-- parse data
var pi, p, pscores, iid, idata, iscore, ivalue, avalue;
for (pi=0; pi < data.profiles.length; ++pi) {
p = data.profiles[pi];
p.label = String(p.label);
dkeys.push(p.label);
//-- simplify label
p.label = p.label.replace(/^([0-9]+)-\1/,'$1').replace(/^0-/,'').replace(/-0$/,'');
dlabels.push(p.label);
pscores = p[p.score];
for (var item in pscores) {
if ((iid=itemid[item]) != null) {
//-- existing item
idata = items[iid];
} else {
//-- new item
itemid[item] = iid = items.length;
items.push(idata={"id":iid,
"item":item,
"label":item.replace(/\t/g, '/'),
"text":item.replace(/\t.*$/,''),
score:[], value:[], avalue:[], sizes:[], opacity:[]
});
if (isDiff) {
idata.N1 = []; //ffmt(p.prf1.N);
idata.N2 = []; //ffmt(p.prf2.N);
idata.af1 = [];
idata.bf1 = [];
idata.af2 = [];
idata.bf2 = [];
idata.af12 = [];
idata.bf12 = [];
idata.ascore=[];
idata.bscore=[];
} else {
idata.N = []; //ffmt(p.N);
idata.f1 = [];
idata.f2 = [];
idata.f12 = [];
}
}
idata.score[pi] = iscore = pscores[item];
idata.value[pi] = ivalue = dcpScoreValue(iscore);
idata.avalue[pi] = avalue = Math.abs(iscore)/amax;
idata.sizes[pi] = dcpItemSize(idata,pi);
idata.opacity[pi] = 1;
if (isDiff) {
idata.N1[pi] = ffmt(p.prf1.N);
idata.N2[pi] = ffmt(p.prf2.N);
idata.af1[pi] = ffmt(p.prf1.f1);
idata.bf1[pi] = ffmt(p.prf2.f1);
idata.af2[pi] = ffmt(p.prf1.f2[item]);
idata.bf2[pi] = ffmt(p.prf2.f2[item]);
idata.af12[pi] = ffmt(p.prf1.f12[item]);
idata.bf12[pi] = ffmt(p.prf2.f12[item]);
idata.ascore[pi] = sfmt(p.prf1[p.score][item]);
idata.bscore[pi] = sfmt(p.prf2[p.score][item]);
} else {
idata.N[pi] = ffmt(p.N);
idata.f1[pi] = ffmt(p.f1);
idata.f2[pi] = ffmt(p.f2[item]);
idata.f12[pi] = ffmt(p.f12[item]);
}
}
}
//-- check again for empty data-set (b/c we might have empty profiles)
if (items.length == 0) {
dcpErrorMsg("Error: no items to display!");
return null;
}
//-- setup date-interpolator
var dltuples = dlabels.map(function(l) { return l.split("-"); });
var dln = d3.max(dltuples, function(tup) { return tup.length; });
if (dln <= 1) {
//-- scalar date-labels: easy interpolation
dcpDateInterp = function(di) { return Math.round(linterp(dlabels,di)); };
} else {
//-- multi-component date-labels: build tuple-wise interpolator
var dlscale = [];
for (i=0; i < dln; ++i) {
dlscale[i] = d3.scale.linear()
.domain(dltuples.map(function(e,ei) { return ei }))
.range(dltuples.map(function(e) { return e[i] }))
.clamp(true);
}
dcpDateInterp = function(di) {
return dlscale.map(function(s) { return Math.round(s(di)) }).join("-");
};
}
//-- setup callbacks
if (isBubble) {
brushInterp = dcpForceInterp;
brushSnap = dcpForceSnap;
}
if (isCloud) {
brushInterp = dcpCloudInterp;
brushSnap = dcpCloudSnap;
}
//-- initialize current subprofile index (dcur) from URL fragment
var fragment = locFragment(window.location);
if (fragment != "" && dlabels.indexOf(fragment) >= 0) {
dcur = dlabels.indexOf(fragment);
} else {
dcur = 0;
}
return data;
}
//----------------------------------------------------------------------
// d3: common: interpolating accessors
function vinterp(frac, x0,x1, missing) {
if (missing==null) missing=0;
return ((1.0-frac)*(x0==null ? missing : x0)) + (frac*(x1==null ? missing : x1));
}
function linterp(l,pos,missing) {
return vinterp(pos-Math.floor(pos), l[Math.floor(pos)], l[Math.ceil(pos)], missing);
}
function dcpItemScore(item,pos) { return linterp(item.score, pos); }
function dcpItemValue(item,pos) { return linterp(item.value, pos, dcpValueNull); }
function dcpItemAbsValue(item,pos) { return linterp(item.avalue, pos); }
//dcpItemSize : function variable
function dcpItemScale(item,pos) { return dcpItemSize(item,pos) / item.maxSize; }
function dcpScoreValue(score) {
return (score-dcpScoreRange[0]) / (dcpScoreRange[1]-dcpScoreRange[0]);
}
//-- dcpItemSat, dcpItemVal: for "old" rainbow-style colors
// + green takes up too much space in these for some reason (~ 4 score points on for diff [-8..8])
// + better differentiation using colorbrewer colors and d3 scale, not as pretty for html though
var dcpItemSat = 1;
var dcpItemVal = 1;
function dcpItemColor(item,pos) { return heatcolorf(dcpItemValue(item,pos), dcpItemSat, dcpItemVal); }
function dcpMinColor() { return heatcolorf(0, dcpItemSat, dcpItemVal); }
function dcpMaxColor() { return heatcolorf(1, dcpItemSat, dcpItemVal); }
function dcpItemOpacity(item,pos,max) {
return (max==null ? 1 : max)*linterp(item.opacity,pos);
}
// interpolator = dcpDateInterpolator(dlabel0,dlabel1)
// + returned function is called as "interpolatedDateLabel = interpolator(t)" with 0 <= t <= 1
function dcpDateInterpolator(dlabel0,dlabel1) {
var d0 = dlabel0.split("-");
var d1 = dlabel1.split("-");
if (d0.length==1) {
return d3.interpolateRound(Number(d0[0]),Number(d1[0]));
} else {
var interp = d0.map(function(e,i){ return d3.interpolateRound(Number(d0[i]),Number(d1[i])); });
return function(t) { return interp.map(function(i) { return i(t) }).join("-"); };
}
}
//--------------------------------------------------------------
// d3: common: node titles (bubble,cloud)
function d3NodeTitleText(d) {
return (d.label + " ~ " + dcpItemScore(d,dcur)
+ (user_query.debug ? (": " + JSON.stringify({id:d.id, value:dcpItemValue(d,dcur), avalue:dcpItemAbsValue(d,dcur), size:dcpItemSize(d,dcur)})) : '')
);
}
//--------------------------------------------------------------
// d3: info popup
function d3InfoPopup(d,opts) {
var dsnap = Math.round(dcur);
var dlabel = dlabels[dsnap];
//-- save current info item
d3InfoCur = {data:d};
var dopts = {
title: d.label,
autoOpen: true,
modal: false,
minHeight: 64,
minWidth: 300,
height: "auto",
width: "auto",
show: {effect:"scale",percent:100, duration:150},
hide: {effect:"scale",percent:0, duration:150},
close: function(e,ui) {
d3InfoCur = null;
d3.selectAll(".node").classed("selected",false);
$(".content").focus();
}
};
if (!$("#profileDataPopup").is(":visible")) {
dopts.position = {at:"center",of:this};
}
for (var o in opts) {
if (o == null) {
delete dopts[o];
} else {
dopts[o] = opts[o];
}
}
var content = (''
+'<span class="ui-helper-hidden-accessible"><input type="text"/></span>' //-- disable ugly jquery-ui autofocus
+'<table class="dcslide">'
+'<tr><th>slice:</th><td class="slice">' + dlabel +'</td></tr>'
+ '<th>score:</th><td class="score">' + d.score[dsnap] + '</td></tr>'
);
var tr = [dkeys[dsnap]].concat(d.item.split("\t"));
if (isDiff) {
d3InfoCur.kwic = {"tr":tr,"ilabel":0,
"qtemplate":qinfo.aqtemplate,"text":"KWIC:A","dtrim":/[^0-9].*$/,"dslice":user_query.slice,
title:"DDC KWIC search for point pairs (QUERY)",
classes:"textButtonSmall kwic"
};
d3InfoCur.bkwic = {"tr":tr,"ilabel":0,
"qtemplate":qinfo.bqtemplate,"text":"KWIC:B","dtrim":/^.*[^0-9]/,"dslice":user_query.bslice,
title:"DDC KWIC search for point pairs (~QUERY)",
classes:"textButtonSmall bkwic"
};
content += (''
+'<tr><th>search:</th><td>'
+ kwiclink(d3InfoCur.kwic)
+ ' '
+ kwiclink(d3InfoCur.bkwic)
+ '</td></tr>'
+'<tr><th>details:</th><td class="diff details">'+(
'<table>'
+'<tr><th>N(a/b):</th><td class="num N1">'+d.N1[dsnap]+'</td><td>/</td><td class="num N2">'+d.N2[dsnap]+'</tr>'
+'<tr><th>f1(a/b):</th><td class="num af1">'+d.af1[dsnap]+'</td><td>/</td><td class="num bf1">'+d.bf1[dsnap]+'</tr>'
+'<tr><th>f2(a/b):</th><td class="num af2">'+d.af2[dsnap]+'</td><td>/</td><td class="num bf2">'+d.bf2[dsnap]+'</tr>'
+'<tr><th>f12(a/b):</th><td class="num af12">'+d.af12[dsnap]+'</td><td>/</td><td class="num bf12">'+d.bf12[dsnap]+'</tr>'
+'<tr><th>score(a/b):</th><td class="num ascore">'+d.ascore[dsnap]+'</td><td>/</td><td class="num bscore">'+d.bscore[dsnap]+'</tr>'
+'</table>'
)
);
} else {
d3InfoCur.kwic = {"tr":tr,"ilabel":0,"qtemplate":qinfo.qtemplate,"text":"KWIC",
title:"DDC KWIC search for point pairs",
classes:"textButtonSmall kwic"
};
content += (''
+'<tr><th>search:</th><td>'
+ kwiclink(d3InfoCur.kwic)
+ '</td></tr>'
+'<tr><th>details:</th><td class="details">'+(
'<table>'
+'<tr><th>N:</th><td class="num N">'+d.N[dsnap]+'</td></tr>'
+'<tr><th>f1:</th><td class="num f1">'+d.f1[dsnap]+'</td></tr>'
+'<tr><th>f2:</th><td class="num f2">'+d.f2[dsnap]+'</td></tr>'
+'<tr><th>f12:</th><td class="num f12">'+d.f12[dsnap]+'</td></tr>'
+'</table>'
)
);
}
var dlg = $("#profileDataPopup").html(content).dialog(dopts);
//-- add node-class
d3.selectAll(".node").classed("selected",false);
d3.select("#g"+d.id).classed("selected",true);
return false;
}
//--------------------------------------------------------------
// d3: info popup: update
function d3InfoPopupUpdate(snapto) {
//-- maybe update info box
if (d3InfoCur != null && snapto != dsnapto) {
var dlg = $("#profileDataPopup");
var d = d3InfoCur.data;
dlg.find(".slice").text(String(dlabels[snapto]));
dlg.find(".score").text(String(d.score[snapto]));
if (d3InfoCur.kwic != null) { d3InfoCur.kwic.tr[0] = dkeys[snapto]; dlg.find(".kwic").prop('href',kwicurl(d3InfoCur.kwic)); }
if (d3InfoCur.bkwic != null) { d3InfoCur.bkwic.tr[0] = dkeys[snapto]; dlg.find(".bkwic").prop('href',kwicurl(d3InfoCur.bkwic)); }
if (isDiff) {
dlg.find(".N1").text(String(d.N1[snapto]));
dlg.find(".N2").text(String(d.N2[snapto]));
dlg.find(".af1").text(String(d.af1[snapto]));
dlg.find(".bf1").text(String(d.bf1[snapto]));
dlg.find(".af2").text(String(d.af2[snapto]));
dlg.find(".bf2").text(String(d.bf2[snapto]));
dlg.find(".af12").text(String(d.af12[snapto]));
dlg.find(".bf12").text(String(d.bf12[snapto]));
dlg.find(".ascore").text(String(d.ascore[snapto]));
dlg.find(".bscore").text(String(d.bscore[snapto]));
} else {
dlg.find(".N").text(String(d.N[snapto]));
dlg.find(".f1").text(String(d.f1[snapto]));
dlg.find(".f2").text(String(d.f2[snapto]));
dlg.find(".f12").text(String(d.f12[snapto]));
}
//dlg.parent().stop(true,true).effect("highlight");
d3.select("#g"+d.id).classed("selected",true);
}
}
//--------------------------------------------------------------
// d3: brush-slider (date-slice selector)
// + see http://bl.ocks.org/mbostock/6452972
// dbrush = d3brush(dlabels, selector, opts)
// + sets global dbrush=brush, bhandle=handle, bsvg=brush-svg
var dbrush, bhandle, bsvg;
function dcpTransportSlider(dlabels, parent_selector, opts) {
//-- setup defaults
if (opts.id==null) opts.id = "d3slider";
if (opts.width==null) opts.width = 800;
if (opts.height==null) opts.height = 50;
var margin = opts.margin==null ? {} : opts.margin;
if (margin.left==null) margin.left = 0;
if (margin.right==null) margin.right = 0;
if (margin.top==null) margin.top = 0;
if (margin.bottom==null) margin.bottom = 0;
if (opts.translate==null) opts.translate = {x:0,y:0};
//debug_log("dcpTransportSlider(dlabels="+JSON.stringify(dlabels)+", parent_selector="+JSON.stringify(parent_selector)+", opts="+JSON.stringify(opts)+")");
//-- common variables
var width = opts.width - margin.left - margin.right;
var height = opts.height - margin.top - margin.bottom;
var xscale = d3.scale.linear() //d3.v4: d3.scaleLinear()
.domain([0,dlabels.length-1])
.range([0,width])
.clamp(true);
var brush = dbrush = d3.svg.brush() //d3.v4: d3.brushX()
.x(xscale) //d3.v4: ???
.extent([dcur, dcur])
.on("brushstart", dcpOnBrushStart) //d3.v4: ???
.on("brush", dcpOnBrush) //d3.v4: ???
.on("brushend", dcpOnBrushEnd) //d3.v4: ???
;
var parent = d3.select(parent_selector);
var svg = bsvg = parent.append("g")
.attr("id", opts.id)
.attr("width", opts.width)
.attr("height", opts.height)
.append("g")
.attr("class","brush")
.attr("transform", "translate(" + (margin.left+opts.translate.x) + "," + (margin.top+opts.translate.y) + ")");
svg.append("title")
.text("Date-slice to display (drag, left/right arrow, Home, End)");
var labelPad = 6;
var dy = 15+labelPad; //height/2;
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + dy + ")")
.call(d3.svg.axis()
.scale(xscale)
.orient("bottom")
//--^ d3.v4: d3.axisBottom(xscale)
.tickSize(12)
.tickPadding(3)
.ticks(dlabels.length-1)
);
$("#profileDataD3").fadeIn(); //-- must be displayed in order to compute sizes
var ticks = svg.selectAll(".x.axis .tick");
ticks
.data(dlabels)
.attr("id",function(d,i) { return "tick"+i; });
ticks.each(function(d,i) { d3.select("#tick"+i+" text").text(d); });
//svg.select(".tick:first-of-type text").style("text-anchor","start");
//svg.select(".tick:last-of-type text").style("text-anchor","end");
//-- check for tick overflow
var nticks = ticks.size();
var tickLabelWidth = [];
ticks.each(function(d,i) { tickLabelWidth.push(d3.select("#tick"+i+" text").node().getComputedTextLength()); });
var tickPad = 5;
var tickWidthMax = d3.max(tickLabelWidth) + tickPad;
var tickmod = 1;
while ( (nticks/tickmod)*tickWidthMax >= opts.width ) {
++tickmod;
}
ticks.each(function(d,i) {
if ((i % tickmod) != 0) {
d3.select("#tick"+i).classed("minor",true);
}
});
//-- setup slider
var slider = svg.append("g")
.attr("class", "slider")
.call(brush);
slider.selectAll(".extent,.resize")
.remove();