]> git.donarmstrong.com Git - mothur.git/blob - makecontigscommand.cpp
Merge branch 'master' of https://github.com/mothur/mothur.git
[mothur.git] / makecontigscommand.cpp
1 //
2 //  makecontigscommand.cpp
3 //  Mothur
4 //
5 //  Created by Sarah Westcott on 5/15/12.
6 //  Copyright (c) 2012 Schloss Lab. All rights reserved.
7 //
8
9 #include "makecontigscommand.h"
10
11 //**********************************************************************************************************************
12 vector<string> MakeContigsCommand::setParameters(){     
13         try {
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 palign("align", "Multiple", "needleman-gotoh-blast-noalign", "needleman", "", "", "",false,false); parameters.push_back(palign);
17                 CommandParameter pmatch("match", "Number", "", "1.0", "", "", "",false,false); parameters.push_back(pmatch);
18                 CommandParameter pmismatch("mismatch", "Number", "", "-1.0", "", "", "",false,false); parameters.push_back(pmismatch);
19                 CommandParameter pgapopen("gapopen", "Number", "", "-2.0", "", "", "",false,false); parameters.push_back(pgapopen);
20                 CommandParameter pgapextend("gapextend", "Number", "", "-1.0", "", "", "",false,false); parameters.push_back(pgapextend);
21                 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
22                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
23                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
24                 
25                 vector<string> myArray;
26                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
27                 return myArray;
28         }
29         catch(exception& e) {
30                 m->errorOut(e, "MakeContigsCommand", "setParameters");
31                 exit(1);
32         }
33 }
34 //**********************************************************************************************************************
35 string MakeContigsCommand::getHelpString(){     
36         try {
37                 string helpString = "";
38                 helpString += "The make.contigs command reads a forward fastq file and a reverse fastq file and outputs new fasta and quality files.\n";
39                 helpString += "The make.contigs command parameters are ffastq, rfastq, align, match, mismatch, gapopen, gapextend and processors.\n";
40                 helpString += "The ffastq and rfastq parameter is required.\n";
41                 helpString += "The align parameter allows you to specify the alignment method to use.  Your options are: gotoh, needleman, blast and noalign. The default is needleman.\n";
42                 helpString += "The match parameter allows you to specify the bonus for having the same base. The default is 1.0.\n";
43                 helpString += "The mistmatch parameter allows you to specify the penalty for having different bases.  The default is -1.0.\n";
44                 helpString += "The gapopen parameter allows you to specify the penalty for opening a gap in an alignment. The default is -2.0.\n";
45                 helpString += "The gapextend parameter allows you to specify the penalty for extending a gap in an alignment.  The default is -1.0.\n";
46         helpString += "The processors parameter allows you to specify how many processors you would like to use.  The default is 1. \n";
47         helpString += "The make.contigs command should be in the following format: \n";
48                 helpString += "make.contigs(ffastq=yourForwardFastqFile, rfastq=yourReverseFastqFile, align=yourAlignmentMethod) \n";
49                 helpString += "Note: No spaces between parameter labels (i.e. ffastq), '=' and parameters (i.e.yourForwardFastqFile).\n";
50                 return helpString;
51         }
52         catch(exception& e) {
53                 m->errorOut(e, "MakeContigsCommand", "getHelpString");
54                 exit(1);
55         }
56 }
57
58 //**********************************************************************************************************************
59 MakeContigsCommand::MakeContigsCommand(){       
60         try {
61                 abort = true; calledHelp = true; 
62                 setParameters();
63                 vector<string> tempOutNames;
64                 outputTypes["fasta"] = tempOutNames;
65                 outputTypes["qfile"] = tempOutNames;
66         }
67         catch(exception& e) {
68                 m->errorOut(e, "MakeContigsCommand", "MakeContigsCommand");
69                 exit(1);
70         }
71 }
72 //**********************************************************************************************************************
73 MakeContigsCommand::MakeContigsCommand(string option)  {
74         try {
75                 abort = false; calledHelp = false;   
76         
77                 //allow user to run help
78                 if(option == "help") { help(); abort = true; calledHelp = true; }
79                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
80                 
81                 else {
82                         vector<string> myArray = setParameters();
83                         
84                         OptionParser parser(option);
85                         map<string, string> parameters = parser.getParameters(); 
86                         
87                         ValidParameters validParameter("pairwise.seqs");
88                         map<string, string>::iterator it;
89                         
90                         //check to make sure all parameters are valid for command
91                         for (it = parameters.begin(); it != parameters.end(); it++) { 
92                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
93                         }
94                         
95                         //initialize outputTypes
96                         vector<string> tempOutNames;
97                         outputTypes["fasta"] = tempOutNames;
98                         outputTypes["qfile"] = tempOutNames;
99                         
100             
101                         //if the user changes the input directory command factory will send this info to us in the output parameter 
102                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
103                         if (inputDir == "not found"){   inputDir = "";          }
104                         else { 
105                                 string path;
106                 it = parameters.find("ffastq");
107                                 //user has given a template file
108                                 if(it != parameters.end()){ 
109                                         path = m->hasPath(it->second);
110                                         //if the user has not given a path then, add inputdir. else leave path alone.
111                                         if (path == "") {       parameters["ffastq"] = inputDir + it->second;           }
112                                 }
113                 
114                 it = parameters.find("rfastq");
115                                 //user has given a template file
116                                 if(it != parameters.end()){ 
117                                         path = m->hasPath(it->second);
118                                         //if the user has not given a path then, add inputdir. else leave path alone.
119                                         if (path == "") {       parameters["rfastq"] = inputDir + it->second;           }
120                                 }
121             }
122             
123             ffastqfile = validParameter.validFile(parameters, "ffastq", true);
124                         if (ffastqfile == "not open") { ffastqfile = ""; abort = true; }        
125                         else if (ffastqfile == "not found") { ffastqfile = ""; abort=true;  m->mothurOut("The ffastq parameter is required.\n"); }
126                         
127                         rfastqfile = validParameter.validFile(parameters, "rfastq", true);
128                         if (rfastqfile == "not open") { rfastqfile = ""; abort = true; }        
129                         else if (rfastqfile == "not found") { rfastqfile = ""; abort=true;  m->mothurOut("The rfastq parameter is required.\n"); }
130             
131             //if the user changes the output directory command factory will send this info to us in the output parameter 
132                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = m->hasPath(ffastqfile);             }
133                         
134
135                         //check for optional parameter and set defaults
136                         // ...at some point should added some additional type checking...
137                         string temp;
138                         temp = validParameter.validFile(parameters, "match", false);            if (temp == "not found"){       temp = "1.0";                   }
139                         m->mothurConvert(temp, match);  
140                         
141                         temp = validParameter.validFile(parameters, "mismatch", false);         if (temp == "not found"){       temp = "-1.0";                  }
142                         m->mothurConvert(temp, misMatch);  
143             if (misMatch > 0) { m->mothurOut("[ERROR]: mismatch must be negative.\n"); abort=true; }
144                         
145                         temp = validParameter.validFile(parameters, "gapopen", false);          if (temp == "not found"){       temp = "-2.0";                  }
146                         m->mothurConvert(temp, gapOpen);  
147             if (gapOpen > 0) { m->mothurOut("[ERROR]: gapopen must be negative.\n"); abort=true; }
148                         
149                         temp = validParameter.validFile(parameters, "gapextend", false);        if (temp == "not found"){       temp = "-1.0";                  }
150                         m->mothurConvert(temp, gapExtend); 
151             if (gapExtend > 0) { m->mothurOut("[ERROR]: gapextend must be negative.\n"); abort=true; }
152                         
153                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = m->getProcessors();      }
154                         m->setProcessors(temp);
155                         m->mothurConvert(temp, processors);
156                         
157                         align = validParameter.validFile(parameters, "align", false);           if (align == "not found"){      align = "needleman";    }
158                         if ((align != "needleman") && (align != "blast") && (align != "gotoh") && (align != "noalign")) { m->mothurOut(align + " is not a valid alignment method. Options are needleman, blast, gotoh and noalign. I will use needleman."); m->mothurOutEndLine(); align = "needleman"; }
159         }
160                 
161         }
162         catch(exception& e) {
163                 m->errorOut(e, "MakeContigsCommand", "MakeContigsCommand");
164                 exit(1);
165         }
166 }
167 //**********************************************************************************************************************
168 int MakeContigsCommand::execute(){
169         try {
170                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
171         
172         //read ffastq and rfastq files creating fasta and qual files.
173         //this function will create a forward and reverse, fasta and qual files for each processor.
174         //files has an entry for each processor. files[i][0] = forwardFasta, files[i][1] = forwardQual, files[i][2] = reverseFasta, files[i][3] = reverseQual
175         int numReads = 0;
176         m->mothurOut("Reading fastq data..."); cout.flush();
177         vector< vector<string> > files = readFastqFiles(numReads);  
178         m->mothurOut("Done.\n");
179         
180         
181        
182         
183         string currentFasta = "";
184                 itTypes = outputTypes.find("fasta");
185                 if (itTypes != outputTypes.end()) {
186                         if ((itTypes->second).size() != 0) { currentFasta = (itTypes->second)[0]; m->setFastaFile(currentFasta); }
187                 }
188         
189         string currentQual = "";
190                 itTypes = outputTypes.find("qfile");
191                 if (itTypes != outputTypes.end()) {
192                         if ((itTypes->second).size() != 0) { currentQual = (itTypes->second)[0]; m->setQualFile(currentQual); }
193                 }
194                 
195         //output files created by command
196                 m->mothurOutEndLine();
197                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
198                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
199                 m->mothurOutEndLine();
200
201         
202         return 0;
203     }
204         catch(exception& e) {
205                 m->errorOut(e, "MakeContigsCommand", "execute");
206                 exit(1);
207         }
208 }
209 //**********************************************************************************************************************
210 vector< vector<string> > MakeContigsCommand::readFastqFiles(int& count){
211     try {
212         vector< vector<string> > files;
213         
214         //maps processors number to file pointer
215         map<int, vector<ofstream*> > tempfiles;  //tempfiles[0] = forwardFasta, [1] = forwardQual, [2] = reverseFasta, [3] = reverseQual
216         map<int, vector<ofstream*> >::iterator it;
217         
218         //create files to write to
219         for (int i = 0; i < processors; i++) {
220             vector<ofstream*> temp;
221             ofstream* outFF = new ofstream;     temp.push_back(outFF);
222             ofstream* outFQ = new ofstream;     temp.push_back(outFQ);
223             ofstream* outRF = new ofstream;     temp.push_back(outRF);
224             ofstream* outRQ = new ofstream;     temp.push_back(outRQ);
225             tempfiles[i] = temp;
226             
227             vector<string> names;
228             string ffastafilename = outputDir + m->getRootName(m->getSimpleName(ffastqfile)) + toString(i) + "ffasta.temp";
229             string rfastafilename = outputDir + m->getRootName(m->getSimpleName(rfastqfile)) + toString(i) + "rfasta.temp";
230             string fqualfilename = outputDir + m->getRootName(m->getSimpleName(ffastqfile)) + toString(i) + "fqual.temp";
231             string rqualfilename = outputDir + m->getRootName(m->getSimpleName(rfastqfile)) + toString(i) + "rqual.temp";
232             names.push_back(ffastafilename); names.push_back(fqualfilename);
233             names.push_back(rfastafilename); names.push_back(rqualfilename);
234             files.push_back(names);
235             
236             m->openOutputFile(ffastafilename, *outFF);
237             m->openOutputFile(rfastafilename, *outRF);
238             m->openOutputFile(fqualfilename, *outFQ);
239             m->openOutputFile(rqualfilename, *outRQ);
240         }
241         
242         if (m->control_pressed) {
243             //close files, delete ofstreams
244             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]; } }
245             //remove files
246             for (int i = 0; i < files.size(); i++) {  
247                 for(int j = 0; j < files[i].size(); j++) { m->mothurRemove(files[i][j]); }
248             }
249         }
250         
251         ifstream inForward;
252         m->openInputFile(ffastqfile, inForward);
253         
254         ifstream inReverse;
255         m->openInputFile(rfastqfile, inReverse);
256         
257         count = 0;
258         while ((!inForward.eof()) && (!inReverse.eof())) {
259             
260             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; }
261             
262             //get a read from forward and reverse fastq files
263             fastqRead fread = readFastq(inForward);
264             fastqRead rread = readFastq(inReverse);
265             checkReads(fread, rread);
266             
267             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; }
268             
269             //if the reads are okay write to output files
270             int process = count % processors;
271             
272             *(tempfiles[process][0]) << ">" << fread.name << endl << fread.sequence << endl;
273             *(tempfiles[process][1]) << ">" << fread.name << endl;
274             for (int i = 0; i < fread.scores.size(); i++) { *(tempfiles[process][1]) << fread.scores[i] << " "; }
275             *(tempfiles[process][1]) << endl;
276             *(tempfiles[process][2]) << ">" << rread.name << endl << rread.sequence << endl;
277             *(tempfiles[process][3]) << ">" << rread.name << endl;
278             for (int i = 0; i < rread.scores.size(); i++) { *(tempfiles[process][3]) << rread.scores[i] << " "; }
279             *(tempfiles[process][3]) << endl;
280             
281             count++;
282             
283             //report progress
284                         if((count) % 10000 == 0){       m->mothurOut(toString(count)); m->mothurOutEndLine();           }
285                         
286                 }
287                 //report progress
288                 if((count) % 10000 != 0){       m->mothurOut(toString(count)); m->mothurOutEndLine();           }
289                 
290
291         
292         //close files, delete ofstreams
293         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]; } }
294         inForward.close();
295         inReverse.close();
296         
297         //adjust for really large processors or really small files
298         if (count < processors) { 
299             for (int i = count; i < processors; i++) { for(int j = 0; j < files[i].size(); j++) { m->mothurRemove(files[i][j]); } files[i].clear(); }
300             files.resize(count);
301             processors = count; 
302         }
303         
304         return files;
305     }
306     catch(exception& e) {
307         m->errorOut(e, "MakeContigsCommand", "readFastqFiles");
308         exit(1);
309     }
310 }
311
312 //**********************************************************************************************************************
313 fastqRead MakeContigsCommand::readFastq(ifstream& in){
314     try {
315         fastqRead read;
316         
317         //read sequence name
318         string name = m->getline(in); m->gobble(in);
319         if (name == "") {  m->mothurOut("[ERROR]: Blank fasta name."); m->mothurOutEndLine(); m->control_pressed = true; return read; }
320         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; }
321         else { name = name.substr(1); }
322         
323         //read sequence
324         string sequence = m->getline(in); m->gobble(in);
325         if (sequence == "") {  m->mothurOut("[ERROR]: missing sequence for " + name); m->mothurOutEndLine(); m->control_pressed = true; return read; }
326         
327         //read sequence name
328         string name2 = m->getline(in); m->gobble(in);
329         if (name2 == "") {  m->mothurOut("[ERROR]: Blank quality name."); m->mothurOutEndLine(); m->control_pressed = true; return read; }
330         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; }
331         else { name2 = name2.substr(1);  }
332         
333         //read quality scores
334         string quality = m->getline(in); m->gobble(in);
335         if (quality == "") {  m->mothurOut("[ERROR]: missing quality for " + name2); m->mothurOutEndLine(); m->control_pressed = true; return read; }
336         
337         //sanity check sequence length and number of quality scores match
338         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; } }
339         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; }
340         
341         vector<int> qualScores;
342                 int controlChar = int('@');
343                 for (int i = 0; i < quality.length(); i++) { 
344                         int temp = int(quality[i]);
345                         temp -= controlChar;
346                         
347                         qualScores.push_back(temp);
348                 }
349
350         read.name = name;
351         read.sequence = sequence;
352         read.scores = qualScores;
353
354         return read;
355     }
356     catch(exception& e) {
357         m->errorOut(e, "MakeContigsCommand", "readFastq");
358         exit(1);
359     }
360 }
361 //**********************************************************************************************************************
362 bool MakeContigsCommand::checkReads(fastqRead& forward, fastqRead& reverse){
363     try {
364         bool good = true;
365         
366         //fix names
367         if ((forward.name.length() > 2) && (reverse.name.length() > 2)) {
368             forward.name = forward.name.substr(0, forward.name.length()-2);
369             reverse.name = reverse.name.substr(0, reverse.name.length()-2);
370         }else { good = false; m->control_pressed = true; }
371         
372         //do names match
373         if (forward.name != reverse.name) {
374             m->mothurOut("[ERROR]: read " + forward.name + " from " + ffastqfile + ", but read " + reverse.name + " from " + rfastqfile + ".\n");
375             good = false; m->control_pressed = true;
376         }
377         
378         //do sequence lengths match
379         if (forward.sequence.length() != reverse.sequence.length()) {
380             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");
381             good = false; m->control_pressed = true;
382         }
383         
384         //do number of qual scores match 
385         if (forward.scores.size() != reverse.scores.size()) {
386             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");
387             good = false; m->control_pressed = true;
388         }
389
390         return good;
391     }
392     catch(exception& e) {
393         m->errorOut(e, "MakeContigsCommand", "readFastq");
394         exit(1);
395     }
396 }
397 //**********************************************************************************************************************
398
399
400
401