]> git.donarmstrong.com Git - mothur.git/blob - getotuscommand.cpp
Merge remote-tracking branch 'mothur/master'
[mothur.git] / getotuscommand.cpp
1 /*
2  *  getotuscommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 11/10/10.
6  *  Copyright 2010 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "getotuscommand.h"
11 #include "inputdata.h"
12 #include "sharedutilities.h"
13
14
15 //**********************************************************************************************************************
16 vector<string> GetOtusCommand::setParameters(){ 
17         try {
18                 CommandParameter pgroup("group", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pgroup);
19                 CommandParameter plist("list", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(plist);
20                 CommandParameter paccnos("accnos", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(paccnos);
21                 CommandParameter pgroups("groups", "String", "", "", "", "", "",false,false); parameters.push_back(pgroups);
22                 CommandParameter plabel("label", "String", "", "", "", "", "",false,false); parameters.push_back(plabel);
23                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
24                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
25                 
26                 vector<string> myArray;
27                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
28                 return myArray;
29         }
30         catch(exception& e) {
31                 m->errorOut(e, "GetOtusCommand", "setParameters");
32                 exit(1);
33         }
34 }
35 //**********************************************************************************************************************
36 string GetOtusCommand::getHelpString(){ 
37         try {
38                 string helpString = "";
39                 helpString += "The get.otus command selects otus containing sequences from a specfic group or set of groups.\n";
40                 helpString += "It outputs a new list file containing the otus containing sequences from in the those specified groups.\n";
41                 helpString += "The get.otus command parameters are accnos, group, list, label and groups. The group and list parameters are required, unless you have valid current files.\n";
42                 helpString += "You must also provide an accnos containing the list of groups to get or set the groups parameter to the groups you wish to select.\n";
43                 helpString += "The groups parameter allows you to specify which of the groups in your groupfile you would like.  You can separate group names with dashes.\n";
44                 helpString += "The label parameter allows you to specify which distance you want to process.\n";
45                 helpString += "The get.otus command should be in the following format: get.otus(accnos=yourAccnos, list=yourListFile, group=yourGroupFile, label=yourLabel).\n";
46                 helpString += "Example get.otus(accnos=amazon.accnos, list=amazon.fn.list, group=amazon.groups, label=0.03).\n";
47                 helpString += "or get.otus(groups=pasture, list=amazon.fn.list, amazon.groups, label=0.03).\n";
48                 helpString += "Note: No spaces between parameter labels (i.e. list), '=' and parameters (i.e.yourListFile).\n";
49                 return helpString;
50         }
51         catch(exception& e) {
52                 m->errorOut(e, "GetOtusCommand", "getHelpString");
53                 exit(1);
54         }
55 }
56 //**********************************************************************************************************************
57 string GetOtusCommand::getOutputFileNameTag(string type, string inputName=""){  
58         try {
59         string outputFileName = "";
60                 map<string, vector<string> >::iterator it;
61         
62         //is this a type this command creates
63         it = outputTypes.find(type);
64         if (it == outputTypes.end()) {  m->mothurOut("[ERROR]: this command doesn't create a " + type + " output file.\n"); }
65         else {
66             if (type == "group")            {   outputFileName = "pick" + m->getExtension(inputName);  }
67             else if (type == "list")        {   outputFileName = "pick" + m->getExtension(inputName);  }
68             else { m->mothurOut("[ERROR]: No definition for type " + type + " output file tag.\n"); m->control_pressed = true;  }
69         }
70         return outputFileName;
71         }
72         catch(exception& e) {
73                 m->errorOut(e, "GetOtusCommand", "getOutputFileNameTag");
74                 exit(1);
75         }
76 }
77 //**********************************************************************************************************************
78 GetOtusCommand::GetOtusCommand(){       
79         try {
80                 abort = true; calledHelp = true;
81                 setParameters();
82                 vector<string> tempOutNames;
83                 outputTypes["group"] = tempOutNames;
84                 outputTypes["list"] = tempOutNames;
85         }
86         catch(exception& e) {
87                 m->errorOut(e, "GetOtusCommand", "GetOtusCommand");
88                 exit(1);
89         }
90 }
91 //**********************************************************************************************************************
92 GetOtusCommand::GetOtusCommand(string option)  {
93         try {
94                 abort = false; calledHelp = false;   
95                 
96                 //allow user to run help
97                 if(option == "help") { help(); abort = true; calledHelp = true; }
98                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
99                 
100                 else {
101                         vector<string> myArray = setParameters();
102                         
103                         OptionParser parser(option);
104                         map<string,string> parameters = parser.getParameters();
105                         
106                         ValidParameters validParameter;
107                         map<string,string>::iterator it;
108                         
109                         //check to make sure all parameters are valid for command
110                         for (it = parameters.begin(); it != parameters.end(); it++) { 
111                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
112                         }
113                         
114                         //initialize outputTypes
115                         vector<string> tempOutNames;
116                         outputTypes["group"] = tempOutNames;
117                         outputTypes["list"] = tempOutNames;
118                         
119                         
120                         //if the user changes the output directory command factory will send this info to us in the output parameter 
121                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = "";         }
122                         
123                         //if the user changes the input directory command factory will send this info to us in the output parameter 
124                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
125                         if (inputDir == "not found"){   inputDir = "";          }
126                         else {
127                                 string path;
128                                 it = parameters.find("accnos");
129                                 //user has given a template file
130                                 if(it != parameters.end()){ 
131                                         path = m->hasPath(it->second);
132                                         //if the user has not given a path then, add inputdir. else leave path alone.
133                                         if (path == "") {       parameters["accnos"] = inputDir + it->second;           }
134                                 }
135                                 
136                                 it = parameters.find("list");
137                                 //user has given a template file
138                                 if(it != parameters.end()){ 
139                                         path = m->hasPath(it->second);
140                                         //if the user has not given a path then, add inputdir. else leave path alone.
141                                         if (path == "") {       parameters["list"] = inputDir + it->second;             }
142                                 }
143                                 
144                                 it = parameters.find("group");
145                                 //user has given a template file
146                                 if(it != parameters.end()){ 
147                                         path = m->hasPath(it->second);
148                                         //if the user has not given a path then, add inputdir. else leave path alone.
149                                         if (path == "") {       parameters["group"] = inputDir + it->second;            }
150                                 }
151                         }
152                         
153                         
154                         //check for required parameters
155                         accnosfile = validParameter.validFile(parameters, "accnos", true);
156                         if (accnosfile == "not open") { abort = true; }
157                         else if (accnosfile == "not found") {  accnosfile = ""; }
158                         else { m->setAccnosFile(accnosfile); }
159                         
160                         groupfile = validParameter.validFile(parameters, "group", true);
161                         if (groupfile == "not open") { abort = true; }
162                         else if (groupfile == "not found") {                            
163                                 groupfile = m->getGroupFile(); 
164                                 if (groupfile != "") { m->mothurOut("Using " + groupfile + " as input file for the group parameter."); m->mothurOutEndLine(); }
165                                 else {  m->mothurOut("You have no current group file and the group parameter is required."); m->mothurOutEndLine(); abort = true; }
166                         }else { m->setGroupFile(groupfile); }   
167                         
168                         listfile = validParameter.validFile(parameters, "list", true);
169                         if (listfile == "not open") { abort = true; }
170                         else if (listfile == "not found") {                             
171                                 listfile = m->getListFile(); 
172                                 if (listfile != "") { m->mothurOut("Using " + listfile + " as input file for the list parameter."); m->mothurOutEndLine(); }
173                                 else {  m->mothurOut("You have no current list file and the list parameter is required."); m->mothurOutEndLine(); abort = true; }
174                         }else { m->setListFile(listfile); }     
175                         
176                         groups = validParameter.validFile(parameters, "groups", false);                 
177                         if (groups == "not found") { groups = ""; }
178                         else { 
179                                 m->splitAtDash(groups, Groups);
180                         }
181                         
182                         label = validParameter.validFile(parameters, "label", false);                   
183                         if (label == "not found") { label = ""; m->mothurOut("You did not provide a label, I will use the first label in your inputfile."); m->mothurOutEndLine(); label=""; }  
184                         
185                         if ((accnosfile == "") && (Groups.size() == 0)) { m->mothurOut("You must provide an accnos file or specify groups using the groups parameter."); m->mothurOutEndLine(); abort = true; }
186                 }
187                 
188         }
189         catch(exception& e) {
190                 m->errorOut(e, "GetOtusCommand", "GetOtusCommand");
191                 exit(1);
192         }
193 }
194 //**********************************************************************************************************************
195
196 int GetOtusCommand::execute(){
197         try {
198                 
199                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
200                 
201                 groupMap = new GroupMap(groupfile);
202                 groupMap->readMap();
203                 
204                 //get groups you want to get
205                 if (accnosfile != "") { m->readAccnos(accnosfile, Groups); m->setGroups(Groups); }
206                 
207                 //make sure groups are valid
208                 //takes care of user setting groupNames that are invalid or setting groups=all
209                 SharedUtil* util = new SharedUtil();
210                 vector<string> gNamesOfGroups = groupMap->getNamesOfGroups();
211                 util->setGroups(Groups, gNamesOfGroups);
212                 groupMap->setNamesOfGroups(gNamesOfGroups);
213                 delete util;
214                 
215                 if (m->control_pressed) { delete groupMap; return 0; }
216                 
217                 //read through the list file keeping any otus that contain any sequence from the groups selected
218                 readListGroup();
219                 
220                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]); } return 0; }
221                                 
222                 if (outputNames.size() != 0) {
223                         m->mothurOutEndLine();
224                         m->mothurOut("Output File names: "); m->mothurOutEndLine();
225                         for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
226                         m->mothurOutEndLine();
227                         
228                         //set list file as new current listfile
229                         string current = "";
230                         itTypes = outputTypes.find("group");
231                         if (itTypes != outputTypes.end()) {
232                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setGroupFile(current); }
233                         }
234                         
235                         itTypes = outputTypes.find("list");
236                         if (itTypes != outputTypes.end()) {
237                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setListFile(current); }
238                         }
239                 }
240                 
241                 return 0;               
242         }
243         
244         catch(exception& e) {
245                 m->errorOut(e, "GetOtusCommand", "execute");
246                 exit(1);
247         }
248 }
249 //**********************************************************************************************************************
250 int GetOtusCommand::readListGroup(){
251         try {
252                 string thisOutputDir = outputDir;
253                 if (outputDir == "") {  thisOutputDir += m->hasPath(listfile);  }
254                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(listfile)) + label + "." + getOutputFileNameTag("list", listfile);
255                 
256                 ofstream out;
257                 m->openOutputFile(outputFileName, out);
258                 
259                 string GroupOutputDir = outputDir;
260                 if (outputDir == "") {  GroupOutputDir += m->hasPath(groupfile);  }
261                 string outputGroupFileName = GroupOutputDir + m->getRootName(m->getSimpleName(groupfile)) + label + "." + getOutputFileNameTag("group", groupfile);
262                 
263                 ofstream outGroup;
264                 m->openOutputFile(outputGroupFileName, outGroup);
265                         
266                 InputData* input = new InputData(listfile, "list");
267                 ListVector* list = input->getListVector();
268                 string lastLabel = list->getLabel();
269                 
270                 //using first label seen if none is provided
271                 if (label == "") { label = lastLabel; }
272                 
273                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
274                 set<string> labels; labels.insert(label);
275                 set<string> processedLabels;
276                 set<string> userLabels = labels;
277                 
278                 bool wroteSomething = false;
279
280                 //as long as you are not at the end of the file or done wih the lines you want
281                 while((list != NULL) && (userLabels.size() != 0)) {
282                         
283                         if (m->control_pressed) {  delete list; delete input; out.close();  outGroup.close(); m->mothurRemove(outputFileName);  m->mothurRemove(outputGroupFileName);return 0;  }
284                         
285                         if(labels.count(list->getLabel()) == 1){
286                                 processList(list, groupMap, out, outGroup, wroteSomething);
287                                 
288                                 processedLabels.insert(list->getLabel());
289                                 userLabels.erase(list->getLabel());
290                         }
291                         
292                         if ((m->anyLabelsToProcess(list->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
293                                 string saveLabel = list->getLabel();
294                                 
295                                 delete list; 
296                                 
297                                 list = input->getListVector(lastLabel);
298                                 
299                                 processList(list, groupMap, out, outGroup, wroteSomething);
300                                 
301                                 processedLabels.insert(list->getLabel());
302                                 userLabels.erase(list->getLabel());
303                                 
304                                 //restore real lastlabel to save below
305                                 list->setLabel(saveLabel);
306                         }
307                         
308                         lastLabel = list->getLabel();
309                         
310                         delete list; list = NULL;
311                         
312                         //get next line to process
313                         list = input->getListVector();                          
314                 }
315                 
316                 
317                 if (m->control_pressed) {  if (list != NULL) { delete list; } delete input; out.close(); outGroup.close(); m->mothurRemove(outputFileName);  m->mothurRemove(outputGroupFileName); return 0;  }
318                 
319                 //output error messages about any remaining user labels
320                 set<string>::iterator it;
321                 bool needToRun = false;
322                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
323                         m->mothurOut("Your file does not include the label " + *it); 
324                         if (processedLabels.count(lastLabel) != 1) {
325                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
326                                 needToRun = true;
327                         }else {
328                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
329                         }
330                 }
331                 
332                 //run last label if you need to
333                 if (needToRun == true)  {
334                         if (list != NULL) { delete list; }
335                         
336                         list = input->getListVector(lastLabel);
337                         
338                         processList(list, groupMap, out, outGroup, wroteSomething);
339                         
340                         delete list; list = NULL;
341                 }
342                                         
343                 out.close();
344                 outGroup.close();
345                 
346                 if (wroteSomething == false) {  m->mothurOut("At distance " + label + " your file does NOT contain any otus containing sequences from the groups you wish to get."); m->mothurOutEndLine();  }
347                 outputTypes["list"].push_back(outputFileName); outputNames.push_back(outputFileName);
348                 outputTypes["group"].push_back(outputGroupFileName); outputNames.push_back(outputGroupFileName);
349                 
350                 return 0;
351                 
352         }
353         catch(exception& e) {
354                 m->errorOut(e, "GetOtusCommand", "readList");
355                 exit(1);
356         }
357 }
358 //**********************************************************************************************************************
359 int GetOtusCommand::processList(ListVector*& list, GroupMap*& groupMap, ofstream& out, ofstream& outGroup, bool& wroteSomething){
360         try {
361                 
362                 //make a new list vector
363                 ListVector newList;
364                 newList.setLabel(list->getLabel());
365                 
366                 int numOtus = 0;
367                 //for each bin
368                 for (int i = 0; i < list->getNumBins(); i++) {
369                         if (m->control_pressed) { return 0; }
370                         
371                         //parse out names that are in accnos file
372                         string binnames = list->get(i);
373                         
374                         bool keepBin = false;
375                         string groupFileOutput = "";
376                         
377                         //parse names
378                         string individual = "";
379                         int length = binnames.length();
380                         for(int j=0;j<length;j++){
381                                 if(binnames[j] == ','){
382                                         string group = groupMap->getGroup(individual);
383                                         if (group == "not found") { m->mothurOut("[ERROR]: " + individual + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
384                                         
385                                         if (m->inUsersGroups(group, Groups)) {  keepBin = true; }
386                                         groupFileOutput += individual + "\t" + group + "\n";
387                                         individual = "";        
388                                         
389                                 }
390                                 else{  individual += binnames[j];  }
391                         }
392                         
393                         string group = groupMap->getGroup(individual);
394                         if (group == "not found") { m->mothurOut("[ERROR]: " + individual + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
395                         
396                         if (m->inUsersGroups(group, Groups)) {  keepBin = true; }
397                         groupFileOutput += individual + "\t" + group + "\n";
398                         
399                         //if there are sequences from the groups we want in this bin add to new list, output to groupfile
400                         if (keepBin) {  
401                                 newList.push_back(binnames);    
402                                 outGroup << groupFileOutput;
403                                 numOtus++;
404                         }
405                 }
406                 
407                 //print new listvector
408                 if (newList.getNumBins() != 0) {
409                         wroteSomething = true;
410                         newList.print(out);
411                 }
412                 
413                 m->mothurOut(newList.getLabel() + " - selected " + toString(numOtus) + " of the " + toString(list->getNumBins()) + " OTUs."); m->mothurOutEndLine();
414         
415                 return 0;
416         }
417         catch(exception& e) {
418                 m->errorOut(e, "GetOtusCommand", "processList");
419                 exit(1);
420         }
421 }
422 //**********************************************************************************************************************
423
424