/
cordpub.js
695 lines (590 loc) · 21.9 KB
/
cordpub.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
/*
Assumes d3 and Google's japi have both been loaded. For example,
<script type="text/javascript" src="http://d3js.org/d3.v2.js" charset="utf-8"></script>
<script type="text/javascript" src="http://www.google.com/jsapi?fake=.js" charset="utf-8"></script>
Author: Bob Baxley, bob@rjbaxley.com
License: MIT
*/
if (typeof google == 'undefined') {
console.log('google jsapi not found');
console.log('run: <script type="text/javascript" src="http://www.google.com/jsapi?fake=.js" charset="utf-8"></script>');
}
if (typeof d3 == 'undefined') {
console.log('d3 not found');
console.log('run: <script type="text/javascript" src="http://d3js.org/d3.v2.js" charset="utf-8"></script>');
}
google.load('visualization', '1');
var cordpub = (function() {
function columnToLetter(column) {
column += 1;
var temp, letter = '';
while (column > 0) {
temp = (column - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
column = (column - temp - 1) / 26;
}
return letter;
}
var formatValues = {
Authors: function(value) {
var out = value.split(",");
var author_list = [];
// exclude extra commas
for (k in out){
if (out[k].length>2){
author_list.push(out[k]);
}
}
var num_authors = author_list.length;
if (num_authors > 1) {
return (author_list
.slice(0, num_authors - 1)
.join(', ') + " & " + author_list[num_authors - 1]);
} else {
return author_list[0];
}
},
Month: function(value) {
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
return monthNames[value - 1];
}
}
var formats = {
"Patent": '<div class="row"><div class="type_count col">[P%%Counter%%]</div><div class="citation col">%%Authors%%, %%Title%%, %%Misc_Description%%, %%Month%% %%Year%%.</div></div>',
"Conference": '<div class="row"><div class="type_count col">[C%%Counter%%]</div><div class="citation col">%%Authors%%, "%%Title%%," in <i>Proc. %%Venue%%</i>, pp. %%Pages%%, %%Location%%, %%Month%% %%Year%%.<br>[<a href="https://scholar.google.com/scholar?cites=%%Google_ID%%">cites</a>]</div></div>',
"Journal": '<div class="row"><div class="type_count col">[J%%Counter%%]</div><div class="citation col">%%Authors%%, "%%Title%%," <i>%%Venue%%</i>, vol. %%Volume%%, no. %%Number%%, pp. %%Pages%%, %%Month%% %%Year%%.<br>[<a href="https://scholar.google.com/scholar?cites=%%Google_ID%%">cites</a>]</div></div>',
"Thesis": '<div class="row"><div class="type_count col">[T%%Counter%%]</div><div class="citation col">%%Authors%%, <i>%%Title%%</i>, %%Misc_Description%%, %%Month%% %%Year%%.</div></div>'
};
default_render_cb = function() {}
var defaults = {
"key":'1hkE7P_fHrtiIFAx53xDyUl3gNOp4MSIYLrEwZIJWcaw',
"formats": formats,
"author_list_div": false,
"cord_plot_div": false,
"colorRange": false,
"print_headers": false,
"sort_clause": "order by %%Year%% asc, %%Month%% asc",
"render_callback": default_render_cb
};
defaults.addVals = function(obj) {
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
this[i] = obj[i];
}
}
return this
};
function pubDoc(opts) {
// INPUTS
// key = google sheets key
// add "&gid=[gid]" to query a sheet other than the first sheet
// formats = json of publication type templates
// author_list_div = name of div id for author list; or false to not show
// cord_plot_div = name of div id for cord plot; or false to not show
// colorRange = list of colors or d3 color scale
// Example arguments:
// colorRange = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728"]
// or
// colorRange = d3.scale.category10()
// formats = {
// "Journal": '<div class="row"><div class="type_count col">[J%%Counter%%]</div><div class="citation col">%%Authors%%, "%%Title%%," <i>%%Venue%%</i>, vol. %%Volume%%, no. %%Number%%, pp. %%Pages%%, %%Month%% %%Year%%.</div></div>',
// "Patent": '<div class="row"><div class="type_count col">[P%%Counter%%]</div><div class="citation col">%%Authors%%, %%Title%%, %%Misc_Description%%, %%Month%% %%Year%%.</div></div>'
// }
this.pubs = {};
this.authors = {};
this.year = {};
this.venues = {};
this.authorGraph = new TwoDNamedArray();
this.columsByName = {};
this.columsArray = [];
this.settings = defaults.addVals(opts);
}
pubDoc.prototype.columnifyQuery = function(queryText) {
/*
Converts a string like
"select * order by %%Author%%"
to
"select * order by B"
*/
for (var col = 0; col < this.columsArray.length; col++) {
// replace value in template
queryText = queryText.replace(
"%%" + this.columsArray[col] + "%%",
columnToLetter(col));
}
return queryText
}
pubDoc.prototype.createLabels = function() {
// loop through publication types and store as two jsons
for (var col = 0; col < this.dataTable.getNumberOfColumns(); col++) {
columnLabel = this.dataTable.getColumnLabel(col);
this.columsByName[columnLabel] = col;
this.columsArray[col] = columnLabel;
// check to see if we have a formatter for column
if (typeof formatValues[this.columsArray[col]] == "undefined") {
formatValues[this.columsArray[col]] = function(value) {
return value;
}
}
}
}
pubDoc.prototype.initalizeTypeData = function() {
this.typeCount = {};
this.stringsByType = {}
for (var key in this.formats) {
if (this.formats.hasOwnProperty(key)) {
this.typeCount[key] = 0;
this.stringsByType[key] = [];
}
}
}
pubDoc.prototype.printTable = function() {
for (var key in this.stringsByType) {
if (this.formats.hasOwnProperty(key)) {
d3.select("#" + key)
.html("")
if (this.stringsByType[key].length > 0) {
// add publications
d3.select("#" + key)
.selectAll("div")
.data(this.stringsByType[key])
.enter()
.append("div")
.html(function(d) {
return d;
})
.attr("id", key + "-entries")
.attr("class", "div-table");
if (this.print_headers) {
// add headers
d3.select("#" + key)
.insert("div", ":first-child")
.attr("id", key + "-header")
.attr("class", "key-header")
.text(key.replace("_"," "));
}
}
}
}
}
pubDoc.prototype.createStrings = function() {
/*
Loops through dataTable and applies format template to each row.
*/
this.initalizeTypeData();
// loop through row data
for (var row = 0; row < this.dataTable.getNumberOfRows(); row++) {
// extract type
var pubType = this.dataTable.getFormattedValue(
row,
this.columsByName.Type);
this.typeCount[pubType]++;
// extract template
if (!(pubType in this.formats)) {
console.log("**Error**")
console.log(pubType + " is not in Google Sheet " + this.key);
}
var current = this.formats[pubType];
// replace counter in template
current = current.replace(
"%%Counter%%",
this.typeCount[pubType]);
// loop through columns
for (var col = 0; col < this.columsArray.length; col++) {
// apply formatter for column
var formatted_value = formatValues[this.columsArray[col]](
this.dataTable.getFormattedValue(row, col));
// replace value in template
current = current.replace(
"%%" + this.columsArray[col] + "%%",
formatted_value);
}
this.stringsByType[pubType].push(current);
}
}
pubDoc.prototype.queryBase = function(queryText, callback) {
var baseURL = 'http://docs.google.com/spreadsheet/tq?key=';
var query = new google.visualization.Query(baseURL + this.key);
var th = this
query.setQuery(this.columnifyQuery(queryText));
query.send(function(response) {
callback(response.getDataTable(), th);
});
}
pubDoc.prototype.getAllPubs = function() {
this.queryBase(
"select * " + this.sort_clause,
this.handle_getPubs);
}
pubDoc.prototype.getPubsForAuthor = function(author) {
this.queryBase(
"select * where %%Authors%% contains '" + author + "' " + this.sort_clause,
this.handle_getPubs);
}
pubDoc.prototype.getPubsForYear = function(year) {
this.queryBase(
"select * where %%Year%% = " + year + " " + this.sort_clause,
this.handle_getPubs);
}
pubDoc.prototype.getPubsForVenue = function(venue) {
this.queryBase(
"select * where %%Venue%% = " + venue + " " + this.sort_clause,
this.handle_getPubs);
}
pubDoc.prototype.handle_getPubs = function(dataTable, th) {
// th is the current pubDoc object
th.dataTable = dataTable;
// find publication types
th.createLabels();
// use format template to make html rows for each publication
th.createStrings();
// print table to page
th.printTable();
if (th.cord_plot_div || th.author_list_div) {
// create author graph
th.createTwoDNamedArrayFromTable();
}
if (th.cord_plot_div) {
// draw cord plot
th.drawChordPlot(th.authorGraph, th.cord_plot_div);
}
if (th.author_list_div) {
// draw author links
th.drawAuthorList(th.authorGraph, th.author_list_div);
}
th.settings.render_callback();
}
pubDoc.prototype.createTwoDNamedArrayFromTable = function() {
this.authorGraph = new TwoDNamedArray();
// loop through each row
for (var row = 0; row < this.dataTable.getNumberOfRows(); row++) {
var out =
this.dataTable.getFormattedValue(row, this.columsByName.Authors)
.split(',');
var author_list = [];
// exclude extra commas
for (k in out){
if (out[k].length>2){
author_list.push(out[k]);
}
}
var num_authors = author_list.length;
// create weights for the symetric graph
for (var arow = 0; arow < num_authors; arow++) {
for (var acol = 0; acol < num_authors; acol++) {
var currentWeight = this.authorGraph.getVal(
author_list[arow],
author_list[acol]);
this.authorGraph.setVal(
author_list[arow],
author_list[acol],
1 / (num_authors) + currentWeight);
}
}
}
}
pubDoc.prototype.init = function() {
// google sheets key
this.key = this.settings.key;
// json of formats for each document type
// prints data to div with id equal to json key
console.log(this.settings)
this.formats = this.settings.formats;
this.author_list_div = this.settings.author_list_div;
this.cord_plot_div = this.settings.cord_plot_div;
this.print_headers = this.settings.print_headers;
this.sort_clause = this.settings.sort_clause;
if (this.settings.colorRange) {
// convert list to d3 color scale
if (typeof this.settings.colorRange != "function") {
this.settings.colorRange = d3.scale.ordinal()
.domain(d3.range(this.settings.colorRange.length))
.range(this.settings.colorRange);
}
}
this.colorRange = this.settings.colorRange
this.queryBase(
"select * limit 1",
function(dataTable, th) {
th.dataTable = dataTable;
th.createLabels();
th.getAllPubs();
}
);
}
pubDoc.prototype.mouseHoverSVG = function(i, out) {
d3.select('#' + this.author_list_div)
.select("#aut" + i)
.style("background-color", out ? 'transparent' : this.colorRange(i));
d3.select('#' + this.cord_plot_div)
.selectAll("g.chord path")
.filter(function(d) {
return d.source.index != i && d.target.index != i;
})
.transition()
.style("opacity", out ? 1 : .1);
}
pubDoc.prototype.nameClick = function(i) {
var name = d3.select('#' + this.author_list_div).select("#aut" + i).text();
this.getPubsForAuthor(name);
}
pubDoc.prototype.drawChordPlot = function(data, id, hoverCallback, clickCallback) {
/*
Adds Chord diagram plot to element "id"
Width and height of diagram are inherited from element css
Code based on http://bl.ocks.org/mbostock/4062006
Inputs:
id = element id where plot is created
data = TwoDNamedArray object with plot data
*/
var inVars = data.ob2arr_dict();
var th = this;
// clear element of old vis
document.getElementById(id).innerHTML = '';
var width = document.getElementById(id).offsetWidth;
var height = document.getElementById(id).offsetHeight;
var chord = d3
.layout
.chord()
.padding(.05)
.sortSubgroups(d3.descending)
.matrix((inVars.mat));
var innerRadius = Math.min(width, height) * .41,
outerRadius = innerRadius * 1.1;
var fill = d3.scale.category20c();
// Create SVG
var svg = d3
.select("#" + id)
.append("svg")
.attr("id", 'mainSVG')
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
// Add chords
svg
.append("g")
.attr("class", "chord")
.selectAll("path")
.data(chord.chords)
.enter()
.append("path")
.style("fill", function(d) {
return th.colorRange(d.target.index);
})
.attr("d", d3.svg.chord().radius(innerRadius))
.style("opacity", 1);
// Add chord groups (edges around chords)
var groupPath = svg
.append("g")
.selectAll("path")
.data(chord.groups)
.enter()
.append("path")
.style("fill", function(d) {
return th.colorRange(d.index);
})
.style("stroke", function(d) {
return th.colorRange(d.index);
})
.attr("d", d3.svg.arc().innerRadius(innerRadius).outerRadius(outerRadius))
.on("mouseover", function(g, i) {
th.mouseHoverSVG(i, false);
})
.on("mouseout", function(g, i) {
th.mouseHoverSVG(i, true);
})
.on("mousedown", function(g, i) {
th.nameClick(i);
})
.attr("id", function(d, i) {
return "p" + i;
});
// create chord labels
var groupText = svg
.append("g")
.selectAll("text")
.data(chord.groups)
.enter()
.append("text")
.attr("dy", 15)
.attr("x", 6);
// add text to chord labels
groupText.append("textPath")
.attr("xlink:href", function(d, i) {
return "#p" + i;
})
.text(function(d, i) {
return inVars.labels[i];
})
.on("mouseover", function(g, i) {
th.mouseHoverSVG(i, false);
})
.on("mouseout", function(g, i) {
th.mouseHoverSVG(i, true);
})
.on("mousedown", function(g, i) {
th.nameClick(i);
})
.style("cursor", "default")
.attr("class", "chord_labels");
// Remove the labels that don't fit
groupText
.filter(function(d, i) {
return groupPath[0][i].getTotalLength() / 2 - 30 < this.getComputedTextLength();
})
.remove();
// Add tent objects
var ticks = svg
.append("g")
.selectAll("g")
.data(chord.groups)
.enter()
.append("g")
.selectAll("g")
.data(groupTicks)
.enter()
.append("g")
.attr("transform", function(d) {
return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")" + "translate(" + outerRadius + ",0)";
});
// Add actual tick lines
ticks
.append("line")
.attr("x1", 1)
.attr("y1", 0)
.attr("x2", 5)
.attr("y2", 0)
.style("stroke", "#000");
// Add tick labels
ticks
.append("text")
.attr("x", 8)
.attr("dy", ".35em")
.attr("text-anchor", function(d) {
return d.angle > Math.PI ? "end" : null;
})
.attr("transform", function(d) {
return d.angle > Math.PI ? "rotate(180)translate(-16)" : null;
})
.text(function(d) {
return d.label;
})
.attr("class", "tick_labels");
// Define tick locations
function groupTicks(d) {
var k = (d.endAngle - d.startAngle) / d.value;
return d3.range(0, d.value, 1).map(function(v, i) {
if (v != 0) {
return {
angle: v * k + d.startAngle,
label: (i % 5) ? null : v + ""
};
} else {
return {
angle: v * k + d.startAngle,
label: null
};
}
});
}
}
pubDoc.prototype.drawAuthorList = function(data, id) {
var th = this;
var out = data.ob2arr_dict();
var myNode = document.getElementById(id);
myNode.innerHTML = '';
d3.select("#" + id)
.selectAll("div")
.data(out.labels)
.enter()
.append("div")
.text(function(d, i) {
return out.labels[i];
})
.on("mouseover", function(g, i) {
th.mouseHoverSVG(i, false);
})
.on("mouseout", function(g, i) {
th.mouseHoverSVG(i, true);
})
.on("mousedown", function(g, i) {
th.nameClick(i);
})
.attr("id", function(d, i) {
return "aut" + i;
})
.attr("class", "author_box");
}
function TwoDNamedArray() {
/*
Object that stores named and weighted adjacency matrices
*/
this.arr = {};
}
TwoDNamedArray.prototype.setVal = function(row, col, val) {
if (row in this.arr) {
var temp = this.arr[row];
} else {
var temp = {};
}
temp[col] = val;
this.arr[row] = temp;
}
TwoDNamedArray.prototype.getVal = function(row, col) {
var val = 0;
if (row in this.arr) {
if (col in this.arr[row]) {
var val = this.arr[row][col];
}
}
return val;
}
TwoDNamedArray.prototype.printVals = function(roundfac) {
var html = [];
html.push('[');
for (var kk in this.arr) {
html.push(kk + ' [');
for (var jj in this.arr[kk]) {
html.push(jj + ':' + Math.round(this.arr[kk][jj] * roundfac) / roundfac + ',');
}
html.push(']<br />');
}
html.push(']');
return (html.join(''));
}
TwoDNamedArray.prototype.fill = function() {
for (var kk in this.arr) {
for (var jj in this.arr) {
this.setVal(kk, jj, this.getVal(kk, jj));
}
}
}
TwoDNamedArray.prototype.ob2arr_dict = function() {
var out = [];
var names = [];
var row = 0;
for (var kk in this.arr) {
var col = 0;
var temp = [];
for (var jj in this.arr) {
temp[col] = this.getVal(kk, jj);
col++;
}
out[row] = temp;
names[row] = kk;
row++;
}
return {
mat: out,
labels: names
};
}
return {
cordpub: function(opts) {
return new pubDoc(opts);
}
}
}());