X-Git-Url: https://git.donarmstrong.com/?a=blobdiff_plain;f=makecontigscommand.cpp;h=691d706ab00efa8823412753b72f08e5198873b1;hb=96dbe925073caefaed6e6db85659c144a806aeb1;hp=431fc42ef9149658a42ebab3e99e52b21265e313;hpb=4c302368ef34f0d897afefc7853edf86fb45b9f3;p=mothur.git diff --git a/makecontigscommand.cpp b/makecontigscommand.cpp index 431fc42..691d706 100644 --- a/makecontigscommand.cpp +++ b/makecontigscommand.cpp @@ -13,11 +13,12 @@ vector MakeContigsCommand::setParameters(){ try { CommandParameter pfasta("ffastq", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pfasta); CommandParameter prfasta("rfastq", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(prfasta); - CommandParameter palign("align", "Multiple", "needleman-gotoh-blast-noalign", "needleman", "", "", "",false,false); parameters.push_back(palign); + CommandParameter palign("align", "Multiple", "needleman-gotoh", "needleman", "", "", "",false,false); parameters.push_back(palign); CommandParameter pmatch("match", "Number", "", "1.0", "", "", "",false,false); parameters.push_back(pmatch); CommandParameter pmismatch("mismatch", "Number", "", "-1.0", "", "", "",false,false); parameters.push_back(pmismatch); CommandParameter pgapopen("gapopen", "Number", "", "-2.0", "", "", "",false,false); parameters.push_back(pgapopen); CommandParameter pgapextend("gapextend", "Number", "", "-1.0", "", "", "",false,false); parameters.push_back(pgapextend); + CommandParameter pthreshold("threshold", "Number", "", "40", "", "", "",false,false); parameters.push_back(pthreshold); CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors); CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir); CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir); @@ -37,12 +38,13 @@ string MakeContigsCommand::getHelpString(){ string helpString = ""; helpString += "The make.contigs command reads a forward fastq file and a reverse fastq file and outputs new fasta and quality files.\n"; helpString += "The make.contigs command parameters are ffastq, rfastq, align, match, mismatch, gapopen, gapextend and processors.\n"; - helpString += "The ffastq and rfastq parameter is required.\n"; - helpString += "The align parameter allows you to specify the alignment method to use. Your options are: gotoh, needleman, blast and noalign. The default is needleman.\n"; + helpString += "The ffastq and rfastq parameters are required.\n"; + helpString += "The align parameter allows you to specify the alignment method to use. Your options are: gotoh and needleman. The default is needleman.\n"; helpString += "The match parameter allows you to specify the bonus for having the same base. The default is 1.0.\n"; helpString += "The mistmatch parameter allows you to specify the penalty for having different bases. The default is -1.0.\n"; helpString += "The gapopen parameter allows you to specify the penalty for opening a gap in an alignment. The default is -2.0.\n"; helpString += "The gapextend parameter allows you to specify the penalty for extending a gap in an alignment. The default is -1.0.\n"; + helpString += "The threshold parameter allows you to set a quality scores threshold. In the case where we are trying to decide whether to keep a base or remove it because the base is compared to a gap in the other fragment, if the base has a quality score below the threshold we eliminate it. Default=40.\n"; helpString += "The processors parameter allows you to specify how many processors you would like to use. The default is 1. \n"; helpString += "The make.contigs command should be in the following format: \n"; helpString += "make.contigs(ffastq=yourForwardFastqFile, rfastq=yourReverseFastqFile, align=yourAlignmentMethod) \n"; @@ -54,7 +56,28 @@ string MakeContigsCommand::getHelpString(){ exit(1); } } - +//********************************************************************************************************************** +string MakeContigsCommand::getOutputFileNameTag(string type, string inputName=""){ + try { + string outputFileName = ""; + map >::iterator it; + + //is this a type this command creates + it = outputTypes.find(type); + if (it == outputTypes.end()) { m->mothurOut("[ERROR]: this command doesn't create a " + type + " output file.\n"); } + else { + if (type == "fasta") { outputFileName = "contigs.fasta"; } + else if (type == "qfile") { outputFileName = "contigs.qual"; } + else if (type == "mismatch") { outputFileName = "contigs.mismatch"; } + else { m->mothurOut("[ERROR]: No definition for type " + type + " output file tag.\n"); m->control_pressed = true; } + } + return outputFileName; + } + catch(exception& e) { + m->errorOut(e, "MakeContigsCommand", "getOutputFileNameTag"); + exit(1); + } +} //********************************************************************************************************************** MakeContigsCommand::MakeContigsCommand(){ try { @@ -63,6 +86,7 @@ MakeContigsCommand::MakeContigsCommand(){ vector tempOutNames; outputTypes["fasta"] = tempOutNames; outputTypes["qfile"] = tempOutNames; + outputTypes["mismatch"] = tempOutNames; } catch(exception& e) { m->errorOut(e, "MakeContigsCommand", "MakeContigsCommand"); @@ -96,6 +120,7 @@ MakeContigsCommand::MakeContigsCommand(string option) { vector tempOutNames; outputTypes["fasta"] = tempOutNames; outputTypes["qfile"] = tempOutNames; + outputTypes["mismatch"] = tempOutNames; //if the user changes the input directory command factory will send this info to us in the output parameter @@ -150,12 +175,16 @@ MakeContigsCommand::MakeContigsCommand(string option) { m->mothurConvert(temp, gapExtend); if (gapExtend > 0) { m->mothurOut("[ERROR]: gapextend must be negative.\n"); abort=true; } + temp = validParameter.validFile(parameters, "threshold", false); if (temp == "not found"){ temp = "40"; } + m->mothurConvert(temp, threshold); + if ((threshold < 0) || (threshold > 40)) { m->mothurOut("[ERROR]: threshold must be between 0 and 40.\n"); abort=true; } + temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); } m->setProcessors(temp); m->mothurConvert(temp, processors); align = validParameter.validFile(parameters, "align", false); if (align == "not found"){ align = "needleman"; } - if ((align != "needleman") && (align != "blast") && (align != "gotoh") && (align != "noalign")) { m->mothurOut(align + " is not a valid alignment method. Options are needleman, blast, gotoh and noalign. I will use needleman."); m->mothurOutEndLine(); align = "needleman"; } + if ((align != "needleman") && (align != "gotoh")) { m->mothurOut(align + " is not a valid alignment method. Options are needleman or gotoh. I will use needleman."); m->mothurOutEndLine(); align = "needleman"; } } } @@ -172,9 +201,32 @@ int MakeContigsCommand::execute(){ //read ffastq and rfastq files creating fasta and qual files. //this function will create a forward and reverse, fasta and qual files for each processor. //files has an entry for each processor. files[i][0] = forwardFasta, files[i][1] = forwardQual, files[i][2] = reverseFasta, files[i][3] = reverseQual - vector< vector > files = readFastqFiles(); + int numReads = 0; + int start = time(NULL); + longestBase = 1000; + m->mothurOut("Reading fastq data...\n"); + vector< vector > files = readFastqFiles(numReads); + m->mothurOut("Done.\n"); + + if (m->control_pressed) { return 0; } + string outFastaFile = outputDir + m->getRootName(m->getSimpleName(ffastqfile)) + getOutputFileNameTag("fasta"); + string outQualFile = outputDir + m->getRootName(m->getSimpleName(ffastqfile)) + getOutputFileNameTag("qfile"); + string outMisMatchFile = outputDir + m->getRootName(m->getSimpleName(ffastqfile)) + getOutputFileNameTag("mismatch"); + outputNames.push_back(outFastaFile); outputTypes["fasta"].push_back(outFastaFile); + outputNames.push_back(outQualFile); outputTypes["qfile"].push_back(outQualFile); + outputNames.push_back(outMisMatchFile); outputTypes["mismatch"].push_back(outMisMatchFile); + m->mothurOut("Making contigs...\n"); + createProcesses(files, outFastaFile, outQualFile, outMisMatchFile); + m->mothurOut("Done.\n"); + + //remove temp fasta and qual files + for (int i = 0; i < processors; i++) { for(int j = 0; j < files[i].size(); j++) { m->mothurRemove(files[i][j]); } } + + if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } return 0; } + + m->mothurOut("It took " + toString(time(NULL) - start) + " secs to process " + toString(numReads) + " sequences.\n"); string currentFasta = ""; itTypes = outputTypes.find("fasta"); @@ -203,7 +255,266 @@ int MakeContigsCommand::execute(){ } } //********************************************************************************************************************** -vector< vector > MakeContigsCommand::readFastqFiles(){ +int MakeContigsCommand::createProcesses(vector< vector > files, string outputFasta, string outputQual, string outputMisMatches) { + try { + int num = 0; + vector processIDS; +#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix) + int process = 0; + + //loop through and create all the processes you want + while (process != processors-1) { + int pid = fork(); + + if (pid > 0) { + processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later + process++; + }else if (pid == 0){ + num = driver(files[process], outputFasta + toString(getpid()) + ".temp", outputQual + toString(getpid()) + ".temp", outputMisMatches + toString(getpid()) + ".temp"); + + //pass numSeqs to parent + ofstream out; + string tempFile = outputFasta + toString(getpid()) + ".num.temp"; + m->openOutputFile(tempFile, out); + out << num << endl; + out.close(); + + exit(0); + }else { + m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); + for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); } + exit(0); + } + } + + //do my part + num = driver(files[processors-1], outputFasta, outputQual, outputMisMatches); + + //force parent to wait until all the processes are done + for (int i=0;iopenInputFile(tempFile, in); + if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; } + in.close(); m->mothurRemove(tempFile); + } + #else + + ////////////////////////////////////////////////////////////////////////////////////////////////////// + //Windows version shared memory, so be careful when passing variables through the contigsData struct. + //Above fork() will clone, so memory is separate, but that's not the case with windows, + ////////////////////////////////////////////////////////////////////////////////////////////////////// + + vector pDataArray; + DWORD dwThreadIdArray[processors-1]; + HANDLE hThreadArray[processors-1]; + + //Create processor worker threads. + for( int i=0; icount; + CloseHandle(hThreadArray[i]); + delete pDataArray[i]; + } + + #endif + + for (int i = 0; i < processIDS.size(); i++) { + m->appendFiles((outputFasta + toString(processIDS[i]) + ".temp"), outputFasta); + m->mothurRemove((outputFasta + toString(processIDS[i]) + ".temp")); + + m->appendFiles((outputQual + toString(processIDS[i]) + ".temp"), outputQual); + m->mothurRemove((outputQual + toString(processIDS[i]) + ".temp")); + + m->appendFiles((outputMisMatches + toString(processIDS[i]) + ".temp"), outputMisMatches); + m->mothurRemove((outputMisMatches + toString(processIDS[i]) + ".temp")); + } + + return num; + } + catch(exception& e) { + m->errorOut(e, "MakeContigsCommand", "createProcesses"); + exit(1); + } +} +//********************************************************************************************************************** +int MakeContigsCommand::driver(vector files, string outputFasta, string outputQual, string outputMisMatches){ + try { + + Alignment* alignment; + if(align == "gotoh") { alignment = new GotohOverlap(gapOpen, gapExtend, match, misMatch, longestBase); } + else if(align == "needleman") { alignment = new NeedlemanOverlap(gapOpen, match, misMatch, longestBase); } + + int num = 0; + string thisffastafile = files[0]; + string thisfqualfile = files[1]; + string thisrfastafile = files[2]; + string thisrqualfile = files[3]; + + if (m->debug) { m->mothurOut("[DEBUG]: ffasta = " + thisffastafile + ".\n[DEBUG]: fqual = " + thisfqualfile + ".\n[DEBUG]: rfasta = " + thisrfastafile + ".\n[DEBUG]: rqual = " + thisrqualfile + ".\n"); } + + ifstream inFFasta, inRFasta, inFQual, inRQual; + m->openInputFile(thisffastafile, inFFasta); + m->openInputFile(thisfqualfile, inFQual); + m->openInputFile(thisrfastafile, inRFasta); + m->openInputFile(thisrqualfile, inRQual); + + ofstream outFasta, outQual, outMisMatch; + m->openOutputFile(outputFasta, outFasta); + m->openOutputFile(outputQual, outQual); + m->openOutputFile(outputMisMatches, outMisMatch); + outMisMatch << "Name\tLength\tMisMatches\n"; + + while ((!inFQual.eof()) && (!inFFasta.eof()) && (!inRFasta.eof()) && (!inRQual.eof())) { + + if (m->control_pressed) { break; } + + //read seqs and quality info + Sequence fSeq(inFFasta); m->gobble(inFFasta); + Sequence rSeq(inRFasta); m->gobble(inRFasta); + QualityScores fQual(inFQual); m->gobble(inFQual); + QualityScores rQual(inRQual); m->gobble(inRQual); + + //flip the reverse reads + rSeq.reverseComplement(); + rQual.flipQScores(); + + //pairwise align + alignment->align(fSeq.getUnaligned(), rSeq.getUnaligned()); + map ABaseMap = alignment->getSeqAAlnBaseMap(); + map BBaseMap = alignment->getSeqBAlnBaseMap(); + fSeq.setAligned(alignment->getSeqAAln()); + rSeq.setAligned(alignment->getSeqBAln()); + int length = fSeq.getAligned().length(); + + //traverse alignments merging into one contiguous seq + string contig = ""; + vector contigScores; + int numMismatches = 0; + string seq1 = fSeq.getAligned(); + string seq2 = rSeq.getAligned(); + vector scores1 = fQual.getQualityScores(); + vector scores2 = rQual.getQualityScores(); + + // if (num < 5) { cout << fSeq.getStartPos() << '\t' << fSeq.getEndPos() << '\t' << rSeq.getStartPos() << '\t' << rSeq.getEndPos() << endl; } + int overlapStart = fSeq.getStartPos(); + int seq2Start = rSeq.getStartPos(); + //bigger of the 2 starting positions is the location of the overlapping start + if (overlapStart < seq2Start) { //seq2 starts later so take from 0 to seq2Start from seq1 + overlapStart = seq2Start; + for (int i = 0; i < overlapStart; i++) { + contig += seq1[i]; + contigScores.push_back(scores1[ABaseMap[i]]); + } + }else { //seq1 starts later so take from 0 to overlapStart from seq2 + for (int i = 0; i < overlapStart; i++) { + contig += seq2[i]; + contigScores.push_back(scores2[BBaseMap[i]]); + } + } + + int seq1End = fSeq.getEndPos(); + int seq2End = rSeq.getEndPos(); + int overlapEnd = seq1End; + if (seq2End < overlapEnd) { overlapEnd = seq2End; } //smallest end position is where overlapping ends + + for (int i = overlapStart; i < overlapEnd; i++) { + if (seq1[i] == seq2[i]) { //match, add base and choose highest score + contig += seq1[i]; + contigScores.push_back(scores1[ABaseMap[i]]); + if (scores1[ABaseMap[i]] < scores2[BBaseMap[i]]) { contigScores[contigScores.size()-1] = scores2[BBaseMap[i]]; } + }else if (((seq1[i] == '.') || (seq1[i] == '-')) && ((seq2[i] != '-') && (seq2[i] != '.'))) { //seq1 is a gap and seq2 is a base, choose seq2, unless quality score for base is below threshold. In that case eliminate base + if (scores2[BBaseMap[i]] < threshold) { } // + else { + contig += seq2[i]; + contigScores.push_back(scores2[BBaseMap[i]]); + } + }else if (((seq2[i] == '.') || (seq2[i] == '-')) && ((seq1[i] != '-') && (seq1[i] != '.'))) { //seq2 is a gap and seq1 is a base, choose seq1, unless quality score for base is below threshold. In that case eliminate base + if (scores1[ABaseMap[i]] < threshold) { } // + else { + contig += seq1[i]; + contigScores.push_back(scores1[ABaseMap[i]]); + } + }else if (((seq1[i] != '-') && (seq1[i] != '.')) && ((seq2[i] != '-') && (seq2[i] != '.'))) { //both bases choose one with better quality + char c = seq1[i]; + contigScores.push_back(scores1[ABaseMap[i]]); + if (scores1[ABaseMap[i]] < scores2[BBaseMap[i]]) { contigScores[contigScores.size()-1] = scores2[BBaseMap[i]]; c = seq2[i]; } + contig += c; + numMismatches++; + }else { //should never get here + m->mothurOut("[ERROR]: case I didn't think of seq1 = " + toString(seq1[i]) + " and seq2 = " + toString(seq2[i]) + "\n"); + } + } + + if (seq1End < seq2End) { //seq1 ends before seq2 so take from overlap to length from seq2 + for (int i = overlapEnd; i < length; i++) { + contig += seq2[i]; + contigScores.push_back(scores2[BBaseMap[i]]); + } + }else { //seq2 ends before seq1 so take from overlap to length from seq1 + for (int i = overlapEnd; i < length; i++) { + contig += seq1[i]; + contigScores.push_back(scores1[ABaseMap[i]]); + } + + } + //if (num < 5) { cout << overlapStart << '\t' << overlapEnd << endl << seq1 << endl << seq2 << endl<< contig << endl; } + //output + outFasta << ">" << fSeq.getName() << endl << contig << endl; + outQual << ">" << fSeq.getName() << endl; + for (int i = 0; i < contigScores.size(); i++) { outQual << contigScores[i] << ' '; } + outQual << endl; + outMisMatch << fSeq.getName() << '\t' << contig.length() << '\t' << numMismatches << endl; + + num++; + + //report progress + if((num) % 1000 == 0){ m->mothurOut(toString(num)); m->mothurOutEndLine(); } + } + + //report progress + if((num) % 1000 != 0){ m->mothurOut(toString(num)); m->mothurOutEndLine(); } + + inFFasta.close(); + inFQual.close(); + inRFasta.close(); + inRQual.close(); + outFasta.close(); + outQual.close(); + outMisMatch.close(); + delete alignment; + + if (m->control_pressed) { m->mothurRemove(outputQual); m->mothurRemove(outputFasta); m->mothurRemove(outputMisMatches);} + + return num; + } + catch(exception& e) { + m->errorOut(e, "MakeContigsCommand", "driver"); + exit(1); + } +} +//********************************************************************************************************************** +vector< vector > MakeContigsCommand::readFastqFiles(int& count){ try { vector< vector > files; @@ -250,7 +561,7 @@ vector< vector > MakeContigsCommand::readFastqFiles(){ ifstream inReverse; m->openInputFile(rfastqfile, inReverse); - int count = 0; + count = 0; while ((!inForward.eof()) && (!inReverse.eof())) { if (m->control_pressed) { for (it = tempfiles.begin(); it!=tempfiles.end(); it++) { for (int i = 0; i < (it->second).size(); i++) { (*(it->second)[i]).close(); delete (it->second)[i]; } } for (int i = 0; i < files.size(); i++) { for(int j = 0; j < files[i].size(); j++) { m->mothurRemove(files[i][j]); } } inForward.close(); inReverse.close(); return files; } @@ -275,7 +586,15 @@ vector< vector > MakeContigsCommand::readFastqFiles(){ *(tempfiles[process][3]) << endl; count++; - } + + //report progress + if((count) % 10000 == 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); } + + } + //report progress + if((count) % 10000 != 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); } + + //close files, delete ofstreams for (it = tempfiles.begin(); it!=tempfiles.end(); it++) { for (int i = 0; i < (it->second).size(); i++) { (*(it->second)[i]).close(); delete (it->second)[i]; } } @@ -296,7 +615,6 @@ vector< vector > MakeContigsCommand::readFastqFiles(){ exit(1); } } - //********************************************************************************************************************** fastqRead MakeContigsCommand::readFastq(ifstream& in){ try {