Difference between revisions of "C++ Class: SamFile"

From Genome Analysis Wiki
Jump to navigationJump to search
Line 76: Line 76:
 
=== Class Enums ===
 
=== Class Enums ===
 
{| style="margin: 1em 1em 1em 0; background-color: #f9f9f9; border: 1px #aaa solid; border-collapse: collapse;" border="1"
 
{| style="margin: 1em 1em 1em 0; background-color: #f9f9f9; border: 1px #aaa solid; border-collapse: collapse;" border="1"
|-style="background: #f2f2f2; text-align: center;" '''SamFile Class Methods'''
+
|-style="background: #f2f2f2; text-align: center;"
 
! colspan="2"| enum SortedType
 
! colspan="2"| enum SortedType
 
|-
 
|-

Revision as of 20:03, 6 April 2010

Reading/Writing SAM/BAM Files In Your Program

The SamFile class allows a user to easily read/write a SAM/BAM file.

The SamFile class contains additional functionality that allows a user to read specific sections of sorted & indexed BAM files. In order take advantage of this capability, the index file must be read prior to setting the read section. This logic saves the time of having to read the entire file and takes advantage of the seeking capability of BGZF files.

Future Enhancements: Add the ability to read alignments that match a given start, end position for a specific reference sequence.


Class Methods

Method Name Description
bool SamFile::IsEOF() bool: true if the end of file has been reached, false if not.

Be careful using this method when you are only reading a specific section since you may reach the end of your section without hitting the end of the file

bool SamFile::OpenForRead(const char* filename) Opens the specified file for reading.

Determines if it is a BAM/SAM file by reading the beginning of the file. Returns true if successfully opened reading, false if not.

bool SamFile::OpenForWrite(const char * filename) bool: true if successfully opened, false if not.

Opens as BAM file if the specified filename ends in .bam. Otherwise it is opened as a SAM file. Returns true if successfully opened for writing, false if not.

bool SamFile::ReadBamIndex(const char * filename) bool: true if the bam index file was successfully read, false if not.

Reads the specified bam index file. It must be read prior to setting a read section, for seeking and reading portions of a bam file.

void SamFile::Close() Close the file if there is one open.
bool SamFile::ReadHeader(SamFileHeader& header) Reads the header section from the file and stores it in the passed in header.

Returns true if successfully read, false if not.

bool SamFile::WriteHeader(SamFileHeader& header) Writes the specified header into the file.

Returns true if successfully written, false if not.

bool SamFile::ReadRecord(SamFileHeader& header, SamRecord& record) Reads the next record from the file and stores it in the passed in record.

If it is an indexed BAM file and SetReadSection was called, only alignments in the section specified by SetReadSection are read. If they all have already been read, this method returns false.

Validates that the record is sorted according to the value set by setSortedValidation. No sorting validation is done if specified to be unsorted, or setSortedValidation was never called.

Returns false if the record was not successfully read or not properly sorted. Returns true if successfully read and properly sorted.

bool SamFile::WriteRecord(SamFileHeader& header, SamRecord& record) Writes the specified record into the file.

Validates that the record is sorted according to the value set by setSortedValidation. No sorting validation is done if specified to be unsorted, or setSortedValidation was never called. Returns false and does not write the record if the record was not properly sorted.

Returns false if the record was not properly sorted or not successfully written. Returns true if properly sorted and successfully written.

void SamFile::setSortedValidation(SortedType sortType)<\code> Set the flag to validate that the file is sorted as it is read/written. Must be called after the file has been opened.

sortType specifies the type of sort to be checked for.

uint32_t SamFile::GetCurrentRecordCount() Return the number of records that have been read/written so far.
SamStatus::Status SamFile::GetFailure() Get the type of failure that occurred on a method failure.
bool SamFile::SetReadSection(int32_t refID) Tell the class which reference ID should be read from the BAM file. This is the index into the BAM Index list of reference information: 0 - #references. The records for that reference id will be retrieved on each ReadRecord call. When all records have been retrieved for the specified reference id, ReadRecord will return false until a new read section is set.

Pass in -1 in order to read the section of the bam file not associated with any reference ID. Returns true if the read section was successfully set, false if not. False is returned if the BAM Index File has not yet been read or if a BAM file is not open for reading.

Class Enums

enum SortedType
Enum Value Description
UNSORTED Do not do any sorting validation.
FLAG Validate that the file is sorted by the type specified in the SO Tag of the file's header.
COORDINATE Validate that the file is sorted by Coordinate.
QUERY_NAME Validate that the file is sorted by Query Name.

Usage Example

The following example reads in a sam/bam file and writes it out as a sam/bam file. The file format of the input sam/bam is determined by the SamFile class based on reading the type from the file. The file format of the output sam/bam file is determined by the SamFile class based on the extension of the output file. A ".bam" extension indicates a BAM file. All other extensions indicate SAM files.

int main(int argc, char ** argv)
{
   if(argc != 3)
   {
      printf("./bam <inputFile> <outputFile.sam/bam>\n");
      exit(-1);
   }


   SamFile samIn;
      
   samIn.OpenForRead(argv[1]);

   SamFile samOut;

   samOut.OpenForWrite(argv[2]);

   // Read the sam header.
   SamFileHeader samHeader;
   samIn.ReadHeader(samHeader);

   samOut.WriteHeader(samHeader);

   // Read the first sam record.
   SamRecord samRecord;

   // Track if any of the records are invalid.  Initialize to 0, it will 
   // be set to -1 on an invalid record.
   int status = 0;

   // Keep reading records until the end of the file is reached.
   int numValidRecords = 0;
   while(!samIn.IsEOF())
   {
      if(samIn.ReadRecord(samHeader, samRecord) == true)
      {
         // Successfully read a record from the file, so check to see
         // if it is valid.
         if(samRecord.isValid(samHeader))
         {
            //  It is valid, so write it.
            numValidRecords++;
            samOut.WriteRecord(samHeader, samRecord);
         }
         else
         {
            // There is at least one invalid record, return -1.
            status = -1;
         }
      }
      else
      {
         // Failed to read the record.  Check to see if it failed due to
         // there being no more records, which is not a failure.  Any
         // other failure reason counts as a failure.
         if(samIn.GetFailure() != SamStatus::NO_MORE_RECS)
         {
            // Read failed, invalid.
            status = -1;
         }
      }
   }
   std::cout << "Number of records read = " << 
      samIn.GetCurrentRecordCount() << std::endl;
   std::cout << "Number of records written = " << 
      samOut.GetCurrentRecordCount() << std::endl;
   std::cout << "Number of valid records = " << numValidRecords << std::endl;

   return(status);
}


This example reads in the inputFilename bam file and writes it back out section by section to the specified outputFilename, starting with section -1. It also prints a count of the number of records in each section.

int ReadIndexedBam(const char* inputFilename,
                   const char* outputFilename,
                   const char* indexFilename)
{
   SamFile samIn;
      
   samIn.OpenForRead(inputFilename);
   samIn.ReadBamIndex(indexFilename);

   SamFile samOut;

   samOut.OpenForWrite(outputFilename);

   // Read the sam header.
   SamFileHeader samHeader;
   samIn.ReadHeader(samHeader);
   // Write the sam header.
   samOut.WriteHeader(samHeader);

   SamRecord samRecord;
   
   int numValidRecords = 0;
   int numRecords = 0;

   // Loop through each Reference.
   for(int i = -1; i < 23; i++)
   {
      int numSectionRecords = 0;
      samIn.SetReadSection(i);
      // Keep reading records until they aren't read successfully.
      while(samIn.ReadRecord(samHeader, samRecord) == true)
      {
         numSectionRecords++;
         numRecords++;
         // Successfully read a record from the file, so check to see
         // if it is valid.
         if(samRecord.isValid(samHeader))
         {
            //  It is valid, so write it.
            numValidRecords++;
            samOut.WriteRecord(samHeader, samRecord);
         }
      }
      std::cout << "Reference ID " << i << " has " << numSectionRecords 
                << " records" << std::endl;
   }
      
   std::cout << "Number of records = " << numRecords << std::endl;
   std::cout << "Number of valid records = " << numValidRecords << std::endl;

   return(0);
}