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 pfastq("ffastq", "InputTypes", "", "", "FastaFastqFile", "FastaFastqFile", "fastqGroup","fasta-qfile",false,false,true); parameters.push_back(pfastq);
15 CommandParameter prfastq("rfastq", "InputTypes", "", "", "none", "none", "fastqGroup","fasta-qfile",false,false,true); parameters.push_back(prfastq);
16 CommandParameter pfasta("ffasta", "InputTypes", "", "", "FastaFastqFile", "FastaFastqFile", "fastaGroup","fasta",false,false,true); parameters.push_back(pfasta);
17 CommandParameter prfasta("rfasta", "InputTypes", "", "", "none", "none", "none","fastaGroup",false,false,true); parameters.push_back(prfasta);
18 CommandParameter pfqual("fqfile", "InputTypes", "", "", "none", "none", "qfileGroup","qfile",false,false,true); parameters.push_back(pfqual);
19 CommandParameter prqual("rqfile", "InputTypes", "", "", "none", "none", "qfileGroup","qfile",false,false,true); parameters.push_back(prqual);
20 CommandParameter pfile("file", "InputTypes", "", "", "FastaFastqFile", "FastaFastqFile", "none","fasta-qfile",false,false,true); parameters.push_back(pfile);
21 CommandParameter poligos("oligos", "InputTypes", "", "", "none", "none", "none","group",false,false,true); parameters.push_back(poligos);
22 CommandParameter ppdiffs("pdiffs", "Number", "", "0", "", "", "","",false,false,true); parameters.push_back(ppdiffs);
23 CommandParameter pbdiffs("bdiffs", "Number", "", "0", "", "", "","",false,false,true); parameters.push_back(pbdiffs);
24 // CommandParameter pldiffs("ldiffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(pldiffs);
25 // CommandParameter psdiffs("sdiffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(psdiffs);
26 CommandParameter ptdiffs("tdiffs", "Number", "", "0", "", "", "","",false,false); parameters.push_back(ptdiffs);
28 CommandParameter palign("align", "Multiple", "needleman-gotoh", "needleman", "", "", "","",false,false); parameters.push_back(palign);
29 CommandParameter pallfiles("allfiles", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(pallfiles);
30 CommandParameter pmatch("match", "Number", "", "1.0", "", "", "","",false,false); parameters.push_back(pmatch);
31 CommandParameter pmismatch("mismatch", "Number", "", "-1.0", "", "", "","",false,false); parameters.push_back(pmismatch);
32 CommandParameter pgapopen("gapopen", "Number", "", "-2.0", "", "", "","",false,false); parameters.push_back(pgapopen);
33 CommandParameter pgapextend("gapextend", "Number", "", "-1.0", "", "", "","",false,false); parameters.push_back(pgapextend);
34 CommandParameter pthreshold("threshold", "Number", "", "40", "", "", "","",false,false); parameters.push_back(pthreshold);
35 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "","",false,false,true); parameters.push_back(pprocessors);
36 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
37 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
39 vector<string> myArray;
40 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
44 m->errorOut(e, "MakeContigsCommand", "setParameters");
48 //**********************************************************************************************************************
49 string MakeContigsCommand::getHelpString(){
51 string helpString = "";
52 helpString += "The make.contigs command reads a file, forward fastq file and a reverse fastq file or forward fasta and reverse fasta files and outputs new fasta. It will also provide new quality files if the fastq or file parameter is used.\n";
53 helpString += "If an oligos file is provided barcodes and primers will be trimmed, and a group file will be created.\n";
54 helpString += "The make.contigs command parameters are ffastq, rfastq, oligos, tdiffs, bdiffs, ldiffs, sdiffs, pdiffs, align, match, mismatch, gapopen, gapextend, allfiles and processors.\n";
55 helpString += "The ffastq and rfastq, file, or ffasta and rfasta parameters are required.\n";
56 helpString += "The file parameter is 2 column file containing the forward fastq files in the first column and their matching reverse fastq files in the second column. Mothur will process each pair and create a combined fasta and qual file with all the sequences.\n";
57 helpString += "The ffastq and rfastq parameters are used to provide a forward fastq and reverse fastq file to process. If you provide one, you must provide the other.\n";
58 helpString += "The ffasta and rfasta parameters are used to provide a forward fasta and reverse fasta file to process. If you provide one, you must provide the other.\n";
59 helpString += "The fqfile and rqfile parameters are used to provide a forward quality and reverse quality files to process with the ffasta and rfasta parameters. If you provide one, you must provide the other.\n";
60 helpString += "The align parameter allows you to specify the alignment method to use. Your options are: gotoh and needleman. The default is needleman.\n";
61 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";
62 helpString += "The bdiffs parameter is used to specify the number of differences allowed in the barcode. The default is 0.\n";
63 helpString += "The pdiffs parameter is used to specify the number of differences allowed in the primer. The default is 0.\n";
64 helpString += "The ldiffs parameter is used to specify the number of differences allowed in the linker. The default is 0.\n";
65 helpString += "The sdiffs parameter is used to specify the number of differences allowed in the spacer. The default is 0.\n";
66 helpString += "The match parameter allows you to specify the bonus for having the same base. The default is 1.0.\n";
67 helpString += "The mistmatch parameter allows you to specify the penalty for having different bases. The default is -1.0.\n";
68 helpString += "The gapopen parameter allows you to specify the penalty for opening a gap in an alignment. The default is -2.0.\n";
69 helpString += "The gapextend parameter allows you to specify the penalty for extending a gap in an alignment. The default is -1.0.\n";
70 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";
71 helpString += "The processors parameter allows you to specify how many processors you would like to use. The default is 1. \n";
72 helpString += "The allfiles parameter will create separate group and fasta file for each grouping. The default is F.\n";
73 helpString += "The make.contigs command should be in the following format: \n";
74 helpString += "make.contigs(ffastq=yourForwardFastqFile, rfastq=yourReverseFastqFile, align=yourAlignmentMethod) \n";
75 helpString += "Note: No spaces between parameter labels (i.e. ffastq), '=' and parameters (i.e.yourForwardFastqFile).\n";
79 m->errorOut(e, "MakeContigsCommand", "getHelpString");
83 //**********************************************************************************************************************
84 string MakeContigsCommand::getOutputPattern(string type) {
88 if (type == "fasta") { pattern = "[filename],[tag],contigs.fasta"; }
89 else if (type == "qfile") { pattern = "[filename],[tag],contigs.qual"; }
90 else if (type == "group") { pattern = "[filename],[tag],groups"; }
91 else if (type == "mismatch") { pattern = "[filename],[tag],contigs.mismatch"; }
92 else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true; }
97 m->errorOut(e, "MakeContigsCommand", "getOutputPattern");
101 //**********************************************************************************************************************
102 MakeContigsCommand::MakeContigsCommand(){
104 abort = true; calledHelp = true;
106 vector<string> tempOutNames;
107 outputTypes["fasta"] = tempOutNames;
108 outputTypes["qfile"] = tempOutNames;
109 outputTypes["group"] = tempOutNames;
110 outputTypes["mismatch"] = tempOutNames;
112 catch(exception& e) {
113 m->errorOut(e, "MakeContigsCommand", "MakeContigsCommand");
117 //**********************************************************************************************************************
118 MakeContigsCommand::MakeContigsCommand(string option) {
120 abort = false; calledHelp = false;
122 //allow user to run help
123 if(option == "help") { help(); abort = true; calledHelp = true; }
124 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
127 vector<string> myArray = setParameters();
129 OptionParser parser(option);
130 map<string, string> parameters = parser.getParameters();
132 ValidParameters validParameter("pairwise.seqs");
133 map<string, string>::iterator it;
135 //check to make sure all parameters are valid for command
136 for (it = parameters.begin(); it != parameters.end(); it++) {
137 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
140 //initialize outputTypes
141 vector<string> tempOutNames;
142 outputTypes["fasta"] = tempOutNames;
143 outputTypes["qfile"] = tempOutNames;
144 outputTypes["mismatch"] = tempOutNames;
145 outputTypes["group"] = tempOutNames;
148 //if the user changes the input directory command factory will send this info to us in the output parameter
149 string inputDir = validParameter.validFile(parameters, "inputdir", false);
150 if (inputDir == "not found"){ inputDir = ""; }
153 it = parameters.find("ffastq");
154 //user has given a template file
155 if(it != parameters.end()){
156 path = m->hasPath(it->second);
157 //if the user has not given a path then, add inputdir. else leave path alone.
158 if (path == "") { parameters["ffastq"] = inputDir + it->second; }
161 it = parameters.find("rfastq");
162 //user has given a template file
163 if(it != parameters.end()){
164 path = m->hasPath(it->second);
165 //if the user has not given a path then, add inputdir. else leave path alone.
166 if (path == "") { parameters["rfastq"] = inputDir + it->second; }
169 it = parameters.find("ffasta");
170 //user has given a template file
171 if(it != parameters.end()){
172 path = m->hasPath(it->second);
173 //if the user has not given a path then, add inputdir. else leave path alone.
174 if (path == "") { parameters["ffasta"] = inputDir + it->second; }
177 it = parameters.find("rfasta");
178 //user has given a template file
179 if(it != parameters.end()){
180 path = m->hasPath(it->second);
181 //if the user has not given a path then, add inputdir. else leave path alone.
182 if (path == "") { parameters["rfasta"] = inputDir + it->second; }
185 it = parameters.find("fqfile");
186 //user has given a template file
187 if(it != parameters.end()){
188 path = m->hasPath(it->second);
189 //if the user has not given a path then, add inputdir. else leave path alone.
190 if (path == "") { parameters["fqfile"] = inputDir + it->second; }
193 it = parameters.find("rqfile");
194 //user has given a template file
195 if(it != parameters.end()){
196 path = m->hasPath(it->second);
197 //if the user has not given a path then, add inputdir. else leave path alone.
198 if (path == "") { parameters["rqfile"] = inputDir + it->second; }
201 it = parameters.find("file");
202 //user has given a template file
203 if(it != parameters.end()){
204 path = m->hasPath(it->second);
205 //if the user has not given a path then, add inputdir. else leave path alone.
206 if (path == "") { parameters["file"] = inputDir + it->second; }
209 it = parameters.find("oligos");
210 //user has given a template file
211 if(it != parameters.end()){
212 path = m->hasPath(it->second);
213 //if the user has not given a path then, add inputdir. else leave path alone.
214 if (path == "") { parameters["oligos"] = inputDir + it->second; }
218 ffastqfile = validParameter.validFile(parameters, "ffastq", true);
219 if (ffastqfile == "not open") { abort = true; }
220 else if (ffastqfile == "not found") { ffastqfile = ""; }
222 rfastqfile = validParameter.validFile(parameters, "rfastq", true);
223 if (rfastqfile == "not open") { abort = true; }
224 else if (rfastqfile == "not found") { rfastqfile = ""; }
226 ffastafile = validParameter.validFile(parameters, "ffasta", true);
227 if (ffastafile == "not open") { abort = true; }
228 else if (ffastafile == "not found") { ffastafile = ""; }
230 rfastafile = validParameter.validFile(parameters, "rfasta", true);
231 if (rfastafile == "not open") { abort = true; }
232 else if (rfastafile == "not found") { rfastafile = ""; }
234 fqualfile = validParameter.validFile(parameters, "fqfile", true);
235 if (fqualfile == "not open") { abort = true; }
236 else if (fqualfile == "not found") { fqualfile = ""; }
238 rqualfile = validParameter.validFile(parameters, "rqfile", true);
239 if (rqualfile == "not open") { abort = true; }
240 else if (rqualfile == "not found") { rqualfile = ""; }
242 file = validParameter.validFile(parameters, "file", true);
243 if (file == "not open") { abort = true; }
244 else if (file == "not found") { file = ""; }
246 if ((file == "") && (ffastafile == "") && (ffastqfile == "")) { abort = true; m->mothurOut("[ERROR]: ffastq and rfastq parameters are required.\n"); }
247 if ((ffastqfile != "") && (rfastqfile == "")) { abort = true; }
248 if ((ffastqfile == "") && (rfastqfile != "")) { abort = true; }
250 oligosfile = validParameter.validFile(parameters, "oligos", true);
251 if (oligosfile == "not found") { oligosfile = ""; }
252 else if(oligosfile == "not open") { abort = true; }
253 else { m->setOligosFile(oligosfile); }
255 //if the user changes the output directory command factory will send this info to us in the output parameter
256 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = m->hasPath(ffastqfile); }
259 //check for optional parameter and set defaults
260 // ...at some point should added some additional type checking...
262 temp = validParameter.validFile(parameters, "match", false); if (temp == "not found"){ temp = "1.0"; }
263 m->mothurConvert(temp, match);
265 temp = validParameter.validFile(parameters, "mismatch", false); if (temp == "not found"){ temp = "-1.0"; }
266 m->mothurConvert(temp, misMatch);
267 if (misMatch > 0) { m->mothurOut("[ERROR]: mismatch must be negative.\n"); abort=true; }
269 temp = validParameter.validFile(parameters, "gapopen", false); if (temp == "not found"){ temp = "-2.0"; }
270 m->mothurConvert(temp, gapOpen);
271 if (gapOpen > 0) { m->mothurOut("[ERROR]: gapopen must be negative.\n"); abort=true; }
273 temp = validParameter.validFile(parameters, "gapextend", false); if (temp == "not found"){ temp = "-1.0"; }
274 m->mothurConvert(temp, gapExtend);
275 if (gapExtend > 0) { m->mothurOut("[ERROR]: gapextend must be negative.\n"); abort=true; }
277 temp = validParameter.validFile(parameters, "threshold", false); if (temp == "not found"){ temp = "40"; }
278 m->mothurConvert(temp, threshold);
279 if ((threshold < 0) || (threshold > 40)) { m->mothurOut("[ERROR]: threshold must be between 0 and 40.\n"); abort=true; }
281 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
282 m->setProcessors(temp);
283 m->mothurConvert(temp, processors);
285 temp = validParameter.validFile(parameters, "bdiffs", false); if (temp == "not found") { temp = "0"; }
286 m->mothurConvert(temp, bdiffs);
288 temp = validParameter.validFile(parameters, "pdiffs", false); if (temp == "not found") { temp = "0"; }
289 m->mothurConvert(temp, pdiffs);
291 // temp = validParameter.validFile(parameters, "ldiffs", false); if (temp == "not found") { temp = "0"; }
292 // m->mothurConvert(temp, ldiffs);
295 // temp = validParameter.validFile(parameters, "sdiffs", false); if (temp == "not found") { temp = "0"; }
296 // m->mothurConvert(temp, sdiffs);
299 temp = validParameter.validFile(parameters, "tdiffs", false); if (temp == "not found") { int tempTotal = pdiffs + bdiffs; temp = toString(tempTotal); }
300 m->mothurConvert(temp, tdiffs);
302 if(tdiffs == 0){ tdiffs = bdiffs + pdiffs; } //+ ldiffs + sdiffs;
304 temp = validParameter.validFile(parameters, "allfiles", false); if (temp == "not found") { temp = "F"; }
305 allFiles = m->isTrue(temp);
307 align = validParameter.validFile(parameters, "align", false); if (align == "not found"){ align = "needleman"; }
308 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"; }
312 catch(exception& e) {
313 m->errorOut(e, "MakeContigsCommand", "MakeContigsCommand");
317 //**********************************************************************************************************************
318 int MakeContigsCommand::execute(){
320 if (abort == true) { if (calledHelp) { return 0; } return 2; }
322 //read ffastq and rfastq files creating fasta and qual files.
323 //this function will create a forward and reverse, fasta and qual files for each processor.
324 //files has an entry for each processor. files[i][0] = forwardFasta, files[i][1] = forwardQual, files[i][2] = reverseFasta, files[i][3] = reverseQual
325 unsigned long int numReads = 0;
326 int start = time(NULL);
328 m->mothurOut("Reading fastq data...\n");
329 vector< vector<string> > files = readFastqFiles(numReads);
330 m->mothurOut("Done.\n");
332 if (m->control_pressed) { return 0; }
334 vector<vector<string> > fastaFileNames;
335 vector<vector<string> > qualFileNames;
337 string outputGroupFileName;
338 map<string, string> variables;
339 variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(ffastqfile));
340 variables["[tag]"] = "";
341 if(oligosfile != ""){
342 createGroup = getOligos(fastaFileNames, qualFileNames);
344 outputGroupFileName = getOutputFileName("group",variables);
345 outputNames.push_back(outputGroupFileName); outputTypes["group"].push_back(outputGroupFileName);
349 variables["[tag]"] = "trim";
350 string outFastaFile = getOutputFileName("fasta",variables);
351 string outQualFile = getOutputFileName("qfile",variables);
352 variables["[tag]"] = "scrap";
353 string outScrapFastaFile = getOutputFileName("fasta",variables);
354 string outScrapQualFile = getOutputFileName("qfile",variables);
356 variables["[tag]"] = "";
357 string outMisMatchFile = getOutputFileName("mismatch",variables);
358 outputNames.push_back(outFastaFile); outputTypes["fasta"].push_back(outFastaFile);
359 outputNames.push_back(outQualFile); outputTypes["qfile"].push_back(outQualFile);
360 outputNames.push_back(outScrapFastaFile); outputTypes["fasta"].push_back(outScrapFastaFile);
361 outputNames.push_back(outScrapQualFile); outputTypes["qfile"].push_back(outScrapQualFile);
362 outputNames.push_back(outMisMatchFile); outputTypes["mismatch"].push_back(outMisMatchFile);
364 m->mothurOut("Making contigs...\n");
365 createProcesses(files, outFastaFile, outQualFile, outScrapFastaFile, outScrapQualFile, outMisMatchFile, fastaFileNames, qualFileNames);
366 m->mothurOut("Done.\n");
368 //remove temp fasta and qual files
369 for (int i = 0; i < processors; i++) { for(int j = 0; j < files[i].size(); j++) { m->mothurRemove(files[i][j]); } }
371 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } return 0; }
374 map<string, string> uniqueFastaNames;// so we don't add the same groupfile multiple times
375 map<string, string>::iterator it;
376 set<string> namesToRemove;
377 for(int i=0;i<fastaFileNames.size();i++){
378 for(int j=0;j<fastaFileNames[0].size();j++){
379 if (fastaFileNames[i][j] != "") {
380 if (namesToRemove.count(fastaFileNames[i][j]) == 0) {
381 if(m->isBlank(fastaFileNames[i][j])){
382 m->mothurRemove(fastaFileNames[i][j]);
383 namesToRemove.insert(fastaFileNames[i][j]);
385 m->mothurRemove(qualFileNames[i][j]);
386 namesToRemove.insert(qualFileNames[i][j]);
388 it = uniqueFastaNames.find(fastaFileNames[i][j]);
389 if (it == uniqueFastaNames.end()) {
390 uniqueFastaNames[fastaFileNames[i][j]] = barcodeNameVector[i];
398 //remove names for outputFileNames, just cleans up the output
399 vector<string> outputNames2;
400 for(int i = 0; i < outputNames.size(); i++) { if (namesToRemove.count(outputNames[i]) == 0) { outputNames2.push_back(outputNames[i]); } }
401 outputNames = outputNames2;
403 for (it = uniqueFastaNames.begin(); it != uniqueFastaNames.end(); it++) {
405 m->openInputFile(it->first, in);
408 string thisGroupName = outputDir + m->getRootName(m->getSimpleName(it->first));
409 thisGroupName += getOutputFileName("group",variables); outputNames.push_back(thisGroupName); outputTypes["group"].push_back(thisGroupName);
410 m->openOutputFile(thisGroupName, out);
413 if (m->control_pressed) { break; }
415 Sequence currSeq(in); m->gobble(in);
416 out << currSeq.getName() << '\t' << it->second << endl;
425 m->openOutputFile(outputGroupFileName, outGroup);
426 for (map<string, string>::iterator itGroup = groupMap.begin(); itGroup != groupMap.end(); itGroup++) {
427 outGroup << itGroup->first << '\t' << itGroup->second << endl;
431 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to process " + toString(numReads) + " sequences.\n");
433 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } return 0; }
435 //output group counts
436 m->mothurOutEndLine();
438 if (groupCounts.size() != 0) { m->mothurOut("Group count: \n"); }
439 for (map<string, int>::iterator it = groupCounts.begin(); it != groupCounts.end(); it++) {
440 total += it->second; m->mothurOut(it->first + "\t" + toString(it->second)); m->mothurOutEndLine();
442 if (total != 0) { m->mothurOut("Total of all groups is " + toString(total)); m->mothurOutEndLine(); }
444 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } return 0; }
446 string currentFasta = "";
447 itTypes = outputTypes.find("fasta");
448 if (itTypes != outputTypes.end()) {
449 if ((itTypes->second).size() != 0) { currentFasta = (itTypes->second)[0]; m->setFastaFile(currentFasta); }
452 string currentQual = "";
453 itTypes = outputTypes.find("qfile");
454 if (itTypes != outputTypes.end()) {
455 if ((itTypes->second).size() != 0) { currentQual = (itTypes->second)[0]; m->setQualFile(currentQual); }
458 string currentGroup = "";
459 itTypes = outputTypes.find("group");
460 if (itTypes != outputTypes.end()) {
461 if ((itTypes->second).size() != 0) { currentGroup = (itTypes->second)[0]; m->setGroupFile(currentGroup); }
464 //output files created by command
465 m->mothurOutEndLine();
466 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
467 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
468 m->mothurOutEndLine();
472 catch(exception& e) {
473 m->errorOut(e, "MakeContigsCommand", "execute");
477 //**********************************************************************************************************************
478 int MakeContigsCommand::createProcesses(vector< vector<string> > files, string outputFasta, string outputQual, string outputScrapFasta, string outputScrapQual, string outputMisMatches, vector<vector<string> > fastaFileNames, vector<vector<string> > qualFileNames) {
481 vector<int> processIDS;
482 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
485 //loop through and create all the processes you want
486 while (process != processors-1) {
490 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
493 vector<vector<string> > tempFASTAFileNames = fastaFileNames;
494 vector<vector<string> > tempPrimerQualFileNames = qualFileNames;
499 for(int i=0;i<tempFASTAFileNames.size();i++){
500 for(int j=0;j<tempFASTAFileNames[i].size();j++){
501 if (tempFASTAFileNames[i][j] != "") {
502 tempFASTAFileNames[i][j] += toString(getpid()) + ".temp";
503 m->openOutputFile(tempFASTAFileNames[i][j], temp); temp.close();
505 tempPrimerQualFileNames[i][j] += toString(getpid()) + ".temp";
506 m->openOutputFile(tempPrimerQualFileNames[i][j], temp); temp.close();
512 num = driver(files[process],
513 outputFasta + toString(getpid()) + ".temp",
514 outputQual + toString(getpid()) + ".temp",
515 outputScrapFasta + toString(getpid()) + ".temp",
516 outputScrapQual + toString(getpid()) + ".temp",
517 outputMisMatches + toString(getpid()) + ".temp",
519 tempPrimerQualFileNames);
521 //pass groupCounts to parent
523 string tempFile = toString(getpid()) + ".num.temp";
524 m->openOutputFile(tempFile, out);
527 out << groupCounts.size() << endl;
529 for (map<string, int>::iterator it = groupCounts.begin(); it != groupCounts.end(); it++) {
530 out << it->first << '\t' << it->second << endl;
533 out << groupMap.size() << endl;
534 for (map<string, string>::iterator it = groupMap.begin(); it != groupMap.end(); it++) {
535 out << it->first << '\t' << it->second << endl;
542 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
543 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
549 m->openOutputFile(outputFasta, temp); temp.close();
550 m->openOutputFile(outputQual, temp); temp.close();
551 m->openOutputFile(outputScrapFasta, temp); temp.close();
552 m->openOutputFile(outputScrapQual, temp); temp.close();
555 num = driver(files[processors-1], outputFasta, outputQual, outputScrapFasta, outputScrapQual, outputMisMatches, fastaFileNames, qualFileNames);
557 //force parent to wait until all the processes are done
558 for (int i=0;i<processIDS.size();i++) {
559 int temp = processIDS[i];
563 for (int i = 0; i < processIDS.size(); i++) {
565 string tempFile = toString(processIDS[i]) + ".num.temp";
566 m->openInputFile(tempFile, in);
568 in >> tempNum; num += tempNum; m->gobble(in);
572 in >> tempNum; m->gobble(in);
575 for (int j = 0; j < tempNum; j++) {
577 in >> group >> groupNum; m->gobble(in);
579 map<string, int>::iterator it = groupCounts.find(group);
580 if (it == groupCounts.end()) { groupCounts[group] = groupNum; }
581 else { groupCounts[it->first] += groupNum; }
584 in >> tempNum; m->gobble(in);
586 for (int j = 0; j < tempNum; j++) {
587 string group, seqName;
588 in >> seqName >> group; m->gobble(in);
590 map<string, string>::iterator it = groupMap.find(seqName);
591 if (it == groupMap.end()) { groupMap[seqName] = group; }
592 else { m->mothurOut("[ERROR]: " + seqName + " is in your fasta file more than once. Sequence names must be unique. please correct.\n"); }
596 in.close(); m->mothurRemove(tempFile);
600 //////////////////////////////////////////////////////////////////////////////////////////////////////
601 //Windows version shared memory, so be careful when passing variables through the contigsData struct.
602 //Above fork() will clone, so memory is separate, but that's not the case with windows,
603 //////////////////////////////////////////////////////////////////////////////////////////////////////
605 vector<contigsData*> pDataArray;
606 DWORD dwThreadIdArray[processors-1];
607 HANDLE hThreadArray[processors-1];
609 //Create processor worker threads.
610 for( int h=0; h<processors-1; h++ ){
611 string extension = "";
612 if (h != 0) { extension = toString(h) + ".temp"; processIDS.push_back(h); }
613 vector<vector<string> > tempFASTAFileNames = fastaFileNames;
614 vector<vector<string> > tempPrimerQualFileNames = qualFileNames;
619 for(int i=0;i<tempFASTAFileNames.size();i++){
620 for(int j=0;j<tempFASTAFileNames[i].size();j++){
621 if (tempFASTAFileNames[i][j] != "") {
622 tempFASTAFileNames[i][j] += extension;
623 m->openOutputFile(tempFASTAFileNames[i][j], temp); temp.close();
626 tempPrimerQualFileNames[i][j] += extension;
627 m->openOutputFile(tempPrimerQualFileNames[i][j], temp); temp.close();
634 contigsData* tempcontig = new contigsData(files[h], (outputFasta + extension), (outputQual + extension), (outputScrapFasta + extension), (outputScrapQual + extension),(outputMisMatches + extension), align, m, match, misMatch, gapOpen, gapExtend, threshold, barcodes, primers, tempFASTAFileNames, tempPrimerQualFileNames, barcodeNameVector, primerNameVector, pdiffs, bdiffs, tdiffs, createGroup, allFiles, h);
635 pDataArray.push_back(tempcontig);
637 hThreadArray[h] = CreateThread(NULL, 0, MyContigsThreadFunction, pDataArray[h], 0, &dwThreadIdArray[h]);
640 vector<vector<string> > tempFASTAFileNames = fastaFileNames;
641 vector<vector<string> > tempPrimerQualFileNames = qualFileNames;
645 string extension = toString(processors-1) + ".temp";
647 for(int i=0;i<tempFASTAFileNames.size();i++){
648 for(int j=0;j<tempFASTAFileNames[i].size();j++){
649 if (tempFASTAFileNames[i][j] != "") {
650 tempFASTAFileNames[i][j] += extension;
651 m->openOutputFile(tempFASTAFileNames[i][j], temp); temp.close();
654 tempPrimerQualFileNames[i][j] += extension;
655 m->openOutputFile(tempPrimerQualFileNames[i][j], temp); temp.close();
663 m->openOutputFile(outputFasta, temp); temp.close();
664 m->openOutputFile(outputQual, temp); temp.close();
665 m->openOutputFile(outputScrapFasta, temp); temp.close();
666 m->openOutputFile(outputScrapQual, temp); temp.close();
670 num = driver(files[processors-1], (outputFasta+ toString(processors-1) + ".temp"), (outputQual+ toString(processors-1) + ".temp"), (outputScrapFasta+ toString(processors-1) + ".temp"), (outputScrapQual+ toString(processors-1) + ".temp"), (outputMisMatches+ toString(processors-1) + ".temp"), tempFASTAFileNames, tempPrimerQualFileNames);
672 //Wait until all threads have terminated.
673 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
675 //Close all thread handles and free memory allocations.
676 for(int i=0; i < pDataArray.size(); i++){
677 num += pDataArray[i]->count;
678 for (map<string, int>::iterator it = pDataArray[i]->groupCounts.begin(); it != pDataArray[i]->groupCounts.end(); it++) {
679 map<string, int>::iterator it2 = groupCounts.find(it->first);
680 if (it2 == groupCounts.end()) { groupCounts[it->first] = it->second; }
681 else { groupCounts[it->first] += it->second; }
683 for (map<string, string>::iterator it = pDataArray[i]->groupMap.begin(); it != pDataArray[i]->groupMap.end(); it++) {
684 map<string, string>::iterator it2 = groupMap.find(it->first);
685 if (it2 == groupMap.end()) { groupMap[it->first] = it->second; }
686 else { m->mothurOut("[ERROR]: " + it->first + " is in your fasta file more than once. Sequence names must be unique. please correct.\n"); }
688 CloseHandle(hThreadArray[i]);
689 delete pDataArray[i];
694 for (int i = 0; i < processIDS.size(); i++) {
695 m->appendFiles((outputFasta + toString(processIDS[i]) + ".temp"), outputFasta);
696 m->mothurRemove((outputFasta + toString(processIDS[i]) + ".temp"));
698 m->appendFiles((outputQual + toString(processIDS[i]) + ".temp"), outputQual);
699 m->mothurRemove((outputQual + toString(processIDS[i]) + ".temp"));
701 m->appendFiles((outputScrapFasta + toString(processIDS[i]) + ".temp"), outputScrapFasta);
702 m->mothurRemove((outputScrapFasta + toString(processIDS[i]) + ".temp"));
704 m->appendFiles((outputScrapQual + toString(processIDS[i]) + ".temp"), outputScrapQual);
705 m->mothurRemove((outputScrapQual + toString(processIDS[i]) + ".temp"));
707 m->appendFiles((outputMisMatches + toString(processIDS[i]) + ".temp"), outputMisMatches);
708 m->mothurRemove((outputMisMatches + toString(processIDS[i]) + ".temp"));
711 for(int j=0;j<fastaFileNames.size();j++){
712 for(int k=0;k<fastaFileNames[j].size();k++){
713 if (fastaFileNames[j][k] != "") {
714 m->appendFiles((fastaFileNames[j][k] + toString(processIDS[i]) + ".temp"), fastaFileNames[j][k]);
715 m->mothurRemove((fastaFileNames[j][k] + toString(processIDS[i]) + ".temp"));
717 m->appendFiles((qualFileNames[j][k] + toString(processIDS[i]) + ".temp"), qualFileNames[j][k]);
718 m->mothurRemove((qualFileNames[j][k] + toString(processIDS[i]) + ".temp"));
727 catch(exception& e) {
728 m->errorOut(e, "MakeContigsCommand", "createProcesses");
732 //**********************************************************************************************************************
733 int MakeContigsCommand::driver(vector<string> files, string outputFasta, string outputQual, string outputScrapFasta, string outputScrapQual, string outputMisMatches, vector<vector<string> > fastaFileNames, vector<vector<string> > qualFileNames){
736 Alignment* alignment;
737 if(align == "gotoh") { alignment = new GotohOverlap(gapOpen, gapExtend, match, misMatch, longestBase); }
738 else if(align == "needleman") { alignment = new NeedlemanOverlap(gapOpen, match, misMatch, longestBase); }
741 string thisffastafile = files[0];
742 string thisfqualfile = files[1];
743 string thisrfastafile = files[2];
744 string thisrqualfile = files[3];
746 if (m->debug) { m->mothurOut("[DEBUG]: ffasta = " + thisffastafile + ".\n[DEBUG]: fqual = " + thisfqualfile + ".\n[DEBUG]: rfasta = " + thisrfastafile + ".\n[DEBUG]: rqual = " + thisrqualfile + ".\n"); }
748 ifstream inFFasta, inRFasta, inFQual, inRQual;
749 m->openInputFile(thisffastafile, inFFasta);
750 m->openInputFile(thisfqualfile, inFQual);
751 m->openInputFile(thisrfastafile, inRFasta);
752 m->openInputFile(thisrqualfile, inRQual);
754 ofstream outFasta, outQual, outMisMatch, outScrapFasta, outScrapQual;
755 m->openOutputFile(outputFasta, outFasta);
756 m->openOutputFile(outputQual, outQual);
757 m->openOutputFile(outputScrapFasta, outScrapFasta);
758 m->openOutputFile(outputScrapQual, outScrapQual);
759 m->openOutputFile(outputMisMatches, outMisMatch);
760 outMisMatch << "Name\tLength\tMisMatches\n";
762 TrimOligos trimOligos(pdiffs, bdiffs, 0, 0, primers, barcodes);
764 while ((!inFQual.eof()) && (!inFFasta.eof()) && (!inRFasta.eof()) && (!inRQual.eof())) {
766 if (m->control_pressed) { break; }
769 string trashCode = "";
770 int currentSeqsDiffs = 0;
772 //read seqs and quality info
773 Sequence fSeq(inFFasta); m->gobble(inFFasta);
774 Sequence rSeq(inRFasta); m->gobble(inRFasta);
775 QualityScores fQual(inFQual); m->gobble(inFQual);
776 QualityScores rQual(inRQual); m->gobble(inRQual);
778 int barcodeIndex = 0;
781 if(barcodes.size() != 0){
782 success = trimOligos.stripBarcode(fSeq, rSeq, fQual, rQual, barcodeIndex);
783 if(success > bdiffs) { trashCode += 'b'; }
784 else{ currentSeqsDiffs += success; }
787 if(primers.size() != 0){
788 success = trimOligos.stripForward(fSeq, rSeq, fQual, rQual, primerIndex);
789 if(success > pdiffs) { trashCode += 'f'; }
790 else{ currentSeqsDiffs += success; }
793 if (currentSeqsDiffs > tdiffs) { trashCode += 't'; }
795 //flip the reverse reads
796 rSeq.reverseComplement();
800 alignment->align(fSeq.getUnaligned(), rSeq.getUnaligned());
801 map<int, int> ABaseMap = alignment->getSeqAAlnBaseMap();
802 map<int, int> BBaseMap = alignment->getSeqBAlnBaseMap();
803 fSeq.setAligned(alignment->getSeqAAln());
804 rSeq.setAligned(alignment->getSeqBAln());
805 int length = fSeq.getAligned().length();
807 //traverse alignments merging into one contiguous seq
809 vector<int> contigScores;
810 int numMismatches = 0;
811 string seq1 = fSeq.getAligned();
812 string seq2 = rSeq.getAligned();
813 vector<int> scores1 = fQual.getQualityScores();
814 vector<int> scores2 = rQual.getQualityScores();
816 // if (num < 5) { cout << fSeq.getStartPos() << '\t' << fSeq.getEndPos() << '\t' << rSeq.getStartPos() << '\t' << rSeq.getEndPos() << endl; }
817 int overlapStart = fSeq.getStartPos();
818 int seq2Start = rSeq.getStartPos();
819 //bigger of the 2 starting positions is the location of the overlapping start
820 if (overlapStart < seq2Start) { //seq2 starts later so take from 0 to seq2Start from seq1
821 overlapStart = seq2Start;
822 for (int i = 0; i < overlapStart; i++) {
824 contigScores.push_back(scores1[ABaseMap[i]]);
826 }else { //seq1 starts later so take from 0 to overlapStart from seq2
827 for (int i = 0; i < overlapStart; i++) {
829 contigScores.push_back(scores2[BBaseMap[i]]);
833 int seq1End = fSeq.getEndPos();
834 int seq2End = rSeq.getEndPos();
835 int overlapEnd = seq1End;
836 if (seq2End < overlapEnd) { overlapEnd = seq2End; } //smallest end position is where overlapping ends
838 for (int i = overlapStart; i < overlapEnd; i++) {
839 if (seq1[i] == seq2[i]) { //match, add base and choose highest score
841 contigScores.push_back(scores1[ABaseMap[i]]);
842 if (scores1[ABaseMap[i]] < scores2[BBaseMap[i]]) { contigScores[contigScores.size()-1] = scores2[BBaseMap[i]]; }
843 }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
844 if (scores2[BBaseMap[i]] < threshold) { } //
847 contigScores.push_back(scores2[BBaseMap[i]]);
849 }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
850 if (scores1[ABaseMap[i]] < threshold) { } //
853 contigScores.push_back(scores1[ABaseMap[i]]);
855 }else if (((seq1[i] != '-') && (seq1[i] != '.')) && ((seq2[i] != '-') && (seq2[i] != '.'))) { //both bases choose one with better quality
857 contigScores.push_back(scores1[ABaseMap[i]]);
858 if (scores1[ABaseMap[i]] < scores2[BBaseMap[i]]) { contigScores[contigScores.size()-1] = scores2[BBaseMap[i]]; c = seq2[i]; }
861 }else { //should never get here
862 m->mothurOut("[ERROR]: case I didn't think of seq1 = " + toString(seq1[i]) + " and seq2 = " + toString(seq2[i]) + "\n");
866 if (seq1End < seq2End) { //seq1 ends before seq2 so take from overlap to length from seq2
867 for (int i = overlapEnd; i < length; i++) {
869 contigScores.push_back(scores2[BBaseMap[i]]);
871 }else { //seq2 ends before seq1 so take from overlap to length from seq1
872 for (int i = overlapEnd; i < length; i++) {
874 contigScores.push_back(scores1[ABaseMap[i]]);
879 if(trashCode.length() == 0){
881 if(barcodes.size() != 0){
882 string thisGroup = barcodeNameVector[barcodeIndex];
883 if (primers.size() != 0) {
884 if (primerNameVector[primerIndex] != "") {
885 if(thisGroup != "") {
886 thisGroup += "." + primerNameVector[primerIndex];
888 thisGroup = primerNameVector[primerIndex];
893 if (m->debug) { m->mothurOut(", group= " + thisGroup + "\n"); }
895 groupMap[fSeq.getName()] = thisGroup;
897 map<string, int>::iterator it = groupCounts.find(thisGroup);
898 if (it == groupCounts.end()) { groupCounts[thisGroup] = 1; }
899 else { groupCounts[it->first] ++; }
906 m->openOutputFileAppend(fastaFileNames[barcodeIndex][primerIndex], output);
907 output << ">" << fSeq.getName() << endl << contig << endl;
910 m->openOutputFileAppend(qualFileNames[barcodeIndex][primerIndex], output);
911 output << ">" << fSeq.getName() << endl;
912 for (int i = 0; i < contigScores.size(); i++) { output << contigScores[i] << ' '; }
918 outFasta << ">" << fSeq.getName() << endl << contig << endl;
919 outQual << ">" << fSeq.getName() << endl;
920 for (int i = 0; i < contigScores.size(); i++) { outQual << contigScores[i] << ' '; }
922 outMisMatch << fSeq.getName() << '\t' << contig.length() << '\t' << numMismatches << endl;
925 outScrapFasta << ">" << fSeq.getName() << " | " << trashCode << endl << contig << endl;
926 outScrapQual << ">" << fSeq.getName() << " | " << trashCode << endl;
927 for (int i = 0; i < contigScores.size(); i++) { outScrapQual << contigScores[i] << ' '; }
928 outScrapQual << endl;
933 if((num) % 1000 == 0){ m->mothurOut(toString(num)); m->mothurOutEndLine(); }
937 if((num) % 1000 != 0){ m->mothurOut(toString(num)); m->mothurOutEndLine(); }
945 outScrapFasta.close();
946 outScrapQual.close();
950 if (m->control_pressed) { m->mothurRemove(outputQual); m->mothurRemove(outputFasta); m->mothurRemove(outputScrapQual); m->mothurRemove(outputScrapFasta);m->mothurRemove(outputMisMatches);}
954 catch(exception& e) {
955 m->errorOut(e, "MakeContigsCommand", "driver");
959 //**********************************************************************************************************************
960 vector< vector<string> > MakeContigsCommand::readFastqFiles(unsigned long int& count){
962 vector< vector<string> > files;
964 //maps processors number to file pointer
965 map<int, vector<ofstream*> > tempfiles; //tempfiles[0] = forwardFasta, [1] = forwardQual, [2] = reverseFasta, [3] = reverseQual
966 map<int, vector<ofstream*> >::iterator it;
968 //create files to write to
969 for (int i = 0; i < processors; i++) {
970 vector<ofstream*> temp;
971 ofstream* outFF = new ofstream; temp.push_back(outFF);
972 ofstream* outFQ = new ofstream; temp.push_back(outFQ);
973 ofstream* outRF = new ofstream; temp.push_back(outRF);
974 ofstream* outRQ = new ofstream; temp.push_back(outRQ);
977 vector<string> names;
978 string ffastafilename = outputDir + m->getRootName(m->getSimpleName(ffastqfile)) + toString(i) + "ffasta.temp";
979 string rfastafilename = outputDir + m->getRootName(m->getSimpleName(rfastqfile)) + toString(i) + "rfasta.temp";
980 string fqualfilename = outputDir + m->getRootName(m->getSimpleName(ffastqfile)) + toString(i) + "fqual.temp";
981 string rqualfilename = outputDir + m->getRootName(m->getSimpleName(rfastqfile)) + toString(i) + "rqual.temp";
982 names.push_back(ffastafilename); names.push_back(fqualfilename);
983 names.push_back(rfastafilename); names.push_back(rqualfilename);
984 files.push_back(names);
986 m->openOutputFile(ffastafilename, *outFF);
987 m->openOutputFile(rfastafilename, *outRF);
988 m->openOutputFile(fqualfilename, *outFQ);
989 m->openOutputFile(rqualfilename, *outRQ);
992 if (m->control_pressed) {
993 //close files, delete ofstreams
994 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]; } }
996 for (int i = 0; i < files.size(); i++) {
997 for(int j = 0; j < files[i].size(); j++) { m->mothurRemove(files[i][j]); }
1002 m->openInputFile(ffastqfile, inForward);
1005 m->openInputFile(rfastqfile, inReverse);
1008 map<string, fastqRead> uniques;
1009 map<string, fastqRead>::iterator itUniques;
1010 while ((!inForward.eof()) || (!inReverse.eof())) {
1012 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; }
1014 //get a read from forward and reverse fastq files
1015 bool ignoref, ignorer;
1016 fastqRead thisFread, thisRread;
1017 if (!inForward.eof()) { thisFread = readFastq(inForward, ignoref); }
1018 else { ignoref = true; }
1019 if (!inReverse.eof()) { thisRread = readFastq(inReverse, ignorer); }
1020 else { ignorer = true; }
1022 vector<pairFastqRead> reads = getReads(ignoref, ignorer, thisFread, thisRread, uniques);
1024 for (int i = 0; i < reads.size(); i++) {
1025 fastqRead fread = reads[i].forward;
1026 fastqRead rread = reads[i].reverse;
1028 if (m->debug) { m->mothurOut(toString(count) + '\t' + fread.name + '\t' + rread.name + '\n'); }
1030 if (checkReads(fread, rread)) {
1031 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; }
1033 //if the reads are okay write to output files
1034 int process = count % processors;
1036 *(tempfiles[process][0]) << ">" << fread.name << endl << fread.sequence << endl;
1037 *(tempfiles[process][1]) << ">" << fread.name << endl;
1038 for (int i = 0; i < fread.scores.size(); i++) { *(tempfiles[process][1]) << fread.scores[i] << " "; }
1039 *(tempfiles[process][1]) << endl;
1040 *(tempfiles[process][2]) << ">" << rread.name << endl << rread.sequence << endl;
1041 *(tempfiles[process][3]) << ">" << rread.name << endl;
1042 for (int i = 0; i < rread.scores.size(); i++) { *(tempfiles[process][3]) << rread.scores[i] << " "; }
1043 *(tempfiles[process][3]) << endl;
1048 if((count) % 10000 == 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
1053 if((count) % 10000 != 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
1055 if (uniques.size() != 0) {
1056 for (itUniques = uniques.begin(); itUniques != uniques.end(); itUniques++) {
1057 m->mothurOut("[WARNING]: did not find paired read for " + itUniques->first + ", ignoring.\n");
1059 m->mothurOutEndLine();
1062 //close files, delete ofstreams
1063 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]; } }
1067 //adjust for really large processors or really small files
1068 if (count == 0) { m->mothurOut("[ERROR]: no good reads.\n"); m->control_pressed = true; }
1069 if (count < processors) {
1070 for (int i = count; i < processors; i++) { for(int j = 0; j < files[i].size(); j++) { m->mothurRemove(files[i][j]); } files[i].clear(); }
1071 files.resize(count);
1077 catch(exception& e) {
1078 m->errorOut(e, "MakeContigsCommand", "readFastqFiles");
1082 //**********************************************************************************************************************
1083 vector<pairFastqRead> MakeContigsCommand::getReads(bool ignoref, bool ignorer, fastqRead forward, fastqRead reverse, map<string, fastqRead>& uniques){
1085 vector<pairFastqRead> reads;
1086 map<string, fastqRead>::iterator itUniques;
1088 if (!ignoref && !ignorer) {
1089 if (forward.name == reverse.name) {
1090 pairFastqRead temp(forward, reverse);
1091 reads.push_back(temp);
1094 //if no match are the names only different by 1 and 2?
1095 string tempFRead = forward.name.substr(0, forward.name.length()-1);
1096 string tempRRead = reverse.name.substr(0, reverse.name.length()-1);
1097 if (tempFRead == tempRRead) {
1098 if ((forward.name[forward.name.length()-1] == '1') && (reverse.name[reverse.name.length()-1] == '2')) {
1099 forward.name = tempFRead;
1100 reverse.name = tempRRead;
1101 pairFastqRead temp(forward, reverse);
1102 reads.push_back(temp);
1108 //look for forward pair
1109 itUniques = uniques.find(forward.name);
1110 if (itUniques != uniques.end()) { //we have the pair for this read
1111 pairFastqRead temp(forward, itUniques->second);
1112 reads.push_back(temp);
1113 uniques.erase(itUniques);
1114 }else { //save this read for later
1115 uniques[forward.name] = forward;
1118 //look for reverse pair
1119 itUniques = uniques.find(reverse.name);
1120 if (itUniques != uniques.end()) { //we have the pair for this read
1121 pairFastqRead temp(itUniques->second, reverse);
1122 reads.push_back(temp);
1123 uniques.erase(itUniques);
1124 }else { //save this read for later
1125 uniques[reverse.name] = reverse;
1130 }else if (!ignoref && ignorer) { //ignore reverse keep forward
1131 //look for forward pair
1132 itUniques = uniques.find(forward.name);
1133 if (itUniques != uniques.end()) { //we have the pair for this read
1134 pairFastqRead temp(forward, itUniques->second);
1135 reads.push_back(temp);
1136 uniques.erase(itUniques);
1137 }else { //save this read for later
1138 uniques[forward.name] = forward;
1141 }else if (ignoref && !ignorer) { //ignore forward keep reverse
1142 //look for reverse pair
1143 itUniques = uniques.find(reverse.name);
1144 if (itUniques != uniques.end()) { //we have the pair for this read
1145 pairFastqRead temp(itUniques->second, reverse);
1146 reads.push_back(temp);
1147 uniques.erase(itUniques);
1148 }else { //save this read for later
1149 uniques[reverse.name] = reverse;
1151 }//else ignore both and do nothing
1155 catch(exception& e) {
1156 m->errorOut(e, "MakeContigsCommand", "readFastqFiles");
1160 //**********************************************************************************************************************
1161 fastqRead MakeContigsCommand::readFastq(ifstream& in, bool& ignore){
1167 //read sequence name
1168 string line = m->getline(in); m->gobble(in);
1169 vector<string> pieces = m->splitWhiteSpace(line);
1170 string name = ""; if (pieces.size() != 0) { name = pieces[0]; }
1171 if (name == "") { m->mothurOut("[WARNING]: Blank fasta name, ignoring read."); m->mothurOutEndLine(); ignore=true; }
1172 else if (name[0] != '@') { m->mothurOut("[WARNING]: reading " + name + " expected a name with @ as a leading character, ignoring read."); m->mothurOutEndLine(); ignore=true; }
1173 else { name = name.substr(1); }
1176 string sequence = m->getline(in); m->gobble(in);
1177 if (sequence == "") { m->mothurOut("[WARNING]: missing sequence for " + name + ", ignoring."); ignore=true; }
1179 //read sequence name
1180 line = m->getline(in); m->gobble(in);
1181 pieces = m->splitWhiteSpace(line);
1182 string name2 = ""; if (pieces.size() != 0) { name2 = pieces[0]; }
1183 if (name2 == "") { m->mothurOut("[WARNING]: expected a name with + as a leading character, ignoring."); ignore=true; }
1184 else if (name2[0] != '+') { m->mothurOut("[WARNING]: reading " + name2 + " expected a name with + as a leading character, ignoring."); ignore=true; }
1185 else { name2 = name2.substr(1); if (name2 == "") { name2 = name; } }
1187 //read quality scores
1188 string quality = m->getline(in); m->gobble(in);
1189 if (quality == "") { m->mothurOut("[WARNING]: missing quality for " + name2 + ", ignoring."); ignore=true; }
1191 //sanity check sequence length and number of quality scores match
1192 if (name2 != "") { if (name != name2) { m->mothurOut("[WARNING]: names do not match. read " + name + " for fasta and " + name2 + " for quality, ignoring."); ignore=true; } }
1193 if (quality.length() != sequence.length()) { m->mothurOut("[WARNING]: Lengths do not match for sequence " + name + ". Read " + toString(sequence.length()) + " characters for fasta and " + toString(quality.length()) + " characters for quality scores, ignoring read."); ignore=true; }
1195 vector<int> qualScores;
1196 int controlChar = int('!');
1197 for (int i = 0; i < quality.length(); i++) {
1198 int temp = int(quality[i]);
1199 temp -= controlChar;
1201 qualScores.push_back(temp);
1205 read.sequence = sequence;
1206 read.scores = qualScores;
1210 catch(exception& e) {
1211 m->errorOut(e, "MakeContigsCommand", "readFastq");
1215 //**********************************************************************************************************************
1216 bool MakeContigsCommand::checkReads(fastqRead& forward, fastqRead& reverse){
1220 //do sequence lengths match
1221 if (forward.sequence.length() != reverse.sequence.length()) {
1222 m->mothurOut("[WARNING]: 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 + ", ignoring.\n");
1226 //do number of qual scores match
1227 if (forward.scores.size() != reverse.scores.size()) {
1228 m->mothurOut("[WARNING]: For sequence " + forward.name + " I read " + toString(forward.scores.size()) + " quality scores from " + ffastqfile + ", but read " + toString(reverse.scores.size()) + " quality scores from " + rfastqfile + ", ignoring.\n");
1234 catch(exception& e) {
1235 m->errorOut(e, "MakeContigsCommand", "checkReads");
1239 //***************************************************************************************************************
1240 //illumina data requires paired forward and reverse data
1241 //BARCODE atgcatgc atgcatgc groupName
1242 //PRIMER atgcatgc atgcatgc groupName
1243 //PRIMER atgcatgc atgcatgc
1244 bool MakeContigsCommand::getOligos(vector<vector<string> >& fastaFileNames, vector<vector<string> >& qualFileNames){
1247 m->openInputFile(oligosfile, in);
1251 string type, foligo, roligo, group;
1253 int indexPrimer = 0;
1254 int indexBarcode = 0;
1255 set<string> uniquePrimers;
1256 set<string> uniqueBarcodes;
1262 if (m->debug) { m->mothurOut("[DEBUG]: reading type - " + type + ".\n"); }
1265 while (!in.eof()) { char c = in.get(); if (c == 10 || c == 13){ break; } } // get rest of line if there's any crap there
1270 //make type case insensitive
1271 for(int i=0;i<type.length();i++){ type[i] = toupper(type[i]); }
1275 if (m->debug) { m->mothurOut("[DEBUG]: reading - " + foligo + ".\n"); }
1277 for(int i=0;i<foligo.length();i++){
1278 foligo[i] = toupper(foligo[i]);
1279 if(foligo[i] == 'U') { foligo[i] = 'T'; }
1282 if(type == "FORWARD"){
1287 for(int i=0;i<roligo.length();i++){
1288 roligo[i] = toupper(roligo[i]);
1289 if(roligo[i] == 'U') { roligo[i] = 'T'; }
1291 //roligo = reverseOligo(roligo);
1295 // get rest of line in case there is a primer name
1298 if (c == 10 || c == 13){ break; }
1299 else if (c == 32 || c == 9){;} //space or tab
1300 else { group += c; }
1303 oligosPair newPrimer(foligo, roligo);
1305 //check for repeat barcodes
1306 string tempPair = foligo+roligo;
1307 if (uniquePrimers.count(tempPair) != 0) { m->mothurOut("primer pair " + newPrimer.forward + " " + newPrimer.reverse + " is in your oligos file already."); m->mothurOutEndLine(); }
1308 else { uniquePrimers.insert(tempPair); }
1310 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"); } }
1312 primers[indexPrimer]=newPrimer; indexPrimer++;
1313 primerNameVector.push_back(group);
1314 }else if(type == "BARCODE"){
1319 for(int i=0;i<roligo.length();i++){
1320 roligo[i] = toupper(roligo[i]);
1321 if(roligo[i] == 'U') { roligo[i] = 'T'; }
1323 //roligo = reverseOligo(roligo);
1325 oligosPair newPair(foligo, roligo);
1330 if (c == 10 || c == 13){ break; }
1331 else if (c == 32 || c == 9){;} //space or tab
1332 else { group += c; }
1335 if (m->debug) { m->mothurOut("[DEBUG]: barcode pair " + newPair.forward + " " + newPair.reverse + ", and group = " + group + ".\n"); }
1337 //check for repeat barcodes
1338 string tempPair = foligo+roligo;
1339 if (uniqueBarcodes.count(tempPair) != 0) { m->mothurOut("barcode pair " + newPair.forward + " " + newPair.reverse + " is in your oligos file already, disregarding."); m->mothurOutEndLine(); }
1340 else { uniqueBarcodes.insert(tempPair); }
1342 barcodes[indexBarcode]=newPair; indexBarcode++;
1343 barcodeNameVector.push_back(group);
1344 }else if(type == "LINKER"){
1345 linker.push_back(foligo);
1346 m->mothurOut("[WARNING]: make.contigs is not setup to remove linkers, ignoring.\n");
1347 }else if(type == "SPACER"){
1348 spacer.push_back(foligo);
1349 m->mothurOut("[WARNING]: make.contigs is not setup to remove spacers, ignoring.\n");
1351 else{ m->mothurOut("[WARNING]: " + type + " is not recognized as a valid type. Choices are primer, barcode, linker and spacer. Ignoring " + foligo + "."); m->mothurOutEndLine(); }
1357 if(barcodeNameVector.size() == 0 && primerNameVector[0] == ""){ allFiles = 0; }
1359 //add in potential combos
1360 if(barcodeNameVector.size() == 0){
1361 oligosPair temp("", "");
1363 barcodeNameVector.push_back("");
1366 if(primerNameVector.size() == 0){
1367 oligosPair temp("", "");
1369 primerNameVector.push_back("");
1372 fastaFileNames.resize(barcodeNameVector.size());
1373 for(int i=0;i<fastaFileNames.size();i++){
1374 fastaFileNames[i].assign(primerNameVector.size(), "");
1376 qualFileNames = fastaFileNames;
1379 set<string> uniqueNames; //used to cleanup outputFileNames
1380 for(map<int, oligosPair>::iterator itBar = barcodes.begin();itBar != barcodes.end();itBar++){
1381 for(map<int, oligosPair>::iterator itPrimer = primers.begin();itPrimer != primers.end(); itPrimer++){
1383 string primerName = primerNameVector[itPrimer->first];
1384 string barcodeName = barcodeNameVector[itBar->first];
1386 string comboGroupName = "";
1387 string fastaFileName = "";
1388 string qualFileName = "";
1389 string nameFileName = "";
1390 string countFileName = "";
1392 if(primerName == ""){
1393 comboGroupName = barcodeNameVector[itBar->first];
1396 if(barcodeName == ""){
1397 comboGroupName = primerNameVector[itPrimer->first];
1400 comboGroupName = barcodeNameVector[itBar->first] + "." + primerNameVector[itPrimer->first];
1406 fastaFileName = outputDir + m->getRootName(m->getSimpleName(ffastqfile)) + comboGroupName + ".fasta";
1407 if (uniqueNames.count(fastaFileName) == 0) {
1408 outputNames.push_back(fastaFileName);
1409 outputTypes["fasta"].push_back(fastaFileName);
1410 uniqueNames.insert(fastaFileName);
1413 fastaFileNames[itBar->first][itPrimer->first] = fastaFileName;
1414 m->openOutputFile(fastaFileName, temp); temp.close();
1417 qualFileName = outputDir + m->getRootName(m->getSimpleName(ffastqfile)) + comboGroupName + ".qual";
1418 if (uniqueNames.count(qualFileName) == 0) {
1419 outputNames.push_back(qualFileName);
1420 outputTypes["qfile"].push_back(qualFileName);
1423 qualFileNames[itBar->first][itPrimer->first] = qualFileName;
1424 m->openOutputFile(qualFileName, temp); temp.close();
1429 bool allBlank = true;
1430 for (int i = 0; i < barcodeNameVector.size(); i++) {
1431 if (barcodeNameVector[i] != "") {
1436 for (int i = 0; i < primerNameVector.size(); i++) {
1437 if (primerNameVector[i] != "") {
1444 m->mothurOut("[WARNING]: your oligos file does not contain any group names. mothur will not create a groupfile."); m->mothurOutEndLine();
1452 catch(exception& e) {
1453 m->errorOut(e, "MakeContigsCommand", "getOligos");
1457 //********************************************************************/
1458 string MakeContigsCommand::reverseOligo(string oligo){
1460 string reverse = "";
1462 for(int i=oligo.length()-1;i>=0;i--){
1464 if(oligo[i] == 'A') { reverse += 'T'; }
1465 else if(oligo[i] == 'T'){ reverse += 'A'; }
1466 else if(oligo[i] == 'U'){ reverse += 'A'; }
1468 else if(oligo[i] == 'G'){ reverse += 'C'; }
1469 else if(oligo[i] == 'C'){ reverse += 'G'; }
1471 else if(oligo[i] == 'R'){ reverse += 'Y'; }
1472 else if(oligo[i] == 'Y'){ reverse += 'R'; }
1474 else if(oligo[i] == 'M'){ reverse += 'K'; }
1475 else if(oligo[i] == 'K'){ reverse += 'M'; }
1477 else if(oligo[i] == 'W'){ reverse += 'W'; }
1478 else if(oligo[i] == 'S'){ reverse += 'S'; }
1480 else if(oligo[i] == 'B'){ reverse += 'V'; }
1481 else if(oligo[i] == 'V'){ reverse += 'B'; }
1483 else if(oligo[i] == 'D'){ reverse += 'H'; }
1484 else if(oligo[i] == 'H'){ reverse += 'D'; }
1486 else { reverse += 'N'; }
1492 catch(exception& e) {
1493 m->errorOut(e, "MakeContigsCommand", "reverseOligo");
1497 //**********************************************************************************************************************