]> git.donarmstrong.com Git - mothur.git/blob - binsequencecommand.cpp
fixes while testing
[mothur.git] / binsequencecommand.cpp
1 /*
2  *  binsequencecommand.cpp
3  *  Mothur
4  *
5  *  Created by Sarah Westcott on 4/3/09.
6  *  Copyright 2009 Schloss Lab UMASS Amhers. All rights reserved.
7  *
8  */
9
10 #include "binsequencecommand.h"
11
12 //**********************************************************************************************************************
13 vector<string> BinSeqCommand::getValidParameters(){     
14         try {
15                 string AlignArray[] =  {"fasta","label","name", "group","outputdir","inputdir"};
16                 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
17                 return myArray;
18         }
19         catch(exception& e) {
20                 m->errorOut(e, "BinSeqCommand", "getValidParameters");
21                 exit(1);
22         }
23 }
24 //**********************************************************************************************************************
25 vector<string> BinSeqCommand::getRequiredParameters(){  
26         try {
27                 string AlignArray[] =  {"fasta"};
28                 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
29                 return myArray;
30         }
31         catch(exception& e) {
32                 m->errorOut(e, "BinSeqCommand", "getRequiredParameters");
33                 exit(1);
34         }
35 }
36 //**********************************************************************************************************************
37 vector<string> BinSeqCommand::getRequiredFiles(){       
38         try {
39                 string AlignArray[] =  {"list"};
40                 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
41                 return myArray;
42         }
43         catch(exception& e) {
44                 m->errorOut(e, "BinSeqCommand", "getRequiredFiles");
45                 exit(1);
46         }
47 }
48 //**********************************************************************************************************************
49 BinSeqCommand::BinSeqCommand(){ 
50         try {
51                 abort = true;
52                 //initialize outputTypes
53                 vector<string> tempOutNames;
54                 outputTypes["fasta"] = tempOutNames;
55         }
56         catch(exception& e) {
57                 m->errorOut(e, "BinSeqCommand", "BinSeqCommand");
58                 exit(1);
59         }
60 }
61 //**********************************************************************************************************************
62 BinSeqCommand::BinSeqCommand(string option) {
63         try {
64                 globaldata = GlobalData::getInstance();
65                 abort = false;
66                 allLines = 1;
67                 labels.clear();
68                 
69                 //allow user to run help
70                 if(option == "help") { help(); abort = true; }
71                 
72                 else {
73                         //valid paramters for this command
74                         string AlignArray[] =  {"fasta","label","name", "group","outputdir","inputdir"};
75                         vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
76                         
77                         OptionParser parser(option);
78                         map<string, string> parameters = parser.getParameters();
79                         
80                         ValidParameters validParameter;
81                         map<string, string>::iterator it;
82                 
83                         //check to make sure all parameters are valid for command
84                         for (it = parameters.begin(); it != parameters.end(); it++) { 
85                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
86                         }
87                         
88                         //initialize outputTypes
89                         vector<string> tempOutNames;
90                         outputTypes["fasta"] = tempOutNames;
91                         
92                         //if the user changes the output directory command factory will send this info to us in the output parameter 
93                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
94                                 outputDir = ""; 
95                                 outputDir += m->hasPath(globaldata->getListFile()); //if user entered a file with a path then preserve it       
96                         }
97
98                         
99                         //make sure the user has already run the read.otu command
100                         if (globaldata->getListFile() == "") { 
101                                 m->mothurOut("You must read a listfile before running the bin.seqs command."); 
102                                 m->mothurOutEndLine(); 
103                                 abort = true; 
104                         }
105                         
106                         //if the user changes the input directory command factory will send this info to us in the output parameter 
107                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
108                         if (inputDir == "not found"){   inputDir = "";          }
109                         else {
110                                 string path;
111                                 it = parameters.find("fasta");
112                                 //user has given a template file
113                                 if(it != parameters.end()){ 
114                                         path = m->hasPath(it->second);
115                                         //if the user has not given a path then, add inputdir. else leave path alone.
116                                         if (path == "") {       parameters["fasta"] = inputDir + it->second;            }
117                                 }
118                                 
119                                 it = parameters.find("name");
120                                 //user has given a template file
121                                 if(it != parameters.end()){ 
122                                         path = m->hasPath(it->second);
123                                         //if the user has not given a path then, add inputdir. else leave path alone.
124                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
125                                 }
126                                 
127                                 it = parameters.find("group");
128                                 //user has given a template file
129                                 if(it != parameters.end()){ 
130                                         path = m->hasPath(it->second);
131                                         //if the user has not given a path then, add inputdir. else leave path alone.
132                                         if (path == "") {       parameters["group"] = inputDir + it->second;            }
133                                 }
134                         }
135
136                         
137                         //check for required parameters
138                         fastafile = validParameter.validFile(parameters, "fasta", true);
139                         if (fastafile == "not found") { m->mothurOut("fasta is a required parameter for the bin.seqs command.");  m->mothurOutEndLine(); abort = true; }
140                         else if (fastafile == "not open") { abort = true; }     
141                 
142                         //check for optional parameter and set defaults
143                         // ...at some point should added some additional type checking...
144                         
145                         label = validParameter.validFile(parameters, "label", false);                   
146                         if (label == "not found") { label = ""; }
147                         else { 
148                                 if(label != "all") {  m->splitAtDash(label, labels);  allLines = 0;  }
149                                 else { allLines = 1;  }
150                         }
151                         
152                         //if the user has not specified any labels use the ones from read.otu
153                         if (label == "") {  
154                                 allLines = globaldata->allLines; 
155                                 labels = globaldata->labels; 
156                         }
157                         
158                         namesfile = validParameter.validFile(parameters, "name", true);
159                         if (namesfile == "not open") { abort = true; }  
160                         else if (namesfile == "not found") { namesfile = ""; }
161
162                         groupfile = validParameter.validFile(parameters, "group", true);
163                         if (groupfile == "not open") { abort = true; }
164                         else if (groupfile == "not found") { groupfile = ""; }
165                         
166                         if (abort == false) { 
167 //                              m->openInputFile(fastafile, in);
168                                 fasta = new FastaMap();
169                                 if (groupfile != "") {
170                                         groupMap = new GroupMap(groupfile);
171                                         
172                                         int error = groupMap->readMap();
173                                         if (error == 1) { delete groupMap; abort = true; }
174                                 }
175                         }
176         
177                 }
178         }
179         catch(exception& e) {
180                 m->errorOut(e, "BinSeqCommand", "BinSeqCommand");
181                 exit(1);
182         }
183 }
184 //**********************************************************************************************************************
185
186 void BinSeqCommand::help(){
187         try {
188                 m->mothurOut("The bin.seqs command can only be executed after a successful read.otu command of a listfile.\n");
189                 m->mothurOut("The bin.seqs command parameters are fasta, name, label and group.  The fasta parameter is required.\n");
190                 m->mothurOut("The label parameter allows you to select what distance levels you would like a output files created for, and are separated by dashes.\n");
191                 m->mothurOut("The bin.seqs command should be in the following format: bin.seqs(fasta=yourFastaFile, name=yourNamesFile, group=yourGroupFile, label=yourLabels).\n");
192                 m->mothurOut("Example bin.seqs(fasta=amazon.fasta, group=amazon.groups, name=amazon.names).\n");
193                 m->mothurOut("The default value for label is all lines in your inputfile.\n");
194                 m->mothurOut("The bin.seqs command outputs a .fasta file for each distance you specify appending the OTU number to each name.\n");
195                 m->mothurOut("If you provide a groupfile, then it also appends the sequences group to the name.\n");
196                 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n\n");
197         }
198         catch(exception& e) {
199                 m->errorOut(e, "BinSeqCommand", "help");
200                 exit(1);
201         }
202 }
203
204 //**********************************************************************************************************************
205
206 BinSeqCommand::~BinSeqCommand(){
207         //made new in execute
208         if (abort == false) {
209                 delete input;  globaldata->ginput = NULL;
210                 delete read;
211                 globaldata->gListVector = NULL;
212                 delete fasta;
213                 if (groupfile != "") {  delete groupMap;  globaldata->gGroupmap = NULL; }
214         }
215 }
216
217 //**********************************************************************************************************************
218
219 int BinSeqCommand::execute(){
220         try {
221                 if (abort == true) {    return 0;       }
222         
223                 int error = 0;
224                 
225                 //read fastafile
226                 fasta->readFastaFile(fastafile);
227                 
228                 
229                 //set format to list so input can get listvector
230 //              globaldata->setFormat("list");
231                 
232                 //if user gave a namesfile then use it
233                 if (namesfile != "") {
234                         readNamesFile();
235                 }
236                 
237                 //read list file
238                 read = new ReadOTUFile(globaldata->getListFile());      
239                 read->read(&*globaldata); 
240                 
241                 input = globaldata->ginput;
242                 list = globaldata->gListVector;
243                 string lastLabel = list->getLabel();
244                 
245                 if (m->control_pressed) {  return 0; }
246                 
247                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
248                 set<string> processedLabels;
249                 set<string> userLabels = labels;
250
251                                 
252                 while((list != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
253                         
254                         if(m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str());         } return 0; }   
255                         
256                         if(allLines == 1 || labels.count(list->getLabel()) == 1){
257                                 
258                                 error = process(list);  
259                                 if (error == 1) { for (int i = 0; i < outputNames.size(); i++) {        remove(outputNames[i].c_str());         } return 0; }   
260                                                         
261                                 processedLabels.insert(list->getLabel());
262                                 userLabels.erase(list->getLabel());
263                         }
264                         
265                         if ((m->anyLabelsToProcess(list->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
266                                 string saveLabel = list->getLabel();
267                                 
268                                 delete list;
269                                 list = input->getListVector(lastLabel);
270                                 
271                                 error = process(list);  
272                                 if (error == 1) { for (int i = 0; i < outputNames.size(); i++) {        remove(outputNames[i].c_str());         } return 0; }
273                                                                                                         
274                                 processedLabels.insert(list->getLabel());
275                                 userLabels.erase(list->getLabel());
276                                 
277                                 //restore real lastlabel to save below
278                                 list->setLabel(saveLabel);
279                         }
280                         
281                         lastLabel = list->getLabel();                   
282                         
283                         delete list;
284                         list = input->getListVector();
285                 }
286                 
287                 if(m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str());         } return 0; }   
288
289                 //output error messages about any remaining user labels
290                 set<string>::iterator it;
291                 bool needToRun = false;
292                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
293                         m->mothurOut("Your file does not include the label " + *it); 
294                         if (processedLabels.count(lastLabel) != 1) {
295                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
296                                 needToRun = true;
297                         }else {
298                                 m->mothurOut(". Please refer to " + lastLabel + ".");  m->mothurOutEndLine();
299                         }
300                 }
301                 
302                 //run last label if you need to
303                 if (needToRun == true)  {
304                         if (list != NULL) {             delete list;    }
305                         list = input->getListVector(lastLabel);
306                                 
307                         error = process(list);  
308                         if (error == 1) { for (int i = 0; i < outputNames.size(); i++) {        remove(outputNames[i].c_str());         } return 0; }
309                         
310                         delete list;  
311                 }
312                 
313                 if(m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str());         } return 0; }   
314
315                 m->mothurOutEndLine();
316                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
317                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
318                 m->mothurOutEndLine();
319
320                 
321                 return 0;
322         }
323         catch(exception& e) {
324                 m->errorOut(e, "BinSeqCommand", "execute");
325                 exit(1);
326         }
327 }
328
329 //**********************************************************************************************************************
330 void BinSeqCommand::readNamesFile() {
331         try {
332                 vector<string> dupNames;
333                 m->openInputFile(namesfile, inNames);
334                 
335                 string name, names, sequence;
336         
337                 while(inNames){
338                         inNames >> name;                        //read from first column  A
339                         inNames >> names;               //read from second column  A,B,C,D
340                         
341                         dupNames.clear();
342                         
343                         //parse names into vector
344                         m->splitAtComma(names, dupNames);
345                         
346                         //store names in fasta map
347                         sequence = fasta->getSequence(name);
348                         for (int i = 0; i < dupNames.size(); i++) {
349                                 fasta->push_back(dupNames[i], sequence);
350                         }
351                 
352                         m->gobble(inNames);
353                 }
354                 inNames.close();
355
356         }
357         catch(exception& e) {
358                 m->errorOut(e, "BinSeqCommand", "readNamesFile");
359                 exit(1);
360         }
361 }
362 //**********************************************************************************************************************
363 //return 1 if error, 0 otherwise
364 int BinSeqCommand::process(ListVector* list) {
365         try {
366                                 string binnames, name, sequence;
367                                 
368                                 string outputFileName = outputDir + m->getRootName(m->getSimpleName(globaldata->getListFile())) + list->getLabel() + ".fasta";
369                                 m->openOutputFile(outputFileName, out);
370                                 
371                                 //save to output list of output file names
372                                 outputNames.push_back(outputFileName);  outputTypes["fasta"].push_back(outputFileName);
373
374                                 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
375                                 
376                                 //for each bin in the list vector
377                                 for (int i = 0; i < list->size(); i++) {
378                                         
379                                         if (m->control_pressed) {  return 1; }
380                                         
381                                         binnames = list->get(i);
382                                         while (binnames.find_first_of(',') != -1) { 
383                                                 name = binnames.substr(0,binnames.find_first_of(','));
384                                                 binnames = binnames.substr(binnames.find_first_of(',')+1, binnames.length());
385                                                 
386                                                 //do work for that name
387                                                 sequence = fasta->getSequence(name);
388                                                 if (sequence != "not found") {
389                                                         //if you don't have groups
390                                                         if (groupfile == "") {
391                                                                 name = name + "|" + toString(i+1);
392                                                                 out << ">" << name << endl;
393                                                                 out << sequence << endl;
394                                                         }else {//if you do have groups
395                                                                 string group = groupMap->getGroup(name);
396                                                                 if (group == "not found") {  
397                                                                         m->mothurOut(name + " is missing from your group file. Please correct. ");  m->mothurOutEndLine();
398                                                                         return 1;
399                                                                 }else{
400                                                                         name = name + "|" + group + "|" + toString(i+1);
401                                                                         out << ">" << name << endl;
402                                                                         out << sequence << endl;
403                                                                 }
404                                                         }
405                                                 }else { 
406                                                         m->mothurOut(name + " is missing from your fasta or name file. Please correct. "); m->mothurOutEndLine();
407                                                         return 1;
408                                                 }
409                                                 
410                                         }
411                                         
412                                         //get last name
413                                         sequence = fasta->getSequence(binnames);
414                                         if (sequence != "not found") {
415                                                 //if you don't have groups
416                                                 if (groupfile == "") {
417                                                         binnames = binnames + "|" + toString(i+1);
418                                                         out << ">" << binnames << endl;
419                                                         out << sequence << endl;
420                                                 }else {//if you do have groups
421                                                         string group = groupMap->getGroup(binnames);
422                                                         if (group == "not found") {  
423                                                                 m->mothurOut(binnames + " is missing from your group file. Please correct. "); m->mothurOutEndLine();
424                                                                 return 1;
425                                                         }else{
426                                                                 binnames = binnames + "|" + group + "|" + toString(i+1);
427                                                                 out << ">" << binnames << endl;
428                                                                 out << sequence << endl;
429                                                         }
430                                                 }
431                                         }else { 
432                                                 m->mothurOut(binnames + " is missing from your fasta or name file. Please correct. "); m->mothurOutEndLine();
433                                                 return 1;
434                                         }
435                                 }
436                                         
437                                 out.close();
438                                 return 0;
439
440         }
441         catch(exception& e) {
442                 m->errorOut(e, "BinSeqCommand", "process");
443                 exit(1);
444         }
445 }
446 //**********************************************************************************************************************
447
448