]> git.donarmstrong.com Git - mothur.git/blob - removeotuscommand.cpp
changed random forest output filename
[mothur.git] / removeotuscommand.cpp
1 /*
2  *  removeotuscommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 11/12/10.
6  *  Copyright 2010 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "removeotuscommand.h"
11 #include "inputdata.h"
12 #include "sharedutilities.h"
13
14 //**********************************************************************************************************************
15 vector<string> RemoveOtusCommand::setParameters(){      
16         try {
17                 CommandParameter pgroup("group", "InputTypes", "", "", "none", "none", "none","group",false,true,true); parameters.push_back(pgroup);
18                 CommandParameter plist("list", "InputTypes", "", "", "none", "none", "none","list",false,true,true); parameters.push_back(plist);
19                 CommandParameter paccnos("accnos", "InputTypes", "", "", "none", "none", "none","",false,false); parameters.push_back(paccnos);
20                 CommandParameter pgroups("groups", "String", "", "", "", "", "","",false,false); parameters.push_back(pgroups);
21                 CommandParameter plabel("label", "String", "", "", "", "", "","",false,false); parameters.push_back(plabel);
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, "RemoveOtusCommand", "setParameters");
31                 exit(1);
32         }
33 }
34 //**********************************************************************************************************************
35 string RemoveOtusCommand::getHelpString(){      
36         try {
37                 string helpString = "";
38                 helpString += "The remove.otus command removes otus containing sequences from a specfic group or set of groups.\n";
39                 helpString += "It outputs a new list file containing the otus containing sequences NOT from in the those specified groups.\n";
40                 helpString += "The remove.otus command parameters are accnos, group, list, label and groups. The group and list parameters are required, unless you have valid current files.\n";
41                 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";
42                 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";
43                 helpString += "The label parameter allows you to specify which distance you want to process.\n";
44                 helpString += "The remove.otus command should be in the following format: remove.otus(accnos=yourAccnos, list=yourListFile, group=yourGroupFile, label=yourLabel).\n";
45                 helpString += "Example remove.otus(accnos=amazon.accnos, list=amazon.fn.list, group=amazon.groups, label=0.03).\n";
46                 helpString += "or remove.otus(groups=pasture, list=amazon.fn.list, amazon.groups, label=0.03).\n";
47                 helpString += "Note: No spaces between parameter labels (i.e. list), '=' and parameters (i.e.yourListFile).\n";
48                 return helpString;
49         }
50         catch(exception& e) {
51                 m->errorOut(e, "RemoveOtusCommand", "getHelpString");
52                 exit(1);
53         }
54 }
55 //**********************************************************************************************************************
56 string RemoveOtusCommand::getOutputPattern(string type) {
57     try {
58         string pattern = "";
59         
60         if (type == "group")       {   pattern = "[filename],[tag],pick,[extension]";    }
61         else if (type == "list")        {   pattern = "[filename],[tag],pick,[extension]";    }
62         else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true;  }
63         
64         return pattern;
65     }
66     catch(exception& e) {
67         m->errorOut(e, "RemoveOtusCommand", "getOutputPattern");
68         exit(1);
69     }
70 }
71 ///**********************************************************************************************************************
72 RemoveOtusCommand::RemoveOtusCommand(){ 
73         try {
74                 abort = true; calledHelp = true; 
75                 setParameters();
76                 vector<string> tempOutNames;
77                 outputTypes["group"] = tempOutNames;
78                 outputTypes["list"] = tempOutNames;
79         }
80         catch(exception& e) {
81                 m->errorOut(e, "RemoveOtusCommand", "RemoveOtusCommand");
82                 exit(1);
83         }
84 }
85
86 //**********************************************************************************************************************
87 RemoveOtusCommand::RemoveOtusCommand(string option)  {
88         try {
89                 abort = false; calledHelp = false;   
90                 
91                 //allow user to run help
92                 if(option == "help") { help(); abort = true; calledHelp = true; }
93                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
94                 
95                 else {
96                         vector<string> myArray = setParameters();
97                         
98                         OptionParser parser(option);
99                         map<string,string> parameters = parser.getParameters();
100                         
101                         ValidParameters validParameter;
102                         map<string,string>::iterator it;
103                         
104                         //check to make sure all parameters are valid for command
105                         for (it = parameters.begin(); it != parameters.end(); it++) { 
106                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
107                         }
108                         
109                         //initialize outputTypes
110                         vector<string> tempOutNames;
111                         outputTypes["group"] = tempOutNames;
112                         outputTypes["list"] = tempOutNames;
113                         
114                         
115                         //if the user changes the output directory command factory will send this info to us in the output parameter 
116                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = "";         }
117                         
118                         //if the user changes the input directory command factory will send this info to us in the output parameter 
119                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
120                         if (inputDir == "not found"){   inputDir = "";          }
121                         else {
122                                 string path;
123                                 it = parameters.find("accnos");
124                                 //user has given a template file
125                                 if(it != parameters.end()){ 
126                                         path = m->hasPath(it->second);
127                                         //if the user has not given a path then, add inputdir. else leave path alone.
128                                         if (path == "") {       parameters["accnos"] = inputDir + it->second;           }
129                                 }
130                                 
131                                 it = parameters.find("list");
132                                 //user has given a template file
133                                 if(it != parameters.end()){ 
134                                         path = m->hasPath(it->second);
135                                         //if the user has not given a path then, add inputdir. else leave path alone.
136                                         if (path == "") {       parameters["list"] = inputDir + it->second;             }
137                                 }
138                                 
139                                 it = parameters.find("group");
140                                 //user has given a template file
141                                 if(it != parameters.end()){ 
142                                         path = m->hasPath(it->second);
143                                         //if the user has not given a path then, add inputdir. else leave path alone.
144                                         if (path == "") {       parameters["group"] = inputDir + it->second;            }
145                                 }
146                         }
147                         
148                         
149                         //check for required parameters
150                         accnosfile = validParameter.validFile(parameters, "accnos", true);
151                         if (accnosfile == "not open") { abort = true; }
152                         else if (accnosfile == "not found") {  accnosfile = ""; }
153                         else { m->setAccnosFile(accnosfile); }
154                         
155                         groupfile = validParameter.validFile(parameters, "group", true);
156                         if (groupfile == "not open") { abort = true; }
157                         else if (groupfile == "not found") {                            
158                                 groupfile = m->getGroupFile(); 
159                                 if (groupfile != "") { m->mothurOut("Using " + groupfile + " as input file for the group parameter."); m->mothurOutEndLine(); }
160                                 else {  m->mothurOut("You have no current group file and the group parameter is required."); m->mothurOutEndLine(); abort = true; }
161                         }else { m->setGroupFile(groupfile); }   
162                         
163                         listfile = validParameter.validFile(parameters, "list", true);
164                         if (listfile == "not open") { abort = true; }
165                         else if (listfile == "not found") {                             
166                                 listfile = m->getListFile(); 
167                                 if (listfile != "") { m->mothurOut("Using " + listfile + " as input file for the list parameter."); m->mothurOutEndLine(); }
168                                 else {  m->mothurOut("You have no current list file and the list parameter is required."); m->mothurOutEndLine(); abort = true; }
169                         }else { m->setListFile(listfile); }     
170                         
171                         groups = validParameter.validFile(parameters, "groups", false);                 
172                         if (groups == "not found") { groups = ""; }
173                         else { 
174                                 m->splitAtDash(groups, Groups);
175                         }
176                         
177                         label = validParameter.validFile(parameters, "label", false);                   
178                         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=""; }  
179                         
180                         if ((accnosfile == "") && (Groups.size() == 0)) { m->mothurOut("You must provide an accnos file or specify groups using the groups parameter."); m->mothurOutEndLine(); abort = true; }
181                 }
182                 
183         }
184         catch(exception& e) {
185                 m->errorOut(e, "RemoveOtusCommand", "RemoveOtusCommand");
186                 exit(1);
187         }
188 }
189 //**********************************************************************************************************************
190
191 int RemoveOtusCommand::execute(){
192         try {
193                 
194                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
195                 
196                 groupMap = new GroupMap(groupfile);
197                 groupMap->readMap();
198                 
199                 //get groups you want to remove
200                 if (accnosfile != "") { m->readAccnos(accnosfile, Groups); m->setGroups(Groups);  }
201                 
202                 //make sure groups are valid
203                 //takes care of user setting groupNames that are invalid or setting groups=all
204                 SharedUtil* util = new SharedUtil();
205                 vector<string> allGroups = groupMap->getNamesOfGroups();
206                 util->setGroups(Groups, allGroups);
207                 delete util;
208                 
209                 if (m->control_pressed) { delete groupMap; return 0; }
210                 
211                 //read through the list file keeping any otus that contain any sequence from the groups selected
212                 readListGroup();
213                 
214                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]); } return 0; }
215                 
216                 if (outputNames.size() != 0) {
217                         m->mothurOutEndLine();
218                         m->mothurOut("Output File names: "); m->mothurOutEndLine();
219                         for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
220                         m->mothurOutEndLine();
221                         
222                         //set fasta file as new current fastafile
223                         string current = "";
224                         itTypes = outputTypes.find("group");
225                         if (itTypes != outputTypes.end()) {
226                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setGroupFile(current); }
227                         }
228                         
229                         itTypes = outputTypes.find("list");
230                         if (itTypes != outputTypes.end()) {
231                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setListFile(current); }
232                         }
233                 }
234                 
235                 return 0;               
236         }
237         
238         catch(exception& e) {
239                 m->errorOut(e, "RemoveOtusCommand", "execute");
240                 exit(1);
241         }
242 }
243 //**********************************************************************************************************************
244 int RemoveOtusCommand::readListGroup(){
245         try {
246                 string thisOutputDir = outputDir;
247                 if (outputDir == "") {  thisOutputDir += m->hasPath(listfile);  }
248                 map<string, string> variables; 
249         variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(listfile));
250         variables["[tag]"] = label;
251         variables["[extension]"] = m->getExtension(listfile);
252                 string outputFileName = getOutputFileName("list", variables);
253                 
254                 ofstream out;
255                 m->openOutputFile(outputFileName, out);
256                 
257                 string GroupOutputDir = outputDir;
258                 if (outputDir == "") {  GroupOutputDir += m->hasPath(groupfile);  }
259                 variables["[filename]"] = GroupOutputDir + m->getRootName(m->getSimpleName(groupfile));
260         variables["[extension]"] = m->getExtension(groupfile);
261                 string outputGroupFileName = getOutputFileName("group", variables);
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 ONLY contains otus containing sequences from the groups you wish to remove."); 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, "RemoveOtusCommand", "readList");
355                 exit(1);
356         }
357 }
358 //**********************************************************************************************************************
359 int RemoveOtusCommand::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 removeBin = 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)) {  removeBin = true; break; }
386                                         groupFileOutput += individual + "\t" + group + "\n";
387                                         individual = "";        
388                                         
389                                 }
390                                 else{  individual += binnames[j];  }
391                         }
392                         
393                         if (!removeBin) { 
394                                 //get last name
395                                 string group = groupMap->getGroup(individual);
396                                 if (group == "not found") { m->mothurOut("[ERROR]: " + individual + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
397                                 
398                                 if (m->inUsersGroups(group, Groups)) {  removeBin = true; }
399                                 groupFileOutput += individual + "\t" + group + "\n";                            
400                                 
401                                 if (!removeBin) {
402                                         //if there are no sequences from the groups we want to remove in this bin add to new list, output to groupfile
403                                         newList.push_back(binnames);    
404                                         outGroup << groupFileOutput;
405                                 }else {
406                                         numOtus++;
407                                 }
408                         }else {
409                                 numOtus++;
410                         }
411                         
412                 }
413                 
414                 //print new listvector
415                 if (newList.getNumBins() != 0) {
416                         wroteSomething = true;
417                         newList.print(out);
418                 }
419                 
420                 m->mothurOut(newList.getLabel() + " - removed " + toString(numOtus) + " of the " + toString(list->getNumBins()) + " OTUs."); m->mothurOutEndLine();
421                 
422                 return 0;
423                 
424         }
425         catch(exception& e) {
426                 m->errorOut(e, "RemoveOtusCommand", "processList");
427                 exit(1);
428         }
429 }
430 //**********************************************************************************************************************
431
432
433