]> git.donarmstrong.com Git - mothur.git/blob - makecontigscommand.cpp
added list.labels command. started work on make.contigs command. fixed fastq.info...
[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         vector< vector<string> > files = readFastqFiles();  
176         
177         
178         
179         string currentFasta = "";
180                 itTypes = outputTypes.find("fasta");
181                 if (itTypes != outputTypes.end()) {
182                         if ((itTypes->second).size() != 0) { currentFasta = (itTypes->second)[0]; m->setFastaFile(currentFasta); }
183                 }
184         
185         string currentQual = "";
186                 itTypes = outputTypes.find("qfile");
187                 if (itTypes != outputTypes.end()) {
188                         if ((itTypes->second).size() != 0) { currentQual = (itTypes->second)[0]; m->setQualFile(currentQual); }
189                 }
190                 
191         //output files created by command
192                 m->mothurOutEndLine();
193                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
194                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
195                 m->mothurOutEndLine();
196
197         
198         return 0;
199     }
200         catch(exception& e) {
201                 m->errorOut(e, "MakeContigsCommand", "execute");
202                 exit(1);
203         }
204 }
205 //**********************************************************************************************************************
206 vector< vector<string> > MakeContigsCommand::readFastqFiles(){
207     try {
208         vector< vector<string> > files;
209         
210         //maps processors number to file pointer
211         map<int, vector<ofstream*> > tempfiles;  //tempfiles[0] = forwardFasta, [1] = forwardQual, [2] = reverseFasta, [3] = reverseQual
212         map<int, vector<ofstream*> >::iterator it;
213         
214         //create files to write to
215         for (int i = 0; i < processors; i++) {
216             vector<ofstream*> temp;
217             ofstream* outFF = new ofstream;     temp.push_back(outFF);
218             ofstream* outFQ = new ofstream;     temp.push_back(outFQ);
219             ofstream* outRF = new ofstream;     temp.push_back(outRF);
220             ofstream* outRQ = new ofstream;     temp.push_back(outRQ);
221             tempfiles[i] = temp;
222             
223             vector<string> names;
224             string ffastafilename = outputDir + m->getRootName(m->getSimpleName(ffastqfile)) + toString(i) + "ffasta.temp";
225             string rfastafilename = outputDir + m->getRootName(m->getSimpleName(rfastqfile)) + toString(i) + "rfasta.temp";
226             string fqualfilename = outputDir + m->getRootName(m->getSimpleName(ffastqfile)) + toString(i) + "fqual.temp";
227             string rqualfilename = outputDir + m->getRootName(m->getSimpleName(rfastqfile)) + toString(i) + "rqual.temp";
228             names.push_back(ffastafilename); names.push_back(fqualfilename);
229             names.push_back(rfastafilename); names.push_back(rqualfilename);
230             files.push_back(names);
231             
232             m->openOutputFile(ffastafilename, *outFF);
233             m->openOutputFile(rfastafilename, *outRF);
234             m->openOutputFile(fqualfilename, *outFQ);
235             m->openOutputFile(rqualfilename, *outRQ);
236         }
237         
238         if (m->control_pressed) {
239             //close files, delete ofstreams
240             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]; } }
241             //remove files
242             for (int i = 0; i < files.size(); i++) {  
243                 for(int j = 0; j < files[i].size(); j++) { m->mothurRemove(files[i][j]); }
244             }
245         }
246         
247         ifstream inForward;
248         m->openInputFile(ffastqfile, inForward);
249         
250         ifstream inReverse;
251         m->openInputFile(rfastqfile, inReverse);
252         
253         int count = 0;
254         while ((!inForward.eof()) && (!inReverse.eof())) {
255             
256             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; }
257             
258             //get a read from forward and reverse fastq files
259             fastqRead fread = readFastq(inForward);
260             fastqRead rread = readFastq(inReverse);
261             checkReads(fread, rread);
262             
263             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; }
264             
265             //if the reads are okay write to output files
266             int process = count % processors;
267             
268             *(tempfiles[process][0]) << ">" << fread.name << endl << fread.sequence << endl;
269             *(tempfiles[process][1]) << ">" << fread.name << endl;
270             for (int i = 0; i < fread.scores.size(); i++) { *(tempfiles[process][1]) << fread.scores[i] << " "; }
271             *(tempfiles[process][1]) << endl;
272             *(tempfiles[process][2]) << ">" << rread.name << endl << rread.sequence << endl;
273             *(tempfiles[process][3]) << ">" << rread.name << endl;
274             for (int i = 0; i < rread.scores.size(); i++) { *(tempfiles[process][3]) << rread.scores[i] << " "; }
275             *(tempfiles[process][3]) << endl;
276             
277             count++;
278         }
279         
280         //close files, delete ofstreams
281         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]; } }
282         inForward.close();
283         inReverse.close();
284         
285         //adjust for really large processors or really small files
286         if (count < processors) { 
287             for (int i = count; i < processors; i++) { for(int j = 0; j < files[i].size(); j++) { m->mothurRemove(files[i][j]); } files[i].clear(); }
288             files.resize(count);
289             processors = count; 
290         }
291         
292         return files;
293     }
294     catch(exception& e) {
295         m->errorOut(e, "MakeContigsCommand", "readFastqFiles");
296         exit(1);
297     }
298 }
299
300 //**********************************************************************************************************************
301 fastqRead MakeContigsCommand::readFastq(ifstream& in){
302     try {
303         fastqRead read;
304         
305         //read sequence name
306         string name = m->getline(in); m->gobble(in);
307         if (name == "") {  m->mothurOut("[ERROR]: Blank fasta name."); m->mothurOutEndLine(); m->control_pressed = true; return read; }
308         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; }
309         else { name = name.substr(1); }
310         
311         //read sequence
312         string sequence = m->getline(in); m->gobble(in);
313         if (sequence == "") {  m->mothurOut("[ERROR]: missing sequence for " + name); m->mothurOutEndLine(); m->control_pressed = true; return read; }
314         
315         //read sequence name
316         string name2 = m->getline(in); m->gobble(in);
317         if (name2 == "") {  m->mothurOut("[ERROR]: Blank quality name."); m->mothurOutEndLine(); m->control_pressed = true; return read; }
318         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; }
319         else { name2 = name2.substr(1);  }
320         
321         //read quality scores
322         string quality = m->getline(in); m->gobble(in);
323         if (quality == "") {  m->mothurOut("[ERROR]: missing quality for " + name2); m->mothurOutEndLine(); m->control_pressed = true; return read; }
324         
325         //sanity check sequence length and number of quality scores match
326         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; } }
327         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; }
328         
329         vector<int> qualScores;
330                 int controlChar = int('@');
331                 for (int i = 0; i < quality.length(); i++) { 
332                         int temp = int(quality[i]);
333                         temp -= controlChar;
334                         
335                         qualScores.push_back(temp);
336                 }
337
338         read.name = name;
339         read.sequence = sequence;
340         read.scores = qualScores;
341
342         return read;
343     }
344     catch(exception& e) {
345         m->errorOut(e, "MakeContigsCommand", "readFastq");
346         exit(1);
347     }
348 }
349 //**********************************************************************************************************************
350 bool MakeContigsCommand::checkReads(fastqRead& forward, fastqRead& reverse){
351     try {
352         bool good = true;
353         
354         //fix names
355         if ((forward.name.length() > 2) && (reverse.name.length() > 2)) {
356             forward.name = forward.name.substr(0, forward.name.length()-2);
357             reverse.name = reverse.name.substr(0, reverse.name.length()-2);
358         }else { good = false; m->control_pressed = true; }
359         
360         //do names match
361         if (forward.name != reverse.name) {
362             m->mothurOut("[ERROR]: read " + forward.name + " from " + ffastqfile + ", but read " + reverse.name + " from " + rfastqfile + ".\n");
363             good = false; m->control_pressed = true;
364         }
365         
366         //do sequence lengths match
367         if (forward.sequence.length() != reverse.sequence.length()) {
368             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");
369             good = false; m->control_pressed = true;
370         }
371         
372         //do number of qual scores match 
373         if (forward.scores.size() != reverse.scores.size()) {
374             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");
375             good = false; m->control_pressed = true;
376         }
377
378         return good;
379     }
380     catch(exception& e) {
381         m->errorOut(e, "MakeContigsCommand", "readFastq");
382         exit(1);
383     }
384 }
385 //**********************************************************************************************************************
386
387
388
389