-
Notifications
You must be signed in to change notification settings - Fork 2
/
jscomut.js
executable file
·1956 lines (1712 loc) · 81 KB
/
jscomut.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
function Comut() {
var _this = this;
_this.data = {
genomic: { samples:[], genes:[], cells: [] },
demographics: { headers:[], fields:[], cells: [] },
samples:{},
};
_this.default_options = {
target: '',
editableOptions:true,
grid: {
cellwidth: 20,
cellheight: 30,
maxgridwidth:500,
padding:1,
},
bar: {
width: 200,
//height: same as grid because the data is the same
},
geneLegend: {
width: 70,
},
sampleLegend:{
height: 100,
show:'yes',//if not 'yes' a scale of zero will hide the labels
},
colorLegend:{
width:200,
},
innerLayout:{
margins:5,
},
mutTypeEncoding: {
"wt": { "color": "#D4D4D4", "text": "No alteration","legendOrder":8 },
"missense": { "color": "#0F8500", "text": "Missense","legendOrder":0 },
"stop": {"color": "#000000", "text": "Stop gain","legendOrder":1 },
"fs": { "color": "#5E2700", "text": "Frameshift","legendOrder":2 },
"inframe": { "color": "#C973FF", "text": "Inframe","legendOrder":3 },
"splice": { "color": "#F57564", "text": "Splice site","legendOrder":4 },
"amp": { "color": "#2129FF", "text": "Amplification","legendOrder":5 },
"del": { "color": "#FF0000", "text": "Deletion/loss","legendOrder":6 },
"fusion": { "color": "#00BFFF", "text": "Fusion","legendOrder":7 }
},
dataInput: {
filePicker: true,//if true, adds a button to select a file
pasteBox:false,//if true, adds a textinput for copy/paste
}
};
_this.mode = {
interaction: 'none'
};
var newDragSelection = null;
this.init = function (options) {
//now that the widget has been initialized, add the API function to pass in data
_this.setData=setData;
//extend the default options with the passed-in options, overriding defaults when needed
_this.options = $.extend(true, {}, _this.default_options, options);
options = _this.options;
//where should the widget be located within the page?
if (options.target && $(options.target).length >0 ) {
_this.widget = $(options.target).eq(0);
}
else {
_this.widget = $('<div>', { class: 'comut' }).hide().appendTo('body');
}
//create the widget controls for selecting interactive modes
setupModeControls();
//add div to act as the container for the comut plot widget itself
_this.svgcontainer = $('<div>',{class:'comut-svg-container'}).appendTo(_this.widget);
//select the container as a d3 selection instead of jquery for convenience
_this.d3widget = d3.select(_this.svgcontainer[0]);
//create the configuration panel
setupConfigPanel();
//create elements to allow saving svg via download mechanism
setupSVGDownload();
//set up the tooltip to work to display extra information
setupTooltip();
//create the components of the comut plot (sample grid, demographic grid, legends, titles, graphs, etc)
setupWidgetComponents();
} // end of this.init
function setupWidgetComponents(){
var options = _this.options;
var w = options.bar.width + options.geneLegend.width + options.grid.cellwidth + options.innerLayout.margins * 3 + options.colorLegend.width;
var h = options.grid.cellheight + options.sampleLegend.height+options.innerLayout.margins;
var o = options.sampleLegend.height + options.innerLayout.margins;
var g = options.grid;
_this.svg = _this.d3widget
.append('svg')
.attr('id','comut-svg')
.attr('width', w)
.attr('height', h);
_this.svg.call(_this.tooltip);
_this.zoom = d3.zoom().scaleExtent([1, 4])
.on('zoom', zoomed)
.on('start', function () {
_this.scales.gridX.translateX = d3.event.transform.x;
})
.filter(function () { return _this.mode.interaction == 'zp'; });
_this.drag = d3.drag()
.on('start', gridDragStart)
.on('drag', gridDrag)
.on('end', gridDragEnd)
.filter(function () { return _this.mode.interaction == 'dnd'; });
$('#radio-none').click(); //do this after zoom and drag object are created
_this.gridholder = _this.svg.append('g')
.attr('transform', 'translate(' + (options.bar.width + options.geneLegend.width + options.innerLayout.margins * 2) + ',0)');
_this.zoomable = _this.gridholder.append('g')
.attr('clip-path', 'url(#zoomable-clip)')
.call(_this.zoom);
_this.zoomableClip = _this.zoomable.append('clipPath').attr('id', 'zoomable-clip')
.append('rect').attr('width', 0).attr('height', 0);
_this.grid=_this.zoomable
.append('g')
.attr('class', 'grid')
.attr('transform', 'translate(0,' + o + ')');
_this.demographics = _this.zoomable
.append('g')
.attr('class', 'demographics')
.attr('transform', 'translate(0,' + o + ')');
_this.grid.append('rect')
.attr('class', 'zoom-rect')
.attr('width', 0)
.attr('height', 0)
.attr('stroke', 'none')
.attr('fill','blue')
.attr('fill-opacity',0.0);
_this.bargraph = _this.svg
.append('g')
.attr('transform', 'translate(' + options.bar.width + ',' + o + ')');
_this.bar = _this.bargraph.append('g')
.attr('class', 'bar');
_this.geneLegend = _this.svg
.append('g')
.attr('class', 'gene-legend')
.attr('transform', 'translate(' + (options.bar.width + options.innerLayout.margins) + ',' + (o) + ')');
_this.demoTitles = _this.svg
.append('g')
.attr('class', 'demo-titles')
.attr('transform', 'translate(' + (options.bar.width + options.geneLegend.width) + ',' + (g.cellheight + o) + ')');
_this.demoLegend = _this.gridholder
.append('g')
.attr('class', 'demo-legend');
_this.sampleLegend = _this.zoomable
.append('g')
.attr('class', 'sample-legend')
.attr('transform', 'translate(0,' + (o-options.innerLayout.margins) + ')' +
' scale(1,' + (options.sampleLegend.show ? 1 : 0) + ')');
_this.colorLegend = _this.svg
.append('g')
.attr('class', 'color-legend');
if(!_this.scales) _this.scales={};
}
//------------------------------setupConfigPanel --------------------------------//
function setupConfigPanel(){
var options = _this.options;
var ctrls = $('.comut-ctrls');
$(document).on('click','.panel-header',function(event){
var target = $(this).data('target');
var show = target.is(':hidden');
$(this).data('target').toggleClass('collapsed');
$(this).attr('collapsed',show==false);
})
var optionspanel = $('<div>',{class:'comut-options-panel'}).prependTo(ctrls);
var optionsheader = $('<div>',{class:'optionsheader'}).appendTo(optionspanel);
//Data selection and saving - "File" menu functions
var filepanel = $('<div>',{class:'comut-panel collapsed'}).insertAfter(optionsheader);
var filepanelHeader = $('<div>',{class:'panel-header',collapsed:true}).text('File').prependTo(optionsheader).data('target',filepanel);
var loadpanel = $('<div>',{class:'load-data'}).appendTo(filepanel);
var fileInfo = $('<div>', { id:'file-info', class: 'config-group' }).appendTo(loadpanel);
if (options.dataInput.filePicker == true) {
_this.filePicker = $('<input>', { type: 'file', class: 'comut-file-picker', id: 'mfile' }).insertBefore(fileInfo).on('change', function (e) {
loadFile(e);
});
$('<label>', { for: 'mfile' }).text('Select data file(s) to load').insertBefore(_this.filePicker);
}
if(options.dataInput.pasteBox == true){
_this.pasteBoxM = $('<input>', { type: 'text', class: 'comut-paste-box', placeholder: 'Paste data here' }).insertBefore(fileInfo)
.on('paste', function (e) {
clipboardData = e.originalEvent.clipboardData || window.originalEvent.clipboardData;
pastedData = clipboardData.getData('text');
processTextData(pastedData,'Pasted from clipboard');
$(this).val('');
return false;
});
}
//display info about the selected file(s)
var genomicsInfo = $('<div>', { id:'mutation-file-info'}).appendTo(fileInfo);
var demographicInfo = $('<div>',{id:'demographic-file-info'}).appendTo(fileInfo);
//add button to create the widget with this data
$('<button>', { class: 'add-data-button' }).text('Add this data to the Comut plot').on('click', function () {
$(this).hide();
//filepanelHeader.click();
updateOptions();
configureWidget();
createDataSVG();
}).appendTo(fileInfo).hide();
//"save" panel
var savepanel = $('<div>',{class:'config-panel save-data'}).appendTo(filepanel);
$('<button>').text('Save data and configuration').appendTo(savepanel).on('click',saveDataAndConfig);
$('<button>').text('Save data only').appendTo(savepanel).on('click',saveData);
$('<button>').text('Save configuration only').appendTo(savepanel).on('click',saveConfig);
var configpanel = $('<div>',{class:'comut-panel collapsed'}).appendTo(optionspanel);
//only provide the control to open show this dialog if the initial options allow it
if(_this.options.editableOptions) $('<div>',{class:'panel-header',collapsed:true}).text('Edit').appendTo(optionsheader).data('target',configpanel);
//Other configuration options - layout, colors, gene/demographic filters
_this.optionsEditor = {}; //structure to hold input elements
//layout
var layoutConfig = $('<div>',{class:'comut-panel collapsed'});
$('<div>').appendTo(configpanel).append(layoutConfig);
$('<h4>',{class:'panel-header',collapsed:true}).text('Edit widget layout').data('target',layoutConfig).insertBefore(layoutConfig);
$('<label>').text('Cell width: ').appendTo(layoutConfig);
_this.optionsEditor.gridCellWidth = $('<input>',{type:'number'}).appendTo(layoutConfig).val(_this.options.grid.cellwidth);
$('<label>').text('height: ').appendTo(layoutConfig);
_this.optionsEditor.gridCellHeight = $('<input>',{type:'number'}).appendTo(layoutConfig).val(_this.options.grid.cellheight);
$('<label>').text('padding between cells: ').appendTo(layoutConfig);
_this.optionsEditor.gridPadding = $('<input>',{type:'number'}).appendTo(layoutConfig).val(_this.options.grid.padding);
$('<br>').appendTo(layoutConfig);
$('<label>').text('Max grid width: ').appendTo(layoutConfig);
_this.optionsEditor.gridMaxWidth = $('<input>',{type:'number'}).appendTo(layoutConfig).val(_this.options.grid.maxgridwidth);
$('<br>').appendTo(layoutConfig);
$('<label>').text('Spacing between areas: ').appendTo(layoutConfig);
_this.optionsEditor.innerMargins = $('<input>',{type:'number'}).appendTo(layoutConfig).val(_this.options.innerLayout.margins);
$('<label>').text('Bar plot width ').appendTo(layoutConfig);
_this.optionsEditor.barPlotWidth = $('<input>',{type:'number'}).appendTo(layoutConfig).val(_this.options.bar.width);
$('<br>').appendTo(layoutConfig);
$('<label>').text('Gene label width ').appendTo(layoutConfig);
_this.optionsEditor.geneLegendWidth = $('<input>',{type:'number'}).appendTo(layoutConfig).val(_this.options.geneLegend.width);
$('<br>').appendTo(layoutConfig);
$('<label>').text('Sample label width ').appendTo(layoutConfig);
_this.optionsEditor.sampleLegendHeight = $('<input>',{type:'number'}).appendTo(layoutConfig).val(_this.options.sampleLegend.height);
$('<label>').text('Show sample labels? ').appendTo(layoutConfig);
_this.optionsEditor.sampleLegendShow = $('<input>',{type:'checkbox'}).appendTo(layoutConfig).attr('checked',_this.options.sampleLegend.show);
$('<br>').appendTo(layoutConfig);
$('<label>').text('Color legend width ').appendTo(layoutConfig);
_this.optionsEditor.colorLegendWidth = $('<input>',{type:'number'}).appendTo(layoutConfig).val(_this.options.colorLegend.width);
$('<br>').appendTo(layoutConfig);
//alteration setup
var alterationSetup = $('<div>', { id: 'alteration-setup',class:'comut-panel collapsed' });
$('<div>').appendTo(configpanel).append(alterationSetup);
$('<h4>',{class:'panel-header',collapsed:true}).text('Alteration encoding').data('target',alterationSetup).insertBefore(alterationSetup);
/*$.each(_this.options.mutTypeEncoding,function(k,v){
addAlterationConfig(k,v,alterationSetup);
});*/
setupAlterationConfig();
//gene filter - add configuration area now, will be further set up when data is added
var geneSelection = $('<div>', { id: 'gene-fields',class:'comut-panel collapsed' });
$('<div>').appendTo(configpanel).append(geneSelection);
$('<h4>',{class:'panel-header',collapsed:true}).text('Select genes to display').data('target',geneSelection).insertBefore(geneSelection);
//demographic filter - add configuration area now, will be further set up with data is added
var demographicConfig = $('<div>', { id: 'demographics-fields',class:'comut-panel collapsed' });
$('<div>').appendTo(configpanel).append(demographicConfig);
$('<h4>',{class:'panel-header',collapsed:true}).text('Select demographic info to display').data('target',demographicConfig).insertBefore(demographicConfig);
//add button to update the widget with the new options
$('<button>', { class: 'btn btn-default' }).text('Update Comut plot settings').on('click', function () {
updateOptions();
configureWidget();
createDataSVG();
}).appendTo(configpanel);
} //end of function setupConfigPanel(){...}
//--------------- createDataSVG -----------------------------------------------------------//
function createDataSVG() {
_this.grid.selectAll('.cell').data([]).exit().remove();
_this.demographics.selectAll('.cell').data([]).exit().remove();
_this.geneLegend.selectAll('.gene').data([]).exit().remove();
_this.bar.selectAll('.gene').data([]).exit().remove();
_this.demoTitles.selectAll('.fieldname').data([]).exit().remove();
_this.demoLegend.selectAll('.demolegend').data([]).exit().remove();
_this.sampleLegend.selectAll('.sample').data([]).exit().remove();
var data = _this.data.genomic;
var genomic_samples=data.samples;
_this.grid
.selectAll('.cell')
.data(data.cells)
.enter()
.filter(function (d) {
return _this.options.genesToPlot.includes(d.gene) && genomic_samples.includes(d.sample);
})
.append('g')
.attr('class', 'cell draggable-x draggable-y')
.attr('transform', function (d) {
var e = d3.select(this);
var x = _this.scales.gridX(d.sample);
var y = _this.scales.gridY(d.gene);
e.attr('gx',x);
e.attr('gy',y);
return 'translate(' + x + ','+ y + ')';
})
.each(function(d){
//add visual elements representing alterations
if(d.alterations.length==0){
var type = 'wt';
d3.select(this).append('svg:rect')
.attr('width',_this.scales.gridX.bandwidth())
.attr('height',_this.scales.gridY.bandwidth())
.style('fill',_this.scales.gridC(type))
}
else{
var g = d3.select(this);
var alt = d.alterations.sort(function(a,b){
return _this.options.mutTypeEncoding[a.type] - _this.options.mutTypeEncoding[b.type];
});
for(var i = 0; i<alt.length;++i){
g.append('svg:rect')
.attr('width',_this.scales.gridX.bandwidth())
.attr('height',_this.scales.gridY.bandwidth()/alt.length)
.attr('y',_this.scales.gridY.bandwidth()/alt.length *i )
.style('fill',_this.scales.gridC(alt[i].type));
if(i>0 && alt[i].type==alt[i-1].type){
//add a white line between the two elements
g.append('svg:rect')
.attr('width',_this.scales.gridX.bandwidth())
.attr('x',_this.scales.gridX.bandwidth()*0)
.attr('height',1)
.attr('y',_this.scales.gridY.bandwidth()/alt.length * i-0.5)
.attr('fill','white');
}
}
}
})
.on('mouseover', _this.tooltip.show)
.on('mouseout', _this.tooltip.hide)
.call( _this.drag );
_this.demographics
.selectAll('.cell')
.data(_this.data.demographics.cells)
.enter()
.filter(function (d) {
return _this.options.demofields.indexOf(d.fieldname) != -1 && genomic_samples.indexOf(d.sample)!=-1;
})
.append('svg:rect')
.attr('class', 'cell draggable-x draggable-y')
.attr('x', function (d) {
return _this.scales.gridX(d.sample);
})
.attr('y', function (d) {
return _this.scales.demographicsY(d.fieldname);
})
.attr('width', function (d) {
return _this.scales.gridX.bandwidth();
})
.attr('height', function (d) {
return _this.scales.demographicsY.bandwidth();
})
.style('fill', function (d) {
return _this.scales.demoC[d.fieldname](d.value);
})
.on('mouseover', _this.tooltip.show)
.on('mouseout', _this.tooltip.hide)
.call(_this.drag);
var bar_enter = _this.bar.selectAll('.gene')
.data(data.alteration_count)
.enter()
.filter(function (d) {
return _this.options.genesToPlot.includes(d.key);
})
.append('g')
.attr('class', 'gene draggable-y')
.attr('transform', function (d) {
return 'translate(-'+_this.scales.barX(d.value)+','+_this.scales.gridY(d.key)+')';
})
.call(_this.drag);
bar_enter.append('svg:rect')
.attr('width', function (d) {
return _this.scales.barX(d.value);
})
.attr('height', function (d) {
return _this.scales.gridY.bandwidth();
});
bar_enter.append('svg:text')
.attr('x', -5)
.attr('text-anchor', 'end')
.attr('y', 1+_this.scales.gridY.bandwidth() / 2)
.attr('dominant-baseline', 'middle')
.text(function (d) { return (d.value / _this.data.genomic.samples.length * 100).toFixed(0) + '%'; });
_this.geneLegend.selectAll('.gene')
.data(data.genes)
.enter()
.filter(function (d) {
return _this.options.genesToPlot.includes(d.key);
})
.append('svg:text')
.attr('class', 'gene draggable-y')
.attr('y', function (d) {
return _this.scales.gridY(d.key) + _this.scales.gridY.bandwidth() / 2;
})
.text(function (d) { return d.key; })
.attr('dominant-baseline', 'middle')
.style('cursor','pointer')
.on('click',function(d){
sortByRow('gene',d.key);
})
.call(_this.drag);
_this.demoTitles.selectAll('.fieldname')
.data(_this.data.demographics.fields)
.enter()
.filter(function (d) {
return _this.options.demofields.indexOf(d.field) != -1;
})
.append('svg:text')
.attr('class', 'fieldname draggable-y')
.attr('y', function (d) {
return _this.scales.demographicsY(d.field) + _this.scales.demographicsY.bandwidth() / 2;
})
.text(function (d) { return d.fieldNameOrig; })
.attr('dominant-baseline', 'center')
.attr('text-anchor', 'right')
.style('cursor','pointer')
.on('click',function(d){
sortByRow('demographic',d.field);
})
.call(_this.drag);
var trs = getTranslation(_this.demoTitles.attr('transform'));
trs[0] = trs[0] - _this.demoTitles.node().getBBox().width;
_this.demoTitles.attr('transform', 'translate(' + trs[0] + ',' + trs[1] + ')');
_this.demoLegend.selectAll('.demolegend')
.data(_this.data.demographics.fields)
.enter()
.filter(function (d) {
return _this.options.demofields.indexOf(d.field) != -1;
})
.append('g')
.attr('class', 'demolegend')
.attr('transform', function (d) {
return 'translate(0,' + (_this.scales.demographicsY(d.field)) + ')';
})
.each(function (d, i, g) {
var offset = g[i].getBoundingClientRect().left;
d3.select(g[i]).call(_this.scales.demoC[d.field].legend);
d3.select(g[i])
.selectAll('.cell').each(function (d, i, g) {
var e = d3.select(g[i]);
var t = getTranslation(e.attr('transform'));
var current_left = g[i].getBoundingClientRect().left;
var left = i > 0 ? g[i - 1].getBoundingClientRect().right + 10 : offset;
e.attr('transform', 'translate(' + (t[0] + left - current_left) + ',' + 0 + ')');
});
});
_this.sampleLegend.selectAll('.sample')
.data(data.samples)
.enter()
.append('g')
.attr('class', 'sample draggable-x')
.attr('transform', function (d) {
return 'translate(' +(_this.scales.gridX(d) + _this.scales.gridX.bandwidth() / 2)+',0)';
})
.call(_this.drag)
.append('svg:text')
.text(function (d) { return d; })
.attr('alignment-baseline', 'middle')
.attr('transform', 'rotate(-90)');
_this.zoom.scaleTo(_this.grid, _this.zoom.scaleExtent()[0]);
//_this.sort();
}
function zoomed() {
var t = d3.event.transform;
_this.scales.gridX = rescaleOrdinalX(_this.scales.gridX, t);
draw(0);
}
function loadFile(e) {
var f = e.target.files[0];
if (!f) return;
var reader = new FileReader();
reader.onload = function () {
processTextData(reader.result,'File '+f.name);
};
reader.readAsText(f);
}
function processTextData(d,filename){
//try parsing json first
try{
var json = JSON.parse(d);
if(json.config) _this.options = json.config; //load config first before dealing with data
if(json.scales) _this.scales = json.scales;
if(json.data) {
_this.data = json.data;
associateDemographicsWithSamples();
setupMutationFileDescription();
setupDemographicFileDescription();
setupDemographicsConfig();
}
if(json.config){
setupMutationConfig();
setupAlterationConfig();
}
}
catch (e){
var rows = d.trim().split(/\r\n|[\r\n]/);
var header = rows[0].split('\t').map(function(e){return e.toLowerCase();});
if(header.indexOf('sample')>-1&&header.indexOf('gene')>-1&&header.indexOf('alteration')>-1&&header.indexOf('type')>-1){
processMutationData(d,filename);
associateDemographicsWithSamples();
setupMutationFileDescription();
setupMutationConfig();
setupAlterationConfig();
}
else if(header.indexOf('sample')>-1){
processDemographicData(d,filename);
associateDemographicsWithSamples();
setupDemographicFileDescription();
setupDemographicsConfig();
}
}
//find first line and see if it is a genomic file or demographic file
}
function processMutationData(d,datasource) {
var inputGenomicData = d.trim();
var delimiter = '\t';
//Step 1: Parse input genomic data from text box or flat file input (tab delimited) and convert into an array of JSON objects
var inputDataObject = textToJson(inputGenomicData, delimiter);
if (inputDataObject == false) {
return false;
}
//Step 2: get list of unique gene names across the sample dataset
var uniqGeneList = getGeneList(inputDataObject);
//Step 3: order this gene list in descending order of frequency of alterations in a gene
var sortedGeneAltFreq = orderGeneList(uniqGeneList, inputDataObject);
//Step 4: get unique list of samples from the dataset
var uniqSampleList = getSampleList(inputDataObject);
//Step 5: create 2D array containing genomic alteration status of each gene in the dataset for a given sample
var mutMatrix = createSampleMutationArray(inputDataObject, sortedGeneAltFreq, uniqSampleList);
//Step 6: create modified input genomic data list to accomodate genes for a sample that have no alterations
var completeGenomicData = populateNegatives(inputDataObject, uniqSampleList, uniqGeneList);
//Step 7: sort the mutation matrix recursively descending to get sample order
var sampleMatrix = sortMutMatrix(mutMatrix);
_this.data.genomic = {};
_this.data.genomic.source = datasource;
_this.data.genomic.sortedGenes = sortedGeneAltFreq;
_this.data.genomic.genes = sortedGeneAltFreq.map(function(e){ return {key:e[0], }; });
_this.data.genomic.cells = completeGenomicData;
_this.data.genomic.samples = sampleMatrix;
_this.data.genomic.mutMatrix = mutMatrix;
_this.data.genomic.mutMatrixSampleOrder = mutMatrix.map(function(e){return e[e.length-1]; });
_this.data.genomic.mutMatrixGeneOrder = sortedGeneAltFreq.map(function(e){ return e[0] });
_this.data.genomic.alterationTypes = getAlterationTypes(completeGenomicData);
_this.data.genomic.alteration_count = sortedGeneAltFreq.map(function (e) {
return { key: e[0], value: e[1] };
});
}
function processDemographicData(d,datasource) {
var textarr = d.trim().split(/\r\n|\r|\n/).map(function (e, i) {
return e.trim().split(/\t/);
});
var headers = textarr[0];
textarr = textarr.slice(1);
var fieldMap = {};
headers.forEach(function (e, i) {
fieldMap[e.toLowerCase()] = { field: e.toLowerCase(), index: i, values:[], fieldNameOrig: e };
});
var arr = textarr.map(function (e, i) {
var row = {
celldata: {}
};
$.each(fieldMap, function (k, v) {
row[v.field] = e[v.index];
row.celldata[k] = e[v.index];
});
return row;
});
var cells = [];
arr.forEach(function (e, i) {
$.each(fieldMap, function (k, v) {
cells.push({ fieldname: v.field, sample: e.sample, value: e[v.field], celldata: e.celldata });
});
$.each(e.celldata, function (k, v) {
fieldMap[k].values.push(v);
});
});
_this.data.demographics = {};
_this.data.demographics.datasource = datasource;
_this.data.demographics.samples = d3.nest().key(function (d) { return d.sample; }).entries(arr);
_this.data.demographics.headers = headers;
_this.data.demographics.fields = $.map(fieldMap,function(v,k){
if(v.field != 'sample') return v;
});
_this.data.demographics.cells = cells;
}
function associateDemographicsWithSamples(){
if(!_this.data.genomic){
_this.data.samples={};
return;
}
else if(_this.data.demographics){
_this.data.samples={}
$.each(_this.data.genomic.samples,function(sidx,sampleName){
var cells = _this.data.genomic.cells.filter(function(x){return x.sample==sampleName;});
var demographics = _this.data.demographics.cells.filter(function(x){return x.sample ==sampleName;});
var sampleGeneData = {};
var sampleDemographicData = {};
$.each(cells,function(idx,gene){
sampleGeneData[gene.gene.toLowerCase()]=gene;
});
$.each(demographics,function(idx,demo){
sampleDemographicData[demo.fieldname.toLowerCase()]=demo;
});
_this.data.samples[sampleName.toLowerCase()] = {
sample: sampleName,
gene:sampleGeneData,
demographic:sampleDemographicData,
}
});
}
}
function configureWidget() {
var demographicsToUse = _this.options.demofields;
var genesToPlot = _this.options.genesToPlot;
var options = _this.options;
//First figure out which types of alterations are included in order to set the geometry appropriately
//convert the mutTypeEncoding keys and colors into matched arrays to create the color scale
var mutTypes = Object.keys(options.mutTypeEncoding);
var colors = mutTypes.map(function (k) {
return options.mutTypeEncoding[k].color;
});
_this.scales.gridC = d3.scaleOrdinal().domain(mutTypes).range(colors);
var mutTypeArray = mutTypes.map(function(val){
var obj = options.mutTypeEncoding[val];
obj.type = val;
return obj;
}).sort(function(a,b){
var sortorder = a.legendOrder - b.legendOrder;
if(sortorder) return (sortorder);
return a.type.localeCompare(b.type);
});
//convert the mutTypeEncoding colors and text to arrays in the order defined by options.legendOrder
var legendEntries = mutTypeArray.reduce(function(output,curr){
var include = _this.data.genomic.alterationTypes.includes(curr.type);
if(include) {
output.colors.push(curr.color);
output.text.push(curr.text);
}
return output;
},{colors:[],text:[]});
var legendColors = legendEntries.colors;
var legendText = legendEntries.text;
var g = options.grid,
dh = (g.cellheight + g.padding) * demographicsToUse.length,
gw = (g.cellwidth + g.padding) * _this.data.genomic.samples.length,
gh = (g.cellheight + g.padding) * Math.max(genesToPlot.length, legendColors.length),
o = options.sampleLegend.height + options.innerLayout.margins,
h = gh + dh + g.cellheight + o;
_this.scaleExtent = [1, 2];
if (gw > g.maxgridwidth) {
gw = g.maxgridwidth;
_this.scaleExtent[0] = g.maxgridwidth / gw;
}
_this.zoom.scaleExtent(_this.scaleExtent);
var w = options.bar.width + options.geneLegend.width + gw + options.innerLayout.margins * 3 + g.cellwidth + options.colorLegend.width;
_this.gridsize = { width: gw, height: gh };
_this.svg.attr('width', '100%').attr('height',h).attr('viewBox', '0 0 '+w+' '+h).attr('preserveAspectRatio','xMinYMin');
_this.zoomableClip.attr('width', gw).attr('height', gh + dh +g.cellheight + o);
_this.zoomable.select('.zoom-rect').attr('height', gh).attr('width', gw);
_this.scales.gridX = d3.scaleBand().domain(_this.data.genomic.samples).range([0, gw])
.paddingInner(_this.options.grid.padding / _this.options.grid.cellwidth);
_this.scales.gridY = d3.scaleBand().domain(genesToPlot).range([0, gh])
.paddingInner(_this.options.grid.padding / _this.options.grid.cellheight);
_this.scales.demographicsY = d3.scaleBand().domain(demographicsToUse).range([0, dh])
.paddingInner(_this.options.grid.padding / _this.options.grid.cellheight);
_this.demographics.attr('transform', 'translate(0,' + (gh + g.cellheight + o) + ')');
_this.demoTitles.attr('transform', 'translate(' +(options.bar.width + options.geneLegend.width-5) +',' + (gh + g.cellheight + o) + ')');
_this.gridholder.attr('transform', 'translate(' + (options.bar.width + options.geneLegend.width + options.innerLayout.margins * 2) + ',0)');
_this.grid.attr('transform', 'translate(0,' + o + ')');
_this.bargraph.attr('transform', 'translate(' + options.bar.width + ',' + o + ')');
_this.geneLegend.attr('transform', 'translate(' + (options.bar.width + options.innerLayout.margins) + ',' + (o) + ')');
_this.sampleLegend.attr('transform', 'translate(0,' + (o-options.innerLayout.margins) + ')' +
' scale(1,' + (options.sampleLegend.show ? 1:0) + ')');
//if order information is present in the data, set the domain of the scales here.
if(_this.data.geneorder) {
//_this.scales.gridY.domain(_this.data.geneorder);
//Keep the existing order, with new ones at the end
var new_ordered_list=[];
var current_order=_this.data.geneorder;
var new_unordered_list=_this.scales.gridY.domain();
$.each(current_order,function(i,e){
if(new_unordered_list.indexOf(e)>-1) new_ordered_list.push(e);
});
$.each(new_unordered_list,function(i,e){
if(new_ordered_list.indexOf(e)==-1) new_ordered_list.push(e);
});
_this.scales.gridY.domain(new_ordered_list);
_this.data.geneorder = new_ordered_list;
}
if(_this.data.demoorder){
//Keep the existing order, with new ones at the end
var new_ordered_list=[];
var current_order=_this.data.demoorder;
var new_unordered_list=_this.scales.demographicsY.domain();
$.each(current_order,function(i,e){
if(new_unordered_list.indexOf(e)>-1) new_ordered_list.push(e);
});
$.each(new_unordered_list,function(i,e){
if(new_ordered_list.indexOf(e)==-1) new_ordered_list.push(e);
});
_this.scales.demographicsY.domain(new_ordered_list);
_this.data.demoorder = new_ordered_list;
}
if(_this.data.sampleorder){
_this.scales.gridX.domain(_this.data.sampleorder);
}
_this.scales.legendColor = d3.scaleOrdinal().domain(legendText).range(legendColors);
_this.scales.barX = d3.scaleLinear().domain([0, Math.max.apply(null, _this.data.genomic.alteration_count.map(function (x) { return x.value; })) * 1.25]).range([0, options.bar.width]);
_this.legend = d3.legendColor().orient('vertical').shapeWidth(options.grid.cellwidth).shapeHeight(options.grid.cellheight).scale(_this.scales.legendColor);
_this.colorLegend.call(_this.legend).attr('transform','translate('+ (w-options.colorLegend.width) +','+ o +')');
_this.scales.demoC = {};
_this.data.demographics.fields.forEach(function (d) {
var range = d.options.values.map(function (x) { return x.color; });
var domain = d.options.values.map(function (x) { return x.value; });
_this.scales.demoC[d.field] = d3.scaleOrdinal().domain(domain).range(range);
_this.scales.demoC[d.field].legend = d3.legendColor()
.orient('vertical')
.shapeWidth(options.grid.cellwidth)
.shapeHeight(options.grid.cellheight)
.labelOffset(4)
.scale(_this.scales.demoC[d.field]);
});
_this.demoLegend.attr('transform','translate('+(gw+options.innerLayout.margins+g.cellwidth) + ','+(gh+g.cellheight+o)+')');
}
this.randomize = function () {
_this.scales.gridY.domain(shuffle(_this.scales.gridY.domain()));
_this.scales.gridX.domain(shuffle(_this.scales.gridX.domain()));
_this.data.sampleorder = _this.scales.gridX.domain();
_this.data.geneorder = _this.scales.gridY.domain();
_this.data.demoorder = _this.scales.demographicsY.domain();
draw(1000);
}
this.sort = function (opts) {
if (!opts) opts = { x: true, y: true };
if (opts.y) {
_this.data.genomic.alteration_count = _this.data.genomic.alteration_count.sort(function (a, b) {
return b.value - a.value;
});
_this.scales.gridY.domain(_this.data.genomic.alteration_count.map(function (e) {
return e.key;
}));
}
if (opts.x) {
sortByGeneOrder();
}
_this.data.geneorder = _this.scales.gridY.domain();
_this.data.demoorder = _this.scales.demographicsY.domain();
draw(1000);
}
function draw(duration) {
_this.grid.selectAll('.cell')
.transition()
.duration(duration)
.attr('transform',function(d){
var e = d3.select(this);
if(e.classed('dragging-y')){
var y = parseFloat(e.attr('gy'));
}
else{
var y = _this.scales.gridY(d.gene);
e.attr('gy',y);
}
if(e.classed('dragging-x')){
var x = parseFloat(e.attr('gx'));
}
else{
var x = _this.scales.gridX(d.sample);
e.attr('gx',x);
}
return 'translate(' + x + ',' + y + ')';
}).each(function(d,i) {
var children = d3.selectAll(this.childNodes);
children.attr('width',_this.scales.gridX.bandwidth());
});
_this.demographics.selectAll('.cell')
.transition()
.duration(duration)
.attr('y', function (d) {
var e = d3.select(this);
var y = e.classed('dragging-y')? e.attr('y') : _this.scales.demographicsY(d.fieldname);
e.attr('gy',y);
return y;
})
.attr('x', function (d) {
var e = d3.select(this);
var x = e.classed('dragging-x') ? e.attr('x') : _this.scales.gridX(d.sample);
e.attr('gx',x);
return x;
})
.attr('width', function (d) {
return _this.scales.gridX.bandwidth();
});
_this.zoomable.select('.zoom-rect')
.attr('x', _this.scales.gridX.range()[0])
.attr('width', _this.scales.gridX.range()[1] - _this.scales.gridX.range()[0]);
_this.bar.selectAll('.gene:not(.dragging-y)')
.transition()
.duration(duration)
.attr('transform', function (d) {
var e = d3.select(this);
var y=e.classed('dragging-y')? 0 : _this.scales.gridY(d.key);
e.attr('gy',y);
return 'translate(-' + _this.scales.barX(d.value) + ',' + y + ')';
});
_this.geneLegend.selectAll('.gene:not(.dragging-y)')
.transition()
.duration(duration)
.attr('y', function (d) {
var e = d3.select(this);
var y = _this.scales.gridY(d.key) + _this.scales.gridY.bandwidth() / 2;
e.attr('gy',y);
return y;
})
_this.sampleLegend.selectAll('.sample')
.transition()
.duration(duration)
// .attr('x', 0)
// .attr('y', 0)
.attr('transform', function (d) {
var e = d3.select(this);
var x = e.classed('dragging-x') ? 0 : (_this.scales.gridX(d) + _this.scales.gridX.bandwidth() / 2);
if(e.classed('dragging-x')==false) e.attr('gx',x);
return e.classed('dragging-x') ? e.attr('transform') : 'translate(' + x + ',0)';
});
_this.demoTitles.selectAll('text')
.transition()
.duration(duration)
.attr('y', function (d) {
var e = d3.select(this);
var y = e.classed('dragging-y') ? e.attr('y') : _this.scales.demographicsY(d.field) + _this.scales.demographicsY.bandwidth() / 2;
e.attr('gy',y);
return y;
})
_this.demoLegend.selectAll('.demolegend')
.transition()
.duration(duration)
.attr('transform', function (d) {
var e = d3.select(this);
return e.classed('dragging-y') ? e.attr('transform') : 'translate(0,'+(_this.scales.demographicsY(d.field) )+')';
});
}
function sortByRow(type,rowname,reverse){
rowname = rowname.toLowerCase(); //lookup tables have lowercase keys
var multiplier = reverse? -1 : 1;
var currentOrder = _this.scales.gridX.domain();
var sortableList = currentOrder.map(function(e, i){return {index:i,value:e}; });
var sortedList = sortableList.sort(function (a, b) {
var sampA = _this.data.samples[a.value.toLowerCase()];
var sampB = _this.data.samples[b.value.toLowerCase()];
var valueA = sampA[type][rowname];
var valueB = sampB[type][rowname];
if(type=='gene'){
if(valueA.alterations.length>0 && valueB.alterations.length==0) return -1*multiplier;
else if(valueA.alterations.length==0 && valueB.alterations.length>0) return 1*multiplier;
else return a.index-b.index;
}
else if(type=='demographic'){
var comparison = valueA.value.localeCompare(valueB.value);
if(comparison != 0){
return comparison * multiplier;
}
else return a.index-b.index;
}
});
//if the row is already sorted and this is the first attempt, sort in the opposite order.
sortedSampleOrder = sortedList.map(function(e){ return e.value; });
if(currentOrder.equals(sortedSampleOrder) && !reverse){
sortByRow(type,rowname,true);
return;
}
_this.scales.gridX.domain(sortedSampleOrder);
_this.data.sampleorder = _this.scales.gridX.domain();
draw(1000);
}
function sortByGeneOrder() {
//geneOrder is the current order of genes, as sorted by user or algorithmically
var geneOrder = _this.scales.gridY.domain();
//_this.data.genomic.mutMatrix is a 2d matrix of alteration types- use this to look up whether alterations are present or not
var sortedSampleOrder = _this.data.genomic.samples.sort(function (a, b) {