-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
1410 lines (1218 loc) · 39.7 KB
/
main.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
var canvas = document.getElementById('myCanvas');
var modeButtons = document.getElementsByName('mode');
var normalisationButtons = document.getElementsByName('normalisation');
var colourmapButtons = document.getElementsByName('colourmap');
var context = canvas.getContext('2d');
var minimap = document.getElementById('minimap');
var minimapContext = minimap.getContext('2d');
var selectRectCoords = [0,0,0,0];
var mousedown = false;
var shiftFrom= 0;
var isSeriesBrushed = [];
var seriesCount = 100;
var seriesLength = 100;
var labels = [];
let allData = [] // stores data in single flat array, rather than in an array of arrays
var data = new Array(seriesCount);
var dataImage = new Image;
var dataImageStale = true;
var normalise = percentile; // points to the current normalisation function being used
var colourmap = viridisColorString; // current colour map being used
// attributes is an association array of association arrays (dict-of-dicts)
// attributes[i]['attName'] is the attName attribute of the 'i'th series
var attributes = new Array(seriesCount);
var attributesLoaded = false;
var dataMin = Number.MAX_VALUE;
var dataMax = Number.MIN_VALUE;
Array.prototype.unique = function() {
var o = {}, i, l = this.length, r = [];
for(i=0; i<l;i+=1) o[this[i]] = this[i];
for(i in o) r.push(o[i]);
return r;
};
// prepare startup dataset
for(var i=0;i<data.length;i++)
{
data[i] = new Array(seriesLength);
attributes[i] = {};
attributes[i]['even'] = (i%2)==0;
//attributes[i]['odd'] = (i%2)!=0;
labels[i] = i;
isSeriesBrushed[i] = false;
for(var j=0; j<data[i].length; j++)
{
data[i][j] = Math.round((Math.random()*Math.abs(Math.sin(i/5)*Math.sin(j/5)))*100)/100;
if(data[i][j]<dataMin) dataMin = data[i][j];
if(data[i][j]>dataMax) dataMax = data[i][j];
}
}
// load viridis perceptual colourmap
var viridis = [];
loadJSON('viridis.json', function(response) {
// Parse JSON string into object
viridis = JSON.parse(response);
dataImageStale = true;
drawData();
});
attributesLoaded = true;
// need to force numeric sort
allSortedData = (data.reduce(function(a, b) {return a.concat(b);}, [])).sort(function(a, b){return a-b});
allPercentiles = [];
for(let i=allSortedData.length-1; i>=0; i--) allPercentiles[allSortedData[i]] = i/allSortedData.length
var zoomSelector = document.getElementById('zoomSelector');
zoomSelector.addEventListener("change", function() {setDatumSize(zoomSelector.value)});
datumWidth = zoomSelector.value;
datumHeight = datumWidth;
canvas.width = datumWidth*seriesLength;
canvas.height = datumHeight*seriesCount;
drawData();
// scroll event handler
document.addEventListener('scroll', function(evt)
{
const canvasOffset = canvas.getBoundingClientRect().top - document.body.getBoundingClientRect().top
//if(document.body.scrollTop > canvasOffset-40) //document.body.scrollTop is deprecated
if(document.documentElement.scrollTop > canvasOffset-40)
{ // main canvas about to touch top of window
document.getElementById('tools').style.position = 'fixed';
document.getElementById('tools').style.top = '0.5em';
document.getElementById('minimapContainer').style.position = 'fixed';
document.getElementById('minimapContainer').style.top = '4em';
document.getElementById('myCanvas').style.marginLeft='7.5em'
}
else
{
// main canvas far below top of window
document.getElementById('tools').style.position = '';
document.getElementById('tools').style.top = '';
document.getElementById('minimapContainer').style.position = 'relative';
document.getElementById('minimapContainer').style.top = '0px';
document.getElementById('myCanvas').style.marginLeft='0em'
}
var topmostVisiblePixel = document.documentElement.scrollTop - canvasOffset;
var bottomVisiblePixel = Math.min(topmostVisiblePixel+window.innerHeight,canvas.height);
if(topmostVisiblePixel<0) topmostVisiblePixel = 0;
// draw minimap scroll thumb
minimapContext.clearRect(0,0,minimap.width,minimap.height);
drawMinimap();
minimapContext.beginPath();
minimapContext.rect(0,
Math.round((topmostVisiblePixel/canvas.height)*minimap.height),
minimap.width,
// in the expression below, all the extra parenthesis is necessary. Think about it.
Math.round(((bottomVisiblePixel-topmostVisiblePixel)/canvas.height)*minimap.height));
minimapContext.closePath();
minimapContext.fillStyle = 'rgba(0,0,0,0.5)';
minimapContext.fill();
minimapContext.lineWidth = 1;
minimapContext.strokeStyle = 'rgba(0,0,0,1)';
minimapContext.stroke();
}, false);
//drag event handler for minimap
minimap.addEventListener('mousedown', function(mousedownEvent){
const canvasOffset = canvas.getBoundingClientRect().top - document.body.getBoundingClientRect().top
var mousedownPos = getMousePos(minimap, mousedownEvent);
var topmostVisiblePixel = document.documentElement.scrollTop - canvasOffset;
var bottomVisiblePixel = Math.min(topmostVisiblePixel+window.innerHeight,canvas.height);
// if the drag originates from within the minimap scroll 'thumb'
if(mousedownPos.y>Math.round((topmostVisiblePixel/canvas.height)*minimap.height)
&&mousedownPos.y<Math.round((bottomVisiblePixel/canvas.height)*minimap.height))
{
minimap.onmousemove = function(mousemoveEvent){
var mousemovePos = getMousePos(minimap, mousemoveEvent);
var yOffset = mousemovePos.y - mousedownPos.y;
var pixelsFromThumbTop = mousedownPos.y - Math.round((topmostVisiblePixel/canvas.height)*minimap.height);
//console.log(yOffset);
window.scrollTo(0,
Math.round(canvasOffset+(mousemovePos.y/minimap.height)*canvas.height)
-Math.round((pixelsFromThumbTop/minimap.height)*canvas.height));
};
}
}, false);
minimap.addEventListener('mouseup', function(mousedownEvent){
minimap.onmousemove = function(mousemoveEvent){
// Do nothing
};
}, false);
minimap.addEventListener('mouseout', function(mousedownEvent){
minimap.onmousemove = function(mousemoveEvent){
// Do nothing
};
}, false);
// MAIN CANVAS EVENT HANDLERS
// mousemove event handler
canvas.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(canvas, evt);
// note! the select mode has been retired, in favour of the new brushing options
if(currentMode()==='select' && mousedown)
{
context.clearRect(0, 0, canvas.width, canvas.height);
//context.drawImage(imageObj, 0, 0);
drawData();
/* // Old way -- just a freeform rectangle
context.rect(selectRectCoords[0],
selectRectCoords[1],
mousePos.x-selectRectCoords[0],
mousePos.y-selectRectCoords[1]);
*/
var leftest = Math.min(selectRectCoords[0],mousePos.x);
var rightest = Math.max(selectRectCoords[0],mousePos.x);
var toppest = Math.min(selectRectCoords[1],mousePos.y);
var bottomest = Math.max(selectRectCoords[1],mousePos.y);
var firstSelectedTimeCode = Math.round(leftest/datumWidth);
var firstSelectedSeries = Math.floor(toppest/datumHeight);
var lastSelectedTimeCode = Math.round(rightest/datumWidth);
var lastSelectedSeries = Math.floor(bottomest/datumHeight);
context.beginPath();
//context.rect(upperLeftX,upperLeftY,width,height)
context.rect(0,
firstSelectedSeries*datumHeight,
seriesLength*datumWidth,
(lastSelectedSeries-firstSelectedSeries+1)*datumHeight);
// do I need a context.endPath() here?
context.fillStyle = 'rgba(0,0,255,0.3)';
context.fill();
context.lineWidth = 1;
context.strokeStyle = 'rgba(0,0,255,1)';
context.stroke();
}
else if(currentMode()==='selectBrush' && mousedown)
{
var hoverSeries = Math.floor(mousePos.y/datumHeight);
if(!isSeriesBrushed[hoverSeries])
{
isSeriesBrushed[hoverSeries] = true; // brush row
context.fillStyle = "rgba(255,255,255,0.8)";
context.fillRect(0,hoverSeries*datumHeight,datumWidth*seriesLength,datumHeight); // highlight row
}
dataImageStale = true;
}
else if(currentMode()==='deselectBrush' && mousedown)
{
var hoverSeries = Math.floor(mousePos.y/datumHeight);
if(isSeriesBrushed[hoverSeries])
{
isSeriesBrushed[hoverSeries] = false; // unbrush my row... say you'll love me again
for(var j=0; j<seriesLength; j++)
{
var datum = data[hoverSeries][j];
context.fillStyle = colourmap(normalise(datum));
context.fillRect(j*datumWidth,hoverSeries*datumHeight,datumWidth,datumHeight);
}
}
dataImageStale = true;
}
else if(currentMode()==='shift' && mousedown)
{
var shiftTo = Math.floor(mousePos.y/datumHeight);
if(shiftTo!=shiftFrom)
{
shiftSeries(shiftFrom - shiftTo);
shiftFrom = shiftTo;
dataImageStale = true;
drawData();
}
}
else if(currentMode()==='scan')
{
var hoverSeries = Math.floor(mousePos.y/datumHeight);
// console.log(mousePos.y);
/*
There is potential for a small bug here that I have chosen not to fix at this moment.
The bug is that if datumHeight is 1, then hoverSeries stops being a value from 0 to
seriesCount-1, and instead becomes a value from 1 to seriesCount. Now this causes javascript
to throw an exception when you hover over the *last* time series because that index
is too large, i.e. data[hoverSeries] does not exist when hoverSeries = data.length.
Hmmm... there seems to be a related bug where no matter what datumHeight is, if you hover over
the *last few pixels* of the last time series you get a similar TypeError.
This boils down to the fact that you can get a mousePos.y which is canvas height+1 for some reason.
Of course doing floor((canvas.height+1)/datumHeight) results in an index larger than the last hoverSeries.
As this does not impact the working of the software, I have suppressed the errors by returning early.
*/
var hoverElement = Math.floor(mousePos.x/datumWidth);
// skip when bullshit comes out of mousePos resulting in bad hoverSeries
if(data[hoverSeries]===undefined) return;
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(255,255,255,0.8)";
drawData();
drawScanChart(hoverSeries, hoverElement);
context.fillRect(0,hoverSeries*datumHeight,datumWidth*seriesLength,datumHeight); // highlight row
context.fillRect(hoverElement*datumWidth,0,datumWidth,seriesCount*datumHeight); // highlight column
// to get sharp lines in canvas, offset by 0.5
// see: http://diveintohtml5.info/canvas.html (section on 'ask professor markup')
var scanDisplay = document.createElement('div');
scanDisplay.id = 'scanDisplay';
// this is one of the lines that will get messed up if you start only rearranging labels and not the actual data series
scanDisplay.innerHTML="Series "+labels[hoverSeries]+" | Element "+hoverElement+" | Value: "+data[hoverSeries][hoverElement];
scanDisplay.innerHTML+=HTMLTableFromObject(attributes[labels[hoverSeries]]);
//+JSON.stringify(attributes[labels[hoverSeries]]);
document.getElementById('scanChartContainer').appendChild(scanDisplay);
}
}, false);
// mousedown event handler
canvas.addEventListener('mousedown', function(evt)
{
mousedown = true;
var mousePos = getMousePos(canvas, evt);
if(currentMode()==='select')
{
selectRectCoords[0] = mousePos.x;
selectRectCoords[1] = mousePos.y;
}
else if(currentMode()==='shift')
{
/*
shiftFrom contains the index of the row of data where the user
starts dragging from in shift mode. It ignores the fact that the data might have been
rearranged. So if shiftFrom is 5, it just means the user literally started dragging
the 5th row. It doesn't mean this was the 5th series in the original dataset.
*/
shiftFrom = Math.floor(mousePos.y/datumHeight);
}
else if(currentMode()==='selectBrush')
{
var hoverSeries = Math.floor(mousePos.y/datumHeight);
if(!isSeriesBrushed[hoverSeries])
{
isSeriesBrushed[hoverSeries] = true; // brush row
context.fillStyle = "rgba(255,255,255,0.8)";
context.fillRect(0,hoverSeries*datumHeight,datumWidth*seriesLength,datumHeight); // highlight row
}
dataImageStale = true;
}
else if(currentMode()==='deselectBrush')
{
var hoverSeries = Math.floor(mousePos.y/datumHeight);
if(isSeriesBrushed[hoverSeries])
{
isSeriesBrushed[hoverSeries] = false; // unbrush my row... say you'll love me again
for(var j=0; j<seriesLength; j++)
{
var datum = data[hoverSeries][j];
context.fillStyle = colourmap(normalise(datum));
context.fillRect(j*datumWidth,hoverSeries*datumHeight,datumWidth,datumHeight);
}
}
}
}, false);
// mouseup event handler
canvas.addEventListener('mouseup', function(evt)
{
mousedown = false;
var mousePos = getMousePos(canvas, evt);
if(currentMode()==='select')
{
selectRectCoords[2] = mousePos.x;
selectRectCoords[3] = mousePos.y;
}
else if(currentMode()==='scan')
{
// TODO: create a persistent line graph of the series the user has clicked on
// in a separate div for more detailed inspection
}
else if(currentMode()=='shift')
{
dataImage.src = canvas.toDataURL();
dataImageStale = false;
drawMinimap();
}
}, false);
// mouseout event handler
canvas.addEventListener('mouseout', function(evt)
{
if(currentMode()==='scan')
{
var container = document.getElementById('scanChartContainer');
//while(container.firstChild) container.removeChild(container.firstChild);
container.style.display='none';
drawData();
}
}, false);
// mouseover event handler
canvas.addEventListener('mouseover', function(evt)
{
if(currentMode()==='scan')
{
var container = document.getElementById('scanChartContainer');
//while(container.firstChild) container.removeChild(container.firstChild);
container.style.display='initial';
}
}, false);
canvas.style.cursor = 'default'; // stop annoying selection cursor when brushing
// radio button change event handlers
// primarily to change the cursor on the canvas
for(var i=0;i<modeButtons.length;i++)
{
modeButtons[i].onclick = function(evt)
{
if(currentMode()==='shift')
canvas.style.cursor = 'row-resize'; // all-scroll also ok
else
canvas.style.cursor = 'default';
};
}
var normalisationSelector = document.getElementById('normalisationSelector');
normalisationSelector.addEventListener("change", function() {
currentNormalisation = normalisationSelector.value;
if (currentNormalisation === 'percentile')
normalise = percentile;
else
normalise = rangeNormalise;
dataImageStale = true;
drawData();
});
var colourmapSelector = document.getElementById('colourmapSelector');
colourmapSelector.addEventListener("change", function() {
currentColourMap = colourmapSelector.value;
if (currentColourMap === 'grayscale')
colourmap = getGrayscaleColorString;
else if (currentColourMap === 'redyellowgreen')
colourmap = getRedYellowGreenColorString;
else if (currentColourMap === 'viridis')
colourmap = viridisColorString;
else
colourmap = rainbowColorString;
dataImageStale = true;
colourCache = []
drawData();
});
var gatheringStrategySelector = document.getElementById('gatheringStrategySelector');
// sets up explain tabs
window.onload = function() {
const tabs = document.querySelectorAll('.tabs .tab-links a')
for(let i=0; i<tabs.length; i++) {
tabs[i].onclick = function(e) {
var currentAttrValue = event.target.getAttribute("href")
console.log(currentAttrValue)
// Show/Hide Tabs
document.querySelectorAll('.tab').forEach(function(t) {t.style.display = "none"})
document.querySelector('.tabs ' + currentAttrValue).style.display = "block"
// Change/remove current tab to active
document.querySelectorAll('.tab-links li').forEach(function(t) {t.classList.remove('active')})
event.target.parentNode.classList.add('active')
e.preventDefault();
}
}
}
// START FUNCTION DEFINITIONS
function writeMessage(canvas, message)
{
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
context.font = '1em Helvetica';
context.fillStyle = 'black';
context.fillText(message, 10, 25);
}
function getMousePos(canvas, evt)
{
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function getRedGreenColorString(value)
{
var red;
var green;
var blue;
// Straightforward scaling -- creates a muddy green colour
red = value*255;
green = (1-value)*255;
blue = 0;
red = Math.round(red);
green = Math.round(green);
blue = Math.round(blue);
return "rgb("+red+","+green+","+blue+")";
}
// http://stackoverflow.com/questions/5137831/map-a-range-of-values-e-g-0-255-to-a-range-of-colours-e-g-rainbow-red-b
function rainbowColorString(value) {
// value = value * 240; // for red-blue
// final hue value needs to be between 0 and 240 for red-blue. Goes all the way to 360 but that takes you back to red.
value = value * 300; // red-pinkish?
return 'hsl(' + value + ',100%,50%)';
}
function viridisColorString(value) {
const index = Math.ceil(value*(viridis.length-1));
var red;
var green;
var blue;
try {
red = Math.round(viridis[index][0]*255);
green = Math.round(viridis[index][1]*255);
blue = Math.round(viridis[index][2]*255);
}
catch(e) {
// currently do nothing. Was getting a bunch of 0 and -1, should fix that at some point
//console.log('rogue index is '+index);
}
return "rgb("+red+","+green+","+blue+")";
}
function percentile(value)
{
if (allPercentiles[value] === undefined)
{
allPercentiles[value] = (allSortedData.indexOf(value)/allSortedData.length);
}
return allPercentiles[value];
}
function rangeNormalise(value)
{
// mean & range normalisation
// doesn't do so well with negative numbers in range
return (value-dataMin)/Math.abs(dataMax-dataMin);
}
function getRedYellowGreenColorString(value)
{
var red;
var green;
var blue;
blue = 0;
// Goes through green-red hue transition in HSV space
if(value<0.5)
{
green = 255;
red = 2*value*255;
}
else
{
red = 255;
// green = 255 when norm = 0.5, green = 0 when norm = 1.
// Solve the equation of that line and you end up with the following expression.
green = 2*((-255*value)+255);
}
red = Math.round(red);
green = Math.round(green);
blue = Math.round(blue);
//console.log(value+" --> "+normalised+" --> "+ "rgb("+red+","+green+","+blue+")")
return "rgb("+red+","+green+","+blue+")";
}
function getSpecialColorString(value)
{
// doesn't do so well with negative numbers in range
//var normalised = (value-dataMin)/Math.abs(dataMax-dataMin);
// special normalisation for Gatherminer paper panic time
var normalised = 0;
if(value>0) normalised = 0.4;
if(value>1) normalised = 0.6;
if(value>5) normalised = 0.8;
if(value>10) normalised = 0.9;
if(value>20) normalised = 1.0;
var red;
var green;
var blue;
blue = 0;
// Goes through green-red hue transition in HSV space
if(normalised<0.5)
{
green = 255;
red = 2*normalised*255;
}
else
{
red = 255;
// green = 255 when norm = 0.5, green = 0 when norm = 1.
// Solve the equation of that line and you end up with the following expression.
green = 2*((-255*normalised)+255);
}
red = Math.round(red);
green = Math.round(green);
blue = Math.round(blue);
if (normalised===0) red = 255, green = 255, blue = 255;
//console.log(value+" --> "+normalised+" --> "+ "rgb("+red+","+green+","+blue+")")
return "rgb("+red+","+green+","+blue+")";
}
function getGrayscaleColorString(value)
{
var red;
var green;
var blue;
red = value*255;
green = value*255;
blue = value*255;
red = Math.round(red);
green = Math.round(green);
blue = Math.round(blue);
return "rgb("+red+","+green+","+blue+")";
}
function getReverseGrayscaleColorString(value)
{
var normalised = (value-dataMin)/Math.abs(dataMax-dataMin);
normalised = 1-normalised;
var red;
var green;
var blue;
red = normalised*255;
green = normalised*255;
blue = normalised*255;
red = Math.round(red);
green = Math.round(green);
blue = Math.round(blue);
return "rgb("+red+","+green+","+blue+")";
}
function loadData()
{
var selected_file = document.getElementById('input').files[0];
if(!selected_file)
{
alert("No file chosen!");
return;
}
var reader = new FileReader(); // Create a FileReader object
reader.readAsText(selected_file); // Read the file
reader.onload = function(){ // Define an event handler
var text = reader.result; // This is the file contents
dataMin = Number.MAX_VALUE;
dataMax = Number.MIN_VALUE;
var allTextLines = text.split(/\r\n|\n/);
var lines = [];
for (var i=0; i<allTextLines.length; i++) {
if (allTextLines[i].length===0) continue
var elems = allTextLines[i].split(',');
var tarr = [];
for (var j=0; j<elems.length; j++) {
var floatDatum = parseFloat(elems[j]);
tarr.push(floatDatum);
allData.push(floatDatum)
// need to parse before comparing because otherwise it does a fucking string comparison
// silently, which creates a fucking mess
if(floatDatum<=dataMin) dataMin = floatDatum;
if(floatDatum>=dataMax) dataMax = floatDatum;
}
lines.push(tarr);
}
data = lines;
console.log("Series loaded: "+lines.length);
console.log("Min: "+dataMin+", max: "+dataMax);
// need to force numeric sort
console.log("Sorting")
allSortedData = allData.sort(function(a, b){return a-b});
allPercentiles = [];
console.log("Precomputing percentiles")
for(let i=allSortedData.length-1; i>=0; i--) allPercentiles[allSortedData[i]] = i/allSortedData.length
seriesCount = data.length;
seriesLength = data[0].length;
canvas.height = datumHeight * seriesCount;
canvas.width = datumWidth * seriesLength;
labels = [];
isSeriesBrushed = [];
for(var i=0;i<seriesCount;i++)
{
labels[i] = i;
isSeriesBrushed[i] = false;
}
console.log('Drawing gatherplot')
context.clearRect(0, 0, canvas.width, canvas.height);
dataImageStale = true;
drawData();
// refresh data image
dataImage.src = canvas.toDataURL();
dataImageStale = false;
drawMinimap();
// drawHist([]); // empty argument because no selected series
attributesLoaded = false;
}
}
function loadAttributes()
{
var selected_file = document.getElementById('inputAttributes').files[0];
if(!selected_file)
{
alert("No file chosen!");
return;
}
var reader = new FileReader(); // Create a FileReader object
reader.readAsText(selected_file); // Read the file
reader.onload = function(){ // Define an event handler
var text = reader.result; // This is the file contents
attArray = CSVToArray(text);
var headers = attArray[0];
if((seriesCount+1)!=attArray.length)
{
alert('Size of attribute file does not match data. Please ensure attribute file has a header line and as many entries as there are series in your dataset.');
return;
}
// this is a complicated loop
// it sets each attribute of each time series
// since a header line is assumed, you get attArray[i+1]
attributes = [];
for(var i=0;i<seriesCount;i++)
{
attributes[labels[i]] = {};
for(var j=0;j<headers.length;j++)
{
attributes[labels[i]][headers[j]] = attArray[i+1][j];
}
}
attributesLoaded = true;
console.log('Attributes loaded successfully');
}
}
function gather()
{
var gatherWorker = new Worker("gatherer.js");
var progressDisplay = document.getElementById('gatherProgress');
progressDisplay.style.display="inline-block";
gatherWorker.postMessage({"lists":data,
"strategy":gatheringStrategySelector.value,
"labels":labels,
"precomputeDistances": document.getElementById("precomputeDistancesCheckbox").checked
});
gatherWorker.addEventListener('message', function(e) {
if(e.data.type==='distanceProgress')
{
progressDisplay.innerHTML = 'Computing distances: '+ Math.round((e.data.value*100)/seriesCount)+'%';
}
else if(e.data.type==='recomposeProgress')
{
if(e.data.value==='none')
progressDisplay.innerHTML = 'Recomposing...';
else
progressDisplay.innerHTML = 'Recomposing: '+ Math.round(e.data.value*100)+'%';
}
else if(e.data.type==='labels')
{
labels = e.data.value
console.log("Received labels. Reordering data...")
let reorderedData = []
for(let i=0; i<data.length; i++) reorderedData[i] = data[labels[i]]
data = reorderedData
}
else if(e.data.type==='finished')
{
progressDisplay.innerHTML = "Done";
progressDisplay.style.display="none";
dataImageStale = true;
drawData();
}
}, false);
}
function clearBrush()
{
for(var i=0;i<isSeriesBrushed.length;i++) isSeriesBrushed[i] = false;
dataImageStale = true;
drawData();
}
function drawData()
{
if(dataImageStale)
{
for(var i=0;i<seriesCount;i++)
{
for(var j=0; j<seriesLength; j++)
{
var datum = data[i][j];
context.fillStyle = colourmap(normalise(datum));
context.fillRect(j*datumWidth,i*datumHeight,datumWidth,datumHeight);
}
if(isSeriesBrushed[i])
{
context.fillStyle = "rgba(255,255,255,0.8)";
context.fillRect(0,i*datumHeight,datumWidth*seriesLength,datumHeight); // highlight row
}
}
if(currentMode()!=='shift')
{
// OLD METHOD: dataImage = context.getImageData(0,0,canvas.width,canvas.height);
// shifting creates too many images, so we just wait until user
// is no longer shifting to redraw.
dataImage.src = canvas.toDataURL();
dataImageStale = false;
drawMinimap();
}
}
else
{
//context.putImageData(imgData,x,y,dirtyX,dirtyY,dirtyWidth,dirtyHeight);
//context.putImageData(dataImage,0,0);
context.drawImage(dataImage,0,0);
drawMinimap();
}
}
function drawMinimap()
{
minimapContext.drawImage(dataImage,0,0,minimap.width,minimap.height);
}
// currently unused function
function zoomMainCanvas(scaleFactor)
{
if(Math.round(datumWidth * scaleFactor) < 1) return;
//else, it's not going to get too small
datumWidth = Math.round(datumWidth * scaleFactor);
datumHeight = Math.round(datumHeight * scaleFactor);
canvas.width = datumWidth*seriesLength;
canvas.height = datumHeight*seriesCount;
dataImageStale = true;
drawData();
}
function setDatumSize(size)
{
if(Math.round(size) < 1) return;
//else, it's not going to get too small
datumWidth = Math.round(size);
datumHeight = Math.round(size);
canvas.width = datumWidth*seriesLength;
canvas.height = datumHeight*seriesCount;
dataImageStale = true;
drawData();
}
function drawScanChart(hoverSeries, hoverElement)
{
var series = data[hoverSeries];
var label = labels[hoverSeries];
var labelsForChart = new Array(series.length);
for(var i=0; i<labelsForChart.length; i++) labelsForChart[i] = i+1;
var scanChartData = {
labels: labelsForChart,
datasets: [
{
label: label,
fillColor: "rgba(0,0,0,0.2)",
strokeColor: "rgba(0,0,0,1)",
//pointColor: "rgba(151,187,205,1)",
//pointStrokeColor: "#fff",
//pointHighlightFill: "#fff",
//pointHighlightStroke: "rgba(151,187,205,1)",
data: series
}
]
};
//$('#scanChart').remove(); // removes node with id 'scanChart'
var container = document.getElementById('scanChartContainer');
while(container.firstChild) container.removeChild(container.firstChild);
var node = document.createElement('canvas');
node.id = 'scanChart';
var container = document.getElementById('scanChartContainer');
container.appendChild(node);
container.style.top = (hoverSeries*datumHeight)-160+'px';
container.style.left = (hoverElement*datumWidth)+50+'px';
/*
This complicated expression sets the width for the scan chart to:
The larger of, either:
1000 pixels, or
The smaller of, either:
15*serieslength (i.e. giving 15 pixels per element of the time series), or
window.innerWidth
var chartWidth = Math.max(1000,Math.min(window.innerWidth-70,series.length*15));
*/
var chartWidth = 600;//datumWidth*seriesLength;
document.getElementById('scanChart').width=''+chartWidth;
var ctx = document.getElementById('scanChart').getContext('2d');
var myLineChart = new Chart(ctx).Line(scanChartData,
{
animation:false,
bezierCurve:false,
//pointDotRadius:2,
//pointDotStrokeWidth:1,
pointDot: false,
showTooltips: false,
scaleShowGridLines: false,
scaleShowXLabels: false // my own addition to the Chart.js library
//showScale: false
}
);
}
function drawLineChart(series, label, canvasID)
{
var labelsForChart = new Array(series.length);
for(var i=0; i<labelsForChart.length; i++) labelsForChart[i] = i+1;
var scanChartData = {
labels: labelsForChart,
datasets: [
{
label: label,
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: series
}
]
};
var oldParentNode = document.getElementById(canvasID).parentNode;
//delete all children nodes
while(oldParentNode.firstChild){oldParentNode.removeChild(oldParentNode.firstChild);}
var node = document.createElement('canvas');
node.id = canvasID;
oldParentNode.appendChild(node);
/*
This complicated expression sets the width for the scan chart to:
The larger of, either:
1000 pixels, or
The smaller of, either:
15*seriesLength (i.e. giving 15 pixels per element of the time series), or
window.innerwidth
*/
var chartWidth = Math.max(1000,Math.min(window.innerWidth-150,series.length*15))
document.getElementById(canvasID).width=''+chartWidth;
document.getElementById(canvasID).height='200';
var ctx = document.getElementById(canvasID).getContext('2d');
var myLineChart = new Chart(ctx).Line(scanChartData,
{
animation:false,
bezierCurve:false,
pointDotRadius:2,
pointDotStrokeWidth:1,
pointHitDetectionRadius:1 // lord almighty, this is what I was looking for!