2 // makecontigscommand.cpp
5 // Created by Sarah Westcott on 5/15/12.
6 // Copyright (c) 2012 Schloss Lab. All rights reserved.
9 #include "makecontigscommand.h"
11 //**********************************************************************************************************************
12 vector<string> MakeContigsCommand::setParameters(){
14 CommandParameter pfasta("ffastq", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pfasta);
15 CommandParameter prfasta("rfastq", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(prfasta);
16 CommandParameter poligos("oligos", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(poligos);
17 CommandParameter ppdiffs("pdiffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(ppdiffs);
18 CommandParameter pbdiffs("bdiffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(pbdiffs);
19 CommandParameter pldiffs("ldiffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(pldiffs);
20 CommandParameter psdiffs("sdiffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(psdiffs);
21 CommandParameter ptdiffs("tdiffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(ptdiffs);
23 CommandParameter palign("align", "Multiple", "needleman-gotoh", "needleman", "", "", "",false,false); parameters.push_back(palign);
24 CommandParameter pallfiles("allfiles", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(pallfiles);
25 CommandParameter pmatch("match", "Number", "", "1.0", "", "", "",false,false); parameters.push_back(pmatch);
26 CommandParameter pmismatch("mismatch", "Number", "", "-1.0", "", "", "",false,false); parameters.push_back(pmismatch);
27 CommandParameter pgapopen("gapopen", "Number", "", "-2.0", "", "", "",false,false); parameters.push_back(pgapopen);
28 CommandParameter pgapextend("gapextend", "Number", "", "-1.0", "", "", "",false,false); parameters.push_back(pgapextend);
29 CommandParameter pthreshold("threshold", "Number", "", "40", "", "", "",false,false); parameters.push_back(pthreshold);
30 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
31 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
32 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
34 vector<string> myArray;
35 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
39 m->errorOut(e, "MakeContigsCommand", "setParameters");
43 //**********************************************************************************************************************
44 string MakeContigsCommand::getHelpString(){
46 string helpString = "";
47 helpString += "The make.contigs command reads a forward fastq file and a reverse fastq file and outputs new fasta and quality files.\n";
48 helpString += "If an oligos file is provided barcodes and primers will be trimmed, and a group file will be created.\n";
49 helpString += "The make.contigs command parameters are ffastq, rfastq, oligos, tdiffs, bdiffs, ldiffs, sdiffs, pdiffs, align, match, mismatch, gapopen, gapextend, allfiles and processors.\n";
50 helpString += "The ffastq and rfastq parameters are required.\n";
51 helpString += "The align parameter allows you to specify the alignment method to use. Your options are: gotoh and needleman. The default is needleman.\n";
52 helpString += "The tdiffs parameter is used to specify the total number of differences allowed in the sequence. The default is pdiffs + bdiffs + sdiffs + ldiffs.\n";
53 helpString += "The bdiffs parameter is used to specify the number of differences allowed in the barcode. The default is 0.\n";
54 helpString += "The pdiffs parameter is used to specify the number of differences allowed in the primer. The default is 0.\n";
55 helpString += "The ldiffs parameter is used to specify the number of differences allowed in the linker. The default is 0.\n";
56 helpString += "The sdiffs parameter is used to specify the number of differences allowed in the spacer. The default is 0.\n";
57 helpString += "The match parameter allows you to specify the bonus for having the same base. The default is 1.0.\n";
58 helpString += "The mistmatch parameter allows you to specify the penalty for having different bases. The default is -1.0.\n";
59 helpString += "The gapopen parameter allows you to specify the penalty for opening a gap in an alignment. The default is -2.0.\n";
60 helpString += "The gapextend parameter allows you to specify the penalty for extending a gap in an alignment. The default is -1.0.\n";
61 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";
62 helpString += "The processors parameter allows you to specify how many processors you would like to use. The default is 1. \n";
63 helpString += "The allfiles parameter will create separate group and fasta file for each grouping. The default is F.\n";
64 helpString += "The make.contigs command should be in the following format: \n";
65 helpString += "make.contigs(ffastq=yourForwardFastqFile, rfastq=yourReverseFastqFile, align=yourAlignmentMethod) \n";
66 helpString += "Note: No spaces between parameter labels (i.e. ffastq), '=' and parameters (i.e.yourForwardFastqFile).\n";
70 m->errorOut(e, "MakeContigsCommand", "getHelpString");
74 //**********************************************************************************************************************
75 string MakeContigsCommand::getOutputFileNameTag(string type, string inputName=""){
77 string outputFileName = "";
78 map<string, vector<string> >::iterator it;
80 //is this a type this command creates
81 it = outputTypes.find(type);
82 if (it == outputTypes.end()) { m->mothurOut("[ERROR]: this command doesn't create a " + type + " output file.\n"); }
84 if (type == "fasta") { outputFileName = "contigs.fasta"; }
85 else if (type == "qfile") { outputFileName = "contigs.qual"; }
86 else if (type == "group") { outputFileName = "groups"; }
87 else if (type == "mismatch") { outputFileName = "contigs.mismatch"; }
88 else { m->mothurOut("[ERROR]: No definition for type " + type + " output file tag.\n"); m->control_pressed = true; }
90 return outputFileName;
93 m->errorOut(e, "MakeContigsCommand", "getOutputFileNameTag");
97 //**********************************************************************************************************************
98 MakeContigsCommand::MakeContigsCommand(){
100 abort = true; calledHelp = true;
102 vector<string> tempOutNames;
103 outputTypes["fasta"] = tempOutNames;
104 outputTypes["qfile"] = tempOutNames;
105 outputTypes["group"] = tempOutNames;
106 outputTypes["mismatch"] = tempOutNames;
108 catch(exception& e) {
109 m->errorOut(e, "MakeContigsCommand", "MakeContigsCommand");
113 //**********************************************************************************************************************
114 MakeContigsCommand::MakeContigsCommand(string option) {
116 abort = false; calledHelp = false;
118 //allow user to run help
119 if(option == "help") { help(); abort = true; calledHelp = true; }
120 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
123 vector<string> myArray = setParameters();
125 OptionParser parser(option);
126 map<string, string> parameters = parser.getParameters();
128 ValidParameters validParameter("pairwise.seqs");
129 map<string, string>::iterator it;
131 //check to make sure all parameters are valid for command
132 for (it = parameters.begin(); it != parameters.end(); it++) {
133 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
136 //initialize outputTypes
137 vector<string> tempOutNames;
138 outputTypes["fasta"] = tempOutNames;
139 outputTypes["qfile"] = tempOutNames;
140 outputTypes["mismatch"] = tempOutNames;
141 outputTypes["group"] = tempOutNames;
144 //if the user changes the input directory command factory will send this info to us in the output parameter
145 string inputDir = validParameter.validFile(parameters, "inputdir", false);
146 if (inputDir == "not found"){ inputDir = ""; }
149 it = parameters.find("ffastq");
150 //user has given a template file
151 if(it != parameters.end()){
152 path = m->hasPath(it->second);
153 //if the user has not given a path then, add inputdir. else leave path alone.
154 if (path == "") { parameters["ffastq"] = inputDir + it->second; }
157 it = parameters.find("rfastq");
158 //user has given a template file
159 if(it != parameters.end()){
160 path = m->hasPath(it->second);
161 //if the user has not given a path then, add inputdir. else leave path alone.
162 if (path == "") { parameters["rfastq"] = inputDir + it->second; }
165 it = parameters.find("oligos");
166 //user has given a template file
167 if(it != parameters.end()){
168 path = m->hasPath(it->second);
169 //if the user has not given a path then, add inputdir. else leave path alone.
170 if (path == "") { parameters["oligos"] = inputDir + it->second; }
174 ffastqfile = validParameter.validFile(parameters, "ffastq", true);
175 if (ffastqfile == "not open") { ffastqfile = ""; abort = true; }
176 else if (ffastqfile == "not found") { ffastqfile = ""; abort=true; m->mothurOut("The ffastq parameter is required.\n"); }
178 rfastqfile = validParameter.validFile(parameters, "rfastq", true);
179 if (rfastqfile == "not open") { rfastqfile = ""; abort = true; }
180 else if (rfastqfile == "not found") { rfastqfile = ""; abort=true; m->mothurOut("The rfastq parameter is required.\n"); }
182 oligosfile = validParameter.validFile(parameters, "oligos", true);
183 if (oligosfile == "not found") { oligosfile = ""; }
184 else if(oligosfile == "not open") { abort = true; }
185 else { m->setOligosFile(oligosfile); }
187 //if the user changes the output directory command factory will send this info to us in the output parameter
188 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = m->hasPath(ffastqfile); }
191 //check for optional parameter and set defaults
192 // ...at some point should added some additional type checking...
194 temp = validParameter.validFile(parameters, "match", false); if (temp == "not found"){ temp = "1.0"; }
195 m->mothurConvert(temp, match);
197 temp = validParameter.validFile(parameters, "mismatch", false); if (temp == "not found"){ temp = "-1.0"; }
198 m->mothurConvert(temp, misMatch);
199 if (misMatch > 0) { m->mothurOut("[ERROR]: mismatch must be negative.\n"); abort=true; }
201 temp = validParameter.validFile(parameters, "gapopen", false); if (temp == "not found"){ temp = "-2.0"; }
202 m->mothurConvert(temp, gapOpen);
203 if (gapOpen > 0) { m->mothurOut("[ERROR]: gapopen must be negative.\n"); abort=true; }
205 temp = validParameter.validFile(parameters, "gapextend", false); if (temp == "not found"){ temp = "-1.0"; }
206 m->mothurConvert(temp, gapExtend);
207 if (gapExtend > 0) { m->mothurOut("[ERROR]: gapextend must be negative.\n"); abort=true; }
209 temp = validParameter.validFile(parameters, "threshold", false); if (temp == "not found"){ temp = "40"; }
210 m->mothurConvert(temp, threshold);
211 if ((threshold < 0) || (threshold > 40)) { m->mothurOut("[ERROR]: threshold must be between 0 and 40.\n"); abort=true; }
213 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
214 m->setProcessors(temp);
215 m->mothurConvert(temp, processors);
217 temp = validParameter.validFile(parameters, "bdiffs", false); if (temp == "not found") { temp = "0"; }
218 m->mothurConvert(temp, bdiffs);
220 temp = validParameter.validFile(parameters, "pdiffs", false); if (temp == "not found") { temp = "0"; }
221 m->mothurConvert(temp, pdiffs);
223 temp = validParameter.validFile(parameters, "ldiffs", false); if (temp == "not found") { temp = "0"; }
224 m->mothurConvert(temp, ldiffs);
226 temp = validParameter.validFile(parameters, "sdiffs", false); if (temp == "not found") { temp = "0"; }
227 m->mothurConvert(temp, sdiffs);
229 temp = validParameter.validFile(parameters, "tdiffs", false); if (temp == "not found") { int tempTotal = pdiffs + bdiffs + ldiffs + sdiffs; temp = toString(tempTotal); }
230 m->mothurConvert(temp, tdiffs);
232 if(tdiffs == 0){ tdiffs = bdiffs + pdiffs + ldiffs + sdiffs; }
234 temp = validParameter.validFile(parameters, "allfiles", false); if (temp == "not found") { temp = "F"; }
235 allFiles = m->isTrue(temp);
237 align = validParameter.validFile(parameters, "align", false); if (align == "not found"){ align = "needleman"; }
238 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"; }
242 catch(exception& e) {
243 m->errorOut(e, "MakeContigsCommand", "MakeContigsCommand");
247 //**********************************************************************************************************************
248 int MakeContigsCommand::execute(){
250 if (abort == true) { if (calledHelp) { return 0; } return 2; }
252 //read ffastq and rfastq files creating fasta and qual files.
253 //this function will create a forward and reverse, fasta and qual files for each processor.
254 //files has an entry for each processor. files[i][0] = forwardFasta, files[i][1] = forwardQual, files[i][2] = reverseFasta, files[i][3] = reverseQual
256 int start = time(NULL);
258 m->mothurOut("Reading fastq data...\n");
259 vector< vector<string> > files = readFastqFiles(numReads);
260 m->mothurOut("Done.\n");
262 if (m->control_pressed) { return 0; }
264 string outFastaFile = outputDir + m->getRootName(m->getSimpleName(ffastqfile)) + getOutputFileNameTag("fasta");
265 string outQualFile = outputDir + m->getRootName(m->getSimpleName(ffastqfile)) + getOutputFileNameTag("qfile");
266 string outMisMatchFile = outputDir + m->getRootName(m->getSimpleName(ffastqfile)) + getOutputFileNameTag("mismatch");
267 outputNames.push_back(outFastaFile); outputTypes["fasta"].push_back(outFastaFile);
268 outputNames.push_back(outQualFile); outputTypes["qfile"].push_back(outQualFile);
269 outputNames.push_back(outMisMatchFile); outputTypes["mismatch"].push_back(outMisMatchFile);
271 m->mothurOut("Making contigs...\n");
272 createProcesses(files, outFastaFile, outQualFile, outMisMatchFile);
273 m->mothurOut("Done.\n");
275 //remove temp fasta and qual files
276 for (int i = 0; i < processors; i++) { for(int j = 0; j < files[i].size(); j++) { m->mothurRemove(files[i][j]); } }
278 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } return 0; }
280 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to process " + toString(numReads) + " sequences.\n");
282 string currentFasta = "";
283 itTypes = outputTypes.find("fasta");
284 if (itTypes != outputTypes.end()) {
285 if ((itTypes->second).size() != 0) { currentFasta = (itTypes->second)[0]; m->setFastaFile(currentFasta); }
288 string currentQual = "";
289 itTypes = outputTypes.find("qfile");
290 if (itTypes != outputTypes.end()) {
291 if ((itTypes->second).size() != 0) { currentQual = (itTypes->second)[0]; m->setQualFile(currentQual); }
294 string currentGroup = "";
295 itTypes = outputTypes.find("group");
296 if (itTypes != outputTypes.end()) {
297 if ((itTypes->second).size() != 0) { currentGroup = (itTypes->second)[0]; m->setGroupFile(currentGroup); }
300 //output files created by command
301 m->mothurOutEndLine();
302 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
303 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
304 m->mothurOutEndLine();
308 catch(exception& e) {
309 m->errorOut(e, "MakeContigsCommand", "execute");
313 //**********************************************************************************************************************
314 int MakeContigsCommand::createProcesses(vector< vector<string> > files, string outputFasta, string outputQual, string outputMisMatches) {
317 vector<int> processIDS;
318 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
321 //loop through and create all the processes you want
322 while (process != processors-1) {
326 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
329 num = driver(files[process], outputFasta + toString(getpid()) + ".temp", outputQual + toString(getpid()) + ".temp", outputMisMatches + toString(getpid()) + ".temp");
331 //pass numSeqs to parent
333 string tempFile = outputFasta + toString(getpid()) + ".num.temp";
334 m->openOutputFile(tempFile, out);
340 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
341 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
347 num = driver(files[processors-1], outputFasta, outputQual, outputMisMatches);
349 //force parent to wait until all the processes are done
350 for (int i=0;i<processIDS.size();i++) {
351 int temp = processIDS[i];
355 for (int i = 0; i < processIDS.size(); i++) {
357 string tempFile = outputFasta + toString(processIDS[i]) + ".num.temp";
358 m->openInputFile(tempFile, in);
359 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
360 in.close(); m->mothurRemove(tempFile);
364 //////////////////////////////////////////////////////////////////////////////////////////////////////
365 //Windows version shared memory, so be careful when passing variables through the contigsData struct.
366 //Above fork() will clone, so memory is separate, but that's not the case with windows,
367 //////////////////////////////////////////////////////////////////////////////////////////////////////
369 vector<contigsData*> pDataArray;
370 DWORD dwThreadIdArray[processors-1];
371 HANDLE hThreadArray[processors-1];
373 //Create processor worker threads.
374 for( int i=0; i<processors-1; i++ ){
375 string extension = toString(i) + ".temp";
377 contigsData* tempcontig = new contigsData(files[i], (outputFasta + extension), (outputQual + extension), (outputMisMatches + extension), align, m, match, misMatch, gapOpen, gapExtend, threshold, i);
378 pDataArray.push_back(tempcontig);
379 processIDS.push_back(i);
381 hThreadArray[i] = CreateThread(NULL, 0, MyContigsThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);
384 num = driver(files[processors-1], outputFasta, outputQual, outputMisMatches);
386 //Wait until all threads have terminated.
387 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
389 //Close all thread handles and free memory allocations.
390 for(int i=0; i < pDataArray.size(); i++){
391 num += pDataArray[i]->count;
392 CloseHandle(hThreadArray[i]);
393 delete pDataArray[i];
398 for (int i = 0; i < processIDS.size(); i++) {
399 m->appendFiles((outputFasta + toString(processIDS[i]) + ".temp"), outputFasta);
400 m->mothurRemove((outputFasta + toString(processIDS[i]) + ".temp"));
402 m->appendFiles((outputQual + toString(processIDS[i]) + ".temp"), outputQual);
403 m->mothurRemove((outputQual + toString(processIDS[i]) + ".temp"));
405 m->appendFiles((outputMisMatches + toString(processIDS[i]) + ".temp"), outputMisMatches);
406 m->mothurRemove((outputMisMatches + toString(processIDS[i]) + ".temp"));
411 catch(exception& e) {
412 m->errorOut(e, "MakeContigsCommand", "createProcesses");
416 //**********************************************************************************************************************
417 int MakeContigsCommand::driver(vector<string> files, string outputFasta, string outputQual, string outputMisMatches){
420 Alignment* alignment;
421 if(align == "gotoh") { alignment = new GotohOverlap(gapOpen, gapExtend, match, misMatch, longestBase); }
422 else if(align == "needleman") { alignment = new NeedlemanOverlap(gapOpen, match, misMatch, longestBase); }
425 string thisffastafile = files[0];
426 string thisfqualfile = files[1];
427 string thisrfastafile = files[2];
428 string thisrqualfile = files[3];
430 if (m->debug) { m->mothurOut("[DEBUG]: ffasta = " + thisffastafile + ".\n[DEBUG]: fqual = " + thisfqualfile + ".\n[DEBUG]: rfasta = " + thisrfastafile + ".\n[DEBUG]: rqual = " + thisrqualfile + ".\n"); }
432 ifstream inFFasta, inRFasta, inFQual, inRQual;
433 m->openInputFile(thisffastafile, inFFasta);
434 m->openInputFile(thisfqualfile, inFQual);
435 m->openInputFile(thisrfastafile, inRFasta);
436 m->openInputFile(thisrqualfile, inRQual);
438 ofstream outFasta, outQual, outMisMatch;
439 m->openOutputFile(outputFasta, outFasta);
440 m->openOutputFile(outputQual, outQual);
441 m->openOutputFile(outputMisMatches, outMisMatch);
442 outMisMatch << "Name\tLength\tMisMatches\n";
444 while ((!inFQual.eof()) && (!inFFasta.eof()) && (!inRFasta.eof()) && (!inRQual.eof())) {
446 if (m->control_pressed) { break; }
448 //read seqs and quality info
449 Sequence fSeq(inFFasta); m->gobble(inFFasta);
450 Sequence rSeq(inRFasta); m->gobble(inRFasta);
451 QualityScores fQual(inFQual); m->gobble(inFQual);
452 QualityScores rQual(inRQual); m->gobble(inRQual);
454 //flip the reverse reads
455 rSeq.reverseComplement();
459 alignment->align(fSeq.getUnaligned(), rSeq.getUnaligned());
460 map<int, int> ABaseMap = alignment->getSeqAAlnBaseMap();
461 map<int, int> BBaseMap = alignment->getSeqBAlnBaseMap();
462 fSeq.setAligned(alignment->getSeqAAln());
463 rSeq.setAligned(alignment->getSeqBAln());
464 int length = fSeq.getAligned().length();
466 //traverse alignments merging into one contiguous seq
468 vector<int> contigScores;
469 int numMismatches = 0;
470 string seq1 = fSeq.getAligned();
471 string seq2 = rSeq.getAligned();
472 vector<int> scores1 = fQual.getQualityScores();
473 vector<int> scores2 = rQual.getQualityScores();
475 // if (num < 5) { cout << fSeq.getStartPos() << '\t' << fSeq.getEndPos() << '\t' << rSeq.getStartPos() << '\t' << rSeq.getEndPos() << endl; }
476 int overlapStart = fSeq.getStartPos();
477 int seq2Start = rSeq.getStartPos();
478 //bigger of the 2 starting positions is the location of the overlapping start
479 if (overlapStart < seq2Start) { //seq2 starts later so take from 0 to seq2Start from seq1
480 overlapStart = seq2Start;
481 for (int i = 0; i < overlapStart; i++) {
483 contigScores.push_back(scores1[ABaseMap[i]]);
485 }else { //seq1 starts later so take from 0 to overlapStart from seq2
486 for (int i = 0; i < overlapStart; i++) {
488 contigScores.push_back(scores2[BBaseMap[i]]);
492 int seq1End = fSeq.getEndPos();
493 int seq2End = rSeq.getEndPos();
494 int overlapEnd = seq1End;
495 if (seq2End < overlapEnd) { overlapEnd = seq2End; } //smallest end position is where overlapping ends
497 for (int i = overlapStart; i < overlapEnd; i++) {
498 if (seq1[i] == seq2[i]) { //match, add base and choose highest score
500 contigScores.push_back(scores1[ABaseMap[i]]);
501 if (scores1[ABaseMap[i]] < scores2[BBaseMap[i]]) { contigScores[contigScores.size()-1] = scores2[BBaseMap[i]]; }
502 }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
503 if (scores2[BBaseMap[i]] < threshold) { } //
506 contigScores.push_back(scores2[BBaseMap[i]]);
508 }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
509 if (scores1[ABaseMap[i]] < threshold) { } //
512 contigScores.push_back(scores1[ABaseMap[i]]);
514 }else if (((seq1[i] != '-') && (seq1[i] != '.')) && ((seq2[i] != '-') && (seq2[i] != '.'))) { //both bases choose one with better quality
516 contigScores.push_back(scores1[ABaseMap[i]]);
517 if (scores1[ABaseMap[i]] < scores2[BBaseMap[i]]) { contigScores[contigScores.size()-1] = scores2[BBaseMap[i]]; c = seq2[i]; }
520 }else { //should never get here
521 m->mothurOut("[ERROR]: case I didn't think of seq1 = " + toString(seq1[i]) + " and seq2 = " + toString(seq2[i]) + "\n");
525 if (seq1End < seq2End) { //seq1 ends before seq2 so take from overlap to length from seq2
526 for (int i = overlapEnd; i < length; i++) {
528 contigScores.push_back(scores2[BBaseMap[i]]);
530 }else { //seq2 ends before seq1 so take from overlap to length from seq1
531 for (int i = overlapEnd; i < length; i++) {
533 contigScores.push_back(scores1[ABaseMap[i]]);
537 //if (num < 5) { cout << overlapStart << '\t' << overlapEnd << endl << seq1 << endl << seq2 << endl<< contig << endl; }
539 outFasta << ">" << fSeq.getName() << endl << contig << endl;
540 outQual << ">" << fSeq.getName() << endl;
541 for (int i = 0; i < contigScores.size(); i++) { outQual << contigScores[i] << ' '; }
543 outMisMatch << fSeq.getName() << '\t' << contig.length() << '\t' << numMismatches << endl;
548 if((num) % 1000 == 0){ m->mothurOut(toString(num)); m->mothurOutEndLine(); }
552 if((num) % 1000 != 0){ m->mothurOut(toString(num)); m->mothurOutEndLine(); }
563 if (m->control_pressed) { m->mothurRemove(outputQual); m->mothurRemove(outputFasta); m->mothurRemove(outputMisMatches);}
567 catch(exception& e) {
568 m->errorOut(e, "MakeContigsCommand", "driver");
572 //**********************************************************************************************************************
573 vector< vector<string> > MakeContigsCommand::readFastqFiles(int& count){
575 vector< vector<string> > files;
577 //maps processors number to file pointer
578 map<int, vector<ofstream*> > tempfiles; //tempfiles[0] = forwardFasta, [1] = forwardQual, [2] = reverseFasta, [3] = reverseQual
579 map<int, vector<ofstream*> >::iterator it;
581 //create files to write to
582 for (int i = 0; i < processors; i++) {
583 vector<ofstream*> temp;
584 ofstream* outFF = new ofstream; temp.push_back(outFF);
585 ofstream* outFQ = new ofstream; temp.push_back(outFQ);
586 ofstream* outRF = new ofstream; temp.push_back(outRF);
587 ofstream* outRQ = new ofstream; temp.push_back(outRQ);
590 vector<string> names;
591 string ffastafilename = outputDir + m->getRootName(m->getSimpleName(ffastqfile)) + toString(i) + "ffasta.temp";
592 string rfastafilename = outputDir + m->getRootName(m->getSimpleName(rfastqfile)) + toString(i) + "rfasta.temp";
593 string fqualfilename = outputDir + m->getRootName(m->getSimpleName(ffastqfile)) + toString(i) + "fqual.temp";
594 string rqualfilename = outputDir + m->getRootName(m->getSimpleName(rfastqfile)) + toString(i) + "rqual.temp";
595 names.push_back(ffastafilename); names.push_back(fqualfilename);
596 names.push_back(rfastafilename); names.push_back(rqualfilename);
597 files.push_back(names);
599 m->openOutputFile(ffastafilename, *outFF);
600 m->openOutputFile(rfastafilename, *outRF);
601 m->openOutputFile(fqualfilename, *outFQ);
602 m->openOutputFile(rqualfilename, *outRQ);
605 if (m->control_pressed) {
606 //close files, delete ofstreams
607 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]; } }
609 for (int i = 0; i < files.size(); i++) {
610 for(int j = 0; j < files[i].size(); j++) { m->mothurRemove(files[i][j]); }
615 m->openInputFile(ffastqfile, inForward);
618 m->openInputFile(rfastqfile, inReverse);
621 while ((!inForward.eof()) && (!inReverse.eof())) {
623 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; }
625 //get a read from forward and reverse fastq files
626 fastqRead fread = readFastq(inForward);
627 fastqRead rread = readFastq(inReverse);
628 checkReads(fread, rread);
630 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; }
632 //if the reads are okay write to output files
633 int process = count % processors;
635 *(tempfiles[process][0]) << ">" << fread.name << endl << fread.sequence << endl;
636 *(tempfiles[process][1]) << ">" << fread.name << endl;
637 for (int i = 0; i < fread.scores.size(); i++) { *(tempfiles[process][1]) << fread.scores[i] << " "; }
638 *(tempfiles[process][1]) << endl;
639 *(tempfiles[process][2]) << ">" << rread.name << endl << rread.sequence << endl;
640 *(tempfiles[process][3]) << ">" << rread.name << endl;
641 for (int i = 0; i < rread.scores.size(); i++) { *(tempfiles[process][3]) << rread.scores[i] << " "; }
642 *(tempfiles[process][3]) << endl;
647 if((count) % 10000 == 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
651 if((count) % 10000 != 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
655 //close files, delete ofstreams
656 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]; } }
660 //adjust for really large processors or really small files
661 if (count < processors) {
662 for (int i = count; i < processors; i++) { for(int j = 0; j < files[i].size(); j++) { m->mothurRemove(files[i][j]); } files[i].clear(); }
669 catch(exception& e) {
670 m->errorOut(e, "MakeContigsCommand", "readFastqFiles");
674 //**********************************************************************************************************************
675 fastqRead MakeContigsCommand::readFastq(ifstream& in){
680 string name = m->getline(in); m->gobble(in);
681 if (name == "") { m->mothurOut("[ERROR]: Blank fasta name."); m->mothurOutEndLine(); m->control_pressed = true; return read; }
682 else if (name[0] != '@') { m->mothurOut("[ERROR]: reading " + name + " expected a name with @ as a leading character."); m->mothurOutEndLine(); m->control_pressed = true; return read; }
683 else { name = name.substr(1); }
686 string sequence = m->getline(in); m->gobble(in);
687 if (sequence == "") { m->mothurOut("[ERROR]: missing sequence for " + name); m->mothurOutEndLine(); m->control_pressed = true; return read; }
690 string name2 = m->getline(in); m->gobble(in);
691 if (name2 == "") { m->mothurOut("[ERROR]: Blank quality name."); m->mothurOutEndLine(); m->control_pressed = true; return read; }
692 else if (name2[0] != '+') { m->mothurOut("[ERROR]: reading " + name2 + " expected a name with + as a leading character."); m->mothurOutEndLine(); m->control_pressed = true; return read; }
693 else { name2 = name2.substr(1); }
695 //read quality scores
696 string quality = m->getline(in); m->gobble(in);
697 if (quality == "") { m->mothurOut("[ERROR]: missing quality for " + name2); m->mothurOutEndLine(); m->control_pressed = true; return read; }
699 //sanity check sequence length and number of quality scores match
700 if (name2 != "") { if (name != name2) { m->mothurOut("[ERROR]: names do not match. read " + name + " for fasta and " + name2 + " for quality."); m->mothurOutEndLine(); m->control_pressed = true; return read; } }
701 if (quality.length() != sequence.length()) { m->mothurOut("[ERROR]: Lengths do not match for sequence " + name + ". Read " + toString(sequence.length()) + " characters for fasta and " + toString(quality.length()) + " characters for quality scores."); m->mothurOutEndLine(); m->control_pressed = true; return read; }
703 vector<int> qualScores;
704 int controlChar = int('@');
705 for (int i = 0; i < quality.length(); i++) {
706 int temp = int(quality[i]);
709 qualScores.push_back(temp);
713 read.sequence = sequence;
714 read.scores = qualScores;
718 catch(exception& e) {
719 m->errorOut(e, "MakeContigsCommand", "readFastq");
723 //**********************************************************************************************************************
724 bool MakeContigsCommand::checkReads(fastqRead& forward, fastqRead& reverse){
729 if ((forward.name.length() > 2) && (reverse.name.length() > 2)) {
730 forward.name = forward.name.substr(0, forward.name.length()-2);
731 reverse.name = reverse.name.substr(0, reverse.name.length()-2);
732 }else { good = false; m->control_pressed = true; }
735 if (forward.name != reverse.name) {
736 m->mothurOut("[ERROR]: read " + forward.name + " from " + ffastqfile + ", but read " + reverse.name + " from " + rfastqfile + ".\n");
737 good = false; m->control_pressed = true;
740 //do sequence lengths match
741 if (forward.sequence.length() != reverse.sequence.length()) {
742 m->mothurOut("[ERROR]: For sequence " + forward.name + " I read a sequence of length " + toString(forward.sequence.length()) + " from " + ffastqfile + ", but read a sequence of length " + toString(reverse.sequence.length()) + " from " + rfastqfile + ".\n");
743 good = false; m->control_pressed = true;
746 //do number of qual scores match
747 if (forward.scores.size() != reverse.scores.size()) {
748 m->mothurOut("[ERROR]: For sequence " + forward.name + " I read " + toString(forward.scores.size()) + " quality scores from " + ffastqfile + ", but read " + toString(reverse.scores.size()) + " quality scores from " + rfastqfile + ".\n");
749 good = false; m->control_pressed = true;
754 catch(exception& e) {
755 m->errorOut(e, "MakeContigsCommand", "readFastq");
759 //***************************************************************************************************************
760 //illumina data requires paired forward and reverse data
761 //BARCODE atgcatgc atgcatgc groupName
762 //PRIMER atgcatgc atgcatgc groupName
763 //PRIMER atgcatgc atgcatgc
764 bool MakeContigsCommand::getOligos(vector<vector<string> >& fastaFileNames, vector<vector<string> >& qualFileNames){
767 m->openInputFile(oligosfile, in);
771 string type, foligo, roligo, group;
774 int indexBarcode = 0;
775 set<string> uniquePrimers;
776 set<string> uniqueBarcodes;
782 if (m->debug) { m->mothurOut("[DEBUG]: reading type - " + type + ".\n"); }
785 while (!in.eof()) { char c = in.get(); if (c == 10 || c == 13){ break; } } // get rest of line if there's any crap there
790 //make type case insensitive
791 for(int i=0;i<type.length();i++){ type[i] = toupper(type[i]); }
795 if (m->debug) { m->mothurOut("[DEBUG]: reading - " + foligo + ".\n"); }
797 for(int i=0;i<foligo.length();i++){
798 foligo[i] = toupper(foligo[i]);
799 if(foligo[i] == 'U') { foligo[i] = 'T'; }
802 if(type == "PRIMER"){
807 for(int i=0;i<roligo.length();i++){
808 roligo[i] = toupper(roligo[i]);
809 if(roligo[i] == 'U') { roligo[i] = 'T'; }
811 roligo = reverseOligo(roligo);
815 // get rest of line in case there is a primer name
818 if (c == 10 || c == 13){ break; }
819 else if (c == 32 || c == 9){;} //space or tab
823 oligosPair newPrimer(foligo, roligo);
825 //check for repeat barcodes
826 string tempPair = foligo+roligo;
827 if (uniquePrimers.count(tempPair) != 0) { m->mothurOut("primer pair " + newPrimer.forward + " " + newPrimer.reverse + " is in your oligos file already."); m->mothurOutEndLine(); }
828 else { uniquePrimers.insert(tempPair); }
830 if (m->debug) { if (group != "") { m->mothurOut("[DEBUG]: reading group " + group + ".\n"); }else{ m->mothurOut("[DEBUG]: no group for primer pair " + newPrimer.forward + " " + newPrimer.reverse + ".\n"); } }
832 primers[indexPrimer]=newPrimer; indexPrimer++;
833 primerNameVector.push_back(group);
834 }else if(type == "BARCODE"){
839 for(int i=0;i<roligo.length();i++){
840 roligo[i] = toupper(roligo[i]);
841 if(roligo[i] == 'U') { roligo[i] = 'T'; }
843 roligo = reverseOligo(roligo);
845 oligosPair newPair(foligo, roligo);
850 if (c == 10 || c == 13){ break; }
851 else if (c == 32 || c == 9){;} //space or tab
855 if (m->debug) { m->mothurOut("[DEBUG]: barcode pair " + newPair.forward + " " + newPair.reverse + ", and group = " + group + ".\n"); }
857 //check for repeat barcodes
858 string tempPair = foligo+roligo;
859 if (uniqueBarcodes.count(tempPair) != 0) { m->mothurOut("barcode pair " + newPair.forward + " " + newPair.reverse + " is in your oligos file already, disregarding."); m->mothurOutEndLine(); }
860 else { uniqueBarcodes.insert(tempPair); }
862 barcodes[indexBarcode]=newPair; indexBarcode++;
863 barcodeNameVector.push_back(group);
864 }else if(type == "LINKER"){
865 linker.push_back(foligo);
866 }else if(type == "SPACER"){
867 spacer.push_back(foligo);
869 else{ m->mothurOut("[WARNING]: " + type + " is not recognized as a valid type. Choices are primer, barcode, linker and spacer. Ignoring " + foligo + "."); m->mothurOutEndLine(); }
875 if(barcodeNameVector.size() == 0 && primerNameVector[0] == ""){ allFiles = 0; }
877 //add in potential combos
878 if(barcodeNameVector.size() == 0){
879 oligosPair temp("", "");
881 barcodeNameVector.push_back("");
884 if(primerNameVector.size() == 0){
885 oligosPair temp("", "");
887 primerNameVector.push_back("");
890 fastaFileNames.resize(barcodeNameVector.size());
891 for(int i=0;i<fastaFileNames.size();i++){
892 fastaFileNames[i].assign(primerNameVector.size(), "");
894 qualFileNames = fastaFileNames;
897 set<string> uniqueNames; //used to cleanup outputFileNames
898 for(map<int, oligosPair>::iterator itBar = barcodes.begin();itBar != barcodes.end();itBar++){
899 for(map<int, oligosPair>::iterator itPrimer = primers.begin();itPrimer != primers.end(); itPrimer++){
901 string primerName = primerNameVector[itPrimer->first];
902 string barcodeName = barcodeNameVector[itBar->first];
904 string comboGroupName = "";
905 string fastaFileName = "";
906 string qualFileName = "";
907 string nameFileName = "";
908 string countFileName = "";
910 if(primerName == ""){
911 comboGroupName = barcodeNameVector[itBar->first];
914 if(barcodeName == ""){
915 comboGroupName = primerNameVector[itPrimer->first];
918 comboGroupName = barcodeNameVector[itBar->first] + "." + primerNameVector[itPrimer->first];
924 fastaFileName = outputDir + m->getRootName(m->getSimpleName(ffastqfile)) + comboGroupName + ".fasta";
925 if (uniqueNames.count(fastaFileName) == 0) {
926 outputNames.push_back(fastaFileName);
927 outputTypes["fasta"].push_back(fastaFileName);
928 uniqueNames.insert(fastaFileName);
931 fastaFileNames[itBar->first][itPrimer->first] = fastaFileName;
932 m->openOutputFile(fastaFileName, temp); temp.close();
935 qualFileName = outputDir + m->getRootName(m->getSimpleName(ffastqfile)) + comboGroupName + ".qual";
936 if (uniqueNames.count(qualFileName) == 0) {
937 outputNames.push_back(qualFileName);
938 outputTypes["qfile"].push_back(qualFileName);
941 qualFileNames[itBar->first][itPrimer->first] = qualFileName;
942 m->openOutputFile(qualFileName, temp); temp.close();
947 bool allBlank = true;
948 for (int i = 0; i < barcodeNameVector.size(); i++) {
949 if (barcodeNameVector[i] != "") {
954 for (int i = 0; i < primerNameVector.size(); i++) {
955 if (primerNameVector[i] != "") {
962 m->mothurOut("[WARNING]: your oligos file does not contain any group names. mothur will not create a groupfile."); m->mothurOutEndLine();
970 catch(exception& e) {
971 m->errorOut(e, "MakeContigsCommand", "getOligos");
975 //********************************************************************/
976 string MakeContigsCommand::reverseOligo(string oligo){
980 for(int i=oligo.length()-1;i>=0;i--){
982 if(oligo[i] == 'A') { reverse += 'T'; }
983 else if(oligo[i] == 'T'){ reverse += 'A'; }
984 else if(oligo[i] == 'U'){ reverse += 'A'; }
986 else if(oligo[i] == 'G'){ reverse += 'C'; }
987 else if(oligo[i] == 'C'){ reverse += 'G'; }
989 else if(oligo[i] == 'R'){ reverse += 'Y'; }
990 else if(oligo[i] == 'Y'){ reverse += 'R'; }
992 else if(oligo[i] == 'M'){ reverse += 'K'; }
993 else if(oligo[i] == 'K'){ reverse += 'M'; }
995 else if(oligo[i] == 'W'){ reverse += 'W'; }
996 else if(oligo[i] == 'S'){ reverse += 'S'; }
998 else if(oligo[i] == 'B'){ reverse += 'V'; }
999 else if(oligo[i] == 'V'){ reverse += 'B'; }
1001 else if(oligo[i] == 'D'){ reverse += 'H'; }
1002 else if(oligo[i] == 'H'){ reverse += 'D'; }
1004 else { reverse += 'N'; }
1010 catch(exception& e) {
1011 m->errorOut(e, "MakeContigsCommand", "reverseOligo");
1015 //**********************************************************************************************************************