-
Notifications
You must be signed in to change notification settings - Fork 199
/
BaseCoverage.js
265 lines (244 loc) · 10.8 KB
/
BaseCoverage.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
define( ['dojo/_base/declare',
'dojo/_base/array',
'JBrowse/View/Track/Wiggle',
'JBrowse/Util'
],
function( declare, array, Wiggle, Util ) {
// feature class for the features we make for the calculated coverage
// values
var CoverageFeature = Util.fastDeclare(
{
get: function(f) { return this[f]; },
tags: function() { return [ 'start', 'end', 'score' ]; },
score: 0,
constructor: function( args ) {
this.start = args.start;
this.end = args.end;
this.score = args.score;
}
});
return declare( Wiggle,
{
_defaultConfig: function() {
return Util.deepUpdate(
dojo.clone( this.inherited(arguments) ),
{
min_score: 0,
max_score: 100
}
);
},
getGlobalStats: function() {
return {};
},
getFeatures: function( query, featureCallback, finishCallback, errorCallback ) {
var thisB = this;
var leftBase = query.start;
var rightBase = query.end;
var scale = query.scale; // px/bp
var widthBp = rightBase-leftBase;
var widthPx = widthBp * ( query.scale || 1/query.basesPerSpan);
var binWidth = Math.ceil( query.basesPerSpan ); // in bp
var coverageBins = {};
var bpToBin = function( bp ) {
return Math.floor( (bp-leftBase) / binWidth );
};
this.store.getFeatures(
query,
dojo.hitch( this, function( feature ) {
var startBin = bpToBin( feature.get('start') );
var endBin = bpToBin( feature.get('end')-1 );
for( var i = startBin; i <= endBin; i++ ) {
if ( coverageBins[i] ) {
coverageBins[i]['matchCoverage']++;
}
else {
coverageBins[i] = {};
coverageBins[i]['matchCoverage'] = 1;
}
}
// Calculate SNP coverage
var mdTag = feature.get('MD');
if(mdTag && binWidth == 1) {
var SNPs = this._mdToMismatches(feature, mdTag);
// loops through mismatches and updates coverage variables accordingly.
for (var i = 0; i<SNPs.length; i++) {
var pos = bpToBin( feature.get('start') + SNPs[i].start);
// Note: we reduce matchCoverage so the sum is the total coverage
coverageBins[pos]['matchCoverage']--;
if ( coverageBins[pos][SNPs[i].bases] ) {
coverageBins[pos][SNPs[i].bases]++;
}
else {
coverageBins[pos][SNPs[i].bases] = 1;
}
}
}
}),
function () {
// make fake features from the coverage
for( var i = 0; i < Math.ceil( widthBp/binWidth ); i++ ) {
var bpOffset = leftBase+binWidth*i;
featureCallback( new CoverageFeature({
start: bpOffset,
end: bpOffset+binWidth,
score: coverageBins[i] || {'matchCoverage': 0}
}));
}
finishCallback();
}
);
},
/*
* Draw a set of features on the canvas.
* @private
*/
_drawFeatures: function( scale, leftBase, rightBase, block, canvas, features, featureRects, dataScale ) {
var context = canvas.getContext('2d');
var canvasHeight = canvas.height;
var toY = dojo.hitch( this, function( val ) {
return canvasHeight * ( 1-dataScale.normalize.call(this, val) );
});
var originY = toY( dataScale.origin );
// a canvas element below the histogram that will contain indicators of likely SNPs
var snpCanvas = dojo.create('canvas',
{height: parseInt(block.parentNode.style.height, 10) - canvas.height,
width: canvas.width,
style: { cursor: 'default'},
innerHTML: 'Your web browser cannot display this type of track.',
className: 'SNP-indicator-track'
}, block);
// widen the canvas and offset it.
snpCanvas.width += snpCanvas.height;
snpCanvas.style.position = 'relative';
snpCanvas.style.left = -snpCanvas.height*0.5 + 'px';
var snpContext = snpCanvas.getContext('2d');
var barColor = {'matchCoverage':'#999', 'A':'#00BF00', 'T':'red', 'C':'#4747ff', 'G':'#d5bb04'}; // base colors from "main.css"
var negColor = this.config.style.neg_color;
var clipColor = this.config.style.clip_marker_color;
var bgColor = this.config.style.bg_color;
var disableClipMarkers = this.config.disable_clip_markers;
var drawRectangle = function(ID, yPos, height, fRect) {
// draw the background color if we are configured to do so
if( bgColor && yPos >= 0 ) {
context.fillStyle = bgColor;
context.fillRect( fRect.l, 0, fRect.w, canvasHeight );
}
if( yPos <= canvasHeight ) { // if the rectangle is visible at all
if( yPos <= originY ) {
// bar goes upward
context.fillStyle = barColor[ID] || 'black';
context.fillRect( fRect.l, yPos, fRect.w, height);
if( !disableClipMarkers && yPos < 0 ) { // draw clip marker if necessary
context.fillStyle = clipColor || negColor;
context.fillRect( fRect.l, 0, fRect.w, 2 );
}
}
else {
// bar goes downward (Should not be reached)
context.fillStyle = negColor;
context.fillRect( fRect.l, originY, fRect.w, height );
if( !disableClipMarkers && yPos >= canvasHeight ) { // draw clip marker if necessary
context.fillStyle = clipColor || barColor[ID];
context.fillRect( fRect.l, canvasHeight-3, fRect.w, 2 );
}
}
}
};
dojo.forEach( features, function(f,i) {
var fRect = featureRects[i];
var score = f.get('score');
var totalHeight = 0;
for (counts in score) {
if (score.hasOwnProperty(counts)) {
totalHeight += score[counts];
}
}
// draw indicators of SNPs if base coverage is greater than 50% of total coverage
for (ID in score) {
if (score.hasOwnProperty(ID) && ID != 'matchCoverage' && score[ID] > 0.5*totalHeight) {
snpContext.beginPath();
snpContext.arc( fRect.l + 0.5*(fRect.w+snpCanvas.height),
0.40*snpCanvas.height,
0.20*snpCanvas.height,
1.75 * Math.PI,
1.25 * Math.PI,
false);
snpContext.lineTo(fRect.l + 0.5*(fRect.w+snpCanvas.height), 0);
snpContext.closePath();
snpContext.fillStyle = barColor[ID] || 'black';
snpContext.fill();
snpContext.lineWidth = 1;
snpContext.strokeStyle = 'black';
snpContext.stroke();
}
}
// Note: 'matchCoverage' is done first to ensure the grey part of the graph is on top
drawRectangle('matchCoverage', toY(totalHeight), originY-toY( score['matchCoverage'] )+1, fRect);
totalHeight -= score['matchCoverage'];
for (var counts in score) {
if (score.hasOwnProperty(counts) && counts != 'matchCoverage') {
drawRectangle( counts, toY(totalHeight), originY-toY( score[counts] )+1, fRect);
totalHeight -= score[counts];
}
}
}, this );
},
/**
* parse a SAM MD tag to find mismatching bases of the template versus the reference
* @returns {Array[Object]} array of mismatches and their positions
*/
_mdToMismatches: function( feature, mdstring ) {
var mismatchRecords = [];
var curr = { start: 0, bases: '' };
var seq = feature.get('seq');
var nextRecord = function() {
mismatchRecords.push( curr );
curr = { start: curr.start + curr.bases.length, bases: ''};
};
array.forEach( mdstring.match(/(\d+|\^[a-z]+|[a-z])/ig), function( token ) {
if( token.match(/^\d/) ) { // matching bases
curr.start += parseInt( token );
}
else if( token.match(/^\^/) ) { // insertion in the template
var i = token.length-1;
while( i-- ) {
curr.bases = '*';
nextRecord();
}
}
else if( token.match(/^[a-z]/i) ) { // mismatch
curr.bases = seq.substr( curr.start, token.length );
nextRecord();
}
});
return mismatchRecords;
},
/*
* The following method is required to override the equivalent method in "WiggleBase.js"
* It displays more complete data.
*/
_showPixelValue: function( scoreDisplay, score ) {
if( score && typeof score['matchCoverage'] == 'number') {
var scoreSummary = '<table>';
if( score['matchCoverage'] ){
scoreSummary +=
"<tr><td>Ref"
+ (score['refBase'] ? ' ('+score['refBase']+')': '')
+ "</td><td>"
+ score['matchCoverage']
+ '</td></tr>';
}
for (var ID in score) {
if( score.hasOwnProperty(ID) && ID != 'matchCoverage' && ID != 'refBase' ) {
scoreSummary += '<tr><td>'+ID + '</td><td>' +score[ID] +'</td></tr>';
}
}
scoreDisplay.innerHTML = scoreSummary+'</table>';
return true;
} else {
return false;
}
}
});
});