-
Notifications
You must be signed in to change notification settings - Fork 2
/
dashboard.js
1288 lines (1148 loc) · 52.3 KB
/
dashboard.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
/*
* Array of colours suited for time series colours etc
*/
var timeseriesColors = ["#5B87FF", "#FFC447", "#865BFF", "#FFE147"]; // colors for four series, add more?
/**
* Calculates difference in days between two dates
* @param {Date} date1 A Date object
* @param {Date} date2 A Date object
* @returns {Number} Difference in days between date2 and date1
*/
function daydiff(date1, date2) {
var day = 1000*60*60*24;
var diff = Math.floor((date2.getTime()-date1.getTime())/(day));
return diff;
}
/**
* Generates a function to compute the interquartile range. Used by drawBoxPlot for whisker length determination
* @param {Number} k whisker limit factor for boxplot
* @returns {Function} Function to compute interquartile range based on k.
*/
function iqr(k) {
return function(d) {
var q1 = d.quartiles[0],
q3 = d.quartiles[2],
iqr = (q3 - q1) * k,
i = -1,
j = d.length;
while (d[++i] < q1 - iqr);
while (d[--j] > q3 + iqr);
return [i, j];
};
}
/**
* Sorting function for runchart data sets
* @param {Array} a An array for a project: [pid, num_samples, doneDate, daysX, daysY, ...]
* @param {Array} b An array for a project: [pid, num_samples, doneDate, daysX, daysY, ...]
* @returns {Number} negative values if a should be sorted before b, and positive values if vice versa
*/
function dateValueSort(a, b){
var datediff = a[2] - b[2]; // Date done
if (datediff == 0) {
//return b[1] - a[1]; // longer del times sorted before shorter
if (a[3] == b[3]) { // Delivery time
if (a[0] < b[0]) { // Project ID, lower ID before higher
//console.log("a: " + a[3] + ", " + a[0] + ", " + a[2] + " / " + "b: " + b[3] + ", " + b[0] + ", " + b[2]);
return -1;
} else {
//console.log("a: " + a[3] + ", " + a[0] + ", " + a[2] + " / " + "b: " + b[3] + ", " + b[0] + ", " + b[2]);
return 1;
}
}
return b[3] - a[3]; // longer del times sorted before shorter
} else {
return datediff;
}
}
/**
* Sorting function for project data sets
* @param {Object} a A project object
* @param {Array} b A project object
* @returns {Number} negative values if a should be sorted before b, and positive values if vice versa, otherwise 0
*/
function sortByQueueArrival (a, b) {
var aV = a["value"];
var bV = b["value"];
var aQD = aV["Queue date"];
var bQD = bV["Queue date"];
var aAD = aV["Arrival date"];
var bAD = bV["Arrival date"];
var aPid = a["key"][0]; // project id
var bPid = b["key"][0]; // project id
//var aAppl = a["key"][2];
//var bAppl = b["key"][2];
if (aQD == "0000-00-00" && bQD == "0000-00-00") {
return 0;
}
if(aQD < bQD) {
if(aQD == "0000-00-00") {
return 1;
} // if no queue date yet => end of queue
return -1;
}
if(aQD > bQD) {
if(bQD == "0000-00-00") {
return -1;
} // if no queue date yet => end of queue
return 1;
}
if(aAD < bAD) { return -1; }
if(aAD > bAD) { return 1; }
if(aPid < bPid) { return -1; }
if(aPid > bPid) { return 1; }
return 0;
}
// Look at calculating and adding a first in queue date. Is this the proper place to do this? On sample level instead?
/**
* Reduces a json object at sample level from statusdb map-reduce view to project level
* @param {Object} jsonview json object of sample level data
* @returns {Object} a reduced json object at project level, sorted on Queue date - Arrival date - proj ID
*/
function reduceToProject(jsonview) {
var rows = jsonview["rows"];
var projects = {};
var prepStarts = {};
// switches for debugging
var debug = false;
var debugID = "P1267"; // Any changes here can be ignored
// Loop through all samples
for (var i = 0; i < rows.length; i++) {
var keys = rows[i]["key"];
var values = rows[i]["value"];
// skip aborted *projects*
var aborted_date = values["Aborted date"];
if (aborted_date != "0000-00-00") {
//console.log("Skipping " + keys[0]);
continue;
}
// Handle aborted *samples*
var aborted = (values["Status"] == "Aborted");
var pid = keys[0]; // project id
var type = keys[1]; // type = Production || Applications
var appl = keys[2]; // application
var pf = keys[3]; // platform
var sid = keys[4]; // sample id
// *** Need to handle start dates here even for aborted samples ****
if(projects[pid] == undefined) { // new project, initialize with keys
projects[pid] = {
"type": type,
"appl": appl,
"pf": pf,
}
for (var valKey in values) {
projects[pid][valKey] = values[valKey]; // intialize all data for proj with values of first sample. This is ok even if sample is aborted
if (debug && pid == debugID) { console.log(sid + " " + valKey + ": " + values[valKey]); }
}
} else {
// update data with appropriat date, or sum up lanes or samples
for (var valKey in values) {
var currVal = values[valKey];
if (debug && pid == debugID) { console.log(sid + " " + valKey + ": " + values[valKey]); }
if (valKey == "Lib prep start") { // capture prep start dates
if (prepStarts[currVal] == undefined) { // no data for this date, so initialize array
prepStarts[currVal] = [ ];
}
prepStarts[currVal].push( projects[pid]); // add project object
}
// set values
if(!aborted && valKey == "Samples" || valKey == "Lanes") {
projects[pid][valKey] += values[valKey];
} else if (valKey.indexOf("start") != -1 && currVal != "0000-00-00") { // get earliest start dates
if (currVal < projects[pid][valKey]) { projects[pid][valKey] = currVal; } // handles 0000-00-00 as well
} else if(!aborted){ // get latest done dates, except 0000-00-00
if (currVal == "0000-00-00" || projects[pid][valKey] == "0000-00-00") { // need to capture if date is already set to 0000-00-00
projects[pid][valKey] = "0000-00-00";
} else if (currVal > projects[pid][valKey]) {
projects[pid][valKey] = currVal;
}
}
}
}
}
var outRows = [];
// go through all projects and put in original structure
for (var pid in projects) {
var newKey = [
pid,
projects[pid]["type"],
projects[pid]["appl"],
projects[pid]["pf"]
];
var newValue = {
"Arrival date":projects[pid]["Arrival date"],
"Rec ctrl start":projects[pid]["Rec ctrl start"],
"Queue date":projects[pid]["Queue date"],
"Lib prep start":projects[pid]["Lib prep start"],
"QC library finished":projects[pid]["QC library finished"],
"Sequencing start":projects[pid]["Sequencing start"],
"All samples sequenced":projects[pid]["All samples sequenced"],
"All raw data delivered":projects[pid]["All raw data delivered"],
"Close date":projects[pid]["Close date"],
"Aborted date":projects[pid]["Aborted date"],
"Samples":projects[pid]["Samples"],
"Lanes":parseFloat(Math.round(projects[pid]["Lanes"]).toFixed(2))
};
var newRow = {
"key": newKey,
"value": newValue
}
outRows.push(newRow);
// a bit of debugging code
if (debug && pid == debugID) { console.log(newRow); }
}
// sort in queue order
outRows.sort(sortByQueueArrival);
// get the prep start dates. Not used at the moment
var prepStartsArr = [];
for (var date in prepStarts) {
if (date != "0000-00-00") {
prepStartsArr.push(date);
}
}
prepStartsArr.sort();
return { "rows": outRows };
}
/**
* Generates a dataset for runchart line plot over time from a couchdb view
* @param {Object} jsonview A parsed json stream
* @param {Date} dateRangeStart A Date object to specify start of date range to include
* @param {Date} dateRangeEnd A Date object to specify end of date range to include
* @param {String} dateFromKey A key to identify start date for diff calculation
* @param {String} ptype Which projects to display, 'Production' or 'Application'"
* @param {String} filter A key to identify records to be selected
* @param {Boolean} inverseSelection If true look for absence of filter string
* @returns {Array} An array [ order, pid, num_samples, date, daysX, daysY, ... ]. Times are in days
*/
function generateRunchartDataset (jsonview, dateRangeStart, dateRangeEnd, dateFromKey, dateToKey, ptype, filter, inverseSelection) {
var dataArray = [];
var rows = jsonview["rows"];
var projects = {};
// Some debugging switches
var listIdSwitch = false; // turn on listing of IDs in data set
var listStartKey = "QC library finished"; // specify dateFromKey to trigger ID listing
var listEndKey = "All samples sequenced"; // specify dateToKey to trigger ID listing
// parse debugging settings above
var listIDs = false;
if (dateFromKey == listStartKey && dateToKey == listEndKey && listIdSwitch) {
listIDs = true;
console.log(dateFromKey + " - " + dateToKey);
}
// Each row is one project
for (var i = 0; i < rows.length; i++) {
//console.log("looping through json array: 1");
var keys = rows[i]["key"];
var values = rows[i]["value"];
var pid = keys[0]; // project id
var type = keys[1]; // type = Production || Applications
var appl = keys[2]; // application
var pf = keys[3]; // platform
//var sid = keys[4]; // sample id
if(type !== ptype) { continue; }// if current type is not expected type, skip
if(filter) {
var filter_field;
if(filter.indexOf("library") != -1) {
filter_field = 2; // index for application in keys array
} else if(filter.indexOf("iSeq") != -1) {
filter_field = 3; // index for platform in keys array
}
// more here... ?
if(!inverseSelection) {
if(keys[filter_field] != null && keys[filter_field].indexOf(filter) == -1 ) { continue; }
} else {
if(keys[filter_field] == null || keys[filter_field].indexOf(filter) != -1 ) { continue; }
}
}
// Handle situation where application is "Finished library" and dateFromKey is "QC library finished",
// in which case dateFromKey should be "Queue date"
if (appl == "Finished library" && dateFromKey == "QC library finished") {
dateFromKey = "Queue date";
}
var sampleDateFrom = values[dateFromKey];
var sampleDateTo = values[dateToKey];
if(projects[pid] == undefined) {
projects[pid] = {
"type": type,
"appl": appl,
"pf": pf,
"num_samples": 1,
"fromDate": sampleDateFrom,
"toDate": sampleDateTo,
"daydiff": daydiff(new Date(sampleDateFrom), new Date(sampleDateTo))
}
} else {
if(sampleDateFrom < projects[pid]["fromDate"]) { projects[pid]["fromDate"] = sampleDateFrom; }
if(sampleDateTo > projects[pid]["toDate"]) { projects[pid]["toDate"] = sampleDateTo; }
projects[pid]["daydiff"] = daydiff(new Date(projects[pid]["fromDate"]), new Date(projects[pid]["toDate"]));
projects[pid]["num_samples"]++;
}
}
// out data structure: [ order, pid, num_samples, date, daysX, daysY, ... ]. Order is added after date sort
for (var pid in projects) {
// if fromDate or toDate is 0000-00-00 not all samples are done, so ignore
if (projects[pid]["fromDate"] == "0000-00-00" || projects[pid]["toDate"] == "0000-00-00") { continue; }
//// check if data is in scope
//// within date range
var toDate = new Date(projects[pid]["toDate"]);
if (toDate < dateRangeStart || toDate > dateRangeEnd) { continue; }
//// we find ourselves with a project that has a toDate within range, so write it to the output array
dataArray.push([
pid,
projects[pid]["num_samples"],
new Date(projects[pid]["toDate"]),
projects[pid]["daydiff"],
]);
}
dataArray.sort(dateValueSort);
// add order number as first element in each array
for (var j = 0; j < dataArray.length; j++) {
var tmpdata = dataArray[j];
tmpdata.unshift(j + 1);
// if debugging project ids
if (listIDs) {
console.log(tmpdata[1] + "\t"+ tmpdata[5]);
}
}
return dataArray;
}
/**
* Adds a time series to an existing dataset for runchart line plot over time from a couchdb view
* @param {Object} jsonview A parsed json stream
* @param {Array} dataArray An array of "project arrays" to which an extra time series shall be added
* @param {Date} dateRangeStart A Date object to specify start of date range to include
* @param {Date} dateRangeEnd A Date object to specify end of date range to include
* @param {String} dateFromKey A key to identify start date for diff calculation
* @param {String} ptype Which projects to display, 'Production' or 'Application'"
* @param {String} filter A key to identify records to be selected
* @param {Boolean} inverseSelection If true look for absence of filter string
* @returns {Array} An array [ order, pid, num_samples, date, daysX, daysY, ... ]. Times are in days
*/
function addToRunchartDataset (jsonview, dataArray, dateRangeStart, dateRangeEnd, dateFromKey, dateToKey, ptype, filter, inverseSelection) {
var rows = jsonview["rows"];
var projects = {};
//console.log(dateToKey);
// Each row is one project
for (var i = 0; i < rows.length; i++) {
//console.log("looping through json array: 1");
var keys = rows[i]["key"];
var values = rows[i]["value"];
var pid = keys[0]; // project id
var type = keys[1]; // type = Production || Applications
var appl = keys[2]; // application
var pf = keys[3]; // platform
//var sid = keys[4]; // sample id
if(type != ptype) { continue; }
if(filter) {
var filter_field;
if(filter.indexOf("library") != -1) {
filter_field = 2; // index for application in keys array
} else if(filter.indexOf("iSeq") != -1) {
filter_field = 3; // index for platform in keys array
}
// more here... ?
if(!inverseSelection) {
if(keys[filter_field] != null && keys[filter_field].indexOf(filter) == -1 ) { continue; }
} else {
if(keys[filter_field] == null || keys[filter_field].indexOf(filter) != -1 ) { continue; }
}
}
var sampleDateFrom = values[dateFromKey];
var sampleDateTo = values[dateToKey];
//console.log(pid + ": " + sampleDateTo);
if(projects[pid] == undefined) {
projects[pid] = {
"type": type,
"appl": appl,
"pf": pf,
"num_samples": 1,
"fromDate": sampleDateFrom,
"toDate": sampleDateTo,
"daydiff": daydiff(new Date(sampleDateFrom), new Date(sampleDateTo))
}
} else {
if(sampleDateFrom < projects[pid]["fromDate"]) { projects[pid]["fromDate"] = sampleDateFrom; }
if(sampleDateTo > projects[pid]["toDate"]) { projects[pid]["toDate"] = sampleDateTo; }
projects[pid]["daydiff"] = daydiff(new Date(projects[pid]["fromDate"]), new Date(projects[pid]["toDate"]));
projects[pid]["num_samples"]++;
}
}
//console.log(projects);
// out data structure: [ order, pid, num_samples, date, daysX, daysY, ... ]. Order is added after date sort
//// THIS SHOULD GO AWAY
//for (var pid in projects) {
// // if fromDate or toDate is 0000-00-00 not all samples are done, so ignore
// if (projects[pid]["fromDate"] == "0000-00-00" || projects[pid]["toDate"] == "0000-00-00") { continue; }
//
// //// check if data is in scope
// //// within date range
// var toDate = new Date(projects[pid]["toDate"]);
// if (toDate < dateRangeStart || toDate > dateRangeEnd) { continue; }
//
// //// we find ourselves with a project that has a toDate within range, so write it to the output array
// dataArray.push([
// pid,
// projects[pid]["num_samples"],
// new Date(projects[pid]["toDate"]),
// projects[pid]["daydiff"]
// ]);
//}
var tmpID=0
var temDiff=0
for (var j = 0; j < dataArray.length; j++) {
tmpID = dataArray[j][1]; // pid
if(projects.hasOwnProperty(tmpID)){
tmpDiff = projects[tmpID]["daydiff"];
}else{
console.log("did not find project "+tmpID)
tmpDiff=0
}
//console.log(tmpID + ": " + tmpDiff);
dataArray[j].push(tmpDiff);
}
//// THIS IS NOT NEEDED
//dataArray.sort(dateValueSort);
//// add order number as first element in each array
//for (var j = 0; j < dataArray.length; j++) {
// var tmpdata = dataArray[j];
// tmpdata.unshift(j + 1);
// //console.log(tmpdata[4]); // project ID
//}
return dataArray;
}
/**
* Generates a dataset for boxplots based on a specified index of the values
* @param {Array} dataset An array of arrays (the dataset used to generate the runchart)
* @param {Number} index index of the array that contains the value
* @returns {Array} An array of arrays of values.
*/
function generateGenericBoxDataset (dataset, index) {
var dataArray = [];
dataArray[0] = [];
for (var i = 0; i<dataset.length; i++) {
var value = dataset[i][index];
if (isNaN(value)) { continue; }
dataArray[0].push(value);
}
return dataArray;
}
// calculate # lanes started for sequencing. WORK IN PROGRESS
function calculateLanesStarted (json, startDate, cmpDate) {
var jsonrows = json.rows;
var dateFormat = d3.time.format("%Y-%m-%d");
var cmpDateStr = dateFormat(cmpDate); // Turn cmp date into a string to compare to dates in data
var startDateStr = dateFormat(startDate);
//console.log(startDateStr + " - " + cmpDateStr);
var tot = { HiSeq: 0, MiSeq: 0, HiSeqSamples: 0, MiSeqSamples: 0 };
for (var i=0; i<jsonrows.length; i++) {
var seqStartDate = jsonrows[i]["value"]["Sequencing start"];
var pf = jsonrows[i]["key"][3];
if (pf != "MiSeq") {
pf = "HiSeq";
}
if (seqStartDate >= startDateStr && seqStartDate <= cmpDateStr) {
var lanes = jsonrows[i]["value"]["Lanes"];
//console.log("lanes: " + lanes);
tot[pf] += lanes;
if(pf == "HiSeq") {
tot["HiSeqSamples"]++;
} else if (pf == "MiSeq") {
tot["MiSeqSamples"]++;
}
}
}
tot.HiSeq = parseFloat(tot.HiSeq).toFixed(1);
tot.MiSeq = parseFloat(tot.MiSeq).toFixed(1);
return tot;
}
// calculate # lanes started for sequencing. WORK IN PROGRESS
function calculateWorksetsStarted (json, startDate, cmpDate) {
var jsonrows = json.rows;
var dateFormat = d3.time.format("%Y-%m-%d");
var cmpDateStr = dateFormat(cmpDate); // Turn cmp date into a string to compare to dates in data
var startDateStr = dateFormat(startDate);
//console.log(startDateStr + " - " + cmpDateStr);
var tot = { DNA: 0, RNA: 0, SeqCap: 0, Other: 0 };
for (var i=0; i<jsonrows.length; i++) {
var prepStartDate = jsonrows[i]["value"]["Lib prep start"];
var appl = jsonrows[i]["key"][2];
//console.log(appl);
var applCat = "";
if(appl == null) {
applCat = "Other";
} else if (appl.indexOf("capture") != -1) {
applCat = "SeqCap";
} else if (appl == "Amplicon" ||
appl == "de novo" ||
appl == "Metagenome" ||
appl == "WG re-seq") {
applCat = "DNA";
} else if (appl == "RNA-seq (total RNA)") {
applCat = "RNA";
} else {
applCat = "Other";
}
if (prepStartDate >= startDateStr && prepStartDate <= cmpDateStr) {
tot[applCat]++;
}
}
return tot;
}
/**
* Code to draw the run chart plot
* @param {Object} dataset Parsed json object
* @param {String} divID Id of DOM div to where plot should reside
* @param {Array} clines Array of numbers representing where x week control lines should be drawn, e.g.[6, 10]
* @param {Number} width plot width
* @param {Number} height plot height
* @param {Number} [padding=30] plot padding
* @param {Number} [maxY] Max value of y axis. To be able to draw different panels on the same scale
*/
function drawRunChart(dataset, divID, clines, width, height, padding, maxY) {
// Set default padding
if(padding === undefined) {
padding = 30;
}
// check how many time series there are in the data set
var numSeries = dataset[0].length - 4; // There are four other pieces of information for each project
// DOM id for svg object
var svgID = divID + "SVG";
// DOM id for data line
var dataLineID = divID + "_data_line";
var numProj = dataset.length;
// Time format
var dateFormat = d3.time.format("%Y-%m-%d");
// Get a handle to the tooltip div & calculate appropriate size for mouseover
var tooltipDiv = d3.select(".tooltip");
var tooltipHeight = tooltipDiv.style("height");
// remove last two letters: "px" & turn into an integer
tooltipHeight = parseInt(tooltipHeight.substring(0, tooltipHeight.length - 2));
var tooltipRowHeight = "13"; // 13px per row
var extraTooltipRows = numSeries - 1; // add space for an extra row(s) if more than one time series
var tooltipNewHeight = tooltipHeight + (extraTooltipRows * tooltipRowHeight);
//Create scale functions
if(maxY == undefined) {
maxY = d3.max(dataset, function(d) { return d[4]; }); // This doesn't handle multiple time series...
}
var xScale = d3.scale.linear()
.domain([0, dataset.length])
.range([padding, width - padding * 0.5]);
var yScale = d3.scale.linear()
//.domain([0, d3.max(dataset, function(d) { return d[1]; })])
.domain([0, maxY])
.range([height - padding, padding]);
//Define X axis
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.ticks(0);
//Define Y axis
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(5);
// Get SVG element (or create a new if not existing)
var svg = d3.select("#" + svgID);
var newchart = false;
if(svg[0][0] == null) {
newchart = true;
//Create new SVG element
svg = d3.select("#" + divID)
.append("svg")
.attr("width", width)
.attr("height", height)
.attr("id", svgID);
}
// remove old circles and lines if updating chart
if(!newchart) {
var circlesToRemove = svg.selectAll("circle");
circlesToRemove.remove();
var linesToRemove = svg.selectAll(".line");
linesToRemove.remove();
}
// Create circles
// draw circles and lines for each time series
var circleRadius = 3;
var lines = [];
var circles = svg.selectAll("circle")
.data(dataset)
.enter()
;
for(var i=0; i < numSeries; i++) {
var seriesIndex = i + 4;
var color = timeseriesColors[i]; //timeseriesColors is a global array
circles.append("circle")
.attr("cx", function(d) {
return xScale(d[0]);
})
.attr("cy", function(d) {
//return yScale(d[4]);
var cyPos = d[seriesIndex];
if (isNaN(cyPos)) {
cyPos = -10;
}
return yScale(cyPos);
})
.attr("fill", color)
.attr("r", circleRadius)
.on("mouseover", function(d) {
var timeString = "";
for (j = 4; j < (numSeries + 4); j++) {
timeString += d[j] + " days<br/>";
}
d3.select(this)
.attr("r", circleRadius + 2)
;
// Make tooltip div visible and fill with appropriate text
tooltipDiv.transition()
.duration(200)
.style("opacity", .9);
tooltipDiv.html(d[1] + "<br/>"
+ dateFormat(d[3]) + "<br/>"
+ timeString
)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px")
.style("height", (tooltipNewHeight + "px"))
;
})
.on("mouseout", function(d) { //Remove the tooltip
d3.select(this)
.attr("r", circleRadius)
;
// Make tooltip div invisible & reset height
tooltipDiv.transition()
.duration(300)
.style("opacity", 0)
.style("height", (tooltipHeight + "px"))
;
})
.on("click", function(d) {
var projID = d[1];
var url = "https://genomics-status.scilifelab.se/project/" + projID;
window.open(url, "genomics-status");
})
;
// Add line (needs sorted array for lines to make sense)
var line = d3.svg.line()
.x(function(d) { return xScale(d[0]); })
.y(function(d) {
var y = d[seriesIndex];
if (isNaN(y)) { // hack to handle missing data
y = -10;
}
return yScale(y);
})
;
svg.append("path")
.attr("class", "line")
.attr("d", line(dataset))
.attr("id", dataLineID + i);
}
// create or update axis
if(newchart){
//Create X axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (height - padding) + ")")
.call(xAxis);
//Create Y axis
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + padding + ",0)")
.call(yAxis);
} else {
//Update X axis
svg.select(".x.axis")
.transition()
.duration(1000)
.call(xAxis);
//Update Y axis
svg.select(".y.axis")
.transition()
.duration(1000)
.call(yAxis);
}
// add axis labels
//if(newchart) {
// y axis label
svg.append("text")
.attr("y", padding - 10 )
.attr("x", padding)
.attr("class", "axis_label")
.text("days");
// x axis label
if (!newchart) {
var labelToRemove = svg.selectAll(".axis_label_x");
labelToRemove.remove();
}
svg.append("text")
.attr("y", height - 3)
.attr("x", width)
.attr("class", "axis_label_x")
.text(numProj + " project");
//}
// define a straight line function for control lines
var clLine = d3.svg.line()
.x(function(d) { return xScale(d[0]); })
.y(function(d) { return yScale(d[1]); });
// add control lines
for(var i = 0; i < clines.length; i++) {
var sw = 3;
if (i > 0) { sw = 1.5; }
var lineY = clines[i] * 7;
var lineID = "line_" + clines[i] + "_weeks";
var labelText = clines[i] + " weeks";
var labelOffset = 1;
var labelY = lineY + labelOffset
var labelID = "text_" + clines[i] + "_weeks";
var xTPosition = xScale(0.1);
var yTPosition = yScale(labelY);
if (newchart) {
svg.append("path")
.attr("class", "ucl_line")
.attr("id", lineID)
.attr("stroke-width", sw)
.attr("d", clLine(
[[0, lineY], [dataset.length, lineY]]
))
;
//Create the line label
svg.append("text")
.attr("class", "line_label")
.attr("id", labelID)
.attr("x", xTPosition)
.attr("y", yTPosition)
.text(labelText)
;
} else {
svg.select("#" + lineID)
.transition()
.duration(1000)
.attr("d", clLine(
[[0, lineY], [dataset.length, lineY]]
))
;
//Move the line label
svg.select("#" + labelID)
.transition()
.duration(1000)
.attr("x", xTPosition)
.attr("y", yTPosition)
;
}
}
}
/**
* Code to draw a boxplot
* @param {Object} dataset Parsed data
* @param {String} divID Id of DOM div to where plot should reside
* @param {Number} plotHeight plot height
* @param {Number} [timeseries=1] the timeseries for which to draw the boxplot. Affects the color
*/
function drawBoxPlot(dataset, divID, plotHeight, maxY, bottom_margin, timeseries) {
var margin = {top: 30, right: 20, bottom: 30, left: 20},
width = 54 - margin.left - margin.right,
//height = 450 - margin.top - margin.bottom;
//height = 400 - margin.top - margin.bottom;
height = plotHeight - margin.top - margin.bottom;
// DOM id for svg object
var svgID = divID + "SVG";
//console.log("svgID: " + svgID);
var boxClass = "box";
if (timeseries == 2) {
boxClass = "box2"; // affects which class and css used for graph elements
} else if (timeseries === 3) {
boxClass = "box3";
}
var min = Infinity,
max = -Infinity;
var chart = d3.box()
.whiskers(iqr(1.5))
.width(width)
.height(height);
if (maxY == undefined) {
max = d3.max(dataset[0]);
} else {
max = maxY;
}
//min = d3.min(dataset[0]);
min = 0;
chart.domain([min, max]);
// Get SVG element (or create a new if not existing)
var svg = d3.select("#" + svgID);
var newchart = false;
if(svg[0][0] == null) {
newchart = true;
//Create new SVG element
svg = d3.select("#" + divID).selectAll("svg")
.data(dataset)
.enter().append("svg")
.attr("class", boxClass)
.attr("id", svgID)
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.bottom + margin.top)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(chart)
;
} else {
var g = d3.select("#" + divID)
.selectAll("svg")
.selectAll("g")
.data(dataset)
.transition() // doesn't work!
.duration(1000)
.call(chart)
;
}
}
/**
* Code to draw barchart plot.
* CURRENTLY ONLY USED FOR PROBLEM KPIS, THAT ARE NOT ACTIVE AT THE MOMENT
* @param {Object} dataset Parsed json dataset
* @param {String} divID Id of DOM div to where plot should reside
* @param {Array} labels Array of labels, e.g.["Rec ctrl", "Lib prep", "Seq"]
* @param {Number} width plot width
* @param {Number} height plot height
* @param {Number} [padding=30] plot padding
* @param {Number} [maxY] Max value of y axis. To be able to draw different panels on the same scale
*/
function drawBarchartPlot(dataset, divID, width, height, bottom_padding, maxY) {
var labels = [];
for (var i = 0; i < dataset.length; i++) {
labels.push(dataset[i].key);
}
if (maxY == undefined) {
maxY = d3.max(dataset, function(d) {return d.value;});
}
var xScale = d3.scale.ordinal()
.domain(d3.range(dataset.length))
.rangeRoundBands([0, width], 0.05);
var yScale = d3.scale.linear()
//.domain([0, d3.max(dataset, function(d) { return d.value; })])
.domain([0, maxY])
.range([0, height - bottom_padding]);
//Define key function, to be used when binding data
var key = function(d) {
return d.key;
//return d.step;
};
//Create SVG element
//var svg = d3.select("#barchart")
var svg = d3.select("#" + divID)
.append("svg")
.attr("width", width)
.attr("height", height);
//Create bars
svg.selectAll("rect")
.data(dataset, key) //Bind data with custom key function
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return (height - bottom_padding) - yScale(d.value);
})
.attr("width", xScale.rangeBand())
.attr("height", function(d) {
return yScale(d.value);
})
//.attr("fill", function(d) {
// return "rgb(0, 0, " + (d.value * 10) + ")";
//})
;
var smallFormat = d3.format(".00r");
//Create labels
svg.selectAll("text")
.data(dataset, key) //Bind data with custom key function
.enter()
.append("text")
.text(function(d) {
if(d.value == 0) { return ""; }
if(d.value < 1) { return smallFormat(d.value); }
return d.value;
})
.attr("class", "bar_label")
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return xScale(i) + xScale.rangeBand() / 2;
})
.attr("y", function(d) {
//return (height - bottom_padding) - yScale(d.value) + 14;
return (height - bottom_padding) - yScale(d.value) + 19;
})
;
// Check if there is info about total data set size, and if so add text to show that
var hasTotal = function(dSet) {
for (var i = 0; i < dSet.length; i++) {
if(dSet[i].total) { return true; }
}
return false;
}
if(hasTotal(dataset)) {
//console.log("We have total");
//console.log(dataset);
svg.selectAll("text")
.data(dataset, key) //Bind data with custom key function
.enter()
.append("text")
.text(function(d) {
//if(d.value < 1) { return smallFormat(d.value); }
var totStr = "(" + d.total + ")";
console.log("TotStr: " + totStr);
return totStr;
})
.attr("class", "bar_label")
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return xScale(i) + xScale.rangeBand() / 2;
})