File: VcfFileReader.cpp

package info (click to toggle)
libstatgen 1.0.15-8
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,588 kB
  • sloc: cpp: 49,624; ansic: 1,408; makefile: 320; sh: 60
file content (551 lines) | stat: -rw-r--r-- 16,445 bytes parent folder | download | duplicates (4)
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
/*
 *  Copyright (C) 2010-2012  Regents of the University of Michigan,
 *                           Hyun Min Kang, Matthew Flickenger, Matthew Snyder,
 *                           and Goncalo Abecasis
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "VcfFileReader.h"

VcfFileReader::VcfFileReader()
    : VcfFile(),
      myVcfIndex(NULL),
      myNewSection(false),
      mySectionChrom(""),
      mySection1BasedStartPos(-1),
      mySection1BasedEndPos(-1),
      mySectionOverlap(false),
      myRecordDiscardRules(),
      mySampleSubset(),
      myUseSubset(false),
      myMinAltAlleleCount(UNSET_MIN_ALT_ALLELE_COUNT),
      myAltAlleleCountSubset(NULL),
      myMinMinorAlleleCount(UNSET_MIN_MINOR_ALLELE_COUNT),
      myMinorAlleleCountSubset(NULL),
      myDiscardRules(0),
      myNumKeptRecords(0),
      myTotalRead(0)
{
  myFilePtr = NULL;
}


VcfFileReader::~VcfFileReader() 
{
    resetFile();
}


bool VcfFileReader::open(const char* filename, VcfHeader& header)
{
    // Close an already open file.
    close();

    myStatus = StatGenStatus::SUCCESS;
    if(VcfFile::open(filename, "r"))
    {
        // Successfully opened, so read the header.
        if(!header.read(myFilePtr))
        {
            // Failed, so copy the status.
            myStatus = header.getStatus();
            return(false);
        }
    }
    else
    {
        // Failed, status set by VcfFile::open.
        return(false);
    }

    // Successfully opened and read the header.
    return(true);
}


bool VcfFileReader::open(const char* filename, VcfHeader& header,
                         const char* includeFileName, const char* excludeSample,
                         const char* excludeFileName, const char* delims)
{
    if(!open(filename, header))
    {
        // Failed to open & read header, so return.
        return(false);
    }

    // Successfully opened and read the header, so setup the sample subset
    // object based on the specified sample files and the header.
    if(!mySampleSubset.init(header, includeFileName, excludeSample,
                            excludeFileName, delims))
    {
        // Failed to setup the subsetting.
        std::cerr << "VcfFileReader - failed to setup sample subsetting\n";
    }

    myUseSubset = true;

    // Successfully opened and read the header.
    return(true);
}


// Read VCF Index file.
bool VcfFileReader::readVcfIndex(const char* vcfIndexFilename)
{
    // Cleanup a previously setup index.
    if(myVcfIndex != NULL)
    {
        delete myVcfIndex;
        myVcfIndex = NULL;
    }

    // Create a new vcf index.
    myVcfIndex = new Tabix();
    StatGenStatus::Status indexStat = myVcfIndex->readIndex(vcfIndexFilename);

    if(indexStat != StatGenStatus::SUCCESS)
    {
        std::string errorMessage = "Failed to read the vcf Index file: ";
        errorMessage += vcfIndexFilename;
        myStatus.setStatus(indexStat, errorMessage.c_str());
        delete myVcfIndex;
        myVcfIndex = NULL;
        return(false);
    }

    if(myVcfIndex->getFormat() != Tabix::FORMAT_VCF)
    {
        std::string errorMessage = "ERROR: Tabix file not in VCF format: ";
        errorMessage += vcfIndexFilename;
        myStatus.setStatus(StatGenStatus::FAIL_PARSE, errorMessage.c_str());
        delete myVcfIndex;
        myVcfIndex = NULL;
        return(false);
    }

    myStatus = StatGenStatus::SUCCESS;
    return(true);
}


// Read VCF Index file.
bool VcfFileReader::readVcfIndex()
{
    if(myFilePtr == NULL)
    {
        // Can't read the vcf index file because the VCF file has not yet been
        // opened, so we don't know the base filename for the index file.
        std::string errorMessage = "Failed to read the vcf Index file -"
            " the VCF file needs to be read first in order to determine"
            " the index filename.";
        myStatus.setStatus(StatGenStatus::FAIL_ORDER, errorMessage.c_str());
        return(false);
    }

    const char* vcfBaseName = myFilePtr->getFileName();
    
    std::string indexName = vcfBaseName;
    indexName += ".tbi";

    bool foundFile = true;
    std::string failMessage = "";
    try
    {
        if(readVcfIndex(indexName.c_str()) == false)
        {
            foundFile = false;
        }
    }
    catch (std::exception& e)
    {
        foundFile = false;
        failMessage = e.what();
    }

    // Check to see if the index file was found.
    if(!foundFile)
    {
        // Not found - try without the vcf extension.
        // Locate the start of the vcf extension
        size_t startExt = indexName.find(".vcf");
        if(startExt == std::string::npos)
        {
            // Could not find the .vcf extension, so just return false since the
            // call to readVcfIndex set the status.
            return(false);
        }
        // Remove ".vcf" and try reading the index again.
        indexName.erase(startExt,  4);
        try
        {
            return(readVcfIndex(indexName.c_str()));
        }
        catch (std::exception& e)
        {
            failMessage += "\n";
            failMessage += e.what();
            throw(std::runtime_error(failMessage));
            return(false);
        }
    }
    return(true);
}


// return a pointer to the VCF Index file.
const Tabix* VcfFileReader::getVcfIndex()
{
    return(myVcfIndex);
}


bool VcfFileReader::readRecord(VcfRecord& record, VcfSubsetSamples* subset)
{
    myStatus = StatGenStatus::SUCCESS;
    // Subset the read if there are subsets specified.
    VcfSubsetSamples* subsetPtr = subset;
    if((subsetPtr == NULL) && myUseSubset)
    {
        subsetPtr = &mySampleSubset;
    }

    // Check to see if a new region has been set.  If so, setup for that region.
    bool searchChrom = false;
    if(myNewSection)
    {
        if(myVcfIndex != NULL)
        {
            // Have an index file so use
            if(!processNewSection())
            {
                // processNewSection sets the status appropriately on failure.
                return(false);
            }
        }
        else if(myTotalRead == 0)
        {
            // ReadSection without an index only works if no records
            // have been read.
            searchChrom = true;
            myNewSection = false;
        }
        else
        {
            myNewSection = false;
            myStatus.setStatus(StatGenStatus::FAIL_ORDER, 
                               "Cannot set read section with no index after reading records");
            return(false);
        }
    }

    // Keep looping until a desired record is found.
    bool recordFound = false;
    while(!recordFound)
    {
        if(!record.read(myFilePtr, mySiteOnly, myRecordDiscardRules, subsetPtr))
        {
            myStatus = record.getStatus();
            myTotalRead += myRecordDiscardRules.getNumDiscarded();
            myNumRecords += myRecordDiscardRules.getNumDiscarded();
            myRecordDiscardRules.clearNumDiscarded();
            return(false);
        }

        ++myTotalRead;
        myTotalRead += myRecordDiscardRules.getNumDiscarded();

        // Check to see if the record is in the section.
        // First check the chromosome.
        if(!mySectionChrom.empty() && (mySectionChrom != record.getChromStr()))
        {
            if(searchChrom)
            {
                // Still searching for the chromosome, so continue
                // to the next record.
                continue;
            }

            // Record is not within the correct chromosome, so return failure.
            myStatus = StatGenStatus::NO_MORE_RECS;
           return(false);
        }
        searchChrom = false;

        // Check if the record is after the section end if applicable.
        if((mySection1BasedEndPos != -1) && 
           (record.get1BasedPosition() >= mySection1BasedEndPos))
        {
            myStatus = StatGenStatus::NO_MORE_RECS;
            return(false);
        }
        
        // Check if the record is prior to the section start if applicable.
        // Determinine the VCF record end position.
        // If we are not requiring overlap, then we only need to check
        // the start position, but if overlap is required, then it needs
        // to incrment the start by the length-1.
        int numIncBases = 0;
        if(mySectionOverlap)
        {
            // The VCF record end position is the start position + length of the
            // reference string - 1.
            numIncBases = record.getNumRefBases() - 1;
        }
        if((mySection1BasedStartPos != -1) &&
           ((record.get1BasedPosition() + numIncBases)
            < mySection1BasedStartPos))
        {
            // This record is prior to the section, so keep reading.
            continue;
        }

        ++myNumRecords;
        myNumRecords += myRecordDiscardRules.getNumDiscarded();
        myRecordDiscardRules.clearNumDiscarded();
        
        // Record successfully read, so check to see if it is discarded.
        if((myDiscardRules & DISCARD_NON_PHASED) && !record.allPhased())
        {
            // Not all samples are phased, so discard this record.
            continue;
        }
        if((myDiscardRules & DISCARD_MISSING_GT) &&
           !record.hasAllGenotypeAlleles())
        {
            // discard missing GTs and this record had missing alleles,
            // so keep reading.
            continue;
        }
        if((myDiscardRules & DISCARD_FILTERED) && 
           !(record.getFilter().passedAllFilters()))
        {
            // Record was filtered, so discard it.
            continue;
        }
        if((myDiscardRules & DISCARD_MULTIPLE_ALTS) &&
           (record.getNumAlts() > 1))
        {
            // Record had multiple alternates, so discard.
            continue;
        }

        // Check allele counts for discarding.
        if(myMinAltAlleleCount != UNSET_MIN_ALT_ALLELE_COUNT)
        {
            // Count the number of alternates.
            int32_t altCount = 0;
            for(int sampleNum = 0; sampleNum < record.getNumSamples(); 
                sampleNum++)
            {
                if((myAltAlleleCountSubset != NULL) &&
                   !(myAltAlleleCountSubset->keep(sampleNum)))
                {
                    // Skip this sample.
                    continue;
                }
                for(int gtNum = 0; gtNum < record.getNumGTs(sampleNum); gtNum++)
                {
                    if(record.getGT(sampleNum, gtNum) > 0)
                    {
                        // Alternate, so increment the count.
                        ++altCount;
                    }
                }
            }
            if(altCount < myMinAltAlleleCount)
            {
                // Not enough alternates so continue to the next sample.
                continue;
            }
        }

        // Check to see if the minimum alternate allele count is met.
        if(myMinMinorAlleleCount != UNSET_MIN_MINOR_ALLELE_COUNT)
        {
            // Get the number of possible alternates.
            unsigned int numAlts = record.getNumAlts();

            // Verify that each allele has the min count.
            bool failMinorAlleleCount = false;
            for(unsigned int i = 0; i <= numAlts; i++)
            {
                if(record.getAlleleCount(i, myMinorAlleleCountSubset) 
                   < myMinMinorAlleleCount)
                {
                    // Not enough of one gt, so not ok.
                    failMinorAlleleCount = true;
                    break;
                }
            }
            if(failMinorAlleleCount)
            {
                // not enough alleles, so continue to the next record.
                continue;
            }
        }

        // Record was not discarded.
        recordFound = true;
    }

    // Increment the number of kept records.
    ++myNumKeptRecords;
    return(true);
}


bool VcfFileReader::setReadSection(const char* chromName)
{
    return(set1BasedReadSection(chromName, -1, -1));
}


bool VcfFileReader::set1BasedReadSection(const char* chromName, 
                                         int32_t start, int32_t end,
                                         bool overlap)
{
    myNewSection = true;
    mySectionChrom = chromName;
    mySection1BasedStartPos = start;
    mySection1BasedEndPos = end;
    mySectionOverlap = overlap;
    return(true);
}


// Returns whether or not the end of the file has been reached.
// return: int - true = EOF; false = not eof.
bool VcfFileReader::isEOF()
{
    if (myFilePtr != NULL)
    {
        // File Pointer is set, so return if eof.
        return(ifeof(myFilePtr));
    }
    // File pointer is not set, so return true, eof.
    return true;
}


bool VcfFileReader::setExcludeIDs(const char* filename)
{
    return(myRecordDiscardRules.setExcludeIDs(filename));
}


bool VcfFileReader::setIncludeIDs(const char* filename)
{
    return(myRecordDiscardRules.setIncludeIDs(filename));
}


void VcfFileReader::addDiscardMinAltAlleleCount(int32_t minAltAlleleCount, 
                                                VcfSubsetSamples* subset)
{
    myMinAltAlleleCount = minAltAlleleCount;
    myAltAlleleCountSubset = subset;
}


void VcfFileReader::rmDiscardMinAltAlleleCount()
{
    myMinAltAlleleCount = UNSET_MIN_ALT_ALLELE_COUNT;
    myAltAlleleCountSubset = NULL;
}


void VcfFileReader::addDiscardMinMinorAlleleCount(int32_t minMinorAlleleCount, 
                                                  VcfSubsetSamples* subset)
{
    myMinMinorAlleleCount = minMinorAlleleCount;
    myMinorAlleleCountSubset = subset;
}


void VcfFileReader::rmDiscardMinMinorAlleleCount()
{
    myMinMinorAlleleCount = UNSET_MIN_ALT_ALLELE_COUNT;
    myMinorAlleleCountSubset = NULL;
}


void VcfFileReader::resetFile()
{
    myRecordDiscardRules.reset(),
    mySampleSubset.reset();
    myUseSubset = false;
    myNumKeptRecords = 0;
    myTotalRead = 0;
    myNewSection = false;
    mySectionChrom = "";
    mySection1BasedStartPos = -1;
    mySection1BasedEndPos = -1;
    mySectionOverlap = false;

    if(myVcfIndex != NULL)
    {
        delete myVcfIndex;
        myVcfIndex = NULL;
    }
}


bool VcfFileReader::processNewSection()
{
    myNewSection = false;
    
    // Check to see if the index file has been read.
    if(myVcfIndex == NULL)
    {
        myStatus.setStatus(StatGenStatus::FAIL_ORDER, 
                           "Cannot read section since there is no index file open");
        throw(std::runtime_error("SOFTWARE BUG: trying to read a VCF record by section prior to opening the VCF Index file."));
        return(false);
    }

    if(myFilePtr == NULL)
    {
        myStatus.setStatus(StatGenStatus::FAIL_ORDER, 
                           "Cannot read section without first opening the VCF file.");
        throw(std::runtime_error("SOFTWARE BUG: trying to read a VCF record by section prior to opening the VCF file."));
        return(false);
    }

    // Using random access, so can't buffer
    myFilePtr->disableBuffering();

    uint64_t startPos = 0;
    // Find where this section starts in the file.
    if(!myVcfIndex->getStartPos(mySectionChrom.c_str(),
                                mySection1BasedStartPos, 
                                startPos))
    {
        // Didn't find the position.
        myStatus = StatGenStatus::NO_MORE_RECS;
        return(false);
    }
    if(startPos != (uint64_t)iftell(myFilePtr))
    {
        // Seek to the start position.
        if(ifseek(myFilePtr, startPos, SEEK_SET) != true)
        {
            // seek failed, return failure.
            myStatus.setStatus(StatGenStatus::FAIL_IO, 
                               "Failed to seek to the specified section");
            return(false);
        }
    }
    return(true);
}