]> git.donarmstrong.com Git - mothur.git/blob - removerarecommand.cpp
changing command name classify.shared to classifyrf.shared
[mothur.git] / removerarecommand.cpp
1 /*
2  *  removerarecommand.cpp
3  *  mothur
4  *
5  *  Created by westcott on 1/21/11.
6  *  Copyright 2011 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "removerarecommand.h"
11 #include "sequence.hpp"
12 #include "groupmap.h"
13 #include "sharedutilities.h"
14 #include "inputdata.h"
15
16 //**********************************************************************************************************************
17 vector<string> RemoveRareCommand::setParameters(){      
18         try {
19                 CommandParameter plist("list", "InputTypes", "", "", "none", "atleast", "none","list",false,false,true); parameters.push_back(plist);
20                 CommandParameter prabund("rabund", "InputTypes", "", "", "none", "atleast", "none","rabund",false,false,true); parameters.push_back(prabund);
21                 CommandParameter psabund("sabund", "InputTypes", "", "", "none", "atleast", "none","sabund",false,false,true); parameters.push_back(psabund);
22                 CommandParameter pshared("shared", "InputTypes", "", "", "none", "atleast", "none","shared",false,false,true); parameters.push_back(pshared);
23         CommandParameter pcount("count", "InputTypes", "", "", "CountGroup", "none", "none","count",false,false); parameters.push_back(pcount);
24                 CommandParameter pgroup("group", "InputTypes", "", "", "CountGroup", "none", "none","group",false,false); parameters.push_back(pgroup);
25                 CommandParameter pgroups("groups", "String", "", "", "", "", "","",false,false); parameters.push_back(pgroups);
26                 CommandParameter plabel("label", "String", "", "", "", "", "","",false,false); parameters.push_back(plabel);
27                 CommandParameter pnseqs("nseqs", "Number", "", "0", "", "", "","",false,true,true); parameters.push_back(pnseqs);
28                 CommandParameter pbygroup("bygroup", "Boolean", "", "f", "", "", "","",false,false); parameters.push_back(pbygroup);
29                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
30                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
31                 
32                 vector<string> myArray;
33                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
34                 return myArray;
35         }
36         catch(exception& e) {
37                 m->errorOut(e, "RemoveRareCommand", "setParameters");
38                 exit(1);
39         }
40 }
41 //**********************************************************************************************************************
42 string RemoveRareCommand::getHelpString(){      
43         try {
44                 string helpString = "";
45                 helpString += "The remove.rare command parameters are list, rabund, sabund, shared, group, count, label, groups, bygroup and nseqs.\n";
46                 helpString += "The remove.rare command reads one of the following file types: list, rabund, sabund or shared file. It outputs a new file after removing the rare otus.\n";
47                 helpString += "The groups parameter allows you to specify which of the groups you would like analyzed.  Default=all. You may separate group names with dashes.\n";
48                 helpString += "The label parameter is used to analyze specific labels in your input. default=all. You may separate label names with dashes.\n";
49                 helpString += "The bygroup parameter is only valid with the shared file. default=f, meaning remove any OTU that has nseqs or fewer sequences across all groups.\n";
50                 helpString += "bygroups=T means remove any OTU that has nseqs or fewer sequences in each group (if groupA has 1 sequence and group B has 100 sequences in OTUZ and nseqs=1, then set the groupA count for OTUZ to 0 and keep groupB's count at 100.) \n";
51                 helpString += "The nseqs parameter allows you to set the cutoff for an otu to be deemed rare. It is required.\n";
52                 helpString += "The remove.rare command should be in the following format: remove.rare(shared=yourSharedFile, nseqs=yourRareCutoff).\n";
53                 helpString += "Example remove.rare(shared=amazon.fn.shared, nseqs=2).\n";
54                 helpString += "Note: No spaces between parameter labels (i.e. shared), '=' and parameters (i.e.yourSharedFile).\n";
55                 return helpString;
56         }
57         catch(exception& e) {
58                 m->errorOut(e, "RemoveRareCommand", "getHelpString");
59                 exit(1);
60         }
61 }
62 //**********************************************************************************************************************
63 string RemoveRareCommand::getOutputPattern(string type) {
64     try {
65         string pattern = "";
66         
67         if (type == "rabund")            {   pattern = "[filename],pick,[extension]";    }
68         else if (type == "sabund")    {   pattern = "[filename],pick,[extension]";    }
69         else if (type == "group")       {   pattern = "[filename],pick,[extension]";    }
70         else if (type == "count")       {   pattern = "[filename],pick,[extension]";    }
71         else if (type == "list")        {   pattern = "[filename],pick,[extension]";    }
72         else if (type == "shared")      {   pattern = "[filename],[tag],pick,[extension]";    }
73         else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true;  }
74         
75         return pattern;
76     }
77     catch(exception& e) {
78         m->errorOut(e, "RemoveRareCommand", "getOutputPattern");
79         exit(1);
80     }
81 }
82 //**********************************************************************************************************************
83 RemoveRareCommand::RemoveRareCommand(){ 
84         try {
85                 abort = true; calledHelp = true; 
86                 setParameters();
87                 vector<string> tempOutNames;
88                 outputTypes["rabund"] = tempOutNames;
89                 outputTypes["sabund"] = tempOutNames;
90                 outputTypes["list"] = tempOutNames;
91                 outputTypes["group"] = tempOutNames;
92         outputTypes["count"] = tempOutNames;
93                 outputTypes["shared"] = tempOutNames;
94         }
95         catch(exception& e) {
96                 m->errorOut(e, "RemoveRareCommand", "RemoveRareCommand");
97                 exit(1);
98         }
99 }
100 //**********************************************************************************************************************
101 RemoveRareCommand::RemoveRareCommand(string option)  {
102         try {
103                 abort = false; calledHelp = false;   
104                 allLines = 1;
105                 
106                 //allow user to run help
107                 if(option == "help") { help(); abort = true; calledHelp = true; }
108                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
109                 
110                 else {
111                         vector<string> myArray = setParameters();
112                         
113                         OptionParser parser(option);
114                         map<string,string> parameters = parser.getParameters();
115                         
116                         ValidParameters validParameter;
117                         map<string,string>::iterator it;
118                         
119                         //check to make sure all parameters are valid for command
120                         for (it = parameters.begin(); it != parameters.end(); it++) { 
121                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
122                         }
123                         
124                         //initialize outputTypes
125                         vector<string> tempOutNames;
126                         outputTypes["rabund"] = tempOutNames;
127                         outputTypes["sabund"] = tempOutNames;
128                         outputTypes["list"] = tempOutNames;
129                         outputTypes["group"] = tempOutNames;
130                         outputTypes["shared"] = tempOutNames;   
131             outputTypes["count"] = tempOutNames;
132                         
133                         //if the user changes the output directory command factory will send this info to us in the output parameter 
134                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = "";         }
135                         
136                         //if the user changes the input directory command factory will send this info to us in the output parameter 
137                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
138                         if (inputDir == "not found"){   inputDir = "";          }
139                         else {
140                                 string path;
141                                 it = parameters.find("list");
142                                 //user has given a template file
143                                 if(it != parameters.end()){ 
144                                         path = m->hasPath(it->second);
145                                         //if the user has not given a path then, add inputdir. else leave path alone.
146                                         if (path == "") {       parameters["list"] = inputDir + it->second;             }
147                                 }
148                                 
149                                 it = parameters.find("group");
150                                 //user has given a template file
151                                 if(it != parameters.end()){ 
152                                         path = m->hasPath(it->second);
153                                         //if the user has not given a path then, add inputdir. else leave path alone.
154                                         if (path == "") {       parameters["group"] = inputDir + it->second;            }
155                                 }
156                                 
157                                 it = parameters.find("sabund");
158                                 //user has given a template file
159                                 if(it != parameters.end()){ 
160                                         path = m->hasPath(it->second);
161                                         //if the user has not given a path then, add inputdir. else leave path alone.
162                                         if (path == "") {       parameters["sabund"] = inputDir + it->second;           }
163                                 }
164                                 
165                                 it = parameters.find("rabund");
166                                 //user has given a template file
167                                 if(it != parameters.end()){ 
168                                         path = m->hasPath(it->second);
169                                         //if the user has not given a path then, add inputdir. else leave path alone.
170                                         if (path == "") {       parameters["rabund"] = inputDir + it->second;           }
171                                 }
172                                 
173                                 it = parameters.find("shared");
174                                 //user has given a template file
175                                 if(it != parameters.end()){ 
176                                         path = m->hasPath(it->second);
177                                         //if the user has not given a path then, add inputdir. else leave path alone.
178                                         if (path == "") {       parameters["shared"] = inputDir + it->second;           }
179                                 }
180                 
181                 it = parameters.find("count");
182                                 //user has given a template file
183                                 if(it != parameters.end()){ 
184                                         path = m->hasPath(it->second);
185                                         //if the user has not given a path then, add inputdir. else leave path alone.
186                                         if (path == "") {       parameters["count"] = inputDir + it->second;            }
187                                 }
188                         }
189                         
190                         
191                         //check for file parameters
192                         listfile = validParameter.validFile(parameters, "list", true);
193                         if (listfile == "not open") { abort = true; }
194                         else if (listfile == "not found") {  listfile = "";  }
195                         else { m->setListFile(listfile); }
196                         
197                         sabundfile = validParameter.validFile(parameters, "sabund", true);
198                         if (sabundfile == "not open") { abort = true; }
199                         else if (sabundfile == "not found") {  sabundfile = "";  }      
200                         else { m->setSabundFile(sabundfile); }
201                         
202                         rabundfile = validParameter.validFile(parameters, "rabund", true);
203                         if (rabundfile == "not open") { abort = true; }
204                         else if (rabundfile == "not found") {  rabundfile = "";  }                              
205                         else { m->setRabundFile(rabundfile); }
206                         
207                         groupfile = validParameter.validFile(parameters, "group", true);
208                         if (groupfile == "not open") { groupfile = ""; abort = true; }
209                         else if (groupfile == "not found") {  groupfile = "";  }        
210                         else { m->setGroupFile(groupfile); }
211                         
212                         sharedfile = validParameter.validFile(parameters, "shared", true);
213                         if (sharedfile == "not open") { sharedfile = "";  abort = true; }
214                         else if (sharedfile == "not found") {  sharedfile = "";  }
215                         else { m->setSharedFile(sharedfile); }
216             
217             countfile = validParameter.validFile(parameters, "count", true);
218                         if (countfile == "not open") { countfile = ""; abort = true; }
219                         else if (countfile == "not found") { countfile = "";  } 
220                         else { m->setCountTableFile(countfile); }
221                                 
222             if ((groupfile != "") && (countfile != "")) {
223                 m->mothurOut("[ERROR]: you may only use one of the following: group or count."); m->mothurOutEndLine(); abort=true;
224             }
225                         
226                         if ((sharedfile == "") && (listfile == "") && (rabundfile == "") && (sabundfile == "")) { 
227                                 //is there are current file available for any of these?
228                                 //give priority to shared, then list, then rabund, then sabund
229                                 //if there is a current shared file, use it
230                                 sharedfile = m->getSharedFile(); 
231                                 if (sharedfile != "") {  m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
232                                 else { 
233                                         listfile = m->getListFile(); 
234                                         if (listfile != "") {  m->mothurOut("Using " + listfile + " as input file for the list parameter."); m->mothurOutEndLine(); }
235                                         else { 
236                                                 rabundfile = m->getRabundFile(); 
237                                                 if (rabundfile != "") {  m->mothurOut("Using " + rabundfile + " as input file for the rabund parameter."); m->mothurOutEndLine(); }
238                                                 else { 
239                                                         sabundfile = m->getSabundFile(); 
240                                                         if (sabundfile != "") {  m->mothurOut("Using " + sabundfile + " as input file for the sabund parameter."); m->mothurOutEndLine(); }
241                                                         else { 
242                                                                 m->mothurOut("No valid current files. You must provide a list, sabund, rabund or shared file."); m->mothurOutEndLine(); 
243                                                                 abort = true;
244                                                         }
245                                                 }
246                                         }
247                                 }
248                         } 
249                         
250                         groups = validParameter.validFile(parameters, "groups", false);                 
251                         if (groups == "not found") { groups = "all"; }
252                         m->splitAtDash(groups, Groups);
253                         
254                         label = validParameter.validFile(parameters, "label", false);                   
255                         if (label == "not found") { label = ""; }
256                         else { 
257                                 if(label != "all") {  m->splitAtDash(label, labels);  allLines = 0;  }
258                                 else { allLines = 1;  }
259                         }
260                         
261                         string temp = validParameter.validFile(parameters, "nseqs", false);      
262                         if (temp == "not found") { m->mothurOut("nseqs is a required parameter."); m->mothurOutEndLine(); abort = true; }
263                         else { m->mothurConvert(temp, nseqs); }
264                         
265                         temp = validParameter.validFile(parameters, "bygroup", false);   if (temp == "not found") { temp = "f"; }
266                         byGroup = m->isTrue(temp);
267                         
268                         if (byGroup && (sharedfile == "")) { m->mothurOut("The byGroup parameter is only valid with a shared file."); m->mothurOutEndLine(); }
269                         
270                         if (((groupfile != "") || (countfile != "")) && (listfile == "")) { m->mothurOut("A group or count file is only valid with a list file."); m->mothurOutEndLine(); groupfile = ""; countfile = ""; }
271                 }
272                 
273         }
274         catch(exception& e) {
275                 m->errorOut(e, "RemoveRareCommand", "RemoveRareCommand");
276                 exit(1);
277         }
278 }
279 //**********************************************************************************************************************
280
281 int RemoveRareCommand::execute(){
282         try {
283                 
284                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
285                 
286                 if (m->control_pressed) { return 0; }
287                 
288                 //read through the correct file and output lines you want to keep
289                 if (sabundfile != "")           {               processSabund();        }
290                 if (rabundfile != "")           {               processRabund();        }
291                 if (listfile != "")                     {               processList();          }
292                 if (sharedfile != "")           {               processShared();        }
293                 
294                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]); } return 0; }
295                         
296                 if (outputNames.size() != 0) {
297                         m->mothurOutEndLine();
298                         m->mothurOut("Output File Names: "); m->mothurOutEndLine();
299                         for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
300                         m->mothurOutEndLine();
301                         
302                         //set rabund file as new current rabundfile
303                         string current = "";
304                         itTypes = outputTypes.find("rabund");
305                         if (itTypes != outputTypes.end()) {
306                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setRabundFile(current); }
307                         }
308                         
309                         itTypes = outputTypes.find("sabund");
310                         if (itTypes != outputTypes.end()) {
311                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSabundFile(current); }
312                         }
313                         
314                         itTypes = outputTypes.find("group");
315                         if (itTypes != outputTypes.end()) {
316                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setGroupFile(current); }
317                         }
318                         
319                         itTypes = outputTypes.find("list");
320                         if (itTypes != outputTypes.end()) {
321                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setListFile(current); }
322                         }
323                         
324                         itTypes = outputTypes.find("shared");
325                         if (itTypes != outputTypes.end()) {
326                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSharedFile(current); }
327                         }
328             
329             itTypes = outputTypes.find("count");
330                         if (itTypes != outputTypes.end()) {
331                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setCountTableFile(current); }
332                         }
333                 }
334                 
335                 return 0;               
336         }
337         
338         catch(exception& e) {
339                 m->errorOut(e, "RemoveRareCommand", "execute");
340                 exit(1);
341         }
342 }
343
344 //**********************************************************************************************************************
345 int RemoveRareCommand::processList(){
346         try {
347                 string thisOutputDir = outputDir;
348                 if (outputDir == "") {  thisOutputDir += m->hasPath(listfile);  }
349         map<string, string> variables; 
350         variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(listfile));
351         variables["[extension]"] = m->getExtension(listfile);
352                 string outputFileName = getOutputFileName("list", variables);
353         variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(groupfile));
354         variables["[extension]"] = m->getExtension(groupfile);
355                 string outputGroupFileName = getOutputFileName("group", variables);
356         variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(countfile));
357         variables["[extension]"] = m->getExtension(countfile);
358         string outputCountFileName = getOutputFileName("count", variables);
359         
360                 ofstream out, outGroup;
361                 m->openOutputFile(outputFileName, out);
362                 
363                 bool wroteSomething = false;
364                 
365                 //you must provide a label because the names in the listfile need to be consistent
366                 string thisLabel = "";
367                 if (allLines) { m->mothurOut("For the listfile you must select one label, using first label in your listfile."); m->mothurOutEndLine(); }
368                 else if (labels.size() > 1) { m->mothurOut("For the listfile you must select one label, using " + (*labels.begin()) + "."); m->mothurOutEndLine(); thisLabel = *labels.begin(); }
369                 else { thisLabel = *labels.begin(); }
370                 
371                 InputData input(listfile, "list");
372                 ListVector* list = input.getListVector();
373                 
374                 //get first one or the one we want
375                 if (thisLabel != "") {  
376                         //use smart distancing
377                         set<string> userLabels; userLabels.insert(thisLabel);
378                         set<string> processedLabels;
379                         string lastLabel = list->getLabel();
380                         while((list != NULL) && (userLabels.size() != 0)) {
381                                 if(userLabels.count(list->getLabel()) == 1){
382                                         processedLabels.insert(list->getLabel());
383                                         userLabels.erase(list->getLabel());
384                                         break;
385                                 }
386                                 
387                                 if ((m->anyLabelsToProcess(list->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
388                                         processedLabels.insert(list->getLabel());
389                                         userLabels.erase(list->getLabel());
390                                         delete list;
391                                         list = input.getListVector(lastLabel);
392                                         break;
393                                 }
394                                 lastLabel = list->getLabel();
395                                 delete list;
396                                 list = input.getListVector();
397                         }
398                         if (userLabels.size() != 0) { 
399                                 m->mothurOut("Your file does not include the label " + thisLabel + ". I will use " + lastLabel + ".");  m->mothurOutEndLine();
400                                 list = input.getListVector(lastLabel); 
401                         }
402                 }
403                 
404                 //if groupfile is given then use it
405                 GroupMap* groupMap;
406         CountTable ct;
407                 if (groupfile != "") { 
408                         groupMap = new GroupMap(groupfile); groupMap->readMap(); 
409                         SharedUtil util;
410                         vector<string> namesGroups = groupMap->getNamesOfGroups();
411                         util.setGroups(Groups, namesGroups);
412                         m->openOutputFile(outputGroupFileName, outGroup);
413                 }else if (countfile != "") {
414             ct.readTable(countfile, true);
415             if (ct.hasGroupInfo()) {
416                 vector<string> namesGroups = ct.getNamesOfGroups();
417                 SharedUtil util;
418                 util.setGroups(Groups, namesGroups);
419             }
420         }
421                 
422                 
423                 if (list != NULL) {     
424                         //make a new list vector
425                         ListVector newList;
426                         newList.setLabel(list->getLabel());
427                         
428                         //for each bin
429                         for (int i = 0; i < list->getNumBins(); i++) {
430                                 if (m->control_pressed) {  if (groupfile != "") { delete groupMap; outGroup.close(); m->mothurRemove(outputGroupFileName); } out.close();  m->mothurRemove(outputFileName);  return 0; }
431                                 
432                                 //parse out names that are in accnos file
433                                 string binnames = list->get(i);
434                                 vector<string> names;
435                                 string saveBinNames = binnames;
436                                 m->splitAtComma(binnames, names);
437                 int binsize = names.size();
438                                 
439                                 vector<string> newGroupFile;
440                                 if (groupfile != "") {
441                                         vector<string> newNames;
442                                         saveBinNames = "";
443                                         for(int k = 0; k < names.size(); k++) {
444                                                 string group = groupMap->getGroup(names[k]);
445                                                 
446                                                 if (m->inUsersGroups(group, Groups)) {
447                                                         newGroupFile.push_back(names[k] + "\t" + group); 
448                                                                 
449                                                         newNames.push_back(names[k]);   
450                                                         saveBinNames += names[k] + ",";
451                                                 }
452                                         }
453                                         names = newNames; binsize = names.size();
454                                         saveBinNames = saveBinNames.substr(0, saveBinNames.length()-1);
455                                 }else if (countfile != "") {
456                                         saveBinNames = "";
457                     binsize = 0;
458                                         for(int k = 0; k < names.size(); k++) {
459                         if (ct.hasGroupInfo()) {
460                             vector<string> thisSeqsGroups = ct.getGroups(names[k]);
461                             
462                             int thisSeqsCount = 0;
463                             for (int n = 0; n < thisSeqsGroups.size(); n++) {
464                                 if (m->inUsersGroups(thisSeqsGroups[n], Groups)) {
465                                     thisSeqsCount += ct.getGroupCount(names[k], thisSeqsGroups[n]);
466                                 }
467                             }
468                             binsize += thisSeqsCount;
469                             //if you don't have any seqs from the groups the user wants, then remove you.
470                             if (thisSeqsCount == 0) { newGroupFile.push_back(names[k]); }
471                             else { saveBinNames += names[k] + ","; }
472                         }else {
473                             binsize += ct.getNumSeqs(names[k]); 
474                             saveBinNames += names[k] + ",";
475                         }
476                                         }
477                                         saveBinNames = saveBinNames.substr(0, saveBinNames.length()-1);
478                 }
479
480                                 if (binsize > nseqs) { //keep bin
481                                         newList.push_back(saveBinNames);
482                                         if (groupfile != "") {  for(int k = 0; k < newGroupFile.size(); k++) { outGroup << newGroupFile[k] << endl; }  }
483                     else if (countfile != "") { for(int k = 0; k < newGroupFile.size(); k++) {  ct.remove(newGroupFile[k]); } }  
484                                 }else {  if (countfile != "") {  for(int k = 0; k < names.size(); k++) {  ct.remove(names[k]); } }  }
485                         }
486                         
487                         //print new listvector
488                         if (newList.getNumBins() != 0) {
489                                 wroteSomething = true;
490                                 newList.print(out);
491                         }
492                 }       
493                 
494                 out.close();
495                 if (groupfile != "") { outGroup.close(); outputTypes["group"].push_back(outputGroupFileName); outputNames.push_back(outputGroupFileName); }
496         if (countfile != "") { 
497             if (ct.hasGroupInfo()) {
498                 vector<string> allGroups = ct.getNamesOfGroups();
499                 for (int i = 0; i < allGroups.size(); i++) {
500                     if (!m->inUsersGroups(allGroups[i], Groups)) { ct.removeGroup(allGroups[i]); }
501                 }
502
503             }
504             ct.printTable(outputCountFileName);
505             outputTypes["count"].push_back(outputCountFileName); outputNames.push_back(outputCountFileName); 
506         }
507                 
508                 if (wroteSomething == false) {  m->mothurOut("Your file contains only rare sequences."); m->mothurOutEndLine();  }
509                 outputTypes["list"].push_back(outputFileName); outputNames.push_back(outputFileName);
510                 
511                 return 0;
512         }
513         catch(exception& e) {
514                 m->errorOut(e, "RemoveRareCommand", "processList");
515                 exit(1);
516         }
517 }
518 //**********************************************************************************************************************
519 int RemoveRareCommand::processSabund(){
520         try {
521                 string thisOutputDir = outputDir;
522                 if (outputDir == "") {  thisOutputDir += m->hasPath(sabundfile);  }
523         map<string, string> variables; 
524         variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(sabundfile));
525         variables["[extension]"] = m->getExtension(sabundfile);
526                 string outputFileName = getOutputFileName("sabund", variables);
527                 outputTypes["sabund"].push_back(outputFileName); outputNames.push_back(outputFileName);
528
529                 ofstream out;
530                 m->openOutputFile(outputFileName, out);
531                 
532                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
533                 InputData input(sabundfile, "sabund");
534                 SAbundVector* sabund = input.getSAbundVector();
535                 string lastLabel = sabund->getLabel();
536                 set<string> processedLabels;
537                 set<string> userLabels = labels;
538                 
539                 while((sabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
540                         
541                         if (m->control_pressed) { delete sabund; out.close(); return 0; }
542                         
543                         if(allLines == 1 || labels.count(sabund->getLabel()) == 1){                     
544                                 
545                                 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
546                                 processedLabels.insert(sabund->getLabel());
547                                 userLabels.erase(sabund->getLabel());
548                                 
549                                 if (sabund->getMaxRank() > nseqs) {
550                                         for(int i = 1; i <=nseqs; i++) {  sabund->set(i, 0); }
551                                 }else { sabund->clear(); }
552                                 
553                                 if (sabund->getNumBins() > 0) { sabund->print(out); }
554                         }
555                         
556                         if ((m->anyLabelsToProcess(sabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
557                                 string saveLabel = sabund->getLabel();
558                                 
559                                 delete sabund;
560                                 sabund = input.getSAbundVector(lastLabel);
561                                 
562                                 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
563                                 processedLabels.insert(sabund->getLabel());
564                                 userLabels.erase(sabund->getLabel());
565                                 
566                                 if (sabund->getMaxRank() > nseqs) {
567                                         for(int i = 1; i <=nseqs; i++) {  sabund->set(i, 0); }
568                                 }else { sabund->clear(); }
569                                 
570                                 if (sabund->getNumBins() > 0) { sabund->print(out); }
571                                                                 
572                                 //restore real lastlabel to save below
573                                 sabund->setLabel(saveLabel);
574                         }               
575                         
576                         lastLabel = sabund->getLabel();                 
577                         
578                         delete sabund;
579                         sabund = input.getSAbundVector();
580                 }
581                 
582                 if (m->control_pressed) {  out.close(); return 0; }     
583                 
584                 //output error messages about any remaining user labels
585                 set<string>::iterator it;
586                 bool needToRun = false;
587                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
588                         m->mothurOut("Your file does not include the label " + *it); 
589                         if (processedLabels.count(lastLabel) != 1) {
590                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
591                                 needToRun = true;
592                         }else {
593                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
594                         }
595                 }
596                 
597                 //run last label if you need to
598                 if (needToRun == true)  {
599                         if (sabund != NULL) {   delete sabund;  }
600                         sabund = input.getSAbundVector(lastLabel);
601                         
602                         m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
603                         
604                         if (sabund->getMaxRank() > nseqs) {
605                                 for(int i = 1; i <=nseqs; i++) {  sabund->set(i, 0); }
606                         }else { sabund->clear(); }
607                         
608                         if (sabund->getNumBins() > 0) { sabund->print(out); }
609                         
610                         delete sabund;
611                 }
612                 
613                 return 0;
614         }
615         catch(exception& e) {
616                 m->errorOut(e, "RemoveRareCommand", "processSabund");
617                 exit(1);
618         }
619 }
620 //**********************************************************************************************************************
621 int RemoveRareCommand::processRabund(){
622         try {
623                 string thisOutputDir = outputDir;
624                 if (outputDir == "") {  thisOutputDir += m->hasPath(rabundfile);  }
625         map<string, string> variables; 
626         variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(rabundfile));
627         variables["[extension]"] = m->getExtension(rabundfile);
628                 string outputFileName = getOutputFileName("rabund", variables);
629                 outputTypes["rabund"].push_back(outputFileName); outputNames.push_back(outputFileName);
630                 
631                 ofstream out;
632                 m->openOutputFile(outputFileName, out);
633                 
634                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
635                 InputData input(rabundfile, "rabund");
636                 RAbundVector* rabund = input.getRAbundVector();
637                 string lastLabel = rabund->getLabel();
638                 set<string> processedLabels;
639                 set<string> userLabels = labels;
640                 
641                 while((rabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
642                         
643                         if (m->control_pressed) { delete rabund; out.close(); return 0; }
644                         
645                         if(allLines == 1 || labels.count(rabund->getLabel()) == 1){                     
646                                 
647                                 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
648                                 processedLabels.insert(rabund->getLabel());
649                                 userLabels.erase(rabund->getLabel());
650                                 
651                                 RAbundVector newRabund; newRabund.setLabel(rabund->getLabel());
652                                 for (int i = 0; i < rabund->getNumBins(); i++) {
653                                         if (rabund->get(i) > nseqs) {
654                                                 newRabund.push_back(rabund->get(i));
655                                         }
656                                 }
657                                 if (newRabund.getNumBins() > 0) { newRabund.print(out); }
658                         }
659                         
660                         if ((m->anyLabelsToProcess(rabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
661                                 string saveLabel = rabund->getLabel();
662                                 
663                                 delete rabund;
664                                 rabund = input.getRAbundVector(lastLabel);
665                                 
666                                 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
667                                 processedLabels.insert(rabund->getLabel());
668                                 userLabels.erase(rabund->getLabel());
669                                 
670                                 RAbundVector newRabund; newRabund.setLabel(rabund->getLabel());
671                                 for (int i = 0; i < rabund->getNumBins(); i++) {
672                                         if (rabund->get(i) > nseqs) {
673                                                 newRabund.push_back(rabund->get(i));
674                                         }
675                                 }
676                                 if (newRabund.getNumBins() > 0) { newRabund.print(out); }                               
677                                 
678                                 //restore real lastlabel to save below
679                                 rabund->setLabel(saveLabel);
680                         }               
681                         
682                         lastLabel = rabund->getLabel();                 
683                         
684                         delete rabund;
685                         rabund = input.getRAbundVector();
686                 }
687                 
688                 if (m->control_pressed) {  out.close(); return 0; }     
689                 
690                 //output error messages about any remaining user labels
691                 set<string>::iterator it;
692                 bool needToRun = false;
693                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
694                         m->mothurOut("Your file does not include the label " + *it); 
695                         if (processedLabels.count(lastLabel) != 1) {
696                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
697                                 needToRun = true;
698                         }else {
699                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
700                         }
701                 }
702                 
703                 //run last label if you need to
704                 if (needToRun == true)  {
705                         if (rabund != NULL) {   delete rabund;  }
706                         rabund = input.getRAbundVector(lastLabel);
707                         
708                         m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
709                         
710                         RAbundVector newRabund; newRabund.setLabel(rabund->getLabel());
711                         for (int i = 0; i < rabund->getNumBins(); i++) {
712                                 if (rabund->get(i) > nseqs) {
713                                         newRabund.push_back(rabund->get(i));
714                                 }
715                         }
716                         if (newRabund.getNumBins() > 0) { newRabund.print(out); }       
717                         
718                         delete rabund;
719                 }
720                 
721                 return 0;
722         }
723         catch(exception& e) {
724                 m->errorOut(e, "RemoveRareCommand", "processRabund");
725                 exit(1);
726         }
727 }
728 //**********************************************************************************************************************
729 int RemoveRareCommand::processShared(){
730         try {
731                 m->setGroups(Groups);
732                 
733                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
734                 InputData input(sharedfile, "sharedfile");
735                 vector<SharedRAbundVector*> lookup = input.getSharedRAbundVectors();
736                 string lastLabel = lookup[0]->getLabel();
737                 set<string> processedLabels;
738                 set<string> userLabels = labels;
739                 
740                 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
741                         
742                         if (m->control_pressed) { for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  }   return 0; }
743                         
744                         if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){                  
745                                 
746                                 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
747                                 processedLabels.insert(lookup[0]->getLabel());
748                                 userLabels.erase(lookup[0]->getLabel());
749                                 
750                                 processLookup(lookup);
751                         }
752                         
753                         if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
754                                 string saveLabel = lookup[0]->getLabel();
755                                 
756                                 for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } 
757                                 lookup = input.getSharedRAbundVectors(lastLabel);
758                                 
759                                 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
760                                 processedLabels.insert(lookup[0]->getLabel());
761                                 userLabels.erase(lookup[0]->getLabel());
762                                 
763                                 processLookup(lookup);                  
764                                 
765                                 //restore real lastlabel to save below
766                                 lookup[0]->setLabel(saveLabel);
767                         }               
768                         
769                         lastLabel = lookup[0]->getLabel();                      
770                         
771                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } 
772                         lookup = input.getSharedRAbundVectors();
773                 }
774                 
775                 if (m->control_pressed) {  return 0; }  
776                 
777                 //output error messages about any remaining user labels
778                 set<string>::iterator it;
779                 bool needToRun = false;
780                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
781                         m->mothurOut("Your file does not include the label " + *it); 
782                         if (processedLabels.count(lastLabel) != 1) {
783                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
784                                 needToRun = true;
785                         }else {
786                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
787                         }
788                 }
789                 
790                 //run last label if you need to
791                 if (needToRun == true)  {
792                         for (int i = 0; i < lookup.size(); i++) {  if (lookup[i] != NULL) {     delete lookup[i];       }  }
793                         lookup = input.getSharedRAbundVectors(lastLabel);
794                         
795                         m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
796                         processLookup(lookup);  
797                         
798                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } 
799                 }
800                 
801                 return 0;
802         }
803         catch(exception& e) {
804                 m->errorOut(e, "RemoveRareCommand", "processSabund");
805                 exit(1);
806         }
807 }
808 //**********************************************************************************************************************
809 int RemoveRareCommand::processLookup(vector<SharedRAbundVector*>& lookup){
810         try {
811                 
812         string thisOutputDir = outputDir;
813                 if (outputDir == "") {  thisOutputDir += m->hasPath(sharedfile);  }
814         map<string, string> variables;
815         variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(sharedfile));
816         variables["[extension]"] = m->getExtension(sharedfile);
817         variables["[tag]"] = lookup[0]->getLabel();
818                 string outputFileName = getOutputFileName("shared", variables);
819                 outputTypes["shared"].push_back(outputFileName); outputNames.push_back(outputFileName);
820                 
821                 ofstream out;
822                 m->openOutputFile(outputFileName, out);
823         
824                 vector<SharedRAbundVector> newRabunds;  newRabunds.resize(lookup.size());
825         vector<string> headers;
826                 for (int i = 0; i < lookup.size(); i++) {  
827                         newRabunds[i].setGroup(lookup[i]->getGroup());
828                         newRabunds[i].setLabel(lookup[i]->getLabel());
829                 }
830                 
831                 if (byGroup) {
832                         
833                         //for each otu
834                         for (int i = 0; i < lookup[0]->getNumBins(); i++) {
835                                 bool allZero = true;
836                                 
837                                 if (m->control_pressed) { out.close(); return 0; }
838                                 
839                                 //for each group
840                                 for (int j = 0; j < lookup.size(); j++) {
841                                         
842                                         //are you rare?
843                                         if (lookup[j]->getAbundance(i) > nseqs) {
844                                                 newRabunds[j].push_back(lookup[j]->getAbundance(i), newRabunds[j].getGroup());
845                                                 allZero = false;
846                                         }else {
847                                                 newRabunds[j].push_back(0, newRabunds[j].getGroup());
848                                         }
849                                 }
850                                 
851                                 //eliminates zero otus
852                                 if (allZero) { for (int j = 0; j < newRabunds.size(); j++) {  newRabunds[j].pop_back(); } }
853                 else { headers.push_back(m->currentBinLabels[i]); }
854                         }
855                 }else {
856                         //for each otu
857                         for (int i = 0; i < lookup[0]->getNumBins(); i++) {
858                                 
859                                 if (m->control_pressed) { out.close(); return 0; }
860                                 
861                                 int totalAbund = 0;
862                                 //get total otu abundance
863                                 for (int j = 0; j < lookup.size(); j++) {
864                                         newRabunds[j].push_back(lookup[j]->getAbundance(i), newRabunds[j].getGroup());
865                                         totalAbund += lookup[j]->getAbundance(i);
866                                 }
867                                 
868                                 //eliminates otus below rare cutoff
869                                 if (totalAbund <= nseqs) { for (int j = 0; j < newRabunds.size(); j++) {  newRabunds[j].pop_back(); } }
870                 else { headers.push_back(m->currentBinLabels[i]); }
871                         }
872                 }
873                 
874                 //do we have any otus above the rare cutoff
875                 if (newRabunds[0].getNumBins() != 0) {
876             out << "label\tGroup\tnumOtus\t";
877             for (int j = 0; j < headers.size(); j++) { out << headers[j] << '\t'; }
878             out << endl;
879                         for (int j = 0; j < newRabunds.size(); j++) { 
880                                 out << newRabunds[j].getLabel() << '\t' << newRabunds[j].getGroup() << '\t';
881                                 newRabunds[j].print(out); 
882                         }
883                 }
884                 
885         out.close();
886         
887                 return 0;
888         }
889         catch(exception& e) {
890                 m->errorOut(e, "RemoveRareCommand", "processLookup");
891                 exit(1);
892         }
893 }
894 //**********************************************************************************************************************
895
896
897
898