pax_global_header00006660000000000000000000000064133710446000014510gustar00rootroot0000000000000052 comment=fecf71152ee923033358306264aaed0a693622cd Lighter-1.1.2/000077500000000000000000000000001337104460000131075ustar00rootroot00000000000000Lighter-1.1.2/.gitignore000077500000000000000000000000131337104460000150740ustar00rootroot00000000000000*.o lighterLighter-1.1.2/ErrorCorrection.cpp000066400000000000000000000636251337104460000167500ustar00rootroot00000000000000#include "ErrorCorrection.h" #include //#define DEBUG extern char nucToNum[26] ; extern char numToNuc[26] ; extern int MAX_CORRECTION ; extern bool ALLOW_TRIMMING ; extern int SET_NEW_QUAL ; void *ErrorCorrection_Thread( void *arg ) { int ind ; int correction, badPrefix, badSuffix, info ; struct _ErrorCorrectionThreadArg *myArg = ( struct _ErrorCorrectionThreadArg *)arg ; bool init = true ; KmerCode kmerCode( myArg->kmerLength ) ; while ( 1 ) { pthread_mutex_lock( myArg->lock ) ; if ( !init ) ++myArg->batchFinished ; ind = myArg->batchUsed ; ++myArg->batchUsed ; pthread_mutex_unlock( myArg->lock ) ; //printf( "%d %d\n", ind, myArg->batchSize ) ; if ( ind >= myArg->batchSize ) break ; correction = ErrorCorrection_Wrapper( myArg->readBatch[ind].seq, myArg->readBatch[ind].qual, kmerCode, myArg->badQuality, myArg->trustedKmers, badPrefix, badSuffix, info ) ; myArg->readBatch[ind].correction = correction ; myArg->readBatch[ind].badPrefix = badPrefix ; myArg->readBatch[ind].badSuffix = badSuffix ; myArg->readBatch[ind].info = info ; init = false ; } pthread_exit( NULL ) ; return NULL ; } // If we could not find an anchor, it is mostly likely there are errors in every kmer. // We will try to find 1 position that can create a stretch of stored kmers. // return-which position is changed. -1: failed int CreateAnchor( char *read, char *qual, int *fix, bool *storedKmer, KmerCode &kmerCode, Store *kmers ) { int readLength = strlen( read ) ; int kmerLength = kmerCode.GetKmerLength() ; int i, j, k ; //if ( readLength < 2 * kmerLength ) // return -1 ; int maxLen = 0 ; int maxLenStats[2] = {0, 0}; // 0-position, 1-which nucleutide changed to // This stored the partial result of substitution, we use two arrays // to keep the result for the optimal plan. int tag = 0 ; int stored[2][MAX_READ_LENGTH] ; int scnt = 0 ; int start = readLength / 2 - kmerLength ; int end = readLength / 2 + kmerLength + 1 ; /*if ( start < 0 ) start = 0 ; if ( end > readLength ) end = readLength ;*/ start = 0 ; end = readLength ; for ( i = start ; i < end ; ++i ) { int from = i - kmerLength + 1 ; if ( from < 0 ) from = 0 ; for ( j = 0 ; j < 4 ; ++j ) { if ( numToNuc[j] == read[i] ) continue ; char c = read[i] ; read[i] = numToNuc[j] ; // For efficiency, use one kmer to test whether we want to choose this candidate // But for bigger kmer, we need more effort // kind of test 1/32 of the kmers. Since the sequencing error are less likely on left-side, // we shift more on left int loop = ( kmerLength - 1 ) / 32 + 1 ; int t ; for ( t = 0 ; t < loop ; ++t ) { int l = i - ( 2 * loop - t - 1 ) * kmerLength / ( 2 * loop ) + 1 ; if ( l < 0 ) l = 0 ; if ( l + kmerLength - 1 >= readLength ) l = readLength - 1 - kmerLength + 1 ; kmerCode.Restart() ; for ( k = l ; k <= l + kmerLength - 1 ; ++k ) kmerCode.Append( read[k] ) ; if ( kmers->IsIn( kmerCode ) ) { break ; } } if ( t >= loop ) { read[i] = c ; continue ; } scnt = 0 ; for ( k = from ; k < from + kmerLength - 1 ; ++k ) kmerCode.Append( read[k] ) ; scnt = 0 ; int missCnt = 0 ; int hitCnt = 0 ; for ( ; k < readLength && k < i + kmerLength ; ++k, ++scnt ) { kmerCode.Append( read[k] ) ; if ( kmers->IsIn( kmerCode ) ) { stored[tag][scnt] = 1 ; ++hitCnt ; } else { stored[tag][scnt] = 0 ; ++missCnt ; if ( kmerLength - missCnt < maxLen ) break ; } } int sum = 0 ; int max = 0 ; for ( k = 0 ; k < scnt ; ++k ) { if ( stored[tag][k] == 0 ) { if ( sum > max ) max = sum ; sum = 0 ; } else ++sum ; } if ( sum > max ) max = sum ; if ( max > maxLen ) { maxLen = max ; maxLenStats[0] = i ; maxLenStats[1] = j ; /*for ( int l = 0 ; l < scnt ; ++l ) printf( "%d ", stored[tag][l] ) ; printf( "\n" ) ;*/ tag = 1 - tag ; //read[i] = c ; //break ; } else if ( max > 0 && max == maxLen && qual[0] != '\0' && qual[i] < qual[ maxLenStats[0] ] ) { maxLenStats[0] = i ; maxLenStats[1] = j ; tag = 1 - tag ; } read[i] = c ; } } if ( maxLen == 0 ) { //printf( "%s\n", read ) ; return -1 ; } // Pass the effect of substitution fix[ maxLenStats[0] ] = maxLenStats[1] ; i = maxLenStats[0] ; //printf( "%d: %d %d\n", maxLen, i, maxLenStats[1] ) ; int from = i - kmerLength + 1 ; if ( from < 0 ) from = 0 ; for ( j = 0, k = from ; k + kmerLength - 1 < readLength && k <= i ; ++k, ++j ) { //printf( "%d %d %d\n", j, k, stored[1 - tag][j] ) ; storedKmer[k] = ( stored[1 - tag][j] == 1 ) ? true : false ; } return maxLenStats[0] ; } int ErrorCorrection( char *read, char *qual, KmerCode& kmerCode, int maxCorrection, char badQuality, Store *kmers, int &badPrefix, int &badSuffix, int &info ) { int i, j, k ; bool storedKmer[MAX_READ_LENGTH] ; int kmerCnt = 0 ; int readLength = 0 ; int fix[MAX_READ_LENGTH] ; // The fixed character for each untrusted position. bool trusted[MAX_READ_LENGTH] ; // Do not correct these makred positions. int tag ; int from, to ; int trimStart = -1 ; int ambiguousCnt = 0 ; int alternativeCnt = 0 ; bool hasAnchor = false ; int createAnchorPos = -1 ; bool noCandidateKmer = false ; // KmerCode kmerCode( inCode ) ; KmerCode tmpKmerCode( 0 ) ; badPrefix = badSuffix = 0 ; info = 0 ; int kmerLength = kmerCode.GetKmerLength() ; kmerCode.Restart() ; for ( i = 0 ; i < kmerLength && read[i] ; ++i ) { kmerCode.Append( read[i] ) ; } if ( !kmers->IsIn( kmerCode ) ) storedKmer[0] = false ; else { storedKmer[0] = true ; hasAnchor = true ; } kmerCnt = 1 ; for ( ; read[i] ; ++i, ++kmerCnt ) { kmerCode.Append( read[i] ) ; if ( !kmers->IsIn( kmerCode ) ) storedKmer[ kmerCnt ] = false ; else { storedKmer[ kmerCnt ] = true ; hasAnchor = true ; } } readLength = i ; if ( readLength < kmerLength ) return 0 ; trimStart = readLength ; for ( i = 0 ; i < readLength ; ++i ) fix[i] = -1 ; for ( i = 0 ; i < readLength ; ++i ) trusted[i] = false ; tag = -1 ; for ( i = 0 ; i < kmerCnt ; ++i ) { if ( storedKmer[i] ) { if ( tag == -1 ) tag = i ; } else { if ( tag != -1 )// && i - tag >= 3 ) { for ( j = tag ; j < i + kmerLength - 1 ; ++j ) trusted[j] = true ; } tag = -1 ; } } if ( !hasAnchor ) { createAnchorPos = CreateAnchor( read, qual, fix, storedKmer, kmerCode, kmers ) ; if ( createAnchorPos == -1 ) { info = 3 ; return -1 ; } ++alternativeCnt ; } //printf( "%d %d %d\n", kmerLength, kmerCnt, i ) ; #ifdef DEBUG printf( "%s\n", read ) ; for ( i = 0 ; i < kmerCnt ; ++i ) printf( "%d", storedKmer[i] ) ; printf( "\n" ) ; #endif //exit( 1 ) ; // All the kmers are reliable. for ( i = 0 ; i < kmerCnt ; ++i ) { if ( storedKmer[i] == false ) break ; } /*if ( !strcmp( read, "TTGCGTAAGATGGGGGTACCCACGTGGTGTCAGAGTGTCTCTCATTTCGGTTTGATCTACGCAGATCTACAAAAAATGCGGGAGAATAGACGCAGAGTTCT" ) ) { printf( "## %d\n", i ) ; exit( 1 ) ; }*/ if ( i >= kmerCnt ) return 0 ; // Find the first trusted kmer int longestStoredKmerCnt = 0, storedKmerCnt = 0 ; tag = -1 ; for ( i = 0 ; i < kmerCnt ; ++i ) { if ( storedKmer[i] ) { ++storedKmerCnt ; } else { if ( storedKmerCnt > longestStoredKmerCnt ) { longestStoredKmerCnt = storedKmerCnt ; tag = i - storedKmerCnt ; } storedKmerCnt = 0 ; } } if ( storedKmerCnt > longestStoredKmerCnt ) { longestStoredKmerCnt = storedKmerCnt ; tag = i - storedKmerCnt ; } if ( longestStoredKmerCnt == 0 ) { info = 3 ; return -1 ; } if ( longestStoredKmerCnt >= kmerCnt ) { //printf( "0%s\n", read ) ; return 0 ; } //if ( tag > 0 ) // return 0 ; for ( k = tag + 1 ; k < kmerCnt ; ++k ) if ( !storedKmer[k] ) break ; // Scan towards right kmerCode.Restart() ; if ( k >= kmerCnt ) // The kmers are all correct after tag, so force skip the correction. i = readLength + 1 ; else { char backupC = '\0' ; if ( createAnchorPos != -1 ) { backupC = read[ createAnchorPos ] ; read[ createAnchorPos ] = numToNuc[ fix[ createAnchorPos ] ] ; } if ( longestStoredKmerCnt < kmerLength ) { for ( i = k - 1 + 1 ; i < k - 1 + kmerLength - 1 + 1 ; ++i ) { kmerCode.Append( read[i] ) ; } } else { // Adjust the anchor if necessary // Test whether the current anchor is good for ( i = k ; i < k + kmerLength ; ++i ) kmerCode.Append( read[i] ) ; int c ; for ( c = 0 ; c < 4 ; ++c ) { if ( numToNuc[c] == read[i - 1] ) continue ; if ( numToNuc[c] == read[i - 1] ) continue ; tmpKmerCode = kmerCode ; tmpKmerCode.ShiftRight() ; tmpKmerCode.Append( numToNuc[c] ) ; if ( kmers->IsIn( tmpKmerCode ) ) { // Test whether this branch makes sense int t = 0 ; for ( t = 0 ; t < kmerLength && read[i + t] ; ++t ) // and it is should be a very good fix { tmpKmerCode.Append( read[i + t] ) ; if ( !kmers->IsIn( tmpKmerCode ) ) break ; } if ( !read[i + t] || t >= kmerLength ) break ; } } if ( c < 4 ) { //kmerCode.ShiftRight( 1 ) ; Seems wrong for ( i = k - 1 ; i < k + kmerLength - 1 ; ++i ) kmerCode.Append( read[i] ) ; } else { // Adjust the right side for ( j = kmerLength / 2 - 1 ; j >= 0 ; --j ) { int c ; KmerCode tmpKmerCode( kmerLength ) ; for ( i = k - j - 1 ; i < k - j + kmerLength - 1 ; ++i ) kmerCode.Append( read[i] ) ; //printf( "%d %d %c\n", j, i, read[i - 1] ) ; for ( c = 0 ; c < 4 ; ++c ) { if ( numToNuc[c] == read[i - 1] ) continue ; tmpKmerCode = kmerCode ; tmpKmerCode.ShiftRight() ; tmpKmerCode.Append( numToNuc[c] ) ; if ( kmers->IsIn( tmpKmerCode ) ) { ++alternativeCnt ; // Test whether this branch makes sense int t = 0 ; for ( t = 0 ; t <= kmerLength / 2 && read[i + t] ; ++t ) // and it is should be a very good fix { tmpKmerCode.Append( read[i + t] ) ; if ( !kmers->IsIn( tmpKmerCode ) ) break ; } if ( t > kmerLength / 2 ) break ; } } if ( c < 4 ) { // adjust the anchor --i ; kmerCode.ShiftRight() ; break ; } } } } if ( createAnchorPos != -1 ) { read[ createAnchorPos ] = backupC ; } } /*for ( i = k ; i < k + kmerLength - 1 ; ++i ) { kmerCode = ( kmerCode << (uint64_t)2 ) & mask ; kmerCode = kmerCode | (uint64_t)nucToNum[ read[i] - 'A' ] ; }*/ for ( ; i < readLength ; ) { KmerCode fixedKmerCode( kmerCode ) ; int maxTo = -1 ; int maxChange = -1 ; int maxCnt = 0 ; int testCnt = 0 ; from = i + 1 ; to = ( i + kmerLength - 1 < readLength ) ? i + kmerLength - 1 : readLength - 1 ; for ( j = 0 ; j < 4 ; ++j ) { //kmerCode = ( fixedKmerCode << (uint64_t)2 ) & mask ; //kmerCode = kmerCode | (uint64_t)j ; kmerCode = fixedKmerCode ; kmerCode.Append( numToNuc[j] ) ; //printf( "?code=%llu\n", kmerCode.GetCode() ) ; if ( !kmers->IsIn( kmerCode ) ) continue ; if ( maxTo == -1 ) maxTo = i ; ++testCnt ; // How many kmers this change can fix for ( k = from ; k <= to ; ++k ) { kmerCode.Append( read[k] ) ; if ( !kmers->IsIn( kmerCode ) ) break ; } // Try to extend 1 position if ( k > to && to == readLength - 1 ) { int l, m ; for ( m = 0 ; m < kmerLength - 1 - ( to - from + 1 ) ; ++m ) { for ( l = 0 ; l < 4 ; ++l ) { KmerCode tmpKmerCode( kmerCode ) ; tmpKmerCode.Append( numToNuc[l] ) ; if ( kmers->IsIn( tmpKmerCode ) ) break ; } if ( l < 4 ) { //printf( "hi\n" ) ; kmerCode.Append( numToNuc[l] ) ; ++k ; } } } //printf( "hi %d %d\n", k, maxTo ) ; if ( k > maxTo ) { /*if ( maxTo - from + 1 >= kmerLength / 2 ) { ++maxCnt ; } else*/ maxCnt = 1 ; maxTo = k ; maxChange = j ; tmpKmerCode = kmerCode ; } /*else if ( k - from + 1 >= kmerLength / 2 ) { ++maxCnt ; }*/ else if ( k == maxTo ) { ++maxCnt ; if ( k == i + 1 && j == nucToNum[ read[i] - 'A' ] ) { maxCnt = 1 ; maxChange = j ; tmpKmerCode = kmerCode ; } else if ( k == i + 1 && maxChange == nucToNum[ read[i] - 'A' ] ) { maxCnt = 1 ; } } //printf( "%d\n", j ) ; } #ifdef DEBUG printf( "+hi %d: %d %d=>%d, (%d)\n", i, maxTo, to, maxChange, maxCnt ) ; #endif if ( testCnt > 1 ) alternativeCnt += ( testCnt - 1 ) ; // TODO: if maxTo is far from i, then we may in a repeat. Try keep this base unfixed // see whether the next fixing makes sense. if ( maxTo == -1 || ( maxCnt > 1 && ( maxTo <= to || to - i + 1 < kmerLength ) ) ) { //printf( "+%s\n", read ) ; // trim //if ( maxCnt > 1 ) //{ if ( maxTo == -1 ) noCandidateKmer = true ; trimStart = i ; info = 2 ; break ; //} //else //return 0 ; } fix[i] = maxChange ; if ( maxCnt > 1 ) { // Remove the effect of the ambiguous fixing fix[i] = -2 ; ++ambiguousCnt ; } if ( maxTo >= readLength ) break ; if ( maxTo <= to ) { // There are multiple errors in the region if ( 0 ) //maxTo > i + 1 ) { // The next start search can start one place earlier //uint64_t tmp ; /*kmerCode.ShiftRi ; if ( fix[maxTo - kmerLength + 1] != -1 ) kmerCode |= ( (uint64_t)fix[maxTo - kmerLength + 1] << ( 2ull * ( kmerLength - 2 ) ) ) ; else kmerCode |= ( (uint64_t)nucToNum[ read[maxTo - kmerLength + 1] - 'A' ] << ( 2ull * ( kmerLength -2 ) ) ) ; i = maxTo - 1 ;*/ } else { kmerCode = tmpKmerCode ; kmerCode.ShiftRight() ; i = maxTo ; } continue ; } else { // Search for next error. for ( k = to - kmerLength + 2 ; k < kmerCnt ; ++k ) if ( !storedKmer[k] ) break ; if ( k >= kmerCnt ) break ; kmerCode.Restart() ; for ( i = k - 1 + 1 ; i < k - 1 + kmerLength - 1 + 1 ; ++i ) { if ( fix[i] < 0 ) kmerCode.Append( read[i] ) ; else kmerCode.Append( numToNuc[ fix[i] ] ) ; } continue ; } } // Scan towards left //printf( "%d\n", tag ) ; if ( tag == 0 ) { // Force skip tag = -1 ; } else { char backupC = '\0' ; if ( createAnchorPos != -1 ) { backupC = read[ createAnchorPos ] ; read[ createAnchorPos ] = numToNuc[ fix[ createAnchorPos ] ] ; } if ( longestStoredKmerCnt < kmerLength ) { kmerCode.Restart() ; for ( i = tag + 1 - 1 ; i < tag + kmerLength - 1 ; ++i ) { kmerCode.Append( read[i] ) ; } kmerCode.Append( 'A' ) ; } else { // Test whether the current anchor is good int c ; j = -1 ; for ( i = tag -1 ; i < tag - 1 + kmerLength ; ++i ) kmerCode.Append( read[i] ) ; for ( c = 0 ; c < 4 ; ++c ) { if ( numToNuc[c] == read[tag + j] ) continue ; tmpKmerCode = kmerCode ; tmpKmerCode.Append( 'A' ) ; tmpKmerCode.Prepend( numToNuc[c] ) ; if ( kmers->IsIn( tmpKmerCode ) ) { // Test whether this branch makes sense int t = 0 ; for ( t = 0 ; t <= kmerLength - 1 && tag + j - t - 1 >= 0 ; ++t ) // and it is should be a very good fix { tmpKmerCode.Prepend( read[tag + j - t - 1] ) ; if ( !kmers->IsIn( tmpKmerCode ) ) break ; } if ( t > kmerLength - 1 || tag + j -t -1 < 0 ) break ; } } if ( c < 4 ) { j = 0 ; kmerCode.Restart() ; for ( i = tag + j ; i < tag + j + kmerLength ; ++i ) kmerCode.Append( read[i] ) ; } else { // Adjust the left side of the anchor for ( j = kmerLength / 2 - 1 ; j >= 0 ; --j ) { int c ; KmerCode tmpKmerCode( kmerLength ) ; kmerCode.Restart() ; for ( i = tag + j ; i < tag + j + kmerLength ; ++i ) kmerCode.Append( read[i] ) ; //printf( "%d %d %c\n", j, i, read[i - 1] ) ; for ( c = 0 ; c < 4 ; ++c ) { if ( numToNuc[c] == read[tag + j] ) continue ; tmpKmerCode = kmerCode ; tmpKmerCode.Append( 'A' ) ; tmpKmerCode.Prepend( numToNuc[c] ) ; if ( kmers->IsIn( tmpKmerCode ) ) { ++alternativeCnt ; // Test whether this branch makes sense int t = 0 ; for ( t = 0 ; t <= kmerLength / 2 && tag + j - t - 1 >= 0 ; ++t ) // and it is should be a very good fix { tmpKmerCode.Prepend( read[tag + j - t - 1] ) ; if ( !kmers->IsIn( tmpKmerCode ) ) break ; } if ( t > kmerLength / 2 ) break ; } } if ( c < 4 ) { // adjust the anchor tag = tag + j + 1 ; kmerCode.Append( 'A' ) ; break ; } } } } if ( createAnchorPos != -1 ) { read[ createAnchorPos ] = backupC ; } } //kmerCode = ( kmerCode << (uint64_t)2 ) & mask ; for ( i = tag - 1 ; i >= 0 ; ) { KmerCode fixedKmerCode( kmerCode ) ; int minTo = readLength + 1 ; int minChange = -1 ; int minCnt = 0 ; int testCnt = 0 ; from = i - 1 ; to = ( i - kmerLength + 1 < 0 ) ? 0 : ( i - kmerLength + 1 ) ; for ( j = 0 ; j < 4 ; ++j ) { //kmerCode = ( fixedKmerCode >> (uint64_t)2 ) & ( mask >> 2ull ) ; //printf( "1.%llu\n", kmerCode.GetCode() ) ; //kmerCode = kmerCode | ( ((uint64_t)j) << (uint64_t)(2 * kmerLength - 2 ) ) ; kmerCode = fixedKmerCode ; kmerCode.Prepend( numToNuc[j] ) ; //printf( "2.%llu\n", kmerCode.GetCode() ) ; //printf( "%d %lld %lld\n", j, (long long int)kmerCode, (long long int)fixedKmerCode ) ; if ( !kmers->IsIn( kmerCode ) ) continue ; if ( minTo == tag + 1 ) minTo = i ; ++testCnt ; // How many kmers this change can fix for ( k = from ; k >= to ; --k ) { kmerCode.Prepend( read[k] ) ; if ( !kmers->IsIn( kmerCode ) ) break ; } // try extension if ( k < to && to == 0 ) { int l, m ; for ( m = 0 ; m < kmerLength - 1 - ( from - to + 1 ) ; ++m ) { for ( l = 0 ; l < 4 ; ++l ) { KmerCode tmpKmerCode( kmerCode ) ; tmpKmerCode.Prepend( numToNuc[l] ) ; if ( kmers->IsIn( tmpKmerCode ) ) break ; } if ( l < 4 ) { //printf( "hi\n" ) ; kmerCode.Prepend( numToNuc[l] ) ; --k ; } } } if ( k < minTo ) { minCnt = 1 ; minTo = k ; minChange = j ; tmpKmerCode = kmerCode ; } else if ( k == minTo ) { ++minCnt ; if ( k == i - 1 && j == nucToNum[ read[i] - 'A' ] ) { minCnt = 1 ; minChange = j ; tmpKmerCode = kmerCode ; } else if ( k == i -1 && minChange == nucToNum[ read[i] - 'A' ] ) { minCnt = 1 ; } } } #ifdef DEBUG printf( "-hi %d: %d %d=>%d, (%d)\n", i, minTo, to, minChange, minCnt ) ; #endif if ( testCnt > 1 ) alternativeCnt += ( testCnt - 1 ) ; if ( minTo == readLength + 1 || ( minCnt > 1 && ( minTo >= to || i - to + 1 < kmerLength ) ) ) { //printf( "-%s\n", read ) ; //return -1 ; if ( minTo == readLength + 1 ) noCandidateKmer = true ; badPrefix = i + 1 ; info = 2 ; break ; } //printf( "---%d %d\n", minChange, nucToNum[read[0] - 'A'] ) ; fix[i] = minChange ; if ( minCnt > 1 ) { fix[i] = -2 ; ++ambiguousCnt ; } if ( minTo < 0 ) break ; if ( minTo >= to ) { /*if ( maxTo > i + 1 ) { // The next start search can start one place earlier kmerCode = tmpKmerCode >> 2ull ; i = maxTo - 1 ; } else*/ //kmerCode = tmpKmerCode << 2ull ; kmerCode = tmpKmerCode ; kmerCode.Append( 'A' ) ; //printf( "i=>minTo: %d=>%d\n", i, minTo ) ; i = minTo ; continue ; } else { // Search for next error. for ( k = to - 1 ; k >= 0 ; --k ) if ( !storedKmer[k] ) break ; if ( k < 0 ) break ; kmerCode.Restart() ; for ( i = k + 2 - 1 ; i < k + 2 + kmerLength - 1 - 1 ; ++i ) { if ( fix[i] < 0 ) kmerCode.Append( read[i] ) ; else kmerCode.Append( numToNuc[ fix[i] ] ) ; } i = k + 1 - 1 ; kmerCode.Append( 'A' ) ; continue ; } /*{ // This happens when the distance between two errors is just of kmerLength //printf( "%llu\n", tmpKmerCode.GetCode() ) ; kmerCode = tmpKmerCode ; i = minTo ; }*/ } #ifdef DEBUG printf( "fix: ") ; for ( i = 0 ; i < readLength; ++i ) { if ( fix[i] == -1 ) printf( "5" ) ; else if ( fix[i] == -2 ) printf( "6" ) ; else printf( "%d", fix[i] ) ; } printf( "\n" ) ; #endif int ret = 0 ; double correctCnt = 0 ; //printf( "%s\n%d\n", read, ret ) ; /*for ( i = badPrefix ; i < trimStart ; ++i ) { if ( trusted[i] && fix[i] != -1 ) return -1 ; if ( fix[i] == -1 || read[i] == numToNuc[ fix[i] ] || read[i] == 'N' ) continue ; ++correctCnt ; if ( correctCnt > maxCorrection ) { // There are too many corrections, adjust the trimStart for ( j = i - 1 ; j >= badPrefix ; --j ) { if ( fix[j] == -1 || read[j] == numToNuc[ fix[j] ] ) break ; } trimStart = j + 1 ; if ( trimStart == badPrefix ) return -1 ; correctCnt = 0 ; for ( i = badPrefix ; i < trimStart ; ++i ) { if ( fix[i] == -1 || read[i] == numToNuc[ fix[i] ] ) continue ; ++correctCnt ; } if ( correctCnt > maxCorrection - 1 ) return -1 ; break ; } }*/ bool overCorrected = false ; int adjustMaxCor = 0 ; for ( i = 0 ; i < readLength ; ++i ) if ( trusted[i] && fix[i] != -1 ) break ; if ( alternativeCnt == 0 && i >= readLength ) adjustMaxCor = 1 ; for ( i = 0 ; i < readLength ; ++i ) { int overCorrectWindow = 20 ; if ( i >= overCorrectWindow && ( fix[i - overCorrectWindow] >= 0 && read[i - overCorrectWindow] != 'N' ) ) { if ( qual[0] != '\0' && qual[i - overCorrectWindow] <= badQuality ) correctCnt -= 0.5 ; else --correctCnt ; } if ( fix[i] >= 0 && read[i] != 'N' ) { if ( qual[0] != '\0' && qual[i] <= badQuality ) correctCnt += 0.5 ; else ++correctCnt ; } int tmp = maxCorrection ; if ( i >= overCorrectWindow && i + overCorrectWindow - 1 < readLength ) tmp += adjustMaxCor ; if ( correctCnt > tmp ) //maxCorrection ) { if ( fix[i] >= 0 ) { fix[i] = 4 ; overCorrected = true ; } } } if ( overCorrected ) { for ( i = 0 ; i < readLength ; ++i ) { if ( fix[i] == 4 ) { fix[i] = -1 ; int tag = i ; for ( j = i - 1 ; j >= 0 && j >= tag - kmerLength + 1 ; --j ) if ( fix[j] >= 0 ) { fix[j] = -1 ; tag = j ; } tag = i ; for ( j = i + 1 ; j < readLength && j <= tag + kmerLength - 1 ; ++j ) if ( fix[j] >= 0 ) { fix[j] = -1 ; tag = j ; } i = j - 1 ; // the minus 1 here is to compensate for the ++i in the outer-loop } } } /*if ( correctCnt > MAX_CORRECTION ) { // Find the point where the correct count become to increase rapidly. //return 0 ; int correctPartialSum[1000] ; correctPartialSum[0] = 0 ; for ( i = 0 ; i < trimStart ; ++i ) { correctPartialSum[i + 1] = correctPartialSum[i - 1] + ( ( fix[i] == -1 || read[i] == numToNuc[ fix[i] ] ) ? 0 : 1 ) ; } for ( i = trimStart - 1 ; i >= 0 ; --i ) { } //int cnt = 0 ; //for ( i = 0 ; i < trimStart ; ++i ) }*/ #ifdef DEBUG printf( "prefix=%d suffix=%d\n", badPrefix, trimStart ) ; printf( "fix: ") ; for ( i = 0 ; i < readLength; ++i ) { if ( fix[i] == -1 ) printf( "5" ) ; else if ( fix[i] == -2 ) printf( "6" ) ; else printf( "%d", fix[i] ) ; } printf( "\n" ) ; #endif for ( i = badPrefix ; i < trimStart ; ++i ) { if ( fix[i] < 0 ) continue ; if ( read[i] != numToNuc[ fix[i] ] ) { read[i] = numToNuc[ fix[i] ] ; //if ( read[i] != 'N' ) if ( qual[0] != '\0' && SET_NEW_QUAL >= 0 ) qual[i] = (char)SET_NEW_QUAL ; ++ret ; } } //printf( "%d %d\n", ret, trimStart ) ; //badPrefix = 0 ; badSuffix = readLength - trimStart ; //if ( ALLOW_TRIMMING ) // else we do partial correction // read[ trimStart ] = '\0' ; //ret += trimmed ; /*if ( !strcmp( read, "GTAAACGCCTTATCCGGCCTACGGAGGGTGCGGGAATTTGTAGGCCTGATAAGACGCGCAAGCGTCGCATCAGGCAGTCGGCACGGTTGCCGGATGCAGCG" ) ) { printf( "## %d\n", i ) ; exit( 1 ) ; }*/ if ( ret == 0 && badPrefix == 0 && badSuffix == 0 && ambiguousCnt > 0 ) { info = 2 ; ret = -1 ; } else if ( ret == 0 && badPrefix == 0 && badSuffix == 0 && overCorrected ) { info = 1 ; ret = -1 ; } if ( noCandidateKmer ) info = 3 ; /*if ( ret == 0 && badSuffix > 0 ) { printf( "%d\n", info ) ; }*/ return ret ; } int ErrorCorrection_Wrapper( char *read, char *qual, KmerCode& kmerCode, char badQuality, Store *kmers, int &badPrefix, int &badSuffix, int &info ) { int correction ; int tmpBadPrefix, tmpBadSuffix, tmpInfo ; int len = (int)strlen( read ) ; int interim = 0 ; info = 0 ; correction = ErrorCorrection( read, qual, kmerCode, MAX_CORRECTION, badQuality, kmers, tmpBadPrefix, tmpBadSuffix, tmpInfo ) ; if ( correction == -1 ) { badPrefix = badSuffix = 0 ; info = tmpInfo ; return -1 ; } badPrefix = tmpBadPrefix ; badSuffix = tmpBadSuffix ; info = tmpInfo ; if ( badPrefix > len / 2 || badPrefix > kmerCode.GetKmerLength() * 2 ) { int tmp ; char c = read[badPrefix] ; read[ badPrefix ] = '\0' ; tmp = ErrorCorrection( read, qual, kmerCode, MAX_CORRECTION, badQuality, kmers, tmpBadPrefix, tmpBadSuffix, tmpInfo ) ; read[ badPrefix ] = c ; if ( tmp != -1 ) { badPrefix = tmpBadPrefix ; correction += tmp ; interim += tmpBadSuffix ; } if ( tmpInfo > info ) info = tmpInfo ; } if ( badSuffix > len / 2 || badSuffix > kmerCode.GetKmerLength() * 2 ) { int tmp ; tmp = ErrorCorrection( read + len - badSuffix, qual + len - badSuffix, kmerCode, MAX_CORRECTION, badQuality, kmers, tmpBadPrefix, tmpBadSuffix, tmpInfo ) ; if ( tmp != -1 ) { badSuffix = tmpBadSuffix ; correction += tmp ; interim += tmpBadPrefix ; } if ( tmpInfo > info ) info = tmpInfo ; } if ( correction == 0 && interim > 0 ) { correction = -1 ; badSuffix = badPrefix = 0 ; } else if ( ALLOW_TRIMMING ) { read[len - badSuffix] = '\0' ; } return correction ; } Lighter-1.1.2/ErrorCorrection.h000066400000000000000000000012461337104460000164040ustar00rootroot00000000000000#ifndef _MOURI_ERROR_CORRECTION #define _MOURI_ERROR_CORRECTION #include #include "Store.h" #include "KmerCode.h" #include "Reads.h" struct _ErrorCorrectionThreadArg { int kmerLength ; Store *trustedKmers ; struct _Read *readBatch ; int batchSize ; int batchUsed ; int batchFinished ; char badQuality ; pthread_mutex_t *lock ; } ; void *ErrorCorrection_Thread( void *arg ) ; //@ return:0: this read is correct. -1-this read is unfixable. Otherwise, return the number // of corrected positions. int ErrorCorrection_Wrapper( char *read, char *qual, KmerCode& kmerCode, char badQuality, Store *kmers, int &badPrefix, int &badSuffix, int &info ) ; #endif Lighter-1.1.2/File.h000066400000000000000000000061631337104460000141450ustar00rootroot00000000000000// The wrapper to handle reading and writingregular files and compressed files #ifndef _MOURISL_FILE #define _MOURISL_FILE #include #include #include #include #include #define UNCOMPRESSED_FILE 0 #define COMPRESSED_FILE 1 extern bool zlibVersionChecked ; class File { private: bool type ; FILE *fp ; gzFile gzFp ; int gzCompressLevel ; bool opened ; public: File() { opened = false ; } ~File() { if ( !opened ) return ; if ( type == COMPRESSED_FILE ) gzclose( gzFp ) ; else if ( type == UNCOMPRESSED_FILE ) fclose( fp ) ; opened = false ; } void Open( char *fileName, const char *mode ) { opened = true ; // Test it is gz or normal file by looking at the last to bit int len = strlen( fileName ) ; if ( fileName[len - 2] == 'g' && fileName[len - 1] == 'z' ) type = COMPRESSED_FILE ; else type = UNCOMPRESSED_FILE ; if ( type == COMPRESSED_FILE ) { char modeBuffer[5] ; strcpy( modeBuffer, mode ) ; if ( modeBuffer[0] == 'w' ) { modeBuffer[1] = gzCompressLevel + '0' ; modeBuffer[2] = '\0' ; } gzFp = gzopen( fileName, modeBuffer ) ; if ( gzFp == Z_NULL ) { fprintf( stderr, "ERROR: Could not access file %s\n", fileName ) ; exit( 1 ) ; } if ( zlibVersionChecked == false ) { zlibVersionChecked = true ; #ifdef ZLIB_VERNUM if ( ZLIB_VERNUM < 0x1240 ) fprintf( stderr, "WARNING: zlib version on your system is %s(< 1.2.4). " "Newer veresion (>=1.2.4) is much faster.\n", ZLIB_VERSION ) ; #else fprintf( stderr, "WARNING: Unknown zlib version. Newer veresion (>=1.2.4) is much faster.\n" ) ; #endif } } else if ( type == UNCOMPRESSED_FILE ) { fp = NULL ; fp = fopen( fileName, mode ) ; if ( fp == NULL ) { fprintf( stderr, "ERROR: Could not access file %s\n", fileName ) ; exit( 1 ) ; } } } void Close() { if ( !opened ) return ; if ( type == COMPRESSED_FILE ) gzclose( gzFp ) ; else if ( type == UNCOMPRESSED_FILE ) fclose( fp ) ; opened = false ; } char *Gets( char *buf, int len ) { if ( type == COMPRESSED_FILE ) { return gzgets( gzFp, buf, len ) ; } else if ( type == UNCOMPRESSED_FILE ) { return fgets( buf, len, fp ) ; } return NULL ; } int Puts( char *buf ) { if ( type == COMPRESSED_FILE ) { return gzwrite( gzFp, buf, strlen( buf ) ) ; } else if ( type == UNCOMPRESSED_FILE ) { return fputs( buf, fp ) ; } return 0 ; } int Printf( const char *fmt, ... ) { char buffer[1024] ; va_list args ; va_start( args, fmt ) ; vsprintf( buffer, fmt, args ) ; if ( type == COMPRESSED_FILE ) { return gzwrite( gzFp, buffer, strlen( buffer ) ) ; } else if ( type == UNCOMPRESSED_FILE ) { return fputs( buffer, fp ) ; } return 0 ; } void Rewind() { if ( type == COMPRESSED_FILE ) { gzrewind( gzFp ) ; } else if ( type == UNCOMPRESSED_FILE ) { rewind( fp ) ; } } void SetCompressLevel( int cl ) { if ( cl < 0 || cl > 9 ) { fprintf( stderr, "Compress level must be 0-9.\n" ) ; exit( 1 ) ; } gzCompressLevel = cl ; } } ; #endif Lighter-1.1.2/GetKmers.cpp000066400000000000000000000252231337104460000153400ustar00rootroot00000000000000#include "GetKmers.h" struct _SampleKmersPutThreadArg { Store *kmers ; KmerCode *kmerCodes ; int kmerCodesCnt ; //pthread_mutex_t *lockPut ; } ; void *SampleKmers_PutThread( void *arg ) { struct _SampleKmersPutThreadArg *myArg = ( struct _SampleKmersPutThreadArg * )arg ; Store *kmers = myArg->kmers ; int i ; //pthread_mutex_lock( myArg->lockPut ) ; for ( i = 0 ; i < myArg->kmerCodesCnt ; ++i ) kmers->Put( myArg->kmerCodes[i], true ) ; //pthread_mutex_unlock( myArg->lockPut ) ; pthread_exit( NULL ) ; return NULL ; } void *SampleKmers_Thread( void *arg ) { struct _SampleKmersThreadArg *myArg = ( struct _SampleKmersThreadArg *)arg ; //char read[MAX_READ_LENGTH], qual[MAX_READ_LENGTH], id[MAX_ID_LENGTH] ; int i, tmp ; int fileInd ; struct _Read *readBatch = ( struct _Read *)malloc( sizeof( *readBatch ) * 128 ) ; struct _SamplePattern *samplePatterns = myArg->samplePatterns ; int kmerLength = myArg->kmerLength ; KmerCode kmerCode( kmerLength ) ; //double p ; Store *kmers = myArg->kmers ; //double factor = 1.0 ; const int bufferSizeFactor = 9 ; KmerCode *kmerCodeBuffer[2] ; //[ ( bufferSizeFactor + 1 )* MAX_READ_LENGTH] ; int bufferTag ; int kmerCodeBufferUsed = 0 ; for ( bufferTag = 0 ; bufferTag < 2 ; ++bufferTag ) { kmerCodeBuffer[ bufferTag ] = ( KmerCode * )malloc( sizeof( KmerCode ) * ( bufferSizeFactor + 1 ) * MAX_READ_LENGTH ) ; for ( i = 0 ; i < ( bufferSizeFactor + 1 ) * MAX_READ_LENGTH ; ++i ) kmerCodeBuffer[bufferTag][i] = kmerCode ; } void *pthreadStatus ; pthread_t putThread ; pthread_attr_t pthreadAttr ; struct _SampleKmersPutThreadArg putArg ; bool threadInit = false ; pthread_attr_init( &pthreadAttr ) ; pthread_attr_setdetachstate( &pthreadAttr, PTHREAD_CREATE_JOINABLE ) ; bufferTag = 0 ; while ( 1 ) { pthread_mutex_lock( myArg->lock ) ; //tmp = myArg->reads->NextWithBuffer( id, read, qual, false ) ; tmp = myArg->reads->GetBatch( readBatch, 128, fileInd, false, false ) ; pthread_mutex_unlock( myArg->lock ) ; int k ; if ( tmp != 0 ) { for ( k = 0 ; k < tmp ; ++k ) { int len ; char *id = readBatch[k].id ; char *read = readBatch[k].seq ; char *qual = readBatch[k].qual ; /*len = strlen( id ) ; if ( id[len - 1] == '\n') id[len - 1] = '\0' ;*/ //int tag = rand() % SAMPLE_PATTERN_COUNT ; // Decide to use which pattern int tag = fileInd ; len = (int)strlen( read ) ; if ( read[len - 1] == '\n' ) read[len - 1] = '\0' ; if ( qual[0] != '\0' ) { if ( qual[len - 1] == '\n' ) qual[len - 1] = '\0' ; } for ( i = 0 ; id[i] ; ++i ) tag = tag * 17 + ( id[i] - 'A' ) ; for ( i = 0 ; read[i] ; ++i ) tag = tag * 7 + ( read[i] - 'A' ) ; for ( i = 0 ; qual[i] ; ++i ) tag = tag * 17+ ( qual[i] - 'A' ) ; tag %= SAMPLE_PATTERN_COUNT ; if ( tag < 0 ) tag += SAMPLE_PATTERN_COUNT ; //tag = rand() % SAMPLE_PATTERN_COUNT ; // Decide to use which pattern //printf( "%d\n", tag ) ; //printf( "%s\n", read ) ; //SampleKmersInRead( read, qual, myArg->kmerLength, myArg->alpha, // kmerCode, myArg->kmers ) ; if ( len - 1 < kmerLength ) continue ; for ( i = 0 ; i < kmerLength ; ++i ) { kmerCode.Append( read[i] ) ; } //printf( "%d %d %d\n", tag, (int)samplePatterns[tag].tag[2], (int)samplePatterns[tag].tag[3] ) ; if ( samplePatterns[tag].tag[ ( i - 1 ) / 8 ] & ( 1 << ( ( i - 1 ) % 8 ) ) ) { //kmers->Put( kmerCode ) ; kmerCodeBuffer[ bufferTag ][ kmerCodeBufferUsed ] = kmerCode ; ++kmerCodeBufferUsed ; } for ( ; read[i] ; ++i ) { kmerCode.Append( read[i] ) ; if ( samplePatterns[tag].tag[ i / 8 ] & ( 1 << ( i % 8 ) ) ) { //kmers->Put( kmerCode ) ; kmerCodeBuffer[bufferTag][ kmerCodeBufferUsed ] = kmerCode ; ++kmerCodeBufferUsed ; } } if ( kmerCodeBufferUsed >= bufferSizeFactor * MAX_READ_LENGTH ) { if ( threadInit ) pthread_join( putThread, &pthreadStatus ) ; putArg.kmers = kmers ; putArg.kmerCodes = ( KmerCode *)kmerCodeBuffer[ bufferTag ] ; putArg.kmerCodesCnt = kmerCodeBufferUsed ; //putArg.lockPut = myArg->lockPut ; //printf( "%d %d\n", bufferTag, kmerCodeBufferUsed ) ; pthread_create( &putThread, &pthreadAttr, SampleKmers_PutThread, ( void *)&putArg ) ; kmerCodeBufferUsed = 0 ; bufferTag = 1 - bufferTag ; threadInit = true ; } } } else break ; } //put the remaining if ( threadInit ) pthread_join( putThread, &pthreadStatus ) ; putArg.kmers = kmers ; putArg.kmerCodes = ( KmerCode *)kmerCodeBuffer[ bufferTag ] ; putArg.kmerCodesCnt = kmerCodeBufferUsed ; //putArg.lockPut = myArg->lockPut ; pthread_create( &putThread, &pthreadAttr, SampleKmers_PutThread, ( void *)&putArg ) ; kmerCodeBufferUsed = 0 ; bufferTag = 1 - bufferTag ; threadInit = true ; pthread_join( putThread, &pthreadStatus ) ; free( readBatch ) ; for ( i = 0 ; i < 2 ; ++i ) free( kmerCodeBuffer[i] ) ; pthread_attr_destroy( &pthreadAttr ) ; pthread_exit( NULL ) ; return NULL ; } void SampleKmersInRead( char *read, char *qual, int kmerLength, double alpha, KmerCode &kmerCode, Store *kmers ) { int i ; double p ; double factor = 1 ; /*int badQualPartialCount[MAX_READ_LENGTH]*/ ; // Get the partial counting sum of not good qualies // NOTICE: we shift one position here /*badQualPartialCount[0] = 0 ; for ( i = 0 ; qual[i] ; ++i ) { if ( qual[0] != '\0' ) badQualPartialCount[i + 1] = badQualPartialCount[i] + ( qual[i] < goodQuality ? 1 : 0 ) ; else badQualPartialCount[i + 1] = i + 1 ; }*/ kmerCode.Restart() ; for ( i = 0 ; i < kmerLength && read[i] ; ++i ) { kmerCode.Append( read[i] ) ; } if ( i < kmerLength ) return ; p = rand() / (double)RAND_MAX ; /*if ( badQualPartialCount[kmerLength] - badQualPartialCount[0] == 0 ) factor = 1 ; else factor = 1 ;*/ //factor = 1 ; //printf( "%lf %lf\n", p, alpha ) ; if ( p < alpha * factor ) { //printf( "%lf %lf\n", p, alpha ) ; kmers->Put( kmerCode ) ; } for ( ; read[i] ; ++i ) { kmerCode.Append( read[i] ) ; /*if ( badQualPartialCount[i + 1] - badQualPartialCount[i - kmerLength + 1] == 0 ) factor = 1 ; else factor = 1 ;*/ //factor = 1 ; p = rand() / (double)RAND_MAX ; if ( p < alpha * factor ) { /*if ( !strcmp( read, "CCAGTACCTGAAATGCTTACGTTGCCGTTGCTGGCTCATCCTGCCCAGAG" ) ) { ExtractKmer( read, i - kmerLength + 1, kmerLength, buffer ) ; printf( "Put %s\n", buffer ) ; }*/ //printf( "%lf %lf\n", p, alpha ) ; kmers->Put( kmerCode ) ; } } } void *StoreKmers_Thread( void *arg ) { struct _StoreKmersThreadArg *myArg = ( struct _StoreKmersThreadArg *)arg ; int i ; int tmp, fileInd ; int maxBatchSize = READ_BUFFER_PER_THREAD ; struct _Read *readBatch = ( struct _Read *)malloc( sizeof( struct _Read ) * maxBatchSize ) ; KmerCode kmerCode( myArg->kmerLength ) ; while ( 1 ) { pthread_mutex_lock( myArg->lock ) ; //tmp = myArg->reads->( id, read, qual, false ) ; tmp = myArg->reads->GetBatch( readBatch, maxBatchSize, fileInd, false, false ) ; pthread_mutex_unlock( myArg->lock ) ; if ( tmp == 0 ) break ; for ( i = 0 ; i < tmp ; ++i ) { /*id = readBatch[i].id ; int len = (int)strlen( id ) ; if ( id[len - 1] == '\n') id[len - 1] = '\0' ;*/ char *read = readBatch[i].seq ; char *qual = readBatch[i].qual ; int len = (int)strlen( read ) ; if ( read[len - 1] == '\n' ) read[len - 1] = '\0' ; if ( qual[0] != '\0' ) { if ( qual[len - 1] == '\n' ) qual[len - 1] = '\0' ; } StoreTrustedKmers( read, qual, myArg->kmerLength, myArg->badQuality, myArg->threshold, kmerCode, myArg->kmers, myArg->trustedKmers ) ; } } free( readBatch ) ; pthread_exit( NULL ) ; return NULL ; } void StoreTrustedKmers( char *read, char *qual, int kmerLength, char badQuality, int *threshold, KmerCode &kmerCode, Store *kmers, Store *trustedKmers ) { bool occur[MAX_READ_LENGTH] ; bool trustedPosition[MAX_READ_LENGTH] ; int i ; kmerCode.Restart() ; for ( i = 0 ; i < kmerLength ; ++i ) { kmerCode.Append( read[i] ) ; } if ( kmers->IsIn( kmerCode) ) occur[i - kmerLength] = true ; else occur[i - kmerLength] = false ; for ( ; read[i] ; ++i ) { kmerCode.Append( read[i] ) ; if ( kmers->IsIn( kmerCode ) ) occur[i - kmerLength + 1] = true ; else { occur[i - kmerLength + 1] = false ; } } int readLength = i ; int occurCnt = readLength - kmerLength + 1 ; int zeroCnt = 0, oneCnt = 0 ; /*printf( "%s\n", read ) ; for ( i = 0 ; i < occurCnt ; ++i ) printf( "%d", occur[i] ) ; printf( "\n" ) ;*/ // Set the trusted positions for ( i = 0 ; i < readLength ; ++i ) { if ( i >= kmerLength ) { if ( occur[i - kmerLength] ) --oneCnt ; else --zeroCnt ; } if ( i < occurCnt ) { if ( occur[i] ) ++oneCnt ; else ++zeroCnt ; } //printf( "%d %d\n",i, oneCnt ) ; int sum = oneCnt + zeroCnt ; int adjust = 0 ; /*if ( i - kmerLength + 1 >= kmerLength - 1 && i + kmerLength - 1 < readLength && qual[i] >= goodQuality ) { adjust -= 1 ; }*/ /*if ( i + kmerLength / 2 - 1 >= readLength || i < kmerLength / 2 ) { adjust += 1 ; }*/ //TODO: play with the parameters here //if ( oneCnt > alpha * sum && // ( oneCnt - alpha * sum ) * ( oneCnt - alpha * sum ) > // 8 * alpha * (1 - alpha ) * sum + 1 ) if ( qual[0] != '\0' && qual[i] <= badQuality ) { trustedPosition[i] = false ; continue ; } if ( oneCnt > threshold[sum] + adjust ) { //if ( !strcmp( read, "CCAGTACCTGAAATGCTTACGTTGCCGTTGCTGGCTCATCCTGCCCAGAG" ) ) // printf( "trustedPosition: %d %d\n", i, oneCnt ) ; trustedPosition[i] = true ; } else { trustedPosition[i] = false ; } //trustedPosition[i] = true ; } oneCnt = 0 ; kmerCode.Restart() ; //printf( "!! %s\n", readId ) ; //printf( "!! %s\n!! ", read ) ; /*for ( i = 0 ; i < readLength ; ++i ) printf( "%d", trustedPosition[i] ) ; printf( "\n" ) ; */ for ( i = 0 ; i < readLength ; ++i ) { if ( trustedPosition[i] ) ++oneCnt ; if ( i >= kmerLength ) { if ( trustedPosition[i - kmerLength] ) --oneCnt ; } kmerCode.Append( read[i] ) ; if ( oneCnt == kmerLength )//|| ( i - kmerLength + 1 >= kmerLength - 1 && i + kmerLength - 1 < readLength && oneCnt >= kmerLength - 1 ) ) { //ExtractKmer( read, i - kmerLength + 1, kmerLength, buffer ) ; //if ( !strcmp( read,"CCAGTACCTGAAATGCTTACGTTGCCGTTGCTGGCTCATCCTGCCCAGAG" ) ) //if ( !strcmp( read, "ATCATCAGAGGGTCTCGTGTAGTGCTCCAGTACCTGAAATGCTTACGTTG" ) ) // printf( "Into table B: %d %d\n", i, oneCnt ) ; //printf( "%d %lld\n", i, kmerCode ) ; trustedKmers->Put( kmerCode, true ) ; } } } Lighter-1.1.2/GetKmers.h000066400000000000000000000025001337104460000147760ustar00rootroot00000000000000// Functions used to smaple kmers and get trusted kmers #ifndef _MOURISL_GETKMERS #define _MOURISL_GETKMERS #include #include #include #include #include #include "Reads.h" #include "Store.h" #include "KmerCode.h" #include "utils.h" // The pattern of sampling for each read. // Marks the bits to indicate whether to sample the // kmer end at that position. #define SAMPLE_PATTERN_COUNT 65536 struct _SamplePattern { char tag[ MAX_READ_LENGTH / 8 ] ; } ; // Strcture for handling multi-threads struct _SampleKmersThreadArg { int kmerLength ; double alpha ; //int batchSize ; Store *kmers ; Reads *reads ; struct _SamplePattern *samplePatterns ; pthread_mutex_t *lock ; pthread_mutex_t *lockPut ; } ; struct _StoreKmersThreadArg { int kmerLength ; //int batchSize ; int *threshold ; Store *kmers ; Store *trustedKmers ; Reads *reads ; char goodQuality ; char badQuality ; pthread_mutex_t *lock ; } ; void *SampleKmers_Thread( void *arg ) ; void SampleKmersInRead( char *read, char *qual, int kmerLength, double alpha, KmerCode &kmerCode, Store *kmers ) ; void *StoreKmers_Thread( void *arg ) ; void StoreTrustedKmers( char *read, char *qual, int kmerLength, char badQuality, int *threshold, KmerCode &kmerCode, Store *kmers, Store *trustedKmers ) ; #endif Lighter-1.1.2/KmerCode.h000066400000000000000000000115171337104460000147560ustar00rootroot00000000000000#ifndef _MOURISL_KMERCODE_HEADER #define _MOURISL_KMERCODE_HEADER #include #include "utils.h" extern char nucToNum[26] ; extern char numToNuc[26] ; const int K_BLOCK_NUM = ( MAX_KMER_LENGTH - 1 ) / ( sizeof( uint64_t ) * 4 ) + 1 ; #if MAX_KMER_LENGTH <= 32 class KmerCode { private: int kmerLength ; int invalidPos ; // The position contains characters other than A,C,G,T in the code uint64_t code ; uint64_t mask ; public: KmerCode() { } KmerCode( int kl ) { int i ; kmerLength = kl ; code = 0 ; invalidPos = -1 ; mask = 0 ; for ( i = 0 ; i < kmerLength ; ++i ) { mask = mask << 2 ; mask = mask | 3 ; } } KmerCode( const KmerCode& in ) { kmerLength = in.kmerLength ; invalidPos = in.invalidPos ; mask = in.mask ; code = in.code ; } void Restart() { code = 0ull ; invalidPos = -1 ; } uint64_t GetCode() { return code ; } int GetKmerLength() { return kmerLength ; } bool IsValid() { /*if ( invalidPos != -1 ) { printf( "hi\n") ; }*/ return ( invalidPos == -1 ) ; } void Append( char c ) { if ( invalidPos != -1 ) ++invalidPos ; code = ( ( code << 2ull ) & mask ) | ( (uint64_t)( nucToNum[ c - 'A' ] & 3 ) ) ; if ( nucToNum[c - 'A'] == -1 ) { invalidPos = 0 ; } if ( invalidPos >= kmerLength ) invalidPos = -1 ; } void Prepend( char c ) { ShiftRight() ; if ( nucToNum[c-'A'] == -1 ) { invalidPos = kmerLength - 1 ; } code = ( code | ( (uint64_t)( nucToNum[c - 'A'] & 3 ) << ( 2ull * ( kmerLength - 1 ) ) ) ) & mask ; } inline void ShiftRight() { if ( invalidPos != -1 ) --invalidPos ; code = ( code >> 2ull ) & ( mask >> 2ull ) ; if ( invalidPos < 0 ) invalidPos = -1 ; } KmerCode& operator=( const KmerCode& in ) { kmerLength = in.kmerLength ; invalidPos = in.invalidPos ; mask = in.mask ; code = in.code ; return *this ; } } ; #else class KmerCode { private: int kmerLength ; int invalidPos ; // The position contains characters other than A,C,G,T in the code int largestBlock ; uint64_t code[K_BLOCK_NUM] ; uint64_t mask ; public: KmerCode() { } KmerCode( int kl ) { int i ; kmerLength = kl ; for ( i = 0 ; i < K_BLOCK_NUM ; ++i ) code[i] = 0 ; invalidPos = -1 ; mask = 0 ; const int residual = ( kmerLength - 1 ) & ( sizeof( uint64_t ) * 4 - 1 ) ; for ( i = 0 ; i <= residual ; ++i ) { mask = mask << 2 ; mask = mask | 3 ; } largestBlock = ( kmerLength - 1 ) / ( sizeof( uint64_t ) * 4 ) ; } KmerCode( const KmerCode& in ) { kmerLength = in.kmerLength ; invalidPos = in.invalidPos ; largestBlock = in.largestBlock ; mask = in.mask ; for ( int i = 0 ; i < K_BLOCK_NUM ; ++i ) code[i] = in.code[i] ; } void Restart() { for ( int i = 0 ; i < K_BLOCK_NUM ; ++i ) code[i] = 0 ; invalidPos = -1 ; } int GetCode( uint64_t outCode[] ) { for ( int i = 0 ; i < K_BLOCK_NUM ; ++i ) outCode[i] = code[i] ; return K_BLOCK_NUM ; } uint64_t GetCodeI( int index ) { return code[index] ; } int GetKmerLength() { return kmerLength ; } bool IsValid() { /*if ( invalidPos != -1 ) { printf( "hi\n") ; }*/ return ( invalidPos == -1 ) ; } // the bits are organsized: // 4321 8765 ... void Append( char c ) { ShiftLeft() ; code[0] |= ( (uint64_t)( nucToNum[ c - 'A' ] & 3 ) ) ; if ( nucToNum[c - 'A'] == -1 ) { invalidPos = 0 ; } } void Prepend( char c ) { ShiftRight() ; if ( nucToNum[c-'A'] == -1 ) { invalidPos = kmerLength - 1 ; } const uint64_t residual = ( kmerLength - 1 ) % ( sizeof( uint64_t ) * 4 ) ; code[largestBlock] = ( code[largestBlock] | ( (uint64_t)( nucToNum[c - 'A'] & 3 ) << ( 2ull * ( residual ) ) ) ) & mask ; } void ShiftLeft() { if ( invalidPos != -1 ) ++invalidPos ; int i ; for ( i = largestBlock ; i >= 0 ; --i ) { code[i] = ( code[i] << (2ull) ) ; if ( i > 0 ) { uint64_t head = ( code[i - 1] >> (62ull ) ) & 3ull; code[i] |= head ; } } code[ largestBlock ] &= mask ; if ( invalidPos >= kmerLength ) invalidPos = -1 ; } void ShiftRight() { if ( invalidPos != -1 ) --invalidPos ; int i ; for ( i = 0 ; i <= largestBlock ; ++i ) { if ( i > 0 ) { uint64_t tail = code[i] & 3ull ; code[i - 1] |= ( tail << ( 2ull * 31 ) ) ; } code[i] = ( code[i] >> ( 2ull ) ) ; } code[ largestBlock ] &= ( mask >> 2ull ) ; if ( invalidPos < 0 ) invalidPos = -1 ; } KmerCode& operator=( const KmerCode& in ) { kmerLength = in.kmerLength ; invalidPos = in.invalidPos ; largestBlock = in.largestBlock ; mask = in.mask ; for ( int i = 0 ; i < K_BLOCK_NUM ; ++i ) code[i] = in.code[i] ; return *this ; } } ; #endif #endif Lighter-1.1.2/LICENSE000066400000000000000000001045131337104460000141200ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 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 . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . Lighter-1.1.2/Makefile000066400000000000000000000011001337104460000145370ustar00rootroot00000000000000CXX = g++ CXXFLAGS= -Wall -O3 LINKFLAGS = -lpthread -lz DEBUG= OBJECTS = ErrorCorrection.o GetKmers.o # For Windows pthreads library: http://www.sourceware.org/pthreads-win32/ ifneq (,$(findstring MINGW,$(shell uname))) LINKFLAGS = -L. -lpthreadGC2 endif all: lighter lighter: main.o $(OBJECTS) $(CXX) -o $@ $(CXXFLAGS) $(OBJECTS) main.o $(LINKFLAGS) main.o: main.cpp utils.h Reads.h Store.h File.h KmerCode.h bloom_filter.hpp ErrorCorrection.o: ErrorCorrection.cpp ErrorCorrection.h utils.h GetKmers.o: GetKmers.cpp GetKmers.h utils.h clean: rm -f *.o *.gch lighter Lighter-1.1.2/README.md000066400000000000000000000137311337104460000143730ustar00rootroot00000000000000Lighter ======= Described in: Song, L., Florea, L. and Langmead, B., [Lighter: Fast and Memory-efficient Sequencing Error Correction without Counting](http://genomebiology.com/2014/15/11/509/). Genome Biol. 2014 Nov 15;15(11):509. Copyright (C) 2012-2013, and GNU GPL, by Li Song, Liliana Florea and Ben Langmead Lighter includes source code from the [`bloom` C++ Bloom filter library](http://code.google.com/p/bloom/). `bloom` is distributed under the [Mozilla Public License (MPL)](http://www.mozilla.org/MPL/) v1.1. ### What is Lighter? Lighter is a kmer-based error correction method for whole genome sequencing data. Lighter uses sampling (rather than counting) to obtain a set of kmers that are likely from the genome. Using this information, Lighter can correct the reads containing sequence errors. ### Install 1. Clone the [GitHub repo](https://github.com/mourisl/lighter), e.g. with `git clone https://github.com/mourisl/Lighter.git` 2. Run `make` in the repo directory Lighter is small and portable, with [pthreads](http://en.wikipedia.org/wiki/POSIX_Threads) and [zlib](http://en.wikipedia.org/wiki/Zlib) being the only library dependency. ### Usage Usage: ./lighter [OPTIONS] OPTIONS: Required parameters: -r seq_file: seq_file is the path to the sequence file. Can use multiple -r to specifiy multiple sequence files The file can be fasta and fastq, and can be gzip'ed with extension *.gz. When the input file is *.gz, the corresponding output file will also be gzip'ed. -k kmer_length genome_size alpha or -K kmer_length genome_size Other parameters: -od output_file_directory: (default: ./) -t num_of_threads: number of threads to use (default: 1) -maxcor INT: the maximum number of corrections within a 20bp window (default: 4) -trim: allow trimming (default: false) -discard: discard unfixable reads. Will LOSE paired-end matching when discarding (default: false) -noQual: ignore the quality socre (default: false) -newQual ascii_quality_score: set the quality for the bases corrected to the specified score (default: not used) -saveTrustedKmers file: save the trusted kmers to specified file then stop (default: not used) -loadTrustedKmers file: directly get solid kmers from specified file (default: not used) -zlib compress_level: set the compression level(1-9) of gzip (default: 1) -h: print the help message and quit -v: print the version information and quit NOTICE: genome_size does not need to be accurate, but it should be at least as large as the size of the sequenced genome. alpha is the sampling rate and decided by the user. A rule of thumb: alpha=(7/C), where C is the average coverage of the data set. When using "-K" instead of "-k", Lighter will go through the reads an extra pass to decide C. And for "-K", genome_size should be relative accurate. Lighter may adjust -maxcor and bad quality threshold if it decides the error rate of the data set is high. You can specify "-maxcor" explicitly to turn off this feature. If you want to use longer kmer, you can adjust the constraints "MAX_KMER_LENGTH" in "utils.h" file before compiling lighter. ### Output For each input file (specified by -r), Lighter will create a corresponding file containing the corrected reads in the directory specified by "-od". If the name of a read file is like A.fq or A.fastq, the corresponding output file name is A.cor.fq. For A.fa or A.fasta, the output file is A.cor.fa. For A.fastq.gz or A.fq.gz, the output file is A.cor.fq.gz. For A.fasta.gz or A.fa.gz, the output file is A.cor.fa.gz. For each header line, Lighter will append some information regarding the correction result. "cor": some bases of the sequence are corrected "bad_suffix", "bad_prefix": the errors in the suffix or prefix of indicated length could not be corrected "unfixable_error": the errors could not be corrected There are some two-characters string to indicate the reason why Lighter could not correct the errors: "lc": low coverage "ak": ambiguous candidate kmer "oc": over corrected ### Example Suppose the data set is from E.Coli whose genome size is about 4.7M. If the data set has 3.3M reads in total with read length 100bp, then the average coverage is about 70x and we can set the alpha to be 7/70=0.1. Single-end data set: ./lighter -r read.fq -k 17 5000000 0.1 -t 10 Paired-end data set: ./lighter -r left.fq -r right.fq -k 17 5000000 0.1 -t 10 Instead of "-k 17 5000000 0.1", you can use "-K 17 4700000" so that Lighter will go through the data set an extra pass to decide alpha. ### Miscellaneous Lighter is available as conda package and can be installed with: ```bash conda install lighter --channel bioconda ``` A Docker container is available with: ```bash docker run quay.io/mulled/lighter:1.1.1--1 lighter -h ``` If you have a [Galaxy](https://galaxyproject.org/) instance you can install Lighter from the [Galaxy Tool Shed](https://toolshed.g2.bx.psu.edu/view/bgruening/lighter). If you are using Brew or Linuxbrew, you can install Lighter with: ```bash brew install lighter ``` ### Terms of use 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 2 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 (LICENSE.txt) a copy of the GNU General Public License along with this program; if not, you can obtain one from http://www.gnu.org/licenses/gpl.txt or by writing to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ### Support Create a [GitHub issue](https://github.com/mourisl/lighter/issues). Lighter-1.1.2/Reads.h000066400000000000000000000244601337104460000143240ustar00rootroot00000000000000// The class for reading reads from a file #ifndef _MOURISL_READS #define _MOURISL_READS #include #include #include #include "utils.h" #include "File.h" #define MAX_READ_FILE 100 struct _Read { char id[MAX_ID_LENGTH] ; char seq[MAX_READ_LENGTH] ; char qual[MAX_READ_LENGTH] ; int correction ; int badPrefix, badSuffix ; int info ; } ; class Reads { private: File fp[MAX_READ_FILE] ; File outputFp[MAX_READ_FILE] ; int FILE_TYPE[MAX_READ_FILE] ; // 0-FASTA, 1-FASTQ int fpUsed ; int currentFpInd ; char outputDirectory[256] ; bool discard ; int compressLevel ; void GetFileName( char *in, char *out ) { int i, j ; int len = (int)strlen( in ) ; for ( i = len ; i >= 0 && in[i] != '.' && in[i] != '/' ; --i ) ; if ( i >= 0 && !strcmp( &in[i], ".gz" ) ) { int tmp = i ; for ( i = i - 1 ; i >= 0 && in[i] != '.' && in[i] != '/' ; --i ) ; in[tmp] = '\0' ; if ( i >= 0 && ( !strcmp( &in[i], ".fastq" ) || !strcmp( &in[i], ".fasta" ) || !strcmp( &in[i], ".fq" ) || !strcmp( &in[i], ".fa" ) ) ) { ; } else { i = tmp ; } in[tmp] = '.' ; } for ( j = len ; j >= 0 && in[j] != '/' ; --j ) ; if ( i >= 0 && in[i] == '.' ) { in[i] = '\0' ; strcpy( out, in + j + 1 ) ; in[i] = '.' ; } else { strcpy( out, in + j + 1 ) ; } } public: char id[MAX_ID_LENGTH] ; char seq[MAX_READ_LENGTH] ; char qual[MAX_READ_LENGTH] ; Reads(): fpUsed(0), currentFpInd(0) { compressLevel = 1 ; strcpy( outputDirectory, "./" ) ; } ~Reads() { int i ; for ( i = 0 ; i < fpUsed ; ++i ) { fp[i].Close() ; outputFp[i].Close() ; } } void SetDiscard( bool d ) { discard = d ; } void SetCompressLevel( int cl ) { compressLevel = cl ; } void AddReadFile( char *file ) { if ( fpUsed >= MAX_READ_FILE ) { fprintf( stderr, "The number of read files exceeds the limit %d.\n", MAX_READ_FILE ) ; exit( 1 ) ; } char buffer[1024], fileName[1024] ; fp[ fpUsed ].Open( file, "r" ) ; fp[ fpUsed ].Gets( buffer, sizeof( buffer ) ) ; if ( buffer[0] == '>' ) { FILE_TYPE[ fpUsed ] = 0 ; qual[0] = '\0' ; } else if ( buffer[0] == '@' ) { FILE_TYPE[ fpUsed ] = 1 ; } else { fprintf( stderr, "\"%s\"'s format is wrong.\n", file ) ; exit( 1 ) ; } fp[fpUsed].Close() ; fp[fpUsed].Open( file, "r" ) ; GetFileName( file, fileName ) ; int len = strlen( file ) ; if ( file[ len - 2] == 'g' && file[ len - 1 ] == 'z' && compressLevel > 0 ) { if ( FILE_TYPE[ fpUsed ] == 1 ) sprintf( buffer, "%s/%s.cor.fq.gz", outputDirectory, fileName ) ; else sprintf( buffer, "%s/%s.cor.fa.gz", outputDirectory, fileName ) ; } else { if ( FILE_TYPE[ fpUsed ] == 1 ) sprintf( buffer, "%s/%s.cor.fq", outputDirectory, fileName ) ; else sprintf( buffer, "%s/%s.cor.fa", outputDirectory, fileName ) ; } outputFp[ fpUsed ].SetCompressLevel( compressLevel ) ; outputFp[ fpUsed ].Open( buffer, "w" ) ; ++fpUsed ; } void SetOutputDirectory( char *d ) { strcpy( outputDirectory, d ) ; } bool HasQuality() { return ( FILE_TYPE[ currentFpInd ] != 0 ) ; } void Rewind() { int i ; for ( i = 0 ; i < fpUsed ; ++i ) { fp[i].Rewind() ; outputFp[i].Rewind() ; } currentFpInd = 0 ; } int Next() { int len ; char buffer[2048] ; while ( currentFpInd < fpUsed && ( fp[currentFpInd].Gets( id, sizeof( id ) ) == NULL ) ) { ++currentFpInd ; } if ( currentFpInd >= fpUsed ) return 0 ; File &lfp = fp[currentFpInd] ; if ( FILE_TYPE[ currentFpInd ] == 0 ) { lfp.Gets( seq, sizeof( seq ) ) ; } else if ( FILE_TYPE[ currentFpInd ] == 1 ) { lfp.Gets( seq, sizeof( seq ) ) ; lfp.Gets( buffer, sizeof( buffer ) ) ; lfp.Gets( qual, sizeof( qual ) ) ; } // Clean the return symbol len = (int)strlen( id ) ; if ( id[len - 1] == '\n') id[len - 1] = '\0' ; len = (int)strlen( seq ) ; if ( seq[len - 1] == '\n' ) seq[len - 1] = '\0' ; if ( FILE_TYPE[ currentFpInd ] == 1 ) { if ( qual[len - 1] == '\n' ) qual[len - 1] = '\0' ; } return 1 ; } int NextWithBuffer( char *id, char *seq, char *qual, bool removeReturn = true, bool stopWhenFileEnds = false ) { int len ; char buffer[2048] ; while ( currentFpInd < fpUsed && ( fp[currentFpInd].Gets( id, sizeof( char ) * MAX_ID_LENGTH ) == NULL ) ) { ++currentFpInd ; if ( stopWhenFileEnds ) return -1 ; } if ( currentFpInd >= fpUsed ) return 0 ; File &lfp = fp[ currentFpInd ] ; if ( FILE_TYPE[ currentFpInd ] == 0 ) { lfp.Gets( seq, sizeof( char ) * MAX_READ_LENGTH ) ; qual[0] = '\0' ; } else if ( FILE_TYPE[ currentFpInd ] == 1 ) { lfp.Gets( seq, sizeof( char ) * MAX_READ_LENGTH ) ; lfp.Gets( buffer, sizeof( buffer ) ) ; lfp.Gets( qual, sizeof( char ) * MAX_READ_LENGTH ) ; } // Clean the return symbol if ( removeReturn ) { len = (int)strlen( id ) ; if ( id[len - 1] == '\n') id[len - 1] = '\0' ; len = (int)strlen( seq ) ; if ( seq[len - 1] == '\n' ) seq[len - 1] = '\0' ; if ( FILE_TYPE[ currentFpInd ] == 1 ) { if ( qual[len - 1] == '\n' ) qual[len - 1] = '\0' ; } } return 1 ; } void Output( int correction, int badPrefix, int badSuffix, int info, bool allowTrimming ) { /* char buffer[1024] ; */ char failReason[4] = "" ; if ( info == 1 ) strcpy( failReason, " oc" ) ; else if ( info == 2 ) strcpy( failReason, " ak" ) ; else if ( info == 3 ) strcpy( failReason, " lc" ) ; if ( correction == 0 && badPrefix == 0 && badSuffix == 0 ) { outputFp[currentFpInd].Printf( "%s\n%s\n", id, seq ) ; if ( FILE_TYPE[ currentFpInd ] != 0 ) outputFp[currentFpInd].Printf( "+\n%s\n", qual ) ; } else if ( correction == -1 ) { /*if ( !strcmp( readId + 1, read ) ) { printf( "%s\n%s\n", readId, read ) ; }*/ if ( discard ) return ; outputFp[ currentFpInd].Printf( "%s unfixable_error%s\n%s\n", id, failReason, seq ) ; if ( FILE_TYPE[ currentFpInd ] != 0 ) outputFp[ currentFpInd ].Printf( "+\n%s\n", qual ) ; //printf( "%s\n%s\n", readId, read ) ; } else { char buffer1[20] = "" ; char buffer2[20] = "" ; char buffer3[20] = "" ; /*if ( allowTrimming ) strcpy( buffer2, "trimmed" ) ; else strcpy( buffer2, "bad_suffix" ) ; if ( badSuffix == 0 ) strcpy( buffer, "cor" ) ; else if ( trimmed > 0 && correction == 0 ) sprintf( buffer, "%s=%d", buffer2, trimmed ) ; else sprintf( buffer, "cor %s=%d", buffer2, trimmed ) ;*/ if ( correction > 0 ) strcpy( buffer1, " cor" ) ; if ( badPrefix > 0 ) sprintf( buffer2, " bad_prefix=%d", badPrefix ) ; if ( badSuffix > 0 ) { if ( allowTrimming ) sprintf( buffer3, " trimmed=%d", badSuffix ) ; else sprintf( buffer3, " bad_suffix=%d", badSuffix ) ; } outputFp[ currentFpInd ].Printf( "%s%s%s%s%s\n%s\n", id, buffer1, buffer2, buffer3, failReason, seq ) ; if ( FILE_TYPE[ currentFpInd ] != 0 ) { if ( allowTrimming ) qual[ strlen( qual ) - badSuffix ] = '\0' ; outputFp[ currentFpInd ].Printf( "+\n%s\n", qual ) ; } } } // Get a batch of reads, it terminates until the buffer is full or // the file ends. int GetBatch( struct _Read *readBatch, int maxBatchSize, int &fileInd, bool trimReturn, bool stopWhenFileEnds ) { int batchSize = 0 ; while ( batchSize < maxBatchSize ) { int tmp = NextWithBuffer( readBatch[ batchSize].id, readBatch[batchSize].seq, readBatch[batchSize].qual, trimReturn, stopWhenFileEnds ) ; if ( tmp <= 0 && batchSize > 0 ) { --currentFpInd ; fileInd = currentFpInd ; return batchSize ; // Finished read current file. } else if ( tmp == -1 && batchSize == 0 ) continue ; // The current read file is empty else if ( tmp == 0 && batchSize == 0 ) { fileInd = currentFpInd ; return 0 ; // Finished reading } ++batchSize ; } fileInd = currentFpInd ; return batchSize ; } void OutputBatch( struct _Read *readBatch, int batchSize, bool allowTrimming, int fileInd = -1 ) { int i ; if ( fileInd == -1 ) fileInd = currentFpInd ; for ( i = 0 ; i < batchSize ; ++i ) { char *id = readBatch[i].id ; char *seq = readBatch[i].seq ; char *qual = readBatch[i].qual ; int correction = readBatch[i].correction ; int badPrefix = readBatch[i].badPrefix ; int badSuffix = readBatch[i].badSuffix ; int info = readBatch[i].info ; char failReason[4] = "" ; if ( info == 1 ) strcpy( failReason, " oc" ) ; else if ( info == 2 ) strcpy( failReason, " ak" ) ; else if ( info == 3 ) strcpy( failReason, " lc" ) ; if ( correction == 0 && badPrefix == 0 && badSuffix == 0 ) { outputFp[ fileInd ].Printf( "%s\n%s\n", id, seq ) ; if ( FILE_TYPE[ fileInd ] != 0 ) outputFp[ fileInd ].Printf( "+\n%s\n", qual ) ; } else if ( correction == -1 ) { /*if ( !strcmp( readId + 1, read ) ) { printf( "%s\n%s\n", readId, read ) ; }*/ if ( discard ) continue ; outputFp[ fileInd ].Printf( "%s unfixable_error%s\n%s\n", id, failReason, seq ) ; if ( FILE_TYPE[ fileInd ] != 0 ) outputFp[ fileInd ].Printf( "+\n%s\n", qual ) ; //printf( "%s\n%s\n", readId, read ) ; } else { char buffer1[20] = "" ; char buffer2[20] = "" ; char buffer3[20] = "" ; if ( correction > 0 ) strcpy( buffer1, " cor" ) ; if ( badPrefix > 0 ) sprintf( buffer2, " bad_prefix=%d", badPrefix ) ; if ( badSuffix > 0 ) { if ( allowTrimming ) sprintf( buffer3, " trimmed=%d", badSuffix ) ; else sprintf( buffer3, " bad_suffix=%d", badSuffix ) ; } outputFp[ fileInd ].Printf( "%s%s%s%s%s\n%s\n", id, buffer1, buffer2, buffer3, failReason, seq ) ; if ( FILE_TYPE[ fileInd ] != 0 ) { if ( allowTrimming ) qual[ strlen( qual ) - badSuffix ] = '\0' ; outputFp[ fileInd ].Printf( "+\n%s\n", qual ) ; } } } } } ; // The class handling read in a batch of reads /*class ReadBatch { } ;*/ #endif Lighter-1.1.2/Store.h000066400000000000000000000124751337104460000143650ustar00rootroot00000000000000#ifndef _MOURISL_CLASS_STORE #define _MOURISL_CLASS_STORE /** The wrapper for bloom filters to store kmers. */ #include #include #include #include "bloom_filter.hpp" #include "KmerCode.h" class Store { private: uint64_t size ; bloom_parameters bfpara ; bloom_filter bf ; std::map hash ; int method ; //0-bloom filter. 1-std:map #if MAX_KMER_LENGTH <= 32 int Put( uint64_t val, int kmerLength, bool testFirst ) { //return 0 ; //printf( "%d\n", method ) ; //printf( "%llu\n", val ) ; val = GetCanonicalKmerCode( val, kmerLength ) ; //printf( "%llu\n", val ) ; //exit(1) ; if ( method == 1 ) { hash[ val ] = 1 ; return 1 ; } if ( numOfThreads > 1 && testFirst && bf.contains( val ) ) return 0 ; bf.insert( val ) ; return 0 ; } int IsIn( uint64_t val, int kmerLength ) { //printf( "1. %llu\n", val ) ; val = GetCanonicalKmerCode( val, kmerLength ) ; //printf( "2. %llu\n", val ) ; if ( method == 1 ) { return ( hash.find( val ) != hash.end() ) ; } return bf.contains( val ) ; } #else int Put( uint64_t code[], int kmerLength, bool testFirst ) { //return 0 ; //printf( "%d\n", method ) ; //printf( "%llu\n", val ) ; GetCanonicalKmerCode( code, kmerLength ) ; //printf( "%llu\n", val ) ; //exit(1) ; if ( method == 1 ) { //hash[ val ] = 1 ; return 1 ; } //printf( "1: %d\n", bf.contains( (char *)code, sizeof( uint64_t ) * ( ( kmerLength - 1 ) / 32 + 1 ) ) ) ; if ( numOfThreads > 1 && testFirst && bf.contains( (char *)code, sizeof( uint64_t ) * ( ( kmerLength - 1 ) / 32 + 1 ) ) ) return 0 ; //printf( "2: %lld %d\n", code[0], sizeof( uint64_t ) * ( ( kmerLength - 1 ) / 32 + 1 ) ) ; bf.insert( (char *)code, sizeof( uint64_t ) * ( ( kmerLength - 1 ) / 32 + 1 ) ) ; //printf( "3: %d\n", bf.contains( (char *)code, sizeof( uint64_t ) * ( ( kmerLength - 1 ) / 32 + 1 ) ) ) ; return 0 ; } int IsIn( uint64_t code[], int kmerLength ) { //printf( "1. %llu\n", val ) ; GetCanonicalKmerCode( code, kmerLength ) ; //printf( "2. %llu\n", val ) ; if ( method == 1 ) { //return ( hash.find( val ) != hash.end() ) ; } return bf.contains( ( char *)code, sizeof( uint64_t ) * ( ( kmerLength - 1 ) / 32 + 1 ) ) ; } #endif int numOfThreads ; public: Store( double fprate = 0.01 ): size( 10000003 ), bfpara( 10000003, fprate ), bf( bfpara ) { numOfThreads = 1 ; method = 0 ; } Store( uint64_t s, double fprate = 0.01 ): size( s ), bfpara( s, fprate ), bf( bfpara ) { numOfThreads = 1 ; method = 0 ; } ~Store() { } double Occupancy() { return bf.occupancy() ; } double GetFP() { if ( method == 1 ) return 0 ; return bf.GetActualFP() ; } int Put( KmerCode &code, bool testFirst = false ) { if ( !code.IsValid() ) return 0 ; #if MAX_KMER_LENGTH <= 32 Put( code.GetCode(), code.GetKmerLength(), testFirst ) ; #else uint64_t c[K_BLOCK_NUM] ; code.GetCode( c ) ; Put( c, code.GetKmerLength(), testFirst ) ; #endif return 0 ; } int IsIn( KmerCode &code ) { if ( !code.IsValid() ) return 0 ; #if MAX_KMER_LENGTH <= 32 return IsIn( code.GetCode(), code.GetKmerLength() ) ; #else uint64_t c[K_BLOCK_NUM] ; code.GetCode( c ) ; return IsIn( c, code.GetKmerLength() ) ; #endif } void SetNumOfThreads( int in ) { numOfThreads = in ; bf.SetNumOfThreads( in ) ; } #if MAX_KMER_LENGTH <= 32 uint64_t GetCanonicalKmerCode( uint64_t code, int k ) { int i ; uint64_t crCode = 0ull ; // complementary code for ( i = 0 ; i < k ; ++i ) { //uint64_t tmp = ( code >> ( 2ull * (k - i - 1) ) ) & 3ull ; //crCode = ( crCode << 2ull ) | ( 3 - tmp ) ; uint64_t tmp = ( code >> ( 2ull * i ) ) & 3ull ; crCode = ( crCode << 2ull ) | ( 3ull - tmp ) ; } return crCode < code ? crCode : code ; } #else void GetCanonicalKmerCode( uint64_t code[], int k ) { int i, j ; uint64_t crCode[ K_BLOCK_NUM ] ; // complementary code const int largestBlock = ( k - 1 ) / ( sizeof( uint64_t ) * 4 ) ; for ( i = 0 ; i < K_BLOCK_NUM ; ++i ) crCode[i] = 0 ; for ( i = 0, j = k - 1 ; i < k ; ++i, --j ) { //uint64_t tmp = ( code >> ( 2ull * (k - i - 1) ) ) & 3ull ; //crCode = ( crCode << 2ull ) | ( 3 - tmp ) ; /*int tagI = i >> 5 ; int tagJ = j >> 5 ; int residualI = i & 31 ; int residualJ = j & 31 ;*/ uint64_t tmp = ( code[ i >> 5 ] >> ( 2ull * ( i & 31 ) ) ) & 3ull ; crCode[j >> 5] = crCode[ j >> 5 ] | ( ( 3ull - tmp ) << ( 2ull * ( j & 31 ) ) ) ; } bool crFlag = false ; for ( i = largestBlock ; i >= 0 ; --i ) { if ( crCode[i] < code[i] ) { crFlag = true ; break ; } else if ( crCode[i] > code[i] ) { crFlag = false ; break ; } } //printf( "%llu,%llu %llu,%llu: %d\n", code[1], code[0], crCode[1], crCode[0], crFlag ) ; if ( crFlag ) { for ( i = 0 ; i < K_BLOCK_NUM ; ++i ) code[i] = crCode[i] ; } } #endif void BloomOutput( char *file) { FILE *fp = fopen( file, "w" ) ; if ( fp == NULL ) { printf( "Could not find file %s.\n", file ) ; exit( EXIT_FAILURE ) ; } bf.Output( fp ) ; fclose( fp ) ; } void BloomInput( char *file ) { FILE *fp = fopen( file, "r" ) ; if ( fp == NULL ) { printf( "Could not find file %s.\n", file ) ; exit( EXIT_FAILURE ) ; } bf.Input( fp ) ; fclose( fp ) ; } int Clear() { return 0 ; } } ; #endif Lighter-1.1.2/bloom_filter.hpp000066400000000000000000000706741337104460000163130ustar00rootroot00000000000000/* ********************************************************************* * * * Open Bloom Filter * * * * Author: Arash Partow - 2000 * * URL: http://www.partow.net * * URL: http://www.partow.net/programming/hashfunctions/index.html * * * * Copyright notice: * * Free use of the Open Bloom Filter Library is permitted under the * * guidelines and in accordance with the most current version of the * * Common Public License. * * http://www.opensource.org/licenses/cpl1.0.php * * * ********************************************************************* */ #ifndef INCLUDE_BLOOM_FILTER_HPP #define INCLUDE_BLOOM_FILTER_HPP #include #include #include #include #include #include #include #include // Add by Li #include #include #define BLOCK_SIZE 256ull #define NUM_OF_PATTERN 65536ull static const std::size_t bits_per_char = 0x08; // 8 bits in 1 char(unsigned) static const unsigned char bit_mask[bits_per_char] = { 0x01, //00000001 0x02, //00000010 0x04, //00000100 0x08, //00001000 0x10, //00010000 0x20, //00100000 0x40, //01000000 0x80 //10000000 }; class bloom_parameters { public: bloom_parameters() : minimum_size(1), maximum_size(std::numeric_limits::max()), minimum_number_of_hashes(1), maximum_number_of_hashes(std::numeric_limits::max()), projected_element_count(10000), false_positive_probability(1.0 / projected_element_count), random_seed(0xA5A5A5A55A5A5A5AULL) {} bloom_parameters( unsigned long long int cnt, double fprate = 0.0001, unsigned long long int seed = 0xA5A5A5A55A5A5A5AULL ): minimum_size(1), maximum_size(std::numeric_limits::max()), minimum_number_of_hashes(1), maximum_number_of_hashes(std::numeric_limits::max() ) { projected_element_count = cnt ; false_positive_probability = fprate ; random_seed = seed ; compute_optimal_parameters() ; } virtual ~bloom_parameters() {} inline bool operator!() { return (minimum_size > maximum_size) || (minimum_number_of_hashes > maximum_number_of_hashes) || (minimum_number_of_hashes < 1) || (0 == maximum_number_of_hashes) || (0 == projected_element_count) || (false_positive_probability < 0.0) || (std::numeric_limits::infinity() == std::abs(false_positive_probability)) || (0 == random_seed) || (0xFFFFFFFFFFFFFFFFULL == random_seed); } //Allowed min/max size of the bloom filter in bits unsigned long long int minimum_size; unsigned long long int maximum_size; //Allowed min/max number of hash functions unsigned int minimum_number_of_hashes; unsigned int maximum_number_of_hashes; //The approximate number of elements to be inserted //into the bloom filter, should be within one order //of magnitude. The default is 10000. unsigned long long int projected_element_count; //The approximate false positive probability expected //from the bloom filter. The default is the reciprocal //of the projected_element_count. double false_positive_probability; unsigned long long int random_seed; struct optimal_parameters_t { optimal_parameters_t() : number_of_hashes(0), table_size(0) {} unsigned int number_of_hashes; unsigned long long int table_size; }; optimal_parameters_t optimal_parameters; virtual bool compute_optimal_parameters() { /* Note: The following will attempt to find the number of hash functions and minimum amount of storage bits required to construct a bloom filter consistent with the user defined false positive probability and estimated element insertion count. */ if (!(*this)) return false; double min_m = std::numeric_limits::infinity(); double min_k = 0.0; double curr_m = 0.0; double k = 2.0; while (k < 1000.0) { double numerator = (- k * projected_element_count) ; double denominator = std::log(1.0 - std::pow(false_positive_probability, 1.0 / k)); //double denominator = std::log(1.0 - std::pow(10, -4.0 / k)); curr_m = numerator / denominator + BLOCK_SIZE ; if (curr_m < min_m) { min_m = curr_m; min_k = k; } //printf( "%lf\n", curr_m ) ; k += 1.0; } //exit( 0 ) ; optimal_parameters_t& optp = optimal_parameters; optp.number_of_hashes = static_cast(min_k); optp.table_size = static_cast(min_m); optp.table_size += (((optp.table_size % bits_per_char) != 0) ? (bits_per_char - (optp.table_size % bits_per_char)) : 0); //++optp.number_of_hashes ; if (optp.number_of_hashes < minimum_number_of_hashes) optp.number_of_hashes = minimum_number_of_hashes; else if (optp.number_of_hashes > maximum_number_of_hashes) optp.number_of_hashes = maximum_number_of_hashes; if (optp.table_size < minimum_size) optp.table_size = minimum_size; else if (optp.table_size > maximum_size) optp.table_size = maximum_size; return true; } }; class bloom_filter { protected: typedef std::size_t bloom_type; typedef unsigned char cell_type; public: bloom_filter() : bit_table_(0), salt_count_(0), table_size_(0), raw_table_size_(0), projected_element_count_(0), inserted_element_count_(0), random_seed_(0), desired_false_positive_probability_(0.0), numOfThreads(1) {} bloom_filter(const bloom_parameters& p) : bit_table_(0), projected_element_count_(p.projected_element_count), inserted_element_count_(0), random_seed_((p.random_seed * 0xA5A5A5A5) + 1), desired_false_positive_probability_(p.false_positive_probability), numOfThreads( 1 ) { salt_count_ = p.optimal_parameters.number_of_hashes; table_size_ = p.optimal_parameters.table_size; generate_unique_salt(); raw_table_size_ = table_size_ / bits_per_char; //printf( "before malloc %d %d\n", (int)raw_table_size_, (int)p.projected_element_count ) ; //bit_table_ = new cell_type[static_cast(raw_table_size_)]; bit_table_ = new cell_type[(raw_table_size_)]; std::fill_n(bit_table_,raw_table_size_,0x00); /*blockSize = 1 ; while ( blockSize <= raw_table_size_ ) blockSize *= 2 ; blockSize /= 2 ;*/ // Add by Li memset( patterns, 0, sizeof( patterns ) ) ; int randomArray[BLOCK_SIZE] ; std::size_t i, j ; for ( i = 0 ; i < BLOCK_SIZE ; ++i ) randomArray[i] = i ; for ( i = 0 ; i < NUM_OF_PATTERN ; ++i ) { // Pick which bits to set for ( j = 0 ; j < salt_count_ ; ++j ) { int k = j + rand() % ( BLOCK_SIZE - j ) ; int tmp = randomArray[k] ; randomArray[k] = randomArray[j] ; randomArray[j] = tmp ; } // Set the patterns for ( j = 0 ; j < salt_count_ ; ++j ) { int r =randomArray[j] ; patterns[i][ r / 64 ] |= ( 1ull << (uint64_t)( r % 64 ) ) ; } } } bloom_filter(const bloom_filter& filter) { this->operator=(filter); } inline bool operator == (const bloom_filter& f) const { if (this != &f) { return (salt_count_ == f.salt_count_) && (table_size_ == f.table_size_) && (raw_table_size_ == f.raw_table_size_) && (projected_element_count_ == f.projected_element_count_) && (inserted_element_count_ == f.inserted_element_count_) && (random_seed_ == f.random_seed_) && (desired_false_positive_probability_ == f.desired_false_positive_probability_) && (salt_ == f.salt_) && std::equal(f.bit_table_,f.bit_table_ + raw_table_size_,bit_table_); } else return true; } inline bool operator != (const bloom_filter& f) const { return !operator==(f); } inline bloom_filter& operator = (const bloom_filter& f) { if (this != &f) { salt_count_ = f.salt_count_; table_size_ = f.table_size_; raw_table_size_ = f.raw_table_size_; projected_element_count_ = f.projected_element_count_; inserted_element_count_ = f.inserted_element_count_; random_seed_ = f.random_seed_; desired_false_positive_probability_ = f.desired_false_positive_probability_; delete[] bit_table_; bit_table_ = new cell_type[static_cast(raw_table_size_)]; std::copy(f.bit_table_,f.bit_table_ + raw_table_size_,bit_table_); salt_ = f.salt_; } return *this; } virtual ~bloom_filter() { delete[] bit_table_; } inline bool operator!() const { return (0 == table_size_); } inline void clear() { std::fill_n(bit_table_,raw_table_size_,0x00); inserted_element_count_ = 0; } double occupancy() { unsigned long long i, j ; unsigned long long used = 0 ; //printf( "(%llu)\n", table_size_ ) ; for ( i = 0, j = 0 ; i = table_size_ - 10 ) // printf( "(%llu)%llu %d\n", table_size_,i, tmp ) ; while ( tmp != 0 ) { if ( j + t < table_size_ ) used += ( tmp & 1 ) ; tmp = tmp >> 1 ; ++t ; } } //printf( "%llu %llu\n", used, total ) ; return (double)used/table_size_ ; } double GetActualFP() { //return pow( occupancy(), salt_.size() ) ; unsigned long long i, j, k ; int tagK ; std::size_t used = 0 ; unsigned long long denum = 0 ; double sum = 0 ; double blockFP[BLOCK_SIZE + 1] ; tagK = 0; k = 0; // Precompute the false positive for each possible block's occupancy rate for ( i = 0 ; i <= BLOCK_SIZE ; ++i ) blockFP[i] = pow( (double)i / BLOCK_SIZE, salt_.size() ) ; //printf( "(%llu)\n", table_size_ ) ; for ( i = 0, j = 0 ; i = table_size_ - 10 ) // printf( "(%llu)%llu %d\n", table_size_,i, tmp ) ; while ( t < bits_per_char ) { /*if ( used > BLOCK_SIZE || used < 0 ) { printf( "BIG ERROR\n" ) ; printf( "%llu %d %llu\n", i, (int)bit_table_[i], used ) ; }*/ if ( j + t < table_size_ ) used += ( ( tmp >> ( bits_per_char - t - 1 ) ) & 1 ) ; else break ; if ( j + t == BLOCK_SIZE - 1 ) { tagK = bits_per_char - 1 ; k = 0 ; } else if ( j + t >= BLOCK_SIZE ) { used -= ( bit_table_[k] >> tagK ) & 1 ; //exit( 1 ) ; --tagK ; if ( tagK < 0 ) { ++k ; tagK = bits_per_char - 1 ; } } //printf( "%u\n", (unsigned int)used ) ; if ( ( j & ( bits_per_char - 1 ) ) == 0 ) { sum += blockFP[used] ; //pow( (double)used / BLOCK_SIZE, salt_.size() ) ; ++denum ; } //tmp = tmp >> 1 ; ++t ; } } //printf( "%llu %llu\n", used, total ) ; //return (double)sum/( table_size_ - BLOCK_SIZE + 1 ) ; //printf( "%lf\n", sum / denum ) ; return (double)sum/denum ; } inline void insert(const unsigned char* key_begin, const std::size_t& length) { //std::size_t bit_index = 0; //std::size_t bit = 0; // Implementation of pattern block bloom filter std::size_t start = 0 ; start = ( hash_ap( key_begin, length, salt_[0] ) ) % ( table_size_ - BLOCK_SIZE + 1 ) ; start = start / bits_per_char ; // Align the start position to char int pid = ( hash_ap( key_begin, length, salt_[1] ) ) & ( NUM_OF_PATTERN - 1 ) ; // Which pattern to use int lockId[2] = { -1, -1 } ; // The stride of lock is BLOCK_SIZE, so one block span at most two lock //for (std::size_t i = 0 ; i < salt_.size(); ++i) if ( numOfThreads > 1 ) { lockId[0] = ( start / BLOCK_SIZE ) & lockMask ; lockId[1] = ( ( ( start + BLOCK_SIZE - 1 ) / BLOCK_SIZE) ) & lockMask ; if ( lockId[0] == lockId[1] ) lockId[1] = -1 ; else if ( lockId[0] > lockId[1] ) { int tmp = lockId[1] ; lockId[1] = lockId[0] ; lockId[0] = tmp ; } pthread_mutex_lock( &locks[ lockId[0] ] ) ; if ( lockId[1] != -1 ) pthread_mutex_lock( &locks[ lockId[1] ] ) ; } for ( std::size_t j = 0 ; j < BLOCK_SIZE / 64 ; ++j ) { *( (uint64_t *)( bit_table_ + start + 8 * j ) ) |= patterns[ pid ][ j ] ; } if ( numOfThreads > 1 ) { if ( lockId[1] != -1 ) pthread_mutex_unlock( &locks[ lockId[1] ] ) ; pthread_mutex_unlock( &locks[ lockId[0]] ) ; } ++inserted_element_count_; } template inline void insert(const T& t) { // Note: T must be a C++ POD type. insert(reinterpret_cast(&t),sizeof(T)); } inline void insert(const std::string& key) { insert(reinterpret_cast(key.c_str()),key.size()); } inline void insert(const char* data, const std::size_t& length) { insert(reinterpret_cast(data),length); } template inline void insert(const InputIterator begin, const InputIterator end) { InputIterator itr = begin; while (end != itr) { insert(*(itr++)); } } inline virtual bool contains(const unsigned char* key_begin, const std::size_t length) const { //std::size_t bit_index = 0; //std::size_t bit = 0; std::size_t start = 0 ; start = ( hash_ap( key_begin, length, salt_[0] ) ) % ( table_size_ - BLOCK_SIZE + 1 ); start /= bits_per_char ; int pid = ( hash_ap( key_begin, length, salt_[1] ) ) & ( NUM_OF_PATTERN - 1 ) ; for ( std::size_t j = 0 ; j < BLOCK_SIZE / 64 ; ++j ) if ( ( *(uint64_t *)( &bit_table_[start + 8 * j ] ) & patterns[ pid ][ j ] ) != patterns[ pid ][j] ) return false ; return true; } template inline bool contains(const T& t) const { return contains(reinterpret_cast(&t),static_cast(sizeof(T))); } inline bool contains( const uint64_t &key) const { return contains(reinterpret_cast(&key),8); } inline bool contains(const std::string& key) const { return contains(reinterpret_cast(key.c_str()),key.size()); } inline bool contains(const char* data, const std::size_t& length) const { return contains(reinterpret_cast(data),length); } template inline InputIterator contains_all(const InputIterator begin, const InputIterator end) const { InputIterator itr = begin; while (end != itr) { if (!contains(*itr)) { return itr; } ++itr; } return end; } template inline InputIterator contains_none(const InputIterator begin, const InputIterator end) const { InputIterator itr = begin; while (end != itr) { if (contains(*itr)) { return itr; } ++itr; } return end; } inline virtual unsigned long long int size() const { return table_size_; } inline std::size_t element_count() const { return inserted_element_count_; } inline double effective_fpp() const { /* Note: The effective false positive probability is calculated using the designated table size and hash function count in conjunction with the current number of inserted elements - not the user defined predicated/expected number of inserted elements. */ return std::pow(1.0 - std::exp(-1.0 * salt_.size() * inserted_element_count_ / size()), 1.0 * salt_.size()); } inline bloom_filter& operator &= (const bloom_filter& f) { /* intersection */ if ( (salt_count_ == f.salt_count_) && (table_size_ == f.table_size_) && (random_seed_ == f.random_seed_) ) { for (std::size_t i = 0; i < raw_table_size_; ++i) { bit_table_[i] &= f.bit_table_[i]; } } return *this; } inline bloom_filter& operator |= (const bloom_filter& f) { /* union */ if ( (salt_count_ == f.salt_count_) && (table_size_ == f.table_size_) && (random_seed_ == f.random_seed_) ) { for (std::size_t i = 0; i < raw_table_size_; ++i) { bit_table_[i] |= f.bit_table_[i]; } } return *this; } inline bloom_filter& operator ^= (const bloom_filter& f) { /* difference */ if ( (salt_count_ == f.salt_count_) && (table_size_ == f.table_size_) && (random_seed_ == f.random_seed_) ) { for (std::size_t i = 0; i < raw_table_size_; ++i) { bit_table_[i] ^= f.bit_table_[i]; } } return *this; } inline const cell_type* table() const { return bit_table_; } inline std::size_t hash_count() { return salt_.size(); } protected: inline virtual void compute_indices(const bloom_type& hash, std::size_t& bit_index, std::size_t& bit) const { bit_index = hash % table_size_; bit = bit_index % bits_per_char; } inline virtual void compute_indices(const bloom_type& hash, std::size_t& bit_index, std::size_t& bit, const std::size_t & start ) const { bit_index = start + ( hash & ( BLOCK_SIZE - 1 ) ) ; bit = bit_index % bits_per_char; } void generate_unique_salt() { /* Note: A distinct hash function need not be implementation-wise distinct. In the current implementation "seeding" a common hash function with different values seems to be adequate. */ const unsigned int predef_salt_count = 128; static const bloom_type predef_salt[predef_salt_count] = { 0xAAAAAAAA, 0x55555555, 0x33333333, 0xCCCCCCCC, 0x66666666, 0x99999999, 0xB5B5B5B5, 0x4B4B4B4B, 0xAA55AA55, 0x55335533, 0x33CC33CC, 0xCC66CC66, 0x66996699, 0x99B599B5, 0xB54BB54B, 0x4BAA4BAA, 0xAA33AA33, 0x55CC55CC, 0x33663366, 0xCC99CC99, 0x66B566B5, 0x994B994B, 0xB5AAB5AA, 0xAAAAAA33, 0x555555CC, 0x33333366, 0xCCCCCC99, 0x666666B5, 0x9999994B, 0xB5B5B5AA, 0xFFFFFFFF, 0xFFFF0000, 0xB823D5EB, 0xC1191CDF, 0xF623AEB3, 0xDB58499F, 0xC8D42E70, 0xB173F616, 0xA91A5967, 0xDA427D63, 0xB1E8A2EA, 0xF6C0D155, 0x4909FEA3, 0xA68CC6A7, 0xC395E782, 0xA26057EB, 0x0CD5DA28, 0x467C5492, 0xF15E6982, 0x61C6FAD3, 0x9615E352, 0x6E9E355A, 0x689B563E, 0x0C9831A8, 0x6753C18B, 0xA622689B, 0x8CA63C47, 0x42CC2884, 0x8E89919B, 0x6EDBD7D3, 0x15B6796C, 0x1D6FDFE4, 0x63FF9092, 0xE7401432, 0xEFFE9412, 0xAEAEDF79, 0x9F245A31, 0x83C136FC, 0xC3DA4A8C, 0xA5112C8C, 0x5271F491, 0x9A948DAB, 0xCEE59A8D, 0xB5F525AB, 0x59D13217, 0x24E7C331, 0x697C2103, 0x84B0A460, 0x86156DA9, 0xAEF2AC68, 0x23243DA5, 0x3F649643, 0x5FA495A8, 0x67710DF8, 0x9A6C499E, 0xDCFB0227, 0x46A43433, 0x1832B07A, 0xC46AFF3C, 0xB9C8FFF0, 0xC9500467, 0x34431BDF, 0xB652432B, 0xE367F12B, 0x427F4C1B, 0x224C006E, 0x2E7E5A89, 0x96F99AA5, 0x0BEB452A, 0x2FD87C39, 0x74B2E1FB, 0x222EFD24, 0xF357F60C, 0x440FCB1E, 0x8BBE030F, 0x6704DC29, 0x1144D12F, 0x948B1355, 0x6D8FD7E9, 0x1C11A014, 0xADD1592F, 0xFB3C712E, 0xFC77642F, 0xF9C4CE8C, 0x31312FB9, 0x08B0DD79, 0x318FA6E7, 0xC040D23D, 0xC0589AA7, 0x0CA5C075, 0xF874B172, 0x0CF914D5, 0x784D3280, 0x4E8CFEBC, 0xC569F575, 0xCDB2A091, 0x2CC016B4, 0x5C5F4421 }; if (salt_count_ <= predef_salt_count) { std::copy(predef_salt, predef_salt + salt_count_, std::back_inserter(salt_)); for (unsigned int i = 0; i < salt_.size(); ++i) { /* Note: This is done to integrate the user defined random seed, so as to allow for the generation of unique bloom filter instances. */ salt_[i] = salt_[i] * salt_[(i + 3) % salt_.size()] + static_cast(random_seed_); } } else { std::copy(predef_salt,predef_salt + predef_salt_count,std::back_inserter(salt_)); srand(static_cast(random_seed_)); while (salt_.size() < salt_count_) { bloom_type current_salt = static_cast(rand()) * static_cast(rand()); if (0 == current_salt) continue; if (salt_.end() == std::find(salt_.begin(), salt_.end(), current_salt)) { salt_.push_back(current_salt); } } } } inline bloom_type hash_ap(const unsigned char* begin, std::size_t remaining_length, bloom_type hash) const { const unsigned char* itr = begin; unsigned int loop = 0; while (remaining_length >= 8) { const unsigned int& i1 = *(reinterpret_cast(itr)); itr += sizeof(unsigned int); const unsigned int& i2 = *(reinterpret_cast(itr)); itr += sizeof(unsigned int); hash ^= (hash << 7) ^ i1 * (hash >> 3) ^ (~((hash << 11) + (i2 ^ (hash >> 5)))); remaining_length -= 8; } if (remaining_length) { if (remaining_length >= 4) { const unsigned int& i = *(reinterpret_cast(itr)); if (loop & 0x01) hash ^= (hash << 7) ^ i * (hash >> 3); else hash ^= (~((hash << 11) + (i ^ (hash >> 5)))); ++loop; remaining_length -= 4; itr += sizeof(unsigned int); } if (remaining_length >= 2) { const unsigned short& i = *(reinterpret_cast(itr)); if (loop & 0x01) hash ^= (hash << 7) ^ i * (hash >> 3); else hash ^= (~((hash << 11) + (i ^ (hash >> 5)))); ++loop; remaining_length -= 2; itr += sizeof(unsigned short); } if (remaining_length) { hash += ((*itr) ^ (hash * 0xA5A5A5A5)) + loop; } } return hash; } std::vector salt_; unsigned char* bit_table_; unsigned int salt_count_; unsigned long long int table_size_; unsigned long long int raw_table_size_; unsigned long long int projected_element_count_; unsigned int inserted_element_count_; unsigned long long int random_seed_; double desired_false_positive_probability_; // Add by Li. variables for multi-threads. int numOfThreads ; pthread_mutex_t *locks ; std::size_t lockMask ; uint64_t patterns[ NUM_OF_PATTERN ][ BLOCK_SIZE / 64 ] ; public: void SetNumOfThreads( int in ) { numOfThreads = in ; if ( in == 1 ) return ; std::size_t i, k ; for ( k = 1 ; k <= (std::size_t)in ; k *= 2 ) ; k *= 8 ; lockMask = k - 1 ; locks = ( pthread_mutex_t * )malloc( sizeof( pthread_mutex_t ) * k ) ; for ( i = 0 ; i < k ; ++i ) pthread_mutex_init( &locks[i], NULL ) ; } void Output( FILE *fp ) { // Output the patterns fwrite( patterns, sizeof( patterns ), 1, fp ) ; // Output the bit table fwrite( bit_table_, sizeof( unsigned char ), raw_table_size_, fp ) ; } void Input( FILE *fp ) { fread( patterns, sizeof( patterns ), 1, fp ) ; fread( bit_table_,sizeof( unsigned char ), raw_table_size_, fp ) ; } }; inline bloom_filter operator & (const bloom_filter& a, const bloom_filter& b) { bloom_filter result = a; result &= b; return result; } inline bloom_filter operator | (const bloom_filter& a, const bloom_filter& b) { bloom_filter result = a; result |= b; return result; } inline bloom_filter operator ^ (const bloom_filter& a, const bloom_filter& b) { bloom_filter result = a; result ^= b; return result; } class compressible_bloom_filter : public bloom_filter { public: compressible_bloom_filter(const bloom_parameters& p) : bloom_filter(p) { size_list.push_back(table_size_); } inline unsigned long long int size() const { return size_list.back(); } inline bool compress(const double& percentage) { if ((0.0 >= percentage) || (percentage >= 100.0)) { return false; } unsigned long long int original_table_size = size_list.back(); unsigned long long int new_table_size = static_cast((size_list.back() * (1.0 - (percentage / 100.0)))); new_table_size -= (((new_table_size % bits_per_char) != 0) ? (new_table_size % bits_per_char) : 0); if ((bits_per_char > new_table_size) || (new_table_size >= original_table_size)) { return false; } desired_false_positive_probability_ = effective_fpp(); cell_type* tmp = new cell_type[static_cast(new_table_size / bits_per_char)]; std::copy(bit_table_, bit_table_ + (new_table_size / bits_per_char), tmp); cell_type* itr = bit_table_ + (new_table_size / bits_per_char); cell_type* end = bit_table_ + (original_table_size / bits_per_char); cell_type* itr_tmp = tmp; while (end != itr) { *(itr_tmp++) |= (*itr++); } delete[] bit_table_; bit_table_ = tmp; size_list.push_back(new_table_size); return true; } private: inline void compute_indices(const bloom_type& hash, std::size_t& bit_index, std::size_t& bit) const { bit_index = hash; for (std::size_t i = 0; i < size_list.size(); ++i) { bit_index %= size_list[i]; } bit = bit_index % bits_per_char; } std::vector size_list; }; #endif /* Note 1: If it can be guaranteed that bits_per_char will be of the form 2^n then the following optimization can be used: hash_table[bit_index >> n] |= bit_mask[bit_index & (bits_per_char - 1)]; Note 2: For performance reasons where possible when allocating memory it should be aligned (aligned_alloc) according to the architecture being used. */ Lighter-1.1.2/main.cpp000066400000000000000000000572611337104460000145520ustar00rootroot00000000000000#include #include #include #include #include #include #include #define __STDC_FORMAT_MACROS #include #include "utils.h" #include "Store.h" #include "ErrorCorrection.h" #include "Reads.h" #include "KmerCode.h" #include "GetKmers.h" #include "pthread.h" char LIGHTER_VERSION[] = "Lighter v1.1.2" ; char nucToNum[26] = { 0, -1, 1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1 } ; char numToNuc[26] = {'A', 'C', 'G', 'T'} ; int MAX_CORRECTION ; bool ALLOW_TRIMMING ; int SET_NEW_QUAL ; bool zlibVersionChecked = false ; struct _summary { uint64_t corrCnt ; uint64_t trimReadsCnt ; uint64_t trimBaseCnt ; uint64_t discardReadsCnt ; uint64_t totalReads ; uint64_t errorFreeReadsCnt ; } ; struct _OutputThreadArg { struct _summary *summary ; struct _Read *readBatch ; int batchSize ; bool paraDiscard ; Reads *reads ; int fileInd ; } ; void PrintHelp() { printf( "Usage: ./lighter [OPTIONS]\n" "OPTIONS:\n" "Required parameters:\n" "\t-r seq_file: seq_file is the path to the sequence file. Can use multiple -r to specifiy multiple sequence files\n" "\t The file can be fasta and fastq, and can be gzip\'ed with extension *.gz.\n" "\t When the input file is *.gz, the corresponding output file will also be gzip\'ed.\n" "\t-k kmer_length genome_size alpha: (see README for information on setting alpha)\n" "\t\t\t\t\tor\n" "\t-K kmer_length genom_size: in this case, the genome size should be relative accurate.\n" "Other parameters:\n" "\t-od output_file_directory: (default: ./)\n" "\t-t num_of_threads: number of threads to use (default: 1)\n" "\t-maxcor INT: the maximum number of corrections within a 20bp window (default: 4)\n" "\t-trim: allow trimming (default: false)\n" "\t-discard: discard unfixable reads. Will LOSE paired-end matching when discarding (default: false)\n" "\t-noQual: ignore the quality socre (default: false)\n" "\t-newQual ascii_quality_score: set the quality for the bases corrected to the specified score (default: not used)\n" //"\t-stable: sequentialize the sampling stage, output the same result with different runs (default: false)\n" "\t-saveTrustedKmers file: save the trusted kmers to specified file then stop (default: not used)\n" "\t-loadTrustedKmers file: directly get solid kmers from specified file (default: not used)\n" "\t-zlib compress_level: set the compression level(0-9) of gzip (default: 1)\n" "\t-h: print the help message and quit\n" "\t-v: print the version information and quit\n") ; } uint64_t StringToUint64( char *s ) { int i ; uint64_t ret = 0 ; for ( i = 0 ; s[i] ; ++i ) { ret = ret * 10 + s[i] - '0' ; } return ret ; } inline void ExtractKmer( char *s, int offset, int kmerLength, char *buffer ) { int i ; for ( i = offset ; i < offset+ kmerLength ; ++i ) buffer[i - offset] = s[i] ; buffer[i - offset] = '\0' ; } void GetCumulativeBinomialDistribution( double F[], int l, double p ) { // p is the probability of getting 1. int i ; double coef = 1 ; double exp = pow( 1 - p, l ) ; F[0] = pow( 1 - p, l ) ; for ( i = 1 ; i <= l ; ++i ) { coef = coef / i * ( l - i + 1 ) ; exp = exp / ( 1 - p ) * p ; F[i] = F[i - 1] + coef * exp ; } } char GetGoodQuality( Reads &reads ) { int i ; int qualHisto[300] ; int totalCnt, cnt ; //Reads reads( readFile ) ; if ( !reads.HasQuality() ) return 127 ; memset( qualHisto, 0, sizeof( qualHisto ) ) ; for ( i = 0 ; i < 1000000 ; ++i ) { if ( !reads.Next() ) break ; ++qualHisto[ (int)reads.qual[0] ] ; } totalCnt = i ; cnt = 0 ; for ( i = 0 ; i < 300 ; ++i ) { cnt += qualHisto[i] ; if ( cnt > totalCnt * 0.25 ) break ; } return (char)i ; } char GetBadQuality( Reads &reads ) { int i ; int qualHisto[300], firstQualHisto[300] ; int totalCnt, cnt ; int t1, t2 ; //Reads reads( readFile ) ; if ( !reads.HasQuality() ) return 0 ; memset( qualHisto, 0, sizeof( qualHisto ) ) ; memset( firstQualHisto, 0, sizeof( firstQualHisto )) ; for ( i = 0 ; i < 1000000 ; ++i ) { if ( !reads.Next() ) break ; ++qualHisto[ (int)reads.qual[ strlen( reads.seq ) - 1 ] ] ; ++firstQualHisto[ (int)reads.qual[0] ] ; } totalCnt = i ; cnt = 0 ; for ( i = 0 ; i < 300 ; ++i ) { cnt += firstQualHisto[i] ; if ( cnt > totalCnt * 0.05 ) break ; } t1 = i - 1 ; cnt = 0 ; for ( i = 0 ; i < 300 ; ++i ) { cnt += qualHisto[i] ; if ( cnt > totalCnt * 0.05 ) break ; } t2 = i ; return (char)( t2 < t1 ? t2 : t1 ) ; } double InferAlpha( Reads &reads, uint64_t genomeSize ) { uint64_t totalLen = 0 ; while ( reads.Next() ) totalLen += strlen( reads.seq ) ; return 7.0 / ( (double)totalLen / genomeSize ) ; } void PrintLog( const char *log ) { time_t rawtime ; struct tm *timeInfo ; char buffer[128] ; //FILE *fp = fopen( "lighter.log", "a" ) ; time( &rawtime ) ; timeInfo = localtime( &rawtime ) ; strftime( buffer, sizeof( buffer ), "%F %H:%M:%S", timeInfo ) ; fprintf( stderr, "[%s] %s\n", buffer, log ) ; //fclose( fp ) ; } void UpdateSummary( char *seq, int correction, int badSuffix, bool paraDiscard, struct _summary &summary ) { if ( correction == 0 ) ++summary.errorFreeReadsCnt ; else if ( correction > 0 ) summary.corrCnt += correction ; else if ( paraDiscard ) // tmp < 0 ++summary.discardReadsCnt ; if ( ALLOW_TRIMMING && badSuffix > 0 ) { ++summary.trimReadsCnt ; summary.trimBaseCnt += badSuffix ; } ++summary.totalReads ; } void PrintSummary( const struct _summary &summary ) { fprintf( stderr, "Processed %" PRIu64 " reads:\n" "\t%" PRIu64 " are error-free\n" "\tCorrected %" PRIu64 " bases(%lf corrections for reads with errors)\n" "\tTrimmed %" PRIu64 " reads with average trimmed bases %lf\n" "\tDiscard %" PRIu64 " reads\n", summary.totalReads, summary.errorFreeReadsCnt, summary.corrCnt, summary.totalReads == summary.errorFreeReadsCnt ? 0.0 : (double)summary.corrCnt / ( summary.totalReads - summary.errorFreeReadsCnt ), summary.trimReadsCnt, summary.trimReadsCnt == 0 ? 0.0 : (double)summary.trimBaseCnt / summary.trimReadsCnt, summary.discardReadsCnt ) ; } void *Output_Thread( void *arg ) { int i ; struct _OutputThreadArg *myArg = ( struct _OutputThreadArg *)arg ; struct _Read *readBatch = myArg->readBatch ; int batchSize = myArg->batchSize ; //fprintf( stderr, "hi\n" ) ; for ( i = 0 ; i < batchSize ; ++i ) UpdateSummary( readBatch[i].seq, readBatch[i].correction, readBatch[i].badSuffix, myArg->paraDiscard, *( myArg->summary ) ) ; myArg->reads->OutputBatch( readBatch, batchSize, ALLOW_TRIMMING, myArg->fileInd ) ; pthread_exit( NULL ) ; return NULL ; } int main( int argc, char *argv[] ) { int kmerLength ; double alpha = -1 ; //char *readId/**, read, *qual*/ ; char buffer[1023] ; double untrustF[100][100] ; //double trustF[100][100] ; int threshold[MAX_KMER_LENGTH+1] ; char goodQuality = '\0', badQuality = '\0' ; int badPrefix, badSuffix ; bool paraDiscard ; bool ignoreQuality, inferAlpha ; //stable ; int zlibLevel ; char *saveTrustedKmers, *loadTrustedKmers ; //double bloomFilterFP = 0.0005 ; int i, j ; //uint64_t kmerCode ; //uint64_t mask ; uint64_t genomeSize = 0; struct _summary summary ; struct _SamplePattern *samplePatterns = NULL ; bool setMaxCor ; // variables for threads int numOfThreads ; pthread_attr_t pthreadAttr ; pthread_t *threads = NULL; pthread_mutex_t mutexSampleKmers, mutexStoreKmers ; if ( argc == 1 ) { PrintHelp() ; exit( EXIT_FAILURE ) ; } Reads reads ; /*reads.AddReadFile( argv[1] ) ; kmerLength = atoi( argv[2] ) ; genomeSize = StringToUint64( argv[3] ) ; alpha = (double)atof( argv[4] ) ;*/ paraDiscard = false ; MAX_CORRECTION = 4 ; setMaxCor = false ; ALLOW_TRIMMING = false ; SET_NEW_QUAL = -1 ; kmerLength = -1 ; numOfThreads = 1 ; ignoreQuality = false ; //stable = false ; inferAlpha = false ; loadTrustedKmers = NULL ; saveTrustedKmers = NULL ; zlibLevel = 1 ; memset( &summary, 0, sizeof( summary ) ) ; // Parse the arguments for ( i = 1 ; i < argc ; ++i ) { if ( !strcmp( "-discard", argv[i] ) ) { paraDiscard = true ; } else if ( !strcmp( "-maxcor", argv[i] ) ) { MAX_CORRECTION = atoi( argv[i + 1] ) ; setMaxCor = true ; ++i ; } else if ( !strcmp( "-r", argv[i] ) ) { //reads.AddReadFile( argv[i + 1 ] ) ; ++i; continue ; // wait to be processed after next round } else if ( !strcmp( "-k", argv[i] ) ) { if(i + 1 >= argc) { fprintf( stderr, "Must specify k-mer length, genome size, and alpha after -k\n"); exit( EXIT_FAILURE ); } kmerLength = atoi( argv[i + 1] ) ; if(i + 2 >= argc) { fprintf( stderr, "Must specify k-mer length, genome size, and alpha after -k\n"); exit( EXIT_FAILURE ); } genomeSize = StringToUint64( argv[i + 2] ) ; if(i + 3 >= argc) { fprintf( stderr, "Must specify k-mer length, genome size, and alpha after -k\n"); exit( EXIT_FAILURE ); } alpha = (double)atof( argv[i + 3] ) ; i += 3 ; } else if ( !strcmp( "-K", argv[i] ) ) { if(i + 1 >= argc) { fprintf( stderr, "Must specify k-mer length, genome size after -K\n"); exit( EXIT_FAILURE ); } kmerLength = atoi( argv[i + 1] ) ; if(i + 2 >= argc) { fprintf( stderr, "Must specify k-mer length, genome size after -K\n"); exit( EXIT_FAILURE ); } genomeSize = StringToUint64( argv[i + 2] ) ; inferAlpha = true ; i += 2 ; } else if ( !strcmp( "-od", argv[i] ) ) { mkdir( argv[i + 1], 0700 ) ; reads.SetOutputDirectory( argv[i + 1] ) ; ++i ; } else if ( !strcmp( "-trim", argv[i] ) ) { ALLOW_TRIMMING = true ; } else if ( !strcmp( "-t", argv[i] ) ) { numOfThreads = atoi( argv[i + 1] ) ; ++i ; } else if ( !strcmp( "-noQual", argv[i] ) ) { ignoreQuality = true ; } else if ( !strcmp( "-newQual", argv[i] ) ) { SET_NEW_QUAL = (int)argv[i + 1][0] ; ++i ; } else if ( !strcmp( "-stable", argv[i] ) ) { //stable = true ; } else if ( !strcmp( "-saveTrustedKmers", argv[i] ) ) { saveTrustedKmers = argv[i + 1] ; ++i ; } else if ( !strcmp( "-loadTrustedKmers", argv[i] ) ) { loadTrustedKmers = argv[i + 1] ; ++i ; } else if ( !strcmp( "-zlib", argv[i] ) ) { zlibLevel = atoi( argv[i+1] ) ; reads.SetCompressLevel( zlibLevel ) ; ++i ; } else if ( !strcmp( "-h", argv[i] ) ) { PrintHelp() ; exit( 0 ) ; } else if ( !strcmp( "-v", argv[i] ) ) { printf( "%s\n", LIGHTER_VERSION ) ; exit( 0 ) ; } else { fprintf( stderr, "Unknown argument %s\n", argv[i] ) ; exit( EXIT_FAILURE ) ; } } // Go the second round to get the reads files for ( i = 1 ; i < argc ; ++i ) { if ( !strcmp( "-r", argv[i] ) ) { reads.AddReadFile( argv[i + 1 ] ) ; ++i; } } if ( kmerLength == -1 ) { fprintf( stderr, "Require -k or -K parameter!\n" ) ; exit( EXIT_FAILURE ) ; } if ( kmerLength > MAX_KMER_LENGTH ) { fprintf( stderr, "K-mer length must be no larger than %d. You can adjust the MAX_KMER_LENGTH constraints in utils.h.\n", MAX_KMER_LENGTH ) ; exit( EXIT_FAILURE ) ; } if ( alpha != -1 && inferAlpha == true ) { fprintf( stderr, "Can not use both -k and -K.\n" ) ; exit( EXIT_FAILURE ) ; } if ( loadTrustedKmers != NULL && saveTrustedKmers != NULL ) { fprintf( stderr, "Can't use both -saveTrustedKmers and -loadTrustedKmers at the same time.\n" ) ; exit( EXIT_FAILURE ) ; } PrintLog( "=============Start====================" ) ; KmerCode kmerCode( kmerLength ) ; reads.SetDiscard( paraDiscard ) ; if ( inferAlpha && loadTrustedKmers == NULL ) { PrintLog( "Scanning the input files to infer alpha(sampling rate)" ) ; alpha = InferAlpha( reads, genomeSize ) ; sprintf( buffer, "Average coverage is %.3lf and alpha is %.3lf", 7.0 / alpha, alpha ) ; PrintLog( buffer ) ; reads.Rewind() ; } // Prepare data structures and other data. //Store kmers(1000000000ull) ; //Store trustedKmers(1000000000ull) ; Store kmers((uint64_t)( genomeSize * 1.5 ), 0.01 ) ; Store trustedKmers((uint64_t)( genomeSize * 1.5 ), 0.0005 ) ; if ( numOfThreads > 1 ) { // Initialized pthread variables pthread_attr_init( &pthreadAttr ) ; pthread_attr_setdetachstate( &pthreadAttr, PTHREAD_CREATE_JOINABLE ) ; threads = ( pthread_t * )malloc( sizeof( pthread_t ) * numOfThreads ) ; pthread_mutex_init( &mutexSampleKmers, NULL ) ; pthread_mutex_init( &mutexStoreKmers, NULL ) ; //kmers.SetNumOfThreads( numOfThreads ) ; trustedKmers.SetNumOfThreads( numOfThreads ) ; } //goodQuality = GetGoodQuality( reads ) ; //reads.Rewind() ; if ( ignoreQuality == false ) badQuality = GetBadQuality( reads ) ; if ( badQuality != '\0' ) { sprintf( buffer, "Bad quality threshold is \"%c\"", badQuality ) ; PrintLog( buffer ) ; } else { PrintLog( "No quality score used." ) ; } reads.Rewind() ; //printf( "%c\n", badQuality ) ; //exit( 1 ) ; /*for ( i = 1 ; i <= kmerLength ; ++i ) { for ( j = 0 ; j <= i ; ++j ) { printf( "%.10lf\t", trustF[i][j] ) ; } printf( "\n" ) ; } exit( 1 ) ;*/ //Store kmers((uint64_t)50000000 * 4, 0.001 ) ; //Store trustedKmers((uint64_t)50000000 * 2, 0.001 ) ; if ( loadTrustedKmers != NULL ) { trustedKmers.BloomInput( loadTrustedKmers ) ; sprintf( buffer, "Finish loading trusted kmers from file %s.", loadTrustedKmers ) ; PrintLog( buffer ) ; } if ( loadTrustedKmers == NULL ) // a very long if state-ment, I avoid the indent here to regard this a macro. { // Step 1: Sample the kmers //printf( "Begin step1. \n" ) ; fflush( stdout ) ; srand( 17 ) ; // Build the patterns for sampling if ( numOfThreads > 1 )//&& stable == false ) { samplePatterns = ( struct _SamplePattern *)malloc( sizeof( *samplePatterns ) * SAMPLE_PATTERN_COUNT ) ; for ( i = 0 ; i < SAMPLE_PATTERN_COUNT ; ++i ) { int k ; for ( k = 0 ; k < MAX_READ_LENGTH / 8 ; ++k ) samplePatterns[i].tag[k] = 0 ; for ( k = 0 ; k < MAX_READ_LENGTH ; ++k ) { double p = rand() / (double)RAND_MAX; if ( p < alpha ) { samplePatterns[i].tag[ k / 8 ] |= ( 1 << ( k % 8 ) ) ; // Notice within the small block, the order is reversed } } } } // It seems serialization is faster than parallel. NOT true now! if ( numOfThreads == 1 ) //|| stable == true ) { while ( reads.Next() != 0 ) { SampleKmersInRead( reads.seq, reads.qual, kmerLength, alpha, kmerCode, &kmers ) ; } } else //if ( 0 ) { struct _SampleKmersThreadArg arg ; void *pthreadStatus ; kmers.SetNumOfThreads( numOfThreads ) ; arg.kmerLength = kmerLength ; arg.alpha = alpha ; arg.kmers = &kmers ; arg.samplePatterns = samplePatterns ; // Since there is no output, so we can just directly read in the // sequence without considering the order. arg.reads = &reads ; arg.lock = &mutexSampleKmers ; //arg.lockPut = &mutexSampleKmersPut ; //numOfThreads = 1 ; for ( i = 0 ; i < numOfThreads / 2 ; ++i ) { pthread_create( &threads[i], &pthreadAttr, SampleKmers_Thread, (void *)&arg ) ; } for ( i = 0 ; i < numOfThreads / 2 ; ++i ) { pthread_join( threads[i], &pthreadStatus ) ; } } if ( numOfThreads > 1 ) //&& stable == false ) free( samplePatterns ) ; //kmers.BloomInput( "sample_bf.out" ) ; //kmers.BloomOutput( "sample_bf.out" ) ; // Update the bloom filter's false positive rate. // Compute the distribution of the # of sampled kmers from untrusted and trusted position double tableAFP = kmers.GetFP() ; for ( i = 1 ; i <= kmerLength ; ++i ) { int d = (int)( 0.1 / alpha * 2 ); double p ; if ( d < 2 ) d = 2 ; p = 1 - pow( ( 1 - alpha ), d ) ; //else // p = 1 - pow( 1 - 0.05, 2 ) ; //double p = 1 - pow( 1 - 0.05, 2 ) ; //p = 0 ; GetCumulativeBinomialDistribution( untrustF[i], i, p + tableAFP - p * tableAFP ) ; //GetCumulativeBinomialDistribution( untrustF[i], i, tableAFP ) ; //GetCumulativeBinomialDistribution( untrustF[i], i, alpha ) ; //GetCumulativeBinomialDistribution( trustF[i], i, 1 - pow( ( 1 - alpha ), 20 ) ) ; } /*for ( i = 1 ; i <= kmerLength ; ++i ) { for ( j = 0 ; j <= i ; ++j ) { printf( "%.20lf\t", untrustF[i][j] ) ; } printf( "\n" ) ; } printf( "===============\n" ) ; exit( 1 ) ;*/ for ( i = 1 ; i <= kmerLength ; ++i ) { for ( j = 0 ; j <= i ; ++j ) { if ( untrustF[i][j] >= 1 - 0.5 * 1e-2 ) { threshold[i] = j ; //if ( threshold[i] <= i / 2 ) // threshold[i] = i / 2 ; break ; } } } /*for ( i = 1 ; i <= kmerLength ; ++i ) { printf( "%d %d\n", threshold[i] + 1, i ) ; } exit( 1 ) ;*/ PrintLog( "Finish sampling kmers" ) ; sprintf( buffer, "Bloom filter A's false positive rate: %lf", tableAFP ) ; PrintLog( buffer ) ; if ( setMaxCor == false && tableAFP > 0.1 ) { ++MAX_CORRECTION ; if ( badQuality != '\0' ) { ++badQuality ; sprintf( buffer, "The error rate is high. Lighter adjusts -maxcor to %d and bad quality threshold to \"%c\".", MAX_CORRECTION, badQuality ) ; } else sprintf( buffer, "The error rate is high. Lighter adjusts -maxcor to %d.", MAX_CORRECTION ) ; PrintLog( buffer ) ; } // Step 2: Store the trusted kmers //printf( "Begin step2.\n") ; fflush( stdout ) ; reads.Rewind() ; if ( numOfThreads == 1 ) { while ( reads.Next() ) { StoreTrustedKmers( reads.seq, reads.qual, kmerLength, badQuality, threshold, kmerCode, &kmers, &trustedKmers ) ; } } else //if ( 0 ) { struct _StoreKmersThreadArg arg ; void *pthreadStatus ; arg.kmerLength = kmerLength ; arg.threshold = threshold ; arg.kmers = &kmers ; arg.trustedKmers = &trustedKmers ; arg.reads = &reads ; arg.goodQuality = goodQuality ; arg.badQuality = badQuality ; arg.lock = &mutexStoreKmers ; for ( i = 0 ; i < numOfThreads ; ++i ) { pthread_create( &threads[i], &pthreadAttr, StoreKmers_Thread, (void *)&arg ) ; } for ( i = 0 ; i < numOfThreads ; ++i ) { pthread_join( threads[i], &pthreadStatus ) ; } } PrintLog( "Finish storing trusted kmers" ) ; if ( saveTrustedKmers != NULL ) { trustedKmers.BloomOutput( saveTrustedKmers ) ; sprintf( buffer, "The trusted kmers are saved in file %s.", saveTrustedKmers ) ; PrintLog( buffer ) ; return 0 ; } } //trustedKmers.BloomInput( "bf.out ") ; //trustedKmers.BloomOutput( "bf.out ") ; // Step 3: error correction //printf( "%lf %lf\n", kmers.GetFP(), trustedKmers.GetFP() ) ; reads.Rewind() ; // Different ways of parallel depending on the number of threads. if ( numOfThreads == 1 ) { while ( reads.Next() ) { //readId = reads.id ; //read = reads.seq ; /*kmerCode = 0 ; for ( i = 0 ; i < kmerLength ; ++i ) { kmerCode = kmerCode << (uint64_t)2 ; kmerCode = kmerCode | (uint64_t)nucToNum[ read[i] - 'A' ] ; } if ( !trustedKmers.IsIn( kmerCode ) ) { //printf( "- %d %lld\n", i, kmerCode ) ; printf( "%s\n%s\n", readId, read ) ; continue ; } for ( ; read[i] ; ++i ) { kmerCode = ( kmerCode << (uint64_t)2 ) & mask ; kmerCode = kmerCode | (uint64_t)nucToNum[ read[i] - 'A' ] ; if ( !trustedKmers.IsIn( kmerCode ) ) { printf( "%s\n%s\n", readId, read ) ; break ; } } continue ;*/ int info ; int tmp = ErrorCorrection_Wrapper( reads.seq, reads.qual, kmerCode, badQuality, &trustedKmers, badPrefix, badSuffix, info ) ; //if ( reads.HasQuality() ) // //else // readId[0] = '>' ; UpdateSummary( reads.seq, tmp, badSuffix, paraDiscard, summary ) ; reads.Output( tmp, badPrefix, badSuffix, info, ALLOW_TRIMMING ) ; } } else if ( numOfThreads == 2 ) { int maxBatchSize = READ_BUFFER_PER_THREAD * numOfThreads ; int batchSize ; int fileInd ; struct _ErrorCorrectionThreadArg arg ; pthread_mutex_t errorCorrectionLock ; void *pthreadStatus ; struct _Read *readBatch = ( struct _Read *)malloc( sizeof( struct _Read ) * maxBatchSize ) ; pthread_mutex_init( &errorCorrectionLock, NULL ) ; arg.kmerLength = kmerLength ; arg.trustedKmers = &trustedKmers ; arg.readBatch = readBatch ; arg.lock = &errorCorrectionLock ; arg.badQuality = badQuality ; while ( 1 ) { batchSize = reads.GetBatch( readBatch, maxBatchSize, fileInd, true, true ) ; if ( batchSize == 0 ) break ; //printf( "batchSize=%d\n", batchSize ) ; arg.batchSize = batchSize ; arg.batchUsed = 0 ; for ( i = 0 ; i < numOfThreads ; ++i ) pthread_create( &threads[i], &pthreadAttr, ErrorCorrection_Thread, (void *)&arg ) ; for ( i = 0 ; i < numOfThreads ; ++i ) pthread_join( threads[i], &pthreadStatus ) ; for ( i = 0 ; i < batchSize ; ++i ) UpdateSummary( readBatch[i].seq, readBatch[i].correction, readBatch[i].badSuffix, paraDiscard, summary ) ; reads.OutputBatch( readBatch, batchSize, ALLOW_TRIMMING, fileInd ) ; } free( readBatch ) ; } else { int maxBatchSize = READ_BUFFER_PER_THREAD * ( numOfThreads - 1 ) ; int batchSize[3] ; bool init = true, canJoinOutputThread = false ; int tag = 2, prevTag ; int fileInd[3] ; int useOutputThread = 0 ; pthread_t outputThread ; struct _OutputThreadArg outputArg ; struct _ErrorCorrectionThreadArg arg ; pthread_mutex_t errorCorrectionLock ; void *pthreadStatus ; struct _Read *readBatch[3] ; readBatch[0] = ( struct _Read *)malloc( sizeof( struct _Read ) * maxBatchSize ) ; readBatch[1] = ( struct _Read *)malloc( sizeof( struct _Read ) * maxBatchSize ) ; readBatch[2] = ( struct _Read *)malloc( sizeof( struct _Read ) * maxBatchSize ) ; pthread_mutex_init( &errorCorrectionLock, NULL ) ; arg.kmerLength = kmerLength ; arg.trustedKmers = &trustedKmers ; //arg.readBatch = readBatch ; arg.lock = &errorCorrectionLock ; arg.badQuality = badQuality ; arg.batchSize = 0 ; arg.batchFinished = 0 ; if ( numOfThreads >= 6 ) useOutputThread = 1 ; while ( 1 ) { prevTag = tag ; tag = ( tag + 1 > 2 ) ? 0 : ( tag + 1 ) ; batchSize[tag] = reads.GetBatch( readBatch[tag], maxBatchSize, fileInd[tag], true, true ) ; // Wait for the previous batch finish if ( !init ) { if ( canJoinOutputThread ) // wait for the finish of the previous previous batch's output pthread_join( outputThread, &pthreadStatus ) ; for ( i = 0 ; i < numOfThreads - 1 - useOutputThread ; ++i ) pthread_join( threads[i], &pthreadStatus ) ; } // Start current batch if ( batchSize[tag] != 0 ) { //printf( "batchSize=%d\n", batchSize ) ; arg.batchSize = batchSize[tag] ; arg.readBatch = readBatch[tag] ; arg.batchUsed = 0 ; arg.batchFinished = 0 ; for ( i = 0 ; i < numOfThreads - 1 - useOutputThread ; ++i ) pthread_create( &threads[i], &pthreadAttr, ErrorCorrection_Thread, (void *)&arg ) ; //for ( i = 0 ; i < numOfThreads - 1 ; ++i ) // pthread_join( threads[i], &pthreadStatus ) ; } // Output previous batch if ( !init ) { // Create another thread to output previous batch if ( !useOutputThread ) { for ( i = 0 ; i < batchSize[prevTag] ; ++i ) UpdateSummary( readBatch[prevTag][i].seq, readBatch[prevTag][i].correction, readBatch[prevTag][i].badSuffix, paraDiscard, summary ) ; reads.OutputBatch( readBatch[prevTag], batchSize[prevTag], ALLOW_TRIMMING, fileInd[prevTag] ) ; } else { outputArg.readBatch = readBatch[ prevTag ] ; outputArg.batchSize = batchSize[prevTag] ; outputArg.summary = &summary ; outputArg.paraDiscard = paraDiscard ; outputArg.reads = &reads ; outputArg.fileInd = fileInd[ prevTag] ; pthread_create( &outputThread, &pthreadAttr, Output_Thread, (void *)&outputArg ) ; canJoinOutputThread = true ; } } if ( batchSize[tag] == 0 ) break ; init = false ; } if ( canJoinOutputThread ) pthread_join( outputThread, &pthreadStatus ) ; //fprintf( stderr, "jump out\n" ) ; free( readBatch[2] ) ; free( readBatch[1] ) ; free( readBatch[0] ) ; } PrintLog( "Finish error correction" ) ; PrintSummary( summary ) ; return 0 ; } Lighter-1.1.2/old_bloom_filter.hpp000066400000000000000000000605061337104460000171420ustar00rootroot00000000000000/* ********************************************************************* * * * Open Bloom Filter * * * * Author: Arash Partow - 2000 * * URL: http://www.partow.net * * URL: http://www.partow.net/programming/hashfunctions/index.html * * * * Copyright notice: * * Free use of the Open Bloom Filter Library is permitted under the * * guidelines and in accordance with the most current version of the * * Common Public License. * * http://www.opensource.org/licenses/cpl1.0.php * * * ********************************************************************* */ #ifndef INCLUDE_BLOOM_FILTER_HPP #define INCLUDE_BLOOM_FILTER_HPP #include #include #include #include #include #include #include #include // Add by Li #include static const std::size_t bits_per_char = 0x08; // 8 bits in 1 char(unsigned) static const unsigned char bit_mask[bits_per_char] = { 0x01, //00000001 0x02, //00000010 0x04, //00000100 0x08, //00001000 0x10, //00010000 0x20, //00100000 0x40, //01000000 0x80 //10000000 }; class bloom_parameters { public: bloom_parameters() : minimum_size(1), maximum_size(std::numeric_limits::max()), minimum_number_of_hashes(1), maximum_number_of_hashes(std::numeric_limits::max()), projected_element_count(10000), false_positive_probability(1.0 / projected_element_count), random_seed(0xA5A5A5A55A5A5A5AULL) {} bloom_parameters( unsigned long long int cnt, double fprate = 0.0001, unsigned long long int seed = 0xA5A5A5A55A5A5A5AULL ): minimum_size(1), maximum_size(std::numeric_limits::max()), minimum_number_of_hashes(1), maximum_number_of_hashes(std::numeric_limits::max() ) { projected_element_count = cnt ; false_positive_probability = fprate ; random_seed = seed ; compute_optimal_parameters() ; } virtual ~bloom_parameters() {} inline bool operator!() { return (minimum_size > maximum_size) || (minimum_number_of_hashes > maximum_number_of_hashes) || (minimum_number_of_hashes < 1) || (0 == maximum_number_of_hashes) || (0 == projected_element_count) || (false_positive_probability < 0.0) || (std::numeric_limits::infinity() == std::abs(false_positive_probability)) || (0 == random_seed) || (0xFFFFFFFFFFFFFFFFULL == random_seed); } //Allowed min/max size of the bloom filter in bits unsigned long long int minimum_size; unsigned long long int maximum_size; //Allowed min/max number of hash functions unsigned int minimum_number_of_hashes; unsigned int maximum_number_of_hashes; //The approximate number of elements to be inserted //into the bloom filter, should be within one order //of magnitude. The default is 10000. unsigned long long int projected_element_count; //The approximate false positive probability expected //from the bloom filter. The default is the reciprocal //of the projected_element_count. double false_positive_probability; unsigned long long int random_seed; struct optimal_parameters_t { optimal_parameters_t() : number_of_hashes(0), table_size(0) {} unsigned int number_of_hashes; unsigned long long int table_size; }; optimal_parameters_t optimal_parameters; virtual bool compute_optimal_parameters() { /* Note: The following will attempt to find the number of hash functions and minimum amount of storage bits required to construct a bloom filter consistent with the user defined false positive probability and estimated element insertion count. */ if (!(*this)) return false; double min_m = std::numeric_limits::infinity(); double min_k = 0.0; double curr_m = 0.0; double k = 1.0; while (k < 1000.0) { double numerator = (- k * projected_element_count); double denominator = std::log(1.0 - std::pow(false_positive_probability, 1.0 / k)); //double denominator = std::log(1.0 - std::pow(10, -4.0 / k)); curr_m = numerator / denominator; if (curr_m < min_m) { min_m = curr_m; min_k = k; } //printf( "%lf\n", curr_m ) ; k += 1.0; } //printf( "%lf %lf\n", min_k, min_m ) ; //exit( 0 ) ; optimal_parameters_t& optp = optimal_parameters; optp.number_of_hashes = static_cast(min_k); optp.table_size = static_cast(min_m); optp.table_size += (((optp.table_size % bits_per_char) != 0) ? (bits_per_char - (optp.table_size % bits_per_char)) : 0); if (optp.number_of_hashes < minimum_number_of_hashes) optp.number_of_hashes = minimum_number_of_hashes; else if (optp.number_of_hashes > maximum_number_of_hashes) optp.number_of_hashes = maximum_number_of_hashes; if (optp.table_size < minimum_size) optp.table_size = minimum_size; else if (optp.table_size > maximum_size) optp.table_size = maximum_size; return true; } }; class bloom_filter { protected: typedef unsigned int bloom_type; typedef unsigned char cell_type; public: bloom_filter() : bit_table_(0), salt_count_(0), table_size_(0), raw_table_size_(0), projected_element_count_(0), inserted_element_count_(0), random_seed_(0), desired_false_positive_probability_(0.0), numOfThreads(1) {} bloom_filter(const bloom_parameters& p) : bit_table_(0), projected_element_count_(p.projected_element_count), inserted_element_count_(0), random_seed_((p.random_seed * 0xA5A5A5A5) + 1), desired_false_positive_probability_(p.false_positive_probability), numOfThreads( 1 ) { salt_count_ = p.optimal_parameters.number_of_hashes; table_size_ = p.optimal_parameters.table_size; generate_unique_salt(); raw_table_size_ = table_size_ / bits_per_char; //printf( "before malloc %d %d\n", (int)raw_table_size_, (int)p.projected_element_count ) ; //bit_table_ = new cell_type[static_cast(raw_table_size_)]; bit_table_ = new cell_type[(raw_table_size_)]; std::fill_n(bit_table_,raw_table_size_,0x00); } bloom_filter(const bloom_filter& filter) { this->operator=(filter); } inline bool operator == (const bloom_filter& f) const { if (this != &f) { return (salt_count_ == f.salt_count_) && (table_size_ == f.table_size_) && (raw_table_size_ == f.raw_table_size_) && (projected_element_count_ == f.projected_element_count_) && (inserted_element_count_ == f.inserted_element_count_) && (random_seed_ == f.random_seed_) && (desired_false_positive_probability_ == f.desired_false_positive_probability_) && (salt_ == f.salt_) && std::equal(f.bit_table_,f.bit_table_ + raw_table_size_,bit_table_); } else return true; } inline bool operator != (const bloom_filter& f) const { return !operator==(f); } inline bloom_filter& operator = (const bloom_filter& f) { if (this != &f) { salt_count_ = f.salt_count_; table_size_ = f.table_size_; raw_table_size_ = f.raw_table_size_; projected_element_count_ = f.projected_element_count_; inserted_element_count_ = f.inserted_element_count_; random_seed_ = f.random_seed_; desired_false_positive_probability_ = f.desired_false_positive_probability_; delete[] bit_table_; bit_table_ = new cell_type[static_cast(raw_table_size_)]; std::copy(f.bit_table_,f.bit_table_ + raw_table_size_,bit_table_); salt_ = f.salt_; } return *this; } virtual ~bloom_filter() { delete[] bit_table_; } inline bool operator!() const { return (0 == table_size_); } inline void clear() { std::fill_n(bit_table_,raw_table_size_,0x00); inserted_element_count_ = 0; } double occupancy() { unsigned long long i, j ; unsigned long long used = 0 ; //printf( "(%llu)\n", table_size_ ) ; for ( i = 0, j = 0 ; i = table_size_ - 10 ) // printf( "(%llu)%llu %d\n", table_size_,i, tmp ) ; while ( tmp != 0 ) { if ( j + t < table_size_ ) used += ( tmp & 1 ) ; tmp = tmp >> 1 ; ++t ; } } //printf( "%llu %llu\n", used, total ) ; return (double)used/table_size_ ; } double GetActualFP() { double f = occupancy() ; return pow( f, salt_.size() ) ; } inline void insert(const unsigned char* key_begin, const std::size_t& length) { std::size_t bit_index = 0; std::size_t bit = 0; for (std::size_t i = 0; i < salt_.size(); ++i) { compute_indices(hash_ap(key_begin,length,salt_[i]),bit_index,bit); // Add by Li if ( numOfThreads > 1 ) pthread_mutex_lock( &locks[ bit_index & lockMask ] ) ; //printf( "%llu %llu\n", bit_index, lockMask ) ; bit_table_[bit_index / bits_per_char] |= bit_mask[bit]; if ( numOfThreads > 1 ) pthread_mutex_unlock( &locks[ bit_index & lockMask ] ) ; } ++inserted_element_count_; } template inline void insert(const T& t) { // Note: T must be a C++ POD type. insert(reinterpret_cast(&t),sizeof(T)); } inline void insert(const std::string& key) { insert(reinterpret_cast(key.c_str()),key.size()); } inline void insert(const char* data, const std::size_t& length) { insert(reinterpret_cast(data),length); } template inline void insert(const InputIterator begin, const InputIterator end) { InputIterator itr = begin; while (end != itr) { insert(*(itr++)); } } inline virtual bool contains(const unsigned char* key_begin, const std::size_t length) const { std::size_t bit_index = 0; std::size_t bit = 0; for (std::size_t i = 0; i < salt_.size(); ++i) { compute_indices(hash_ap(key_begin,length,salt_[i]),bit_index,bit); if ((bit_table_[bit_index / bits_per_char] & bit_mask[bit]) != bit_mask[bit]) { return false; } } return true; } template inline bool contains(const T& t) const { return contains(reinterpret_cast(&t),static_cast(sizeof(T))); } inline bool contains(const std::string& key) const { return contains(reinterpret_cast(key.c_str()),key.size()); } inline bool contains(const char* data, const std::size_t& length) const { return contains(reinterpret_cast(data),length); } template inline InputIterator contains_all(const InputIterator begin, const InputIterator end) const { InputIterator itr = begin; while (end != itr) { if (!contains(*itr)) { return itr; } ++itr; } return end; } template inline InputIterator contains_none(const InputIterator begin, const InputIterator end) const { InputIterator itr = begin; while (end != itr) { if (contains(*itr)) { return itr; } ++itr; } return end; } inline virtual unsigned long long int size() const { return table_size_; } inline std::size_t element_count() const { return inserted_element_count_; } inline double effective_fpp() const { /* Note: The effective false positive probability is calculated using the designated table size and hash function count in conjunction with the current number of inserted elements - not the user defined predicated/expected number of inserted elements. */ return std::pow(1.0 - std::exp(-1.0 * salt_.size() * inserted_element_count_ / size()), 1.0 * salt_.size()); } inline bloom_filter& operator &= (const bloom_filter& f) { /* intersection */ if ( (salt_count_ == f.salt_count_) && (table_size_ == f.table_size_) && (random_seed_ == f.random_seed_) ) { for (std::size_t i = 0; i < raw_table_size_; ++i) { bit_table_[i] &= f.bit_table_[i]; } } return *this; } inline bloom_filter& operator |= (const bloom_filter& f) { /* union */ if ( (salt_count_ == f.salt_count_) && (table_size_ == f.table_size_) && (random_seed_ == f.random_seed_) ) { for (std::size_t i = 0; i < raw_table_size_; ++i) { bit_table_[i] |= f.bit_table_[i]; } } return *this; } inline bloom_filter& operator ^= (const bloom_filter& f) { /* difference */ if ( (salt_count_ == f.salt_count_) && (table_size_ == f.table_size_) && (random_seed_ == f.random_seed_) ) { for (std::size_t i = 0; i < raw_table_size_; ++i) { bit_table_[i] ^= f.bit_table_[i]; } } return *this; } inline const cell_type* table() const { return bit_table_; } inline std::size_t hash_count() { return salt_.size(); } protected: inline virtual void compute_indices(const bloom_type& hash, std::size_t& bit_index, std::size_t& bit) const { bit_index = hash % table_size_; bit = bit_index % bits_per_char; } void generate_unique_salt() { /* Note: A distinct hash function need not be implementation-wise distinct. In the current implementation "seeding" a common hash function with different values seems to be adequate. */ const unsigned int predef_salt_count = 128; static const bloom_type predef_salt[predef_salt_count] = { 0xAAAAAAAA, 0x55555555, 0x33333333, 0xCCCCCCCC, 0x66666666, 0x99999999, 0xB5B5B5B5, 0x4B4B4B4B, 0xAA55AA55, 0x55335533, 0x33CC33CC, 0xCC66CC66, 0x66996699, 0x99B599B5, 0xB54BB54B, 0x4BAA4BAA, 0xAA33AA33, 0x55CC55CC, 0x33663366, 0xCC99CC99, 0x66B566B5, 0x994B994B, 0xB5AAB5AA, 0xAAAAAA33, 0x555555CC, 0x33333366, 0xCCCCCC99, 0x666666B5, 0x9999994B, 0xB5B5B5AA, 0xFFFFFFFF, 0xFFFF0000, 0xB823D5EB, 0xC1191CDF, 0xF623AEB3, 0xDB58499F, 0xC8D42E70, 0xB173F616, 0xA91A5967, 0xDA427D63, 0xB1E8A2EA, 0xF6C0D155, 0x4909FEA3, 0xA68CC6A7, 0xC395E782, 0xA26057EB, 0x0CD5DA28, 0x467C5492, 0xF15E6982, 0x61C6FAD3, 0x9615E352, 0x6E9E355A, 0x689B563E, 0x0C9831A8, 0x6753C18B, 0xA622689B, 0x8CA63C47, 0x42CC2884, 0x8E89919B, 0x6EDBD7D3, 0x15B6796C, 0x1D6FDFE4, 0x63FF9092, 0xE7401432, 0xEFFE9412, 0xAEAEDF79, 0x9F245A31, 0x83C136FC, 0xC3DA4A8C, 0xA5112C8C, 0x5271F491, 0x9A948DAB, 0xCEE59A8D, 0xB5F525AB, 0x59D13217, 0x24E7C331, 0x697C2103, 0x84B0A460, 0x86156DA9, 0xAEF2AC68, 0x23243DA5, 0x3F649643, 0x5FA495A8, 0x67710DF8, 0x9A6C499E, 0xDCFB0227, 0x46A43433, 0x1832B07A, 0xC46AFF3C, 0xB9C8FFF0, 0xC9500467, 0x34431BDF, 0xB652432B, 0xE367F12B, 0x427F4C1B, 0x224C006E, 0x2E7E5A89, 0x96F99AA5, 0x0BEB452A, 0x2FD87C39, 0x74B2E1FB, 0x222EFD24, 0xF357F60C, 0x440FCB1E, 0x8BBE030F, 0x6704DC29, 0x1144D12F, 0x948B1355, 0x6D8FD7E9, 0x1C11A014, 0xADD1592F, 0xFB3C712E, 0xFC77642F, 0xF9C4CE8C, 0x31312FB9, 0x08B0DD79, 0x318FA6E7, 0xC040D23D, 0xC0589AA7, 0x0CA5C075, 0xF874B172, 0x0CF914D5, 0x784D3280, 0x4E8CFEBC, 0xC569F575, 0xCDB2A091, 0x2CC016B4, 0x5C5F4421 }; if (salt_count_ <= predef_salt_count) { std::copy(predef_salt, predef_salt + salt_count_, std::back_inserter(salt_)); for (unsigned int i = 0; i < salt_.size(); ++i) { /* Note: This is done to integrate the user defined random seed, so as to allow for the generation of unique bloom filter instances. */ salt_[i] = salt_[i] * salt_[(i + 3) % salt_.size()] + static_cast(random_seed_); } } else { std::copy(predef_salt,predef_salt + predef_salt_count,std::back_inserter(salt_)); srand(static_cast(random_seed_)); while (salt_.size() < salt_count_) { bloom_type current_salt = static_cast(rand()) * static_cast(rand()); if (0 == current_salt) continue; if (salt_.end() == std::find(salt_.begin(), salt_.end(), current_salt)) { salt_.push_back(current_salt); } } } } inline bloom_type hash_ap(const unsigned char* begin, std::size_t remaining_length, bloom_type hash) const { const unsigned char* itr = begin; unsigned int loop = 0; while (remaining_length >= 8) { const unsigned int& i1 = *(reinterpret_cast(itr)); itr += sizeof(unsigned int); const unsigned int& i2 = *(reinterpret_cast(itr)); itr += sizeof(unsigned int); hash ^= (hash << 7) ^ i1 * (hash >> 3) ^ (~((hash << 11) + (i2 ^ (hash >> 5)))); remaining_length -= 8; } if (remaining_length) { if (remaining_length >= 4) { const unsigned int& i = *(reinterpret_cast(itr)); if (loop & 0x01) hash ^= (hash << 7) ^ i * (hash >> 3); else hash ^= (~((hash << 11) + (i ^ (hash >> 5)))); ++loop; remaining_length -= 4; itr += sizeof(unsigned int); } if (remaining_length >= 2) { const unsigned short& i = *(reinterpret_cast(itr)); if (loop & 0x01) hash ^= (hash << 7) ^ i * (hash >> 3); else hash ^= (~((hash << 11) + (i ^ (hash >> 5)))); ++loop; remaining_length -= 2; itr += sizeof(unsigned short); } if (remaining_length) { hash += ((*itr) ^ (hash * 0xA5A5A5A5)) + loop; } } return hash; } std::vector salt_; unsigned char* bit_table_; unsigned int salt_count_; unsigned long long int table_size_; unsigned long long int raw_table_size_; unsigned long long int projected_element_count_; unsigned int inserted_element_count_; unsigned long long int random_seed_; double desired_false_positive_probability_; // Add by Li. variables for multi-threads. int numOfThreads ; pthread_mutex_t *locks ; std::size_t lockMask ; public: void SetNumOfThreads( int in ) { numOfThreads = in ; if ( in == 1 ) return ; std::size_t i, k ; for ( k = 1 ; k <= (std::size_t)in ; k *= 2 ) ; lockMask = k - 1 ; locks = ( pthread_mutex_t * )malloc( sizeof( pthread_mutex_t ) * k ) ; for ( i = 0 ; i < k ; ++i ) pthread_mutex_init( &locks[i], NULL ) ; } }; inline bloom_filter operator & (const bloom_filter& a, const bloom_filter& b) { bloom_filter result = a; result &= b; return result; } inline bloom_filter operator | (const bloom_filter& a, const bloom_filter& b) { bloom_filter result = a; result |= b; return result; } inline bloom_filter operator ^ (const bloom_filter& a, const bloom_filter& b) { bloom_filter result = a; result ^= b; return result; } class compressible_bloom_filter : public bloom_filter { public: compressible_bloom_filter(const bloom_parameters& p) : bloom_filter(p) { size_list.push_back(table_size_); } inline unsigned long long int size() const { return size_list.back(); } inline bool compress(const double& percentage) { if ((0.0 >= percentage) || (percentage >= 100.0)) { return false; } unsigned long long int original_table_size = size_list.back(); unsigned long long int new_table_size = static_cast((size_list.back() * (1.0 - (percentage / 100.0)))); new_table_size -= (((new_table_size % bits_per_char) != 0) ? (new_table_size % bits_per_char) : 0); if ((bits_per_char > new_table_size) || (new_table_size >= original_table_size)) { return false; } desired_false_positive_probability_ = effective_fpp(); cell_type* tmp = new cell_type[static_cast(new_table_size / bits_per_char)]; std::copy(bit_table_, bit_table_ + (new_table_size / bits_per_char), tmp); cell_type* itr = bit_table_ + (new_table_size / bits_per_char); cell_type* end = bit_table_ + (original_table_size / bits_per_char); cell_type* itr_tmp = tmp; while (end != itr) { *(itr_tmp++) |= (*itr++); } delete[] bit_table_; bit_table_ = tmp; size_list.push_back(new_table_size); return true; } private: inline void compute_indices(const bloom_type& hash, std::size_t& bit_index, std::size_t& bit) const { bit_index = hash; for (std::size_t i = 0; i < size_list.size(); ++i) { bit_index %= size_list[i]; } bit = bit_index % bits_per_char; } std::vector size_list; }; #endif /* Note 1: If it can be guaranteed that bits_per_char will be of the form 2^n then the following optimization can be used: hash_table[bit_index >> n] |= bit_mask[bit_index & (bits_per_char - 1)]; Note 2: For performance reasons where possible when allocating memory it should be aligned (aligned_alloc) according to the architecture being used. */ Lighter-1.1.2/utils.h000066400000000000000000000010211337104460000144120ustar00rootroot00000000000000#ifndef _MOURISL_CORRECTOR_UTIL_HEADER #define _MOURISL_CORRECTOR_UTIL_HEADER #include #define MAX_READ_LENGTH 1024 #define MAX_ID_LENGTH 512 // By changing this definition, the user can use longer kmer length. // Using longer kmer does NOT mean better accuracy!! #define MAX_KMER_LENGTH 32 #define READ_BUFFER_PER_THREAD 1024 /*char nucToNum[26] = { 0, -1, 1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1 } ; char numToNuc[26] = {'A', 'C', 'G', 'T'} ;*/ #endif