本文整理汇总了C++中SamFile::Close方法的典型用法代码示例。如果您正苦于以下问题:C++ SamFile::Close方法的具体用法?C++ SamFile::Close怎么用?C++ SamFile::Close使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SamFile
的用法示例。
在下文中一共展示了SamFile::Close方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: testReadBam
void testReadBam()
{
SamFile inSam;
assert(inSam.OpenForRead("testFiles/testBam.bam"));
// Call generic test which since the sam and bam are identical, should
// contain the same results.
testRead(inSam);
inSam.Close();
testFlagRead("testFiles/testBam.bam");
}
示例2: finalize
bool BamProcessor::finalize (bool success)
{
if (outfile_.IsOpen ())
{
trclog << "Closing output file" << std::endl;
outfile_.Close ();
}
if (logfile_.is_open ())
{
time_t t = time (NULL);
print_stats (logfile_);
logfile_ << "\nFinished " << (success ? "successfully" : "due to error") << " at " << asctime (localtime (&t)) << "\n";
trclog << "Closing log file" << std::endl;
logfile_.close ();
}
if (info.enabled ())
print_stats (info.o_);
return true;
}
示例3: execute
//.........这里部分代码省略.........
if(myDoRecab)
{
myRecab.processReadBuildTable(*recordPtr);
}
// Nothing more to do with this record, so
// release the pointer.
mySamPool.releaseRecord(recordPtr);
}
else
{
if(SamFlag::isDuplicate(flag) && !myForceFlag)
{
// Error: Marked duplicates, and duplicates aren't excluded.
Logger::gLogger->error("There are records already duplicate marked.");
Logger::gLogger->error("Use -f to clear the duplicate flag and start the dedup_LowMem procedure over");
}
checkDups(*recordPtr, recordCount);
mySamPool.releaseRecord(recordPtr);
}
// let the user know we're not napping
if (verboseFlag && (recordCount % 100000 == 0))
{
Logger::gLogger->writeLog("recordCount=%u singleKeyMap=%u pairedKeyMap=%u, dictSize=%u",
recordCount, myFragmentMap.size(),
myPairedMap.size(),
myMateMap.size());
}
}
// we're finished reading record so clean up the duplicate search and
// close the input file
cleanupPriorReads(NULL);
samIn.Close();
// print some statistics
Logger::gLogger->writeLog("--------------------------------------------------------------------------");
Logger::gLogger->writeLog("SUMMARY STATISTICS OF THE READS");
Logger::gLogger->writeLog("Total number of reads: %u",recordCount);
Logger::gLogger->writeLog("Total number of paired-end reads: %u",
pairedCount);
Logger::gLogger->writeLog("Total number of properly paired reads: %u",
properPairCount);
Logger::gLogger->writeLog("Total number of unmapped reads: %u",
unmappedCount);
Logger::gLogger->writeLog("Total number of reverse strand mapped reads: %u",
reverseCount);
Logger::gLogger->writeLog("Total number of QC-failed reads: %u",
qualCheckFailCount);
Logger::gLogger->writeLog("Total number of secondary reads: %u",
secondaryCount);
Logger::gLogger->writeLog("Total number of supplementary reads: %u",
supplementaryCount);
Logger::gLogger->writeLog("Size of singleKeyMap (must be zero): %u",
myFragmentMap.size());
Logger::gLogger->writeLog("Size of pairedKeyMap (must be zero): %u",
myPairedMap.size());
Logger::gLogger->writeLog("Total number of missing mates: %u",
myNumMissingMate);
Logger::gLogger->writeLog("Total number of reads excluded from duplicate checking: %u",
excludedCount);
Logger::gLogger->writeLog("--------------------------------------------------------------------------");
Logger::gLogger->writeLog("Sorting the indices of %d duplicated records",
myDupList.size());
// sort the indices of duplicate records
示例4: if
//.........这里部分代码省略.........
if(myFirstFile == NULL)
{
std::cerr << "Failed to open " << firstOut
<< " so can't convert bam2FastQ.\n";
return(-1);
}
if(mySecondFile == NULL)
{
std::cerr << "Failed to open " << secondOut
<< " so can't convert bam2FastQ.\n";
return(-1);
}
}
if((readName) || (strcmp(mySamHeader.getSortOrder(), "queryname") == 0))
{
readName = true;
}
else
{
// defaulting to coordinate sorted.
samIn.setSortedValidation(SamFile::COORDINATE);
}
// Setup the '=' translation if the reference was specified.
if(!refFile.IsEmpty())
{
GenomeSequence* refPtr = new GenomeSequence(refFile);
samIn.SetReadSequenceTranslation(SamRecord::BASES);
samIn.SetReference(refPtr);
}
SamRecord* recordPtr;
int16_t samFlag;
SamStatus::Status returnStatus = SamStatus::SUCCESS;
while(returnStatus == SamStatus::SUCCESS)
{
recordPtr = myPool.getRecord();
if(recordPtr == NULL)
{
// Failed to allocate a new record.
throw(std::runtime_error("Failed to allocate a new SAM/BAM record"));
}
if(!samIn.ReadRecord(mySamHeader, *recordPtr))
{
// Failed to read a record.
returnStatus = samIn.GetStatus();
continue;
}
// Have a record. Check to see if it is a pair or unpaired read.
samFlag = recordPtr->getFlag();
if(SamFlag::isPaired(samFlag))
{
if(readName)
{
handlePairedRN(*recordPtr);
}
else
{
handlePairedCoord(*recordPtr);
}
}
else
{
++myNumUnpaired;
writeFastQ(*recordPtr, myUnpairedFile,
myUnpairedFileNameExt);
}
}
// Flush All
cleanUpMateMap(0, true);
if(returnStatus == SamStatus::NO_MORE_RECS)
{
returnStatus = SamStatus::SUCCESS;
}
samIn.Close();
closeFiles();
// Output the results
std::cerr << "\nFound " << myNumPairs << " read pairs.\n";
std::cerr << "Found " << myNumUnpaired << " unpaired reads.\n";
if(myNumMateFailures != 0)
{
std::cerr << "Failed to find mates for " << myNumMateFailures
<< " reads, so they were written as unpaired\n"
<< " (not included in either of the above counts).\n";
}
if(myNumQualTagErrors != 0)
{
std::cerr << myNumQualTagErrors << " records did not have tag "
<< myQField.c_str() << " or it was invalid, so the quality field was used for those records.\n";
}
return(returnStatus);
}
示例5: main
//.........这里部分代码省略.........
else if ( static_cast<int>(fastaFile.vnSequenceLengths[i]) != atoi(pSamHeaderRecord->getTagValue("LN")) ) {
gpLogger->error("SequenceLength is not identical between fasta and input BAM file");
}
else {
if ( !sAS.empty() )
samHeader.setSQTag("AS",sAS.c_str(),fastaFile.vsSequenceNames[i].c_str());
samHeader.setSQTag("M5",fastaFile.vsMD5sums[i].c_str(),fastaFile.vsSequenceNames[i].c_str());
if ( !sUR.empty() )
samHeader.setSQTag("UR",sUR.c_str(),fastaFile.vsSequenceNames[i].c_str());
if ( !sSP.empty() )
samHeader.setSQTag("SP",sSP.c_str(),fastaFile.vsSequenceNames[i].c_str());
}
}
gpLogger->write_log("Finished checking the consistency of SQ tags");
}
else {
gpLogger->write_log("Skipped checking the consistency of SQ tags");
}
// go over the headers again,
// assuming order of HD, SQ, RG, PG, and put proper tags at the end of the original tags
gpLogger->write_log("Creating the header of new output file");
//SamFileHeader outHeader;
samHeader.resetHeaderRecordIter();
for(unsigned int i=0; i < vsHDHeaders.size(); ++i) {
samHeader.addHeaderLine(vsHDHeaders[i].c_str());
}
/*
for(int i=0; i < fastaFile.vsSequenceNames.size(); ++i) {
std::string s("@SQ\tSN:");
char buf[1024];
s += fastaFile.vsSequenceNames[i];
sprintf(buf,"\tLN:%d",fastaFile.vnSequenceLengths[i]);
s += buf;
if ( !sAS.empty() ) {
sprintf(buf,"\tAS:%s",sAS.c_str());
s += buf;
}
if ( !sUR.empty() ) {
sprintf(buf,"\tUR:%s",sUR.c_str());
s += buf;
}
sprintf(buf,"\tM5:%s",fastaFile.vsMD5sums[i].c_str());
s += buf;
if ( !sSP.empty() ) {
sprintf(buf,"\tSP:%s",sSP.c_str());
s += buf;
}
outHeader.addHeaderLine(s.c_str());
}*/
for(unsigned int i=0; i < vsRGHeaders.size(); ++i) {
samHeader.addHeaderLine(vsRGHeaders[i].c_str());
}
for(unsigned int i=0; i < vsPGHeaders.size(); ++i) {
samHeader.addHeaderLine(vsPGHeaders[i].c_str());
}
samOut.WriteHeader(samHeader);
gpLogger->write_log("Adding %d HD, %d RG, and %d PG headers",vsHDHeaders.size(), vsRGHeaders.size(), vsPGHeaders.size());
gpLogger->write_log("Finished writing output headers");
// parse RG tag and get RG ID to append
std::string sRGID;
if ( ! vsRGHeaders.empty() ) {
std::vector<std::string> tokens;
FastaFile::tokenizeString( vsRGHeaders[0].c_str(), tokens );
for(unsigned int i=0; i < tokens.size(); ++i) {
if ( tokens[i].find("ID:") == 0 ) {
sRGID = tokens[i].substr(3);
}
}
}
gpLogger->write_log("Writing output BAM file");
SamRecord samRecord;
while (samIn.ReadRecord(samHeader, samRecord) == true) {
if ( !sRGID.empty() ) {
if ( samRecord.addTag("RG",'Z',sRGID.c_str()) == false ) {
gpLogger->error("Failed to add a RG tag %s",sRGID.c_str());
}
// temporary code added
if ( strncmp(samRecord.getReadName(),"seqcore_",8) == 0 ) {
char buf[1024];
sprintf(buf,"UM%s",samRecord.getReadName()+8);
samRecord.setReadName(buf);
}
}
samOut.WriteRecord(samHeader, samRecord);
//if ( samIn.GetCurrentRecordCount() == 1000 ) break;
}
samOut.Close();
gpLogger->write_log("Successfully written %d records",samIn.GetCurrentRecordCount());
delete gpLogger;
return 0;
}
示例6: execute
//.........这里部分代码省略.........
}
else
{
// Coordinate sorted, so work with the pools.
samIn.setSortedValidation(SamFile::COORDINATE);
myPool.setMaxAllocatedRecs(poolSize);
// Reset the number of failures
myNumMateFailures = 0;
myNumPoolFail = 0;
myNumPoolFailNoHandle = 0;
myNumPoolFailHandled = 0;
myNumOutOfOrder = 0;
// Run by coordinate
if(samOutPtr != NULL)
{
// Setup the output buffer for writing.
SamCoordOutput outputBuffer(myPool);
outputBuffer.setOutputFile(samOutPtr, &mySamHeader);
runStatus = handleSortedByCoord(samIn, &outputBuffer);
// Cleanup the output buffer.
if(!outputBuffer.flushAll())
{
std::cerr << "ERROR: Failed to flush the output buffer\n";
runStatus = SamStatus::FAIL_IO;
}
}
else
{
runStatus = handleSortedByCoord(samIn, NULL);
}
}
if(runStatus != SamStatus::SUCCESS)
{
break;
}
// Close the input file, it will be reopened if there are
// multiple steps.
samIn.Close();
if(samOutPtr != NULL)
{
samOutPtr->Close();
delete samOutPtr;
samOutPtr = NULL;
}
}
// Done processing.
// Print Stats
myOverlapHandler->printStats();
if(myNumMateFailures != 0)
{
std::cerr << "WARNING: did not find expected overlapping mates for "
<< myNumMateFailures << " records." << std::endl;
}
if(myNumPoolFail != 0)
{
// Had to skip clipping some records due to running out of
// memory and not being able to wait for the mate.
std::cerr << "WARNING: " << myNumPoolFail
<< " record pool failures\n";
if(myNumPoolFailNoHandle != 0)
{
std::cerr << "Due to hitting the max record poolSize, skipped handling "
<< myNumPoolFailNoHandle << " records." << std::endl;
}
if(myNumPoolFailHandled != 0)
{
std::cerr << "Due to hitting the max record poolSize, default handled "
<< myNumPoolFailHandled << " records." << std::endl;
}
if(myNumOutOfOrder != 0)
{
std::cerr << "WARNING: Resulting File out of Order by "
<< myNumOutOfOrder << " records.\n";
}
}
if(runStatus == SamStatus::SUCCESS)
{
if(myNumPoolFail == 0)
{
std::cerr << "Completed ClipOverlap Successfully.\n";
}
else
{
runStatus = SamStatus::NO_MORE_RECS;
std::cerr << "Completed ClipOverlap with WARNINGS.\n";
}
}
else
{
std::cerr << "Failed to complete ClipOverlap.\n";
}
return(runStatus);
}
示例7: testFlagRead
void testFlagRead(const char* fileName)
{
SamFile inSam;
SamFileHeader samHeader;
SamRecord samRecord;
////////////////////////////////////////////////////////////
// Required flag 0x48 (only flag 73 matches)
// Exclude nothing
assert(inSam.OpenForRead(fileName));
assert(inSam.ReadHeader(samHeader));
validateHeader(samHeader);
inSam.SetReadFlags(0x48, 0x0);
assert(inSam.ReadRecord(samHeader, samRecord) == true);
validateRead1(samRecord);
assert(inSam.ReadRecord(samHeader, samRecord) == false);
inSam.Close();
////////////////////////////////////////////////////////////
// No required flags.
// Exclude 0x48. This leaves just the one read with flag 133.
assert(inSam.OpenForRead(fileName));
assert(inSam.ReadHeader(samHeader));
validateHeader(samHeader);
inSam.SetReadFlags(0x0, 0x48);
assert(inSam.ReadRecord(samHeader, samRecord) == true);
validateRead2(samRecord);
assert(inSam.ReadRecord(samHeader, samRecord) == false);
inSam.Close();
////////////////////////////////////////////////////////////
// Required flag 0x40
// Exclude 0x48.
// This will not find any records since the exclude and required conflict.
assert(inSam.OpenForRead(fileName));
assert(inSam.ReadHeader(samHeader));
validateHeader(samHeader);
inSam.SetReadFlags(0x40, 0x48);
assert(inSam.ReadRecord(samHeader, samRecord) == false);
inSam.Close();
////////////////////////////////////////////////////////////
// Required flag 0x4
// Exclude 0x8.
// Only finds flag 133.
assert(inSam.OpenForRead(fileName));
assert(inSam.ReadHeader(samHeader));
validateHeader(samHeader);
inSam.SetReadFlags(0x4, 0x8);
assert(inSam.ReadRecord(samHeader, samRecord) == true);
validateRead2(samRecord);
assert(inSam.ReadRecord(samHeader, samRecord) == false);
inSam.Close();
////////////////////////////////////////////////////////////
// Required flag 0x4
// Exclude nothing
// Finds flags 133 & 141.
assert(inSam.OpenForRead(fileName));
assert(inSam.ReadHeader(samHeader));
validateHeader(samHeader);
inSam.SetReadFlags(0x4, 0x0);
assert(inSam.ReadRecord(samHeader, samRecord) == true);
validateRead2(samRecord);
assert(inSam.ReadRecord(samHeader, samRecord) == true);
validateRead8(samRecord);
assert(inSam.ReadRecord(samHeader, samRecord) == true);
validateRead10(samRecord);
assert(inSam.ReadRecord(samHeader, samRecord) == false);
inSam.Close();
}
示例8: execute
//.........这里部分代码省略.........
// Keep reading records until ReadRecord returns false.
while(samIn.ReadRecord(samHeader, samRecord)) {
// Successfully read a record from the file, so write it.
strcpy(seq,samRecord.getSequence());
strcpy(qual,samRecord.getQuality());
// Number of bases to trim from the left/right,
// set based on ignoreStrand flag and strand info.
int trimLeft = numTrimBaseL;
int trimRight = numTrimBaseR;
if(!ignoreStrand)
{
if(SamFlag::isReverse(samRecord.getFlag()))
{
// We are reversing the reverse reads,
// so swap the left & right trim counts.
trimRight = numTrimBaseL;
trimLeft = numTrimBaseR;
}
}
len = strlen(seq);
// Do not trim if sequence is '*'
if ( strcmp(seq, "*") != 0 ) {
bool qualValue = true;
if(strcmp(qual, "*") == 0)
{
qualValue = false;
}
int qualLen = strlen(qual);
if ( (qualLen != len) && qualValue ) {
fprintf(stderr,"ERROR: Sequence and Quality have different length\n");
return(-1);
}
if ( len < (trimLeft + trimRight) ) {
// Read Length is less than the total number of bases to trim,
// so trim the entire read.
for(i=0; i < len; ++i) {
seq[i] = 'N';
if ( qualValue ) {
qual[i] = '!';
}
}
}
else
{
// Read Length is larger than the total number of bases to trim,
// so trim from the left, then from the right.
for(i=0; i < trimLeft; ++i)
{
// Trim the bases from the left.
seq[i] = 'N';
if ( qualValue )
{
qual[i] = '!';
}
}
for(i = 0; i < trimRight; i++)
{
seq[len-i-1] = 'N';
if(qualValue)
{
qual[len-i-1] = '!';
}
}
}
samRecord.setSequence(seq);
samRecord.setQuality(qual);
}
if(!samOut.WriteRecord(samHeader, samRecord)) {
// Failed to write a record.
fprintf(stderr, "Failure in writing record %s\n", samOut.GetStatusMessage());
return(-1);
}
}
if(samIn.GetStatus() != SamStatus::NO_MORE_RECS)
{
// Failed to read a record.
fprintf(stderr, "%s\n", samIn.GetStatusMessage());
}
std::cerr << std::endl << "Number of records read = " <<
samIn.GetCurrentRecordCount() << std::endl;
std::cerr << "Number of records written = " <<
samOut.GetCurrentRecordCount() << std::endl;
if(samIn.GetStatus() != SamStatus::NO_MORE_RECS)
{
// Failed reading a record.
return(samIn.GetStatus());
}
// Since the reads were successful, return the status based
samIn.Close();
samOut.Close();
return 0;
}
示例9: of
//.........这里部分代码省略.........
SamFile bam;
SamFileHeader bam_header;
OpenBamAndBai( bam,bam_header, si.bam_name );
for( int i=0; i<pchr_list->size(); i++ ) {
string chr = (*pchr_list)[i];
// if ( !single_chr.empty() && chr.compare(single_chr)!=0 )
// continue;
if ( siteList.find(chr) == siteList.end() )
siteList[chr].clear();
// map<string, map<int, SingleSite> >::iterator pchr = siteList[m].find(chr);
// map<string, map<int, bool> >::iterator coord_chr_ptr = meiCoord[m].find(chr);
// if (coord_chr_ptr == meiCoord[m].end())
// continue;
bool section_status;
if (range_start<0) { // no range
section_status = bam.SetReadSection( chr.c_str() );
if (!section_status) {
string str = "Cannot set read section at chr " + chr;
morphWarning( str );
}
}
else { // set range
section_status = bam.SetReadSection( chr.c_str(), range_start, range_end );
if (!section_status) {
string str = "Cannot set read section at chr " + chr + " " + std::to_string(range_start) + "-" + std::to_string(range_end);
morphWarning( str );
}
}
// DO ADDING
// if (siteList[chr].empty())
// p_reach_last = 1;
// else {
// p_reach_last = 0;
pnearest = siteList[chr].begin();
// }
SingleSite new_site; // temporary cluster. will be added to map later.
new_site.depth = current_depth;
bool start_new = 1; // check if need to add new_site to map and start new new_site
SamRecord rec;
int between = 0; // count #reads after new_site.end. If end changed, add it to rcount and reset to zero
while( bam.ReadRecord( bam_header, rec ) ) {
if (!start_new) {
if (rec.get1BasedPosition() >= new_site.end)
between++;
else
new_site.rcount++;
}
if (rec.getFlag() & 0x2)
continue;
if ( OneEndUnmap( rec.getFlag() ) )
continue;
if ( IsSupplementary(rec.getFlag()) )
continue;
if ( rec.getReadLength() < min_read_length )
continue;
if ( rec.getMapQuality() < MIN_QUALITY )
continue;
if (chr.compare(rec.getMateReferenceName())==0 && rec.getInsertSize() < abs(avr_ins_size*2))
continue;
bool is_mei = 0;
vector<bool> is_in_coord;
is_in_coord.resize(3, 0);
for(int m=0; m<NMEI; m++) {
map<string, map<int, bool> >::iterator coord_chr_ptr = meiCoord[m].find(rec.getMateReferenceName());
if (coord_chr_ptr == meiCoord[m].end())
is_in_coord[m] = 0;
else
is_in_coord[m] = isWithinCoord( rec.get1BasedMatePosition(), coord_chr_ptr->second ); // within MEI coord
if (is_in_coord[m])
is_mei = 1;
}
if (!is_mei)
continue;
if (start_new) {
setNewCluster( is_in_coord, new_site,rec);
start_new = 0;
between = 0;
}
else { // add to existing cluster
if ( rec.get1BasedPosition() > new_site.end + avr_ins_size ) { // start new coord
addClusterToMap(new_site, siteList[chr]);
setNewCluster( is_in_coord, new_site, rec);
start_new = 0;
between = 0;
}
else {
addToCurrentCluster( is_in_coord, new_site, rec);
new_site.rcount += between;
between = 0;
}
}
}
// add last one
if (!start_new)
addClusterToMap(new_site, siteList[chr]);
}
bam.Close();
}