-
Notifications
You must be signed in to change notification settings - Fork 0
/
vcfstream.js
478 lines (449 loc) · 13.2 KB
/
vcfstream.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
const fs = require('fs'),
byline = require('byline'),
EventEmitter = require('events'),
Variant = require('./variant.js');
class VCFStream extends EventEmitter{
constructor(vcfPath){
super();
//read the stream until the lines no longer start with #
if(!fs.existsSync(vcfPath)){
throw(`The VCF path ${vcfPath} is not available.`);
}
this.header = [];
/*
This bind statement facilitates removing the event listener
after the header has been processed.
*/
this.headerParse = this.headerParse.bind(this);
/**
The "variants" property stores variants by contig
*/
this.variants = {};
/**
The contigs property stores contig length information
*/
this.contigs = {};
/**
The format property stores data about the FORMAT fields of
each variant, based on the information from the header.
*/
this.format = {};
/**
The info property stores data about the INFO fields of
each variant, based on the information from the header.
*/
this.info = {};
/**
This array stores the sample names in the order
which they appear in the header line.
*/
this.samples = [];
/**
This array stores samples to be captured during
a filtering operation, if any.
An empty array is ignored during filtering.
*/
this.samplesFilter = [];
/**
This array stores the positional filters
*/
this.intervals = [];
/**
A collection of filters to apply to variants being streamed.
If a variant fails, it's not added to the collection.
*/
this.filters = [];
this.stream = byline.createStream(fs.createReadStream(
vcfPath, { encoding: 'utf8' }));
/**
Automatically process the header, and then pause
*/
this.stream.on('data', this.headerParse);
this.stream.on('end', () => {
this.emit('end');
});
}
/**
pass-through method to native stream "resume"
*/
resume(){
this.stream.resume();
}
/**
pass-through method to native stream "pause"
*/
pause(){
this.stream.pause();
}
headerParse(line){
var self = this;
//Check to make sure VCF is valid.
if(line && !this.header.length && !line.startsWith('#')){
throw {
name: 'FiletypeError',
message: 'This does not appear to be a VCF file.'
};
}
this.header.push(line);
/**
Check if we're on the last line of the header.
If so, capture the sample names from the line and
then halt the stream, switch over to processing
lines as variants, and notify that the header has
been processed.
*/
if(line.startsWith('#CHROM')){
line.split('\t').splice(9).forEach( (samp, index) => {
this.samples.push({
name: samp,
index: index
});
});
this.stream.pause();
this.stream.removeListener('data', this.headerParse);
this.stream.on('data', self.variantParse.bind(self));
this.emit('header');
return;
}
//store contig information
if(line.startsWith('##contig')){
let headerParts = processHeaderField(line);
let contig = headerParts[0][1];
this.contigs[contig] = parseInt(headerParts[1][1]);
this.variants[contig] = [];
return;
}
if(line.startsWith('##FORMAT')){
let headerParts = processHeaderField(line);
this.format[headerParts[0][1]] = {
number: headerParts[1][1],
type: headerParts[2][1],
description: headerParts[1][1]
};
}
if(line.startsWith('##INFO')){
let headerParts = processHeaderField(line);
this.info[headerParts[0][1]] = {
number: headerParts[1][1],
type: headerParts[2][1],
description: headerParts[1][1]
};
}
}
variantParse(line){
line = line.trim();
let fields = line.split('\t');
let contig = fields[0];
if(!this.variants.hasOwnProperty(contig)){
throw {
name: 'FormatError',
message: `Unexpected contig ${contig} found in variant data`
};
}
var newVariant = new Variant(fields, this.samples,
this.format, this.info, this.contigs[contig]);
var failedFilters = false;
//Check position ranges
if(this.intervals.length){
if(!this.intervals.filter((interval) => {
return contig === interval.chrom;
}).some((interval) => {
if(interval.endPos){
return newVariant.position >= interval.startPos
&& newVariant.position <= interval.endPos;
} else {
return newVariant.position >= interval.startPos;
}
})){
failedFilters = true;
}
}
//Check filters
if(!failedFilters && this.filters.length){
if(!this.filters.every((filter) => {
return filter.call(this, newVariant);
})){
failedFilters = true;
}
}
if(!failedFilters){
this.variants[contig].push(newVariant);
this.emit('variant');
}
}
/**
* If one or more `intervals` exist, only
* variants within those intervals will be considered.
*/
addInterval(chrom, startPos, endPos){
var filterData = {
chrom: chrom,
startPos: parseInt(startPos) || 0
};
if(endPos){
filterData['endPos'] = parseInt(endPos) || 0;
}
this.intervals.push(filterData);
}
/**
This is used to filter based on INFO fields which have a type
of "Flag". If `flagPresent` is truthy, the flag must be set on
a variant. Otherwise, the flag must be absent for the variant
being examined.
*/
addInfoFlagFilter(flagName, flagPresent){
flagName = flagName.toUpperCase();
if(!this.info.hasOwnProperty(flagName)){
throw {
name: 'FilterException',
message: `The INFO field ${flagName} was not found in the VCF header`
};
}
if(this.info[flagName].type !== 'Flag'){
throw {
name: 'FilterException',
message: `The INFO field ${flagName} is not a "Flag" type`
};
}
if(flagPresent){
this.filters.push((variant) => {
return variant.info.hasOwnProperty(flagName);
});
} else {
this.filters.push((variant) => {
return !variant.info.hasOwnProperty(flagName);
});
}
}
/**
Filter by string content. Takes an object as its argument,
with the following properties:
string: Required. String. The string for which to perform the match.
field: Required. String. The INFO property on which to perform
the string match. This must be present in the header of the VCF, or an
Exception object with name "FilterException" will be thrown.
fieldType: Required. String. INFO or FORMAT.
exact: Optional. Boolean. if truthy, the string much match exactly, both in case
and content. Otherwise, a case-insensitive check for the presence of
the 'string' value will be performed.
matchType: Optional. String. Applies only to INFO field values where the Number is
something other than "1". Can have one of three values:
'all': (Default) All items must meet the match criteria.
'any': At least one item must meet the match criteria.
'none': None of the items can meet the match criteria.
*/
addStringFilter(filterProps){
['string', 'field', 'fieldType'].forEach((reqProp) => {
if(!filterProps.hasOwnProperty(reqProp)){
throw {
name: 'FilterException',
message: `The required property ${reqProp} is missing.`
};
}
});
let field = filterProps.field.toUpperCase();
let fieldType = filterProps.fieldType.toLowerCase();
let matchType = (filterProps.matchType || 'all').toLowerCase();
if(['format', 'info'].indexOf(fieldType) === -1){
throw {
name: 'FilterException',
message: `Invalid field type ${field} specified.`
};
}
if(!this[fieldType].hasOwnProperty(field)){
throw {
name: 'FilterException',
message: `The ${fieldType} field ${field} was not found in the VCF header`
};
}
if(this[fieldType][field].type !== 'String'){
throw {
name: 'FilterException',
message: `The ${fieldType} field ${field} is not a "String" type`
};
}
if(filterProps.exact){
switch(matchType){
case 'none':
this.filters.push((variant) => {
return variant.fieldValues(fieldType, field, this.samplesFilter).every((infoVal) => {
return infoVal !== filterProps.string;
});
});
break;
case 'any':
this.filters.push((variant) => {
return variant.fieldValues(fieldType, field, this.samplesFilter).some((infoVal) => {
return infoVal === filterProps.string;
});
});
break;
default:
//default to 'all'
this.filters.push((variant) => {
return variant.fieldValues(fieldType, field, this.samplesFilter).every((infoVal) => {
return infoVal === filterProps.string;
});
});
break;
}
} else {
switch(matchType){
case 'none':
this.filters.push((variant) => {
return variant.fieldValues(fieldType, field, this.samplesFilter).every((infoVal) => {
return infoVal.indexOf(filterProps.string) === -1;
});
});
break;
case 'any':
this.filters.push((variant) => {
return variant.fieldValues(fieldType, field, this.samplesFilter).some((infoVal) => {
return infoVal.indexOf(filterProps.string) !== -1;
});
});
break;
default:
//default to 'all'
this.filters.push((variant) => {
return variant.fieldValues(fieldType, field, this.samplesFilter).every((infoVal) => {
return infoVal.indexOf(filterProps.string) !== -1;
});
});
break;
}
}
}
/**
Filter by numeric range. Takes an object as its argument,
with the following properties:
lowValue: Required. Integer or Float. The low end of the range.
field: Required. String. The INFO property on which to perform
the string match. This must be present in the header of the VCF, or an
Exception object with name "FilterException" will be thrown.
fieldType: Required. String. INFO or FORMAT.
highValue: Optional. Integer or Float. The high end of the range.
matchType: Optional. String. Applies only to INFO field values where the Number is
something other than "1". Can have one of three values:
'all': (Default) All items must meet the match criteria.
'any': At least one item must meet the match criteria.
'none': None of the items can meet the match criteria.
*/
addRangeFilter(filterProps){
['lowValue', 'field', 'fieldType'].forEach((reqProp) => {
if(!filterProps.hasOwnProperty(reqProp)){
throw {
name: 'FilterException',
message: `The required property ${reqProp} is missing.`
};
}
});
let lowVal = parseInt(filterProps.lowValue) || 0;
let field = filterProps.field.toUpperCase();
let fieldType = filterProps.fieldType.toLowerCase();
let matchType = (filterProps.matchType || 'all').toLowerCase();
let highVal = parseInt(filterProps.highValue) || null;
if(['format', 'info'].indexOf(fieldType) === -1){
throw {
name: 'FilterException',
message: `Invalid field type ${field} specified.`
};
}
if(!this[fieldType].hasOwnProperty(field)){
throw {
name: 'FilterException',
message: `The ${fieldType} field ${field} was not found in the VCF header`
};
}
if(['Integer', 'Float'].indexOf(this[fieldType][field].type) === -1){
throw {
name: 'FilterException',
message: `The ${fieldType} field ${field} is not a numeric type`
};
}
switch(matchType){
case 'none':
if(highVal){
this.filters.push((variant) => {
return variant.fieldValues(fieldType, field, this.samplesFilter).every((infoVal) => {
return (infoVal < lowVal) || (infoVal > highVal);
});
});
} else {
this.filters.push((variant) => {
return variant.fieldValues(fieldType, field, this.samplesFilter).every((infoVal) => {
return infoVal < lowVal;
});
});
}
break;
case 'any':
if(highVal){
this.filters.push((variant) => {
return variant.fieldValues(fieldType, field, this.samplesFilter).some((infoVal) => {
return infoVal >= lowVal && infoVal <= highVal;
});
});
} else {
this.filters.push((variant) => {
return variant.fieldValues(fieldType, field, this.samplesFilter).some((infoVal) => {
return infoVal >= lowVal;
});
});
}
break;
default:
//default to 'all'
if(highVal){
this.filters.push((variant) => {
return variant.fieldValues(fieldType, field, this.samplesFilter).every((infoVal) => {
return infoVal >= lowVal && infoVal <= highVal;
});
});
} else {
this.filters.push((variant) => {
return variant.fieldValues(fieldType, field, this.samplesFilter).every((infoVal) => {
return infoVal >= lowVal;
});
});
}
break;
}
}
/**
Pass an array of samples to be used in filtering
operations. Samples in the list not present in the
VCF header will be ignored.
*/
addSampleFilter(samples){
var newSamples = [];
samples.forEach((sample) => {
let foundSample = this.samples.find((s) => {
return s.name == sample;
});
if(foundSample){
newSamples.push(sample);
}
});
this.samplesFilter = newSamples;
}
get allVariants(){
var variants = [];
Object.keys(this.variants).forEach((chrom) => {
variants = variants.concat(this.variants[chrom]);
});
return variants;
}
}
function processHeaderField(headerLine){
var interiorSection = headerLine.replace(/>/, '').split('<')[1];
//Split on commas, ignoring commas in quotes
var headerParts = interiorSection.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g);
if(!headerParts.length){
headerParts = [interiorSection];
}
return headerParts.map((unit) => {
return unit.split('=');
});
}
module.exports = VCFStream;