-
Notifications
You must be signed in to change notification settings - Fork 1
/
binarytojson.js
2489 lines (2074 loc) · 80.3 KB
/
binarytojson.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 ready = false;
var ds = {
numWindow: 0,
numPos: 0
};
// JSON object to hold metrics for each pair of positions
var metrics = {};
var filtered = {};
var refString = "-";
// keep track of any annotations we have
var annotations = [];
// the position-ordered sequence of annotations
// (e.g. break an annotation up if it spans multiple sequences of positions)
var annotatePos = [];
// some sort of method to keep track of what the distribution of values looks like
// (populate on loading data)
var threshCounts = {
'depth': [],
'variant': [],
'metric': []
};
// parameters to filter on (eventually make these user-configurable)
var minDepthPercent = 0.25;
var minVariants = 0.1;
var minVarJ = true;
var minMetric = 0.3;
var doHistograms = false;
// JSON object to hold the 2x2 matrix of counts for each pair of positions
var counts = {};
// NOTE: adapts the loadBinaryData() function from matrixviewer.js to output
// data in a JSON format
// general function to read in binary data
// assumes three header ints:
// <window_size> <num_pos> <header_flags>
// ... where <header_flags> is a 32-bit int:
//
// spacing (# data/element)
// precision (n/a for floats) __ |
// is int? (n is float)__| |
// || |
// is a sparse representation_|| |
// ||| |
// uuuuuuuuuuuuuuuuuuuuuuuuuusippnn
var loadBinaryData = function(data, name) {
ready = false;
console.log("trying to parse file %s", name)
console.time("parsing file " + name);
//updateLoadingStatus("parsing " + name + " file...");
var dv = new DataView(data);
console.log("%s has size %d (%s MB)", name, dv.byteLength, (dv.byteLength / 1024 / 1024).toFixed(1));
var thisNumWindow = dv.getInt32(0);
var thisNumPos = dv.getInt32(4);
// parse the header flags
var headerFlagInt = dv.getInt32(8);
// headerFlagInt >>= 8; // for some reason, java puts this stuff in the first two bytes?
var thisSpacing = (headerFlagInt & 3) + 1;
var precision = ((headerFlagInt & 12) >> 2) + 1;
var isInt = (headerFlagInt & 16) > 0;
var isSparse = (headerFlagInt & 32) > 0;
// do some function definition here based on the header flags
var headerSize = 12;
var getDataVal = function(offset) { return DataView.prototype.getFloat32.call(dv, offset); };
if (isInt) {
getDataVal = function(offset) { return DataView.prototype.getInt32.call(dv, offset); };
if (precision == 2) {
getDataVal = function(offset) { return DataView.prototype.getInt16.call(dv, offset); };
} else if (precision == 1) {
getDataVal = function(offset) { return DataView.prototype.getInt8.call(dv, offset); };
}
} else {
precision = 4;
}
// do a bunch of error checking (also serves as documentation)
if (ds.numPos && ds.numPos != thisNumPos) {
console.warn("number of lines in file %s does not match data: expected %d, depth had %d lines", name, ds.numPos, thisNumPos);
}
if (ds.numWindow && ds.numWindow != thisNumWindow) {
console.warn("number of items in a window does not match data in %s: expected %d, depth had a window size of %d", name, ds.numWindow, thisNumWindow);
}
var expectedPositions = 0;
if (isSparse) {
expectedPositions = (dv.byteLength - headerSize) / (thisSpacing * precision + 4);
if (expectedPositions % 1 != 0) {
console.warn("expected to find %d positions of data, found a fraction of %f extra data (each element has %d data values associated of %d bytes of precision each)", expectedPositions, expectedPositions % 1, thisSpacing, precision);
expectedPositions = Math.floor(expectedPositions);
}
} else {
var expectedBytes = (thisNumWindow * thisNumPos * thisSpacing) * precision + headerSize;
if (dv.byteLength !== expectedBytes) {
console.warn("expected to find %d bytes of data from header, found %d instead. unusual truncation may occur", dv.byteLength, expectedBytes);
if (dv.byteLength < expectedBytes) {
console.error("missing data designated by header, please check the file. aborting.");
return false;
}
}
}
// if we don't have any population of numWindow and numPos,
// populate it with this dataset.
var windowOffset = 0;
var numPositions = thisNumPos;
if (ds.numWindow == 0 || ds.numPos == 0) {
ds.numWindow = thisNumWindow;
ds.numPos = thisNumPos;
$("#numWindow").html(Math.floor(ds.numWindow / 2));
}
// set up bounds structure
if (!metrics.hasOwnProperty('bounds'))
metrics['bounds'] = {};
if (thisSpacing > 1) {
metrics['bounds'][name] = [];
for (var n = 0; n < thisSpacing; n++) {
metrics['bounds'][name][n] = {max: -1000000, min: 1000000};
}
} else {
metrics['bounds'][name] = {max: -1000000, min: 1000000};
}
var createPairIfMissing = function(i, j) {
// create an entry for i if it doesn't exist
if (!metrics.hasOwnProperty(i))
metrics[i] = {};
// create an entry for i > j if it doesn't exist
if (!metrics[i].hasOwnProperty(j)) {
metrics[i][j] = {};
metrics[i][j]["posi"] = +i;
metrics[i][j]["posj"] = +j;
}
};
// explode out the sparse representation to a full representation for the GPU
var offset = headerSize;
if (isSparse) {
console.log(name + " is sparse...");
// handle the special fullcounts file
// (which contains a sparse 4x4 matrix of bases for every co-occurrence)
if (name == "fullcounts") {
var bases = ['A', 'T', 'C', 'G'];
var getBasesFromByte = function(byte) {
var bi = bases[byte >> 2];
var bj = bases[byte & 3];
return bi + "," + bj;
};
var counter = 0;
while (dv.byteLength != offset) {
if (++counter % 10000 === 0) {
console.log("fullcounts checkpoint (%s% done)", (offset / dv.byteLength * 100).toFixed(2));
}
var curIndex = dv.getInt32(offset);
offset += 4;
// okay, so we have the index (0-indexed); convert into i, j coordinates (1-index)
var i = Math.floor(curIndex / ds.numWindow) + 1;
var j = (i - 1) - Math.floor(ds.numWindow / 2) + (curIndex % ds.numWindow) + 1;
var numEntries = dv.getInt8(offset);
offset += 1;
if (numEntries == 0)
continue;
createPairIfMissing(i, j);
metrics[i][j][name] = [];
for (var n = 0; n < numEntries; n++) {
var baseByte = dv.getInt8(offset);
offset += 1;
var base = getBasesFromByte(baseByte);
var newEntry = {};
newEntry['base'] = base;
newEntry['num'] = dv.getInt32(offset);
offset += 4;
metrics[i][j][name].push(newEntry);
}
}
} else if (name == "refdata") {
refString = "-";
while (dv.byteLength != offset) {
var thisByte = dv.getInt8(offset);
offset += 1;
// TODO: positions that don't have a reference will default to A (bad?)
var bases = ['A', 'T', 'C', 'G'];
var theseBases = "";
for (var n = 0; n < 4; n++) {
var thisBase = bases[thisByte & 3];
theseBases = thisBase + theseBases;
thisByte >>= 2;
}
refString += theseBases;
}
} else {
for (var n = 0; n < expectedPositions; n++) {
var curIndex = dv.getInt32(offset);
offset += 4;
// okay, so we have the index (0-indexed); convert into i, j coordinates (1-index)
var i = Math.floor(curIndex / ds.numWindow) + 1;
var j = (i - 1) - Math.floor(ds.numWindow / 2) + (curIndex % ds.numWindow) + 1;
// create an entry for i, j if it doesn't exist
createPairIfMissing(i, j);
// fill in the metric
if (thisSpacing > 1) {
if (!metrics[i][j].hasOwnProperty(name))
metrics[i][j][name] = [];
for (var k = 0; k < thisSpacing; k++) {
var curVal = getDataVal(offset);
metrics[i][j][name][k] = curVal;
// calculate bounds
metrics['bounds'][name][k]['max'] = Math.max(metrics['bounds'][name][k]['max'], curVal);
metrics['bounds'][name][k]['min'] = Math.min(metrics['bounds'][name][k]['min'], curVal);
offset += precision;
}
} else {
var curVal = getDataVal(offset);
metrics[i][j][name] = curVal;
// calculate bounds
metrics['bounds'][name]['max'] = Math.max(metrics['bounds'][name]['max'], curVal);
metrics['bounds'][name]['min'] = Math.min(metrics['bounds'][name]['min'], curVal);
// increment the offset counter
offset += precision;
}
}
}
} else {
console.log(name + " is dense...");
for (var i = 0; i < numPositions; i++) {
for (var j = windowOffset; j < ds.numWindow - windowOffset; j++) {
for(var n = 0; n < thisSpacing; n++) {
var curVal = getDataVal(offset);
// increment the offset counter
offset += precision;
// if this number is zero, don't bother recording it
if (curVal == 0)
continue;
// calculate these indicies (and convert to 1-indexed)
var index_i = i + 1;
var index_j = i - Math.floor(ds.numWindow / 2) + j + 1;
// create an entry for i if it doesn't exist
createPairIfMissing(index_i, index_j);
// if there is more than one possible value per position pair,
// create an entry for i > j > name > n
if (thisSpacing > 1) {
if (!metrics[index_i][index_j].hasOwnProperty(name))
metrics[index_i][index_j][name] = [];
metrics[index_i][index_j][name][n] = curVal;
} else {
// fill in the metric
metrics[index_i][index_j][name] = curVal;
}
// calculate bounds
metrics['bounds'][name]['max'] = Math.max(metrics['bounds'][name]['max'], curVal);
metrics['bounds'][name]['min'] = Math.min(metrics['bounds'][name]['min'], curVal);
}
}
}
}
console.timeEnd("parsing file " + name);
continueIfDone();
};
var updateProgress = function(name) {
return function(e) {
if (e.lengthComputable) {
var val = Math.round(e.loaded / e.total * 100);
$("#" + name + "Prog").val(val);
$("#" + name + "ProgVal").html(val + "%");
} else {
$("#" + name + "Prog").val();
$("#" + name + "ProgVal").html("N/A");
}
};
};
var makeBinaryFileRequest = function(filename, name) {
// if a specific name is given, use it; otherwise just use the filename
// as the identifier
name = name || filename;
// jQuery looks too hard here; it's not implemented yet for ArrayBuffer
// xhr requests, which is an HTML5 phenomenon:
// http://www.artandlogic.com/blog/2013/11/jquery-ajax-blobs-and-array-buffers/
var xhr = new XMLHttpRequest();
xhr.open('GET', filename, true);
xhr.responseType = 'arraybuffer';
xhr.addEventListener('progress', updateProgress(name), false);
xhr.addEventListener('load', function() {
if (xhr.status == 200) {
loadBinaryData(xhr.response, name);
} else {
console.warning("failed to load requested file (status: %d)", xhr.status);
console.trace();
}
});
xhr.send(null);
};
var brushes = {};
var firstRun = true;
var continueIfDone = function() {
var theIs = Object.keys(metrics);
if (theIs.length == 0)
return;
// spin until all files have been parsed
var counter = 10;
while (--counter > 0) {
// get an arbitrary index to play with
var i = theIs[Math.floor(Math.random() * theIs.length)];
var theJs = Object.keys(metrics[i]);
var j = theJs[Math.floor(Math.random() * theJs.length)];
var curVal = metrics[i][j];
if (!curVal.hasOwnProperty('depth')) {
console.log("failed to find 'depth' (%s, %s), waiting...", i, j);
return;
}
if (!curVal.hasOwnProperty('fullcounts')) {
console.log("failed to find fullcounts");
return;
}
// metric should only be missing if no variants at either position (assume metric isn't loaded yet)
if (!curVal.hasOwnProperty('metric')) {
console.log("failed to find a metric when one was expected, waiting...");
console.log(curVal);
continue;
}
}
// set a visibility field
Object.keys(metrics).forEach(function(curI) {
Object.keys(metrics[curI]).forEach(function(curJ) {
metrics[curI][curJ]['visible'] = false;
});
});
updateLoadingStatus("collecting data...");
// try doing the scales
if (doHistograms) {
collectStats();
tryCollectStats();
}
makeSlider('depth');
makeSlider('variant');
makeSlider('metric');
firstRun = false;
filterData();
updateVis();
};
var collectStats = function() {
// for each element, gather and save distributions of metrics
console.time('collecting stats');
var is = Object.keys(metrics);
is.forEach(function(curI) {
if (curI === 'bounds') return;
var js = Object.keys(metrics[curI]);
js.forEach(function(curJ) {
var curPair = metrics[curI][curJ];
if (curPair.hasOwnProperty('depth'))
threshCounts.depth.push(curPair.depth);
var thisCounts = getVariantMatrixAtPos(curPair.posi, curPair.posj);
if (curPair.hasOwnProperty('counts')) {
threshCounts.variant.push(
Math.min(
(thisCounts.vivj + thisCounts.vimj) / curPair.depth,
(thisCounts.vivj + thisCounts.mivj) / curPair.depth
)
);
}
if (curPair.hasOwnProperty('metric'))
threshCounts.metric.push(Math.abs(curPair.metric));
});
});
console.timeEnd('collecting stats');
};
var flatMetrics = [];
var tryCollectStats = function() {
console.time('trying new filtering');
flatMetrics = [];
d3.keys(metrics).forEach(function(curI) {
d3.keys(metrics[curI]).forEach(function(curJ) {
// filter here
var curVal = metrics[curI][curJ];
if (!curVal.hasOwnProperty('depth') || !curVal.hasOwnProperty('counts') || !curVal.hasOwnProperty('metric'))
return;
var minDepth = Math.floor(metrics['bounds']['depth']['max'] * minDepthPercent);
if (curVal.depth < minDepth) {
metrics[curI][curJ].visible = false;
return;
}
var thisCounts = getVariantMatrixAtPos(curI, curJ);
var varLevel = (thisCounts.vivj + thisCounts.vimj) / curVal.depth;
if (varLevel < minVariants) {
metrics[curI][curJ].visible = false;
return;
}
varLevel = (thisCounts.vivj + thisCounts.mivj) / curVal.depth;
if (varLevel < minVariants) {
metrics[curI][curJ].visible = false;
return;
}
if (Math.abs(curVal.metric) < minMetric) {
metrics[curI][curJ].visible = false;
return;
}
metrics[curI][curJ].visible = true;
flatMetrics.push(metrics[curI][curJ]);
});
});
console.timeEnd('trying new filtering');
};
var histoScales = {'x': {}, 'y': {}};
var filterData = function() {
// try to filter out anything that doesn't meet the following criteria
updateLoadingStatus("filtering data based on thresholds...");
// try filtering on depth
console.time("filtering");
filtered = [];
Object.keys(metrics).forEach(function(i) {
if (i == 'bounds')
return;
// coerce to number
i = +i;
var theJs = Object.keys(metrics[i]);
theJs.forEach(function(j) {
var curVal = metrics[i][j];
// heuristic: remove self co-occurrences
if (i == j)
return;
// check for minimum depth; quit if fails
var minDepth = Math.floor(metrics['bounds']['depth']['max'] * minDepthPercent);
if (!curVal.hasOwnProperty('depth') || curVal.depth < minDepth)
return;
// calculate the level of variance
// if (!curVal.hasOwnProperty('counts')) {
// console.log("missing counts from " + i + ", " + j);
// return;
// }
// calculate synonymy for those pairs that we care about (short-circuit if already calculated)
getSynonymyCounts(curVal.posi, curVal.posj);
// var thisReads = getVariantMatrixAtPos(i, j);
var thisCounts = getVariantMatrixAtPos(i, j);
var thisLevel = (thisCounts.vivj + thisCounts.vimj) / curVal.depth;
if (thisLevel < minVariants)
return;
// do we enforce a minimum variance for j as well?
thisLevel = (thisCounts.vivj + thisCounts.mivj) / curVal.depth;
if (minVarJ && thisLevel < minVariants)
return;
// check for minimum co-occurrence metric
if (Math.abs(!curVal.hasOwnProperty('metric') || $("#dosynonymy").prop('checked') ? curVal.metric_syn : curVal.metric) < minMetric)
return;
// curVal.posi = +i;
// curVal.posj = +j;
// calculate synonymy for those pairs that we care about (short-circuit if already calculated)
// getSynonymyCounts(curVal.posi, curVal.posj);
// if all other checks pass, copy to filtered
// search if this i already exists: add if not, append to existing if so
var foundExisting = false;
for (var n = 0; n < filtered.length; n++) {
var curEntry = filtered[n];
if (curEntry.pos === i) {
// TODO: update 'interesting-ness' score for i
curEntry.relatedPairs.push(curVal);
curEntry.numFound++;
foundExisting = true;
break;
}
}
if (!foundExisting) {
var newEntry = {
pos: i,
numFound: 1,
relatedPairs: [curVal],
interestingness: 0
};
filtered.push(newEntry);
}
});
});
console.timeEnd("filtering");
hideLoading();
};
binThresholds = {};
var updateHistograms = function() {
if (!doHistograms) return;
// update the histograms
tryCollectStats();
['metric', 'depth', 'variant'].forEach(function(type) {
// collect the data for this histogram
var typeVals = [];
switch (type) {
case 'metric':
case 'depth':
typeVals = flatMetrics.map(function(d) {
return d[type];
});
break;
case 'variant':
typeVals = flatMetrics.map(function(d) {
var thisCounts = getVariantMatrixAtPos(d.posi, d.posj);
return Math.min(
(thisCounts.vivj + thisCounts.vimj) / d.depth,
(thisCounts.vivj + thisCounts.mivj) / d.depth
);
});
break;
default:
console.error('unknown type received when redrawing selected histogram bars');
return;
}
var selBarData = d3.layout.histogram()
.bins(binThresholds[type])
(typeVals);
var selBar = d3.select('.' + type + '-slider').select('.legend-bars').selectAll('.barVisible')
.data(selBarData);
// ENTER
var newBar = selBar.enter()
.append('g')
.attr('class', 'barVisible')
.attr('transform', function(d) {
return 'translate(' + histoScales.x[type](d.x) + ',' + histoScales.y[type](d.y) + ')';
});
newBar.append('rect')
.attr('x', 1)
.attr('width', histoScales.x[type](selBarData[0].dx) - 1)
.style('fill', '#f00');
// ENTER + UPDATE
selBar.attr('transform', function(d) {
return 'translate(' + histoScales.x[type](d.x) + ',' + histoScales.y[type](d.y) + ')';
});
selBar.select('rect')
.attr('width', histoScales.x[type](selBarData[0].dx) - 1)
.attr('height', function(d) {
return 50 - histoScales.y[type](d.y);
});
});
};
var progressStatus = '<div class="progs">' +
'<span id="depthStatus">Loading Depth</span>: ' +
'<progress value="0" max="100" id="depthProg"></progress> ' +
'<span class="progValue" id="depthProgVal">0%</span><br />' +
'<span id="metricStatus">Loading Metric</span>: ' +
'<progress value="0" max="100" id="metricProg"></progress> ' +
'<span class="progValue" id="metricProgVal">0%</span><br />' +
'<span id="fullcountsStatus">Loading Base Counts</span>: ' +
'<progress value="0" max="100" id="fullcountsProg"></progress> ' +
'<span class="progValue" id="fullcountsProgVal">0%</span>' +
'</div>';
var geneColors;
var loadDataset = function(datasetName, datasetObj) {
datasetName = datasetName.replace("|", "/");
var dataDir = "data/" + datasetName + "/";
updateLoadingStatus("loading dataset " + datasetName + "<br />" + progressStatus);
// reset dataset counts/parameters;
ds.numPos = 0;
ds.numWindow = 0;
firstRun = true;
// reset annotations and reload
annotations = [];
annotatePos = [];
layers = [];
geneTip.hide();
tip.hide();
makeBinaryFileRequest(dataDir + datasetObj.attenuation, 'depth');
makeBinaryFileRequest(dataDir + datasetObj.metrics[0], 'metric');
if (datasetObj.hasOwnProperty('annotations')) {
$.getJSON(
dataDir + datasetObj.annotations,
function(data) {
annotations = data;
var curIndex = 0;
annotations.forEach(function(d, i) {
var seqs = d.locations.split(";")
seqs.forEach(function(seq) {
pos = seq.split('-');
newAnnot = {min: +pos[0], max: +pos[1], name: d.gene, geneIndex: i, thisIndex: curIndex++};
annotatePos.push(newAnnot);
});
});
geneColors = d3.scale.category10()
.domain(annotations.map(function(d) { return d.gene; }));
// generate a layout for these domains, minimizing overlaps
generateAnnotationLayout();
}
);
}
if (datasetObj.hasOwnProperty('fullcounts')) {
makeBinaryFileRequest(dataDir + datasetObj.fullcounts, 'fullcounts');
}
if (datasetObj.hasOwnProperty('refdata')) {
makeBinaryFileRequest(dataDir + datasetObj.refdata, 'refdata');
}
};
var getAnnotationForPosition = function(pos) {
if (annotations.length == 0)
return [];
matchedAnnotations = [];
annotatePos.forEach(function(d, i) {
if (pos >= d.min && pos <= d.max)
matchedAnnotations.push(annotations[d.geneIndex]);
});
return matchedAnnotations;
};
// assumes annotations and annotatePos are populated;
// returns: augments annotatePos with layer position to help renderer order named domains
var layers = [];
var generateAnnotationLayout = function() {
// start by sorting genes by number of disjoint domains, then by position
var sortedGenes = annotations.slice().sort(function(a, b) {
numDomainDiff = b.locations.split(";").length - a.locations.split(";").length;
if (numDomainDiff != 0)
return numDomainDiff;
return a.min - b.min;
});
// run through the domains
layers = [[]];
var overlaps = function(layerIndex, reqDomain) {
var doesOverlap = false;
layers[layerIndex].some(function(d) {
var otherDomain = annotatePos[d];
// get actual mins and maxes
var reqMin = Math.min(reqDomain.min, reqDomain.max);
var reqMax = Math.max(reqDomain.min, reqDomain.max);
var oMin = Math.min(otherDomain.min, otherDomain.max);
var oMax = Math.max(otherDomain.min, otherDomain.max);
//if ((reqMin >= oMin && reqMin <= oMax) || (reqMax >= oMin && reqMax <= oMax)) {
if (oMax >= reqMin && oMin <= reqMax) {
return doesOverlap = true;
}
return false;
});
return doesOverlap;
};
sortedGenes.forEach(function(g) {
var curLayer = 0;
var theseDomains = annotatePos.filter(function(d) { return d.name == g.gene; });
// check if this gene overlaps with the other layers, then assign all domains of this gene
// to a layer
while (true) {
var foundFreeLayer = true;
theseDomains.some(function(domain) {
foundFreeLayer = !overlaps(curLayer, domain)
return !foundFreeLayer;
});
if (foundFreeLayer)
break;
curLayer++;
// add a layer if we don't have one at the next index
if (layers[curLayer] === undefined)
layers[curLayer] = [];
}
// actually add these to the layer now
theseDomains.forEach(function(domain) {
layers[curLayer].push(domain.thisIndex);
});
});
};
// checks if this specific read (A, C, T, or G) is a variant at this position
// -- the status of the synonymy checkbox (#dosynonymy) affects the outcome
var DNACodonTable = {
'TTT': 'F', 'TTC': 'F',
'TTA': 'L', 'TTG': 'L', 'CTT': 'L', 'CTC': 'L', 'CTA': 'L', 'CTG': 'L',
'ATT': 'I', 'ATC': 'I', 'ATA': 'I',
'ATG': 'M',
'GTT': 'V', 'GTC': 'V', 'GTA': 'V', 'GTG': 'V',
'TCT': 'S', 'TCC': 'S', 'TCA': 'S', 'TCG': 'S',
'CCT': 'P', 'CCC': 'P', 'CCA': 'P', 'CCG': 'P',
'ACT': 'T', 'ACC': 'T', 'ACA': 'T', 'ACG': 'T',
'GCT': 'A', 'GCC': 'A', 'GCA': 'A', 'GCG': 'A',
'TAT': 'Y', 'TAC': 'Y',
'TAA': 'stop', 'TAG': 'stop', 'TGA': 'stop',
'CAT': 'H', 'CAC': 'H',
'CAA': 'Q', 'CAG': 'Q',
'AAT': 'N', 'AAC': 'N',
'AAA': 'K', 'AAG': 'K',
'GAT': 'D', 'GAC': 'D',
'GAA': 'E', 'GAG': 'E',
'TGT': 'C', 'TGC': 'C',
'TGG': 'W',
'CGT': 'R', 'CGC': 'R', 'CGA': 'R', 'CGG': 'R',
'AGT': 'S', 'AGC': 'S',
'AGA': 'R', 'AGG': 'R',
'GGT': 'G', 'GGC': 'G', 'GGA': 'G', 'GGG': 'A'
};
var isReadVariant = function(read, pos) {
read = read.toUpperCase();
if (read.length != 1)
console.warning("Excpected one character for `read` to `isReadVariant` (got %d instead)", read.length);
// for each annotation that overlaps this position, check if the read at this position
// would result in a differently-coded amino-acid
// ...
// use the function `some` to immediately short-circuit if the read is a non-synoymous
// read in ANY reading frame. returns false iff there is a synonymous read in all reading frames
return getAnnotationForPosition(pos).some(function(annotation) {
var gene = annotatePos.filter(function(d) { return d.name == annotation.gene; })[0];
var isBackward = gene.min > gene.max;
if (isBackward) {
var codonPos = Math.floor((pos - gene.min) / 3) * 3 + gene.min;
var readPosInCodon = (pos - gene.min) % 3;
var containingRefCodon = refString.substring(codonPos, codonPos - 3)
.split("").reverse().join("");
//var containingCodon = containingRefCodon.substr(0,
console.warn("NOT IMPLEMENTED FOR REVERSE READING FRAMES");
} else {
var codonPos = Math.floor((pos - gene.min) / 3) * 3 + gene.min;
var readPosInCodon = (pos - gene.min) % 3;
var containingRefCodon = refString.substring(codonPos, codonPos + 3);
var containingCodon = containingRefCodon.substr(0, readPosInCodon) + read
+ containingRefCodon.substr(readPosInCodon + 1);
//console.log("comparing %s to reference %s (codon starts at %d, this position in codon is at %d)", containingCodon, containingRefCodon, codonPos, readPosInCodon);
return DNACodonTable[containingRefCodon] != DNACodonTable[containingCodon];
}
});
};
// given two positions i, j, calculate the number of variants, non-variants, and synoymic variants
var getSynonymyCounts = function(i, j) {
if (metrics[i][j].hasOwnProperty('metric_syn'))
return;
metrics[i][j].fullcounts.forEach(function(pair) {
var read_i = pair.base.charAt(0);
var read_j = pair.base.charAt(2);
if (!metrics[i][j].fullcounts.hasOwnProperty('i')) {
pair.i = refString.charAt(i) == read_i ? "m" : isReadVariant(read_i, i) ? "v" : "s";
pair.j = refString.charAt(j) == read_j ? "m" : isReadVariant(read_j, j) ? "v" : "s";
}
// add note about synonymous read to metrics entry (if it doesn't exist already)
if (pair.i == 's') {
if (!metrics[i][i].hasOwnProperty('synon'))
metrics[i][i].synon = read_i;
else if (metrics[i][i].synon.indexOf(read_i) == -1)
metrics[i][i].synon += read_i;
}
if (pair.j == 's') {
if (!metrics[j][j].hasOwnProperty('synon'))
metrics[j][j].synon = read_j;
else if (metrics[j][j].synon.indexOf(read_j) == -1)
metrics[j][j].synon += read_j;
}
});
// add synonymy metric to pair
var r = getVariantMatrixAtPosSyn(i, j, true);
var vi = r.vimj + r.vivj;
var mi = r.mimj + r.mivj;
var Pvjvi = vi == 0 ? 0 : r.vivj / vi;
var Pvjmi = mi == 0 ? 0 : r.mivj / mi;
metrics[i][j].metric_syn = Pvjvi - Pvjmi;
};
var getSynAtPos = function(pos) {
return metrics[pos][pos].synon;
};
var isSynAtPos = function(read, pos) {
var syns = metrics[pos][pos].synon;
if (syns)
return metrics[pos][pos].synon.indexOf(read) != -1;
else
return false;
}
var readAtPos = function(read, pos) {
if (read == refString.charAt(pos))
return 'm';
if (isSynAtPos(read, pos))
return 's';
return 'v';
};
var getVariantMatrixAtPos = function(i, j) {
return getVariantMatrixAtPosSyn(i, j, $("#dosynonymy").prop('checked'));
};
var getVariantMatrixAtPosSyn = function(i, j, isSyn) {
var curCounts = metrics[i][j].fullcounts;
var imreads = refString.charAt(i) + (isSyn ? metrics[i][i].synon || "" : "");
var jmreads = refString.charAt(j) + (isSyn ? metrics[j][j].synon || "" : "");
var ivread = function(countEntry) { return imreads.indexOf(countEntry.base.charAt(0)) == -1; };
var jvread = function(countEntry) { return jmreads.indexOf(countEntry.base.charAt(2)) == -1; };
var ret = {};
ret['vivj'] = d3.sum(curCounts.filter(function(d) { return ivread(d) && jvread(d); }), function(d) { return d.num; });
ret['vimj'] = d3.sum(curCounts.filter(function(d) { return ivread(d) && !jvread(d); }), function(d) { return d.num; });
ret['mivj'] = d3.sum(curCounts.filter(function(d) { return !ivread(d) && jvread(d); }), function(d) { return d.num; });
ret['mimj'] = d3.sum(curCounts.filter(function(d) { return !ivread(d) && !jvread(d); }), function(d) { return d.num; });
return ret;
};
var checkFilterEntry = function(i, j) {
curVal = metrics[i][j];
console.log("---- comparison pos %d to %d", +i, +j);
// check for self co-occurrences
if (i == j) {
console.warn("position (%d,%d) is a self co-occurrence; removed.", i, j);
return;
}
// check for minimum depth; quit if fails
var minDepth = Math.floor(metrics['bounds']['depth']['max'] * minDepthPercent);
if (!curVal.hasOwnProperty('depth') || curVal.depth < minDepth) {
console.warn("position (%d, %d) failed depth check: wanted %f% of %d (%d), found %d (%s%)",
i, j, Math.floor(minDepthPercent * 100), metrics['bounds']['depth']['max'], minDepth, curVal.depth, (curVal.depth / metrics['bounds']['depth']['max'] * 100).toFixed(2));
return false;
}
console.log("passed depth check: %d > %d (%s% > %d%)", curVal.depth, minDepth, (curVal.depth / metrics['bounds']['depth']['max'] * 100).toFixed(2), Math.floor(minDepthPercent * 100));
// calculate the level of variance
if (!curVal.hasOwnProperty('counts')) {
console.log("missing counts from " + i + ", " + j);
return false;
}
var thisLevel = (curVal.counts[2] + curVal.counts[3]) / curVal.depth;
if (thisLevel < minVariants) {
console.warn("position (%d, %d) failed i variant percentage check; wanted %f% for pos %d, got %s% instead", i, j, Math.floor(minVariants * 100), i, (thisLevel * 100).toFixed(2));
return false;
}
console.log("passed variant i check: %s% > %f% (%d + %d / %d)", (thisLevel * 100).toFixed(2), Math.floor(minVariants * 100), curVal.counts[2], curVal.counts[3], curVal.depth);
// do we enforce a minimum variance for j as well?
thisLevel = (curVal.counts[1] + curVal.counts[3]) / curVal.depth;
if (minVarJ && thisLevel < minVariants) {
console.warn("position (%d, %d) failed i variant percentage check; wanted %f% for pos %d, got %s% instead", i, j, Math.floor(minVariants * 100), j, (thisLevel * 100).toFixed(2));
return false;
}
console.log("passed variant j check: %s% > %f% (%d + %d / %d)", (thisLevel * 100).toFixed(2), Math.floor(minVariants * 100), curVal.counts[1], curVal.counts[3], curVal.depth);
// check for minimum co-occurrence metric
if (!curVal.hasOwnProperty('metric') || Math.abs(curVal.metric) < minMetric) {
console.warn("position (%d, %d) failed metric check; wanted abs(metric) > %f, got %s instead", i, j, minMetric, curVal.metric.toFixed(4));
return false;
}
console.log("passed metric test: abs(%s) > %f", curVal.metric.toFixed(4), minMetric);
return true;
};
// add a line to separate overview from detail
d3.select('#d3canvas')
.append('line')
.attr('x1', 0)
.attr('y1', 195)
.attr('x2', 1000)
.attr('y2', 195)
.attr('stroke', '#000')
.attr('stroke-width', 1)
.attr('shape-rendering', 'crispEdges');