]> git.donarmstrong.com Git - mothur.git/blob - removegroupscommand.cpp
changing command name classify.shared to classifyrf.shared
[mothur.git] / removegroupscommand.cpp
1 /*
2  *  removegroupscommand.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 "removegroupscommand.h"
11 #include "sequence.hpp"
12 #include "listvector.hpp"
13 #include "sharedutilities.h"
14 #include "inputdata.h"
15
16 //**********************************************************************************************************************
17 vector<string> RemoveGroupsCommand::setParameters(){    
18         try {
19                 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "FNGLT","fasta",false,false,true); parameters.push_back(pfasta);
20                 CommandParameter pshared("shared", "InputTypes", "", "", "none", "sharedGroup", "none","shared",false,false,true); parameters.push_back(pshared);
21         CommandParameter pname("name", "InputTypes", "", "", "NameCount", "none", "none","name",false,false,true); parameters.push_back(pname);
22         CommandParameter pcount("count", "InputTypes", "", "", "NameCount-CountGroup", "none", "none","count",false,false,true); parameters.push_back(pcount);
23                 CommandParameter pgroup("group", "InputTypes", "", "", "CountGroup", "sharedGroup", "FNGLT","group",false,false,true); parameters.push_back(pgroup);            
24         CommandParameter pdesign("design", "InputTypes", "", "", "none", "sharedGroup", "FNGLT","design",false,false); parameters.push_back(pdesign);
25                 CommandParameter plist("list", "InputTypes", "", "", "none", "none", "FNGLT","list",false,false,true); parameters.push_back(plist);
26                 CommandParameter ptaxonomy("taxonomy", "InputTypes", "", "", "none", "none", "FNGLT","taxonomy",false,false,true); parameters.push_back(ptaxonomy);
27                 CommandParameter paccnos("accnos", "InputTypes", "", "", "none", "none", "none","",false,false); parameters.push_back(paccnos);
28                 CommandParameter pgroups("groups", "String", "", "", "", "", "","",false,false); parameters.push_back(pgroups);
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, "RemoveGroupsCommand", "setParameters");
38                 exit(1);
39         }
40 }
41 //**********************************************************************************************************************
42 string RemoveGroupsCommand::getHelpString(){    
43         try {
44                 string helpString = "";
45                 helpString += "The remove.groups command removes sequences from a specfic group or set of groups from the following file types: fasta, name, group, count, list, taxonomy, design or sharedfile.\n";
46                 helpString += "It outputs a file containing the sequences NOT in the those specified groups, or with a sharedfile eliminates the groups you selected.\n";
47                 helpString += "The remove.groups command parameters are accnos, fasta, name, group, list, taxonomy, shared, design and groups. The group or count parameter is required, unless you have a current group or count file or are using a sharedfile.\n";
48                 helpString += "You must also provide an accnos containing the list of groups to remove or set the groups parameter to the groups you wish to remove.\n";
49                 helpString += "The groups parameter allows you to specify which of the groups in your groupfile you would like removed.  You can separate group names with dashes.\n";
50                 helpString += "The remove.groups command should be in the following format: remove.groups(accnos=yourAccnos, fasta=yourFasta, group=yourGroupFile).\n";
51                 helpString += "Example remove.groups(accnos=amazon.accnos, fasta=amazon.fasta, group=amazon.groups).\n";
52                 helpString += "or remove.groups(groups=pasture, fasta=amazon.fasta, amazon.groups).\n";
53                 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n";
54                 return helpString;
55         }
56         catch(exception& e) {
57                 m->errorOut(e, "RemoveGroupsCommand", "getHelpString");
58                 exit(1);
59         }
60 }
61 //**********************************************************************************************************************
62 string RemoveGroupsCommand::getOutputPattern(string type) {
63     try {
64         string pattern = "";
65         
66         if (type == "fasta")            {   pattern = "[filename],pick,[extension]";    }
67         else if (type == "taxonomy")    {   pattern = "[filename],pick,[extension]";    }
68         else if (type == "name")        {   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 if (type == "design")      {   pattern = "[filename],pick,[extension]";    }
74         else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true;  }
75         
76         return pattern;
77     }
78     catch(exception& e) {
79         m->errorOut(e, "RemoveGroupsCommand", "getOutputPattern");
80         exit(1);
81     }
82 }
83 //**********************************************************************************************************************
84 RemoveGroupsCommand::RemoveGroupsCommand(){     
85         try {
86                 abort = true; calledHelp = true; 
87                 setParameters();
88                 vector<string> tempOutNames;
89                 outputTypes["fasta"] = tempOutNames;
90                 outputTypes["taxonomy"] = tempOutNames;
91                 outputTypes["name"] = tempOutNames;
92                 outputTypes["group"] = tempOutNames;
93                 outputTypes["list"] = tempOutNames;
94                 outputTypes["shared"] = tempOutNames;
95         outputTypes["design"] = tempOutNames;
96         outputTypes["count"] = tempOutNames;
97         }
98         catch(exception& e) {
99                 m->errorOut(e, "RemoveGroupsCommand", "RemoveGroupsCommand");
100                 exit(1);
101         }
102 }
103 //**********************************************************************************************************************
104 RemoveGroupsCommand::RemoveGroupsCommand(string option)  {
105         try {
106                 abort = false; calledHelp = false;   
107                 
108                 //allow user to run help
109                 if(option == "help") { help(); abort = true; calledHelp = true; }
110                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
111                 
112                 else {
113                         vector<string> myArray = setParameters();
114                         
115                         OptionParser parser(option);
116                         map<string,string> parameters = parser.getParameters();
117                         
118                         ValidParameters validParameter;
119                         map<string,string>::iterator it;
120                         
121                         //check to make sure all parameters are valid for command
122                         for (it = parameters.begin(); it != parameters.end(); it++) { 
123                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
124                         }
125                         
126                         //initialize outputTypes
127                         vector<string> tempOutNames;
128                         outputTypes["fasta"] = tempOutNames;
129                         outputTypes["taxonomy"] = tempOutNames;
130                         outputTypes["name"] = tempOutNames;
131                         outputTypes["group"] = tempOutNames;
132                         outputTypes["list"] = tempOutNames;
133                         outputTypes["shared"] = tempOutNames;
134             outputTypes["design"] = tempOutNames;
135             outputTypes["count"] = tempOutNames;
136                         
137                         
138                         //if the user changes the output directory command factory will send this info to us in the output parameter 
139                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = "";         }
140                         
141                         //if the user changes the input directory command factory will send this info to us in the output parameter 
142                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
143                         if (inputDir == "not found"){   inputDir = "";          }
144                         else {
145                                 string path;
146                                 it = parameters.find("fasta");
147                                 //user has given a template file
148                                 if(it != parameters.end()){ 
149                                         path = m->hasPath(it->second);
150                                         //if the user has not given a path then, add inputdir. else leave path alone.
151                                         if (path == "") {       parameters["fasta"] = inputDir + it->second;            }
152                                 }
153                                 
154                                 it = parameters.find("accnos");
155                                 //user has given a template file
156                                 if(it != parameters.end()){ 
157                                         path = m->hasPath(it->second);
158                                         //if the user has not given a path then, add inputdir. else leave path alone.
159                                         if (path == "") {       parameters["accnos"] = inputDir + it->second;           }
160                                 }
161                                 
162                                 it = parameters.find("list");
163                                 //user has given a template file
164                                 if(it != parameters.end()){ 
165                                         path = m->hasPath(it->second);
166                                         //if the user has not given a path then, add inputdir. else leave path alone.
167                                         if (path == "") {       parameters["list"] = inputDir + it->second;             }
168                                 }
169                                 
170                                 it = parameters.find("name");
171                                 //user has given a template file
172                                 if(it != parameters.end()){ 
173                                         path = m->hasPath(it->second);
174                                         //if the user has not given a path then, add inputdir. else leave path alone.
175                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
176                                 }
177                                 
178                                 it = parameters.find("group");
179                                 //user has given a template file
180                                 if(it != parameters.end()){ 
181                                         path = m->hasPath(it->second);
182                                         //if the user has not given a path then, add inputdir. else leave path alone.
183                                         if (path == "") {       parameters["group"] = inputDir + it->second;            }
184                                 }
185                                 
186                                 it = parameters.find("taxonomy");
187                                 //user has given a template file
188                                 if(it != parameters.end()){ 
189                                         path = m->hasPath(it->second);
190                                         //if the user has not given a path then, add inputdir. else leave path alone.
191                                         if (path == "") {       parameters["taxonomy"] = inputDir + it->second;         }
192                                 }
193                                 
194                                 it = parameters.find("shared");
195                                 //user has given a template file
196                                 if(it != parameters.end()){ 
197                                         path = m->hasPath(it->second);
198                                         //if the user has not given a path then, add inputdir. else leave path alone.
199                                         if (path == "") {       parameters["shared"] = inputDir + it->second;           }
200                                 }
201                 
202                 it = parameters.find("design");
203                                 //user has given a template file
204                                 if(it != parameters.end()){ 
205                                         path = m->hasPath(it->second);
206                                         //if the user has not given a path then, add inputdir. else leave path alone.
207                                         if (path == "") {       parameters["design"] = inputDir + it->second;           }
208                                 }
209                 
210                 it = parameters.find("count");
211                                 //user has given a template file
212                                 if(it != parameters.end()){ 
213                                         path = m->hasPath(it->second);
214                                         //if the user has not given a path then, add inputdir. else leave path alone.
215                                         if (path == "") {       parameters["count"] = inputDir + it->second;            }
216                                 }
217                         }
218                         
219                         
220                         //check for required parameters
221                         accnosfile = validParameter.validFile(parameters, "accnos", true);
222                         if (accnosfile == "not open") { accnosfile = ""; abort = true; }
223                         else if (accnosfile == "not found") {  accnosfile = ""; }       
224                         else { m->setAccnosFile(accnosfile); }
225                         
226                         fastafile = validParameter.validFile(parameters, "fasta", true);
227                         if (fastafile == "not open") { fastafile = ""; abort = true; }
228                         else if (fastafile == "not found") {  fastafile = "";  }        
229                         else { m->setFastaFile(fastafile); }
230                         
231                         namefile = validParameter.validFile(parameters, "name", true);
232                         if (namefile == "not open") { namefile = ""; abort = true; }
233                         else if (namefile == "not found") {  namefile = "";  }  
234                         else { m->setNameFile(namefile); }
235                         
236                         groupfile = validParameter.validFile(parameters, "group", true);
237                         if (groupfile == "not open") { groupfile = "";  abort = true; }
238                         else if (groupfile == "not found") {    groupfile = "";         }
239                         else { m->setGroupFile(groupfile); }    
240                         
241                         listfile = validParameter.validFile(parameters, "list", true);
242                         if (listfile == "not open") { listfile = ""; abort = true; }
243                         else if (listfile == "not found") {  listfile = "";  }
244                         else { m->setListFile(listfile); }
245                         
246                         taxfile = validParameter.validFile(parameters, "taxonomy", true);
247                         if (taxfile == "not open") { taxfile = ""; abort = true; }
248                         else if (taxfile == "not found") {  taxfile = "";  }
249                         else { m->setTaxonomyFile(taxfile); }
250             
251             designfile = validParameter.validFile(parameters, "design", true);
252                         if (designfile == "not open") { designfile = ""; abort = true; }
253                         else if (designfile == "not found") {  designfile = "";  }
254                         else { m->setDesignFile(designfile); }
255                         
256                         groups = validParameter.validFile(parameters, "groups", false);                 
257                         if (groups == "not found") { groups = ""; }
258                         else { 
259                                 m->splitAtDash(groups, Groups);
260                                 m->setGroups(Groups);
261                         }
262                         
263                         sharedfile = validParameter.validFile(parameters, "shared", true);
264                         if (sharedfile == "not open") { sharedfile = ""; abort = true; }
265                         else if (sharedfile == "not found") {  sharedfile = "";  }
266                         else { m->setSharedFile(sharedfile); }
267                         
268                         
269                         countfile = validParameter.validFile(parameters, "count", true);
270             if (countfile == "not open") { countfile = ""; abort = true; }
271             else if (countfile == "not found") { countfile = "";  }     
272             else { m->setCountTableFile(countfile); }
273             
274             if ((namefile != "") && (countfile != "")) {
275                 m->mothurOut("[ERROR]: you may only use one of the following: name or count."); m->mothurOutEndLine(); abort = true;
276             }
277             
278             if ((groupfile != "") && (countfile != "")) {
279                 m->mothurOut("[ERROR]: you may only use one of the following: group or count."); m->mothurOutEndLine(); abort=true;
280             }
281             
282                         
283                         if ((sharedfile == "") && (groupfile == "") && (designfile == "") && (countfile == "")) { 
284                                 //is there are current file available for any of these?
285                                 if ((namefile != "") || (fastafile != "") || (listfile != "") || (taxfile != "")) {
286                                         //give priority to group, then shared
287                                         groupfile = m->getGroupFile(); 
288                                         if (groupfile != "") {  m->mothurOut("Using " + groupfile + " as input file for the group parameter."); m->mothurOutEndLine(); }
289                                         else { 
290                                                 sharedfile = m->getSharedFile(); 
291                                                 if (sharedfile != "") { m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
292                                                 else { 
293                                                         countfile = m->getCountTableFile(); 
294                             if (countfile != "") { m->mothurOut("Using " + countfile + " as input file for the count parameter."); m->mothurOutEndLine(); }
295                             else { 
296                                 m->mothurOut("You have no current groupfile, countfile or sharedfile and one is required."); m->mothurOutEndLine(); abort = true;
297                             }
298                                                 }
299                                         }
300                                 }else {
301                                         //give priority to shared, then group
302                                         sharedfile = m->getSharedFile(); 
303                                         if (sharedfile != "") {  m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
304                                         else { 
305                                                 groupfile = m->getGroupFile(); 
306                                                 if (groupfile != "") { m->mothurOut("Using " + groupfile + " as input file for the group parameter."); m->mothurOutEndLine(); }
307                                                 else { 
308                                                         designfile = m->getDesignFile(); 
309                             if (designfile != "") { m->mothurOut("Using " + designfile + " as input file for the design parameter."); m->mothurOutEndLine(); }
310                             else { 
311                                 countfile = m->getCountTableFile(); 
312                                 if (countfile != "") { m->mothurOut("Using " + countfile + " as input file for the count parameter."); m->mothurOutEndLine(); }
313                                 else { 
314                                     m->mothurOut("You have no current groupfile, designfile, countfile or sharedfile and one is required."); m->mothurOutEndLine(); abort = true;
315                                 }
316                                 
317                             }
318                                                 }
319                                         }
320                                 }
321                         }
322                         
323                         if ((accnosfile == "") && (Groups.size() == 0)) { m->mothurOut("You must provide an accnos file containing group names or specify groups using the groups parameter."); m->mothurOutEndLine(); abort = true; }
324                         
325                         if ((fastafile == "") && (namefile == "") && (countfile == "") && (groupfile == "")  && (designfile == "") && (sharedfile == "") && (listfile == "") && (taxfile == ""))  { m->mothurOut("You must provide at least one of the following: fasta, name, taxonomy, group, shared, design, count or list."); m->mothurOutEndLine(); abort = true; }
326                         if (((groupfile == "") && (countfile == "")) && ((namefile != "") || (fastafile != "") || (listfile != "") || (taxfile != "")))  { m->mothurOut("If using a fasta, name, taxonomy, group or list, then you must provide a group or count file."); m->mothurOutEndLine(); abort = true; }
327             
328             if (countfile == "") {
329                 if ((namefile == "") && ((fastafile != "") || (taxfile != ""))){
330                     vector<string> files; files.push_back(fastafile); files.push_back(taxfile);
331                     parser.getNameFile(files);
332                 }
333             }
334                 }
335                 
336         }
337         catch(exception& e) {
338                 m->errorOut(e, "RemoveGroupsCommand", "RemoveGroupsCommand");
339                 exit(1);
340         }
341 }
342 //**********************************************************************************************************************
343
344 int RemoveGroupsCommand::execute(){
345         try {
346                 
347                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
348                 
349                 //get groups you want to remove
350                 if (accnosfile != "") { m->readAccnos(accnosfile, Groups); m->setGroups(Groups);  }
351                 
352                 if (groupfile != "") {
353                         groupMap = new GroupMap(groupfile);
354                         groupMap->readMap();
355                         
356                         //make sure groups are valid
357                         //takes care of user setting groupNames that are invalid or setting groups=all
358                         vector<string> namesGroups = groupMap->getNamesOfGroups();
359                         vector<string> checkedGroups;
360             for (int i = 0; i < Groups.size(); i++) {
361                 if (m->inUsersGroups(Groups[i], namesGroups)) { checkedGroups.push_back(Groups[i]); }
362                 else {  m->mothurOut("[WARNING]: " + Groups[i] + " is not a valid group in your groupfile, ignoring.\n"); }
363             }
364             
365             if (checkedGroups.size() == 0) { m->mothurOut("[ERROR]: no valid groups, aborting.\n"); delete groupMap; return 0; }
366                         else {
367                 Groups = checkedGroups;
368                 m->setGroups(Groups);
369             }
370             
371                         //fill names with names of sequences that are from the groups we want to remove 
372                         fillNames();
373                         
374                         delete groupMap;
375                 }else if (countfile != ""){
376             if ((fastafile != "") || (listfile != "") || (taxfile != "")) { 
377                 m->mothurOut("\n[NOTE]: The count file should contain only unique names, so mothur assumes your fasta, list and taxonomy files also contain only uniques.\n\n");
378             }
379             CountTable ct;
380             ct.readTable(countfile, true);
381             if (!ct.hasGroupInfo()) { m->mothurOut("[ERROR]: your count file does not contain group info, aborting.\n"); return 0; }
382             
383             vector<string> gNamesOfGroups = ct.getNamesOfGroups();
384             SharedUtil util;
385             util.setGroups(Groups, gNamesOfGroups);
386             vector<string> namesOfSeqs = ct.getNamesOfSeqs();
387             sort(Groups.begin(), Groups.end());
388             
389             for (int i = 0; i < namesOfSeqs.size(); i++) {
390                 vector<string> thisSeqsGroups = ct.getGroups(namesOfSeqs[i]);
391                 if (m->isSubset(Groups, thisSeqsGroups)) { //you only have seqs from these groups so remove you
392                     names.insert(namesOfSeqs[i]);
393                 }
394             }
395         }
396
397                                 
398                 if (m->control_pressed) { return 0; }
399                 
400                 //read through the correct file and output lines you want to keep
401                 if (namefile != "")                     {               readName();             }
402                 if (fastafile != "")            {               readFasta();    }
403                 if (groupfile != "")            {               readGroup();    }
404         if (countfile != "")            {               readCount();    }
405                 if (listfile != "")                     {               readList();             }
406                 if (taxfile != "")                      {               readTax();              }
407                 if (sharedfile != "")           {               readShared();   }
408         if (designfile != "")           {               readDesign();   }
409                 
410                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]); } return 0; }
411                                 
412                 if (outputNames.size() != 0) {
413                         m->mothurOutEndLine();
414                         m->mothurOut("Output File names: "); m->mothurOutEndLine();
415                         for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
416                         m->mothurOutEndLine();
417                         
418                         //set fasta file as new current fastafile
419                         string current = "";
420                         itTypes = outputTypes.find("fasta");
421                         if (itTypes != outputTypes.end()) {
422                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
423                         }
424                         
425                         itTypes = outputTypes.find("name");
426                         if (itTypes != outputTypes.end()) {
427                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
428                         }
429                         
430                         itTypes = outputTypes.find("group");
431                         if (itTypes != outputTypes.end()) {
432                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setGroupFile(current); }
433                         }
434                         
435                         itTypes = outputTypes.find("list");
436                         if (itTypes != outputTypes.end()) {
437                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setListFile(current); }
438                         }
439                         
440                         itTypes = outputTypes.find("taxonomy");
441                         if (itTypes != outputTypes.end()) {
442                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setTaxonomyFile(current); }
443                         }
444                         
445                         itTypes = outputTypes.find("shared");
446                         if (itTypes != outputTypes.end()) {
447                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSharedFile(current); }
448                         }
449             
450             itTypes = outputTypes.find("design");
451                         if (itTypes != outputTypes.end()) {
452                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setDesignFile(current); }
453                         }
454             
455             itTypes = outputTypes.find("count");
456                         if (itTypes != outputTypes.end()) {
457                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setCountTableFile(current); }
458                         }
459                 }
460                 
461                 return 0;               
462         }
463         
464         catch(exception& e) {
465                 m->errorOut(e, "RemoveGroupsCommand", "execute");
466                 exit(1);
467         }
468 }
469
470 //**********************************************************************************************************************
471 int RemoveGroupsCommand::readFasta(){
472         try {
473                 string thisOutputDir = outputDir;
474                 if (outputDir == "") {  thisOutputDir += m->hasPath(fastafile);  }
475         map<string, string> variables; 
476         variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(fastafile));
477         variables["[extension]"] = m->getExtension(fastafile);
478                 string outputFileName = getOutputFileName("fasta", variables);
479                 
480                 ofstream out;
481                 m->openOutputFile(outputFileName, out);
482                 
483                 ifstream in;
484                 m->openInputFile(fastafile, in);
485                 string name;
486                 
487                 bool wroteSomething = false;
488                 int removedCount = 0;
489                 
490                 while(!in.eof()){
491                         if (m->control_pressed) { in.close();  out.close();  m->mothurRemove(outputFileName);  return 0; }
492                         
493                         Sequence currSeq(in);
494                         name = currSeq.getName();
495                         
496                         if (name != "") {
497                                 //if this name is in the accnos file
498                                 if (names.count(name) == 0) {
499                                         wroteSomething = true;
500                                         currSeq.printSequence(out); 
501                                 }else { 
502                                         //if you are not in the accnos file check if you are a name that needs to be changed
503                                         map<string, string>::iterator it = uniqueToRedundant.find(name);
504                                         if (it != uniqueToRedundant.end()) {
505                                                 wroteSomething = true;
506                                                 currSeq.setName(it->second);
507                                                 currSeq.printSequence(out);
508                                         }else { removedCount++; }
509                                 }
510                         }
511                         m->gobble(in);
512                 }
513                 in.close();     
514                 out.close();
515                 
516                 if (wroteSomething == false) {  m->mothurOut("Your file contains only sequences from the groups you wish to remove."); m->mothurOutEndLine();  }
517                 outputTypes["fasta"].push_back(outputFileName);  outputNames.push_back(outputFileName);
518                 
519                 m->mothurOut("Removed " + toString(removedCount) + " sequences from your fasta file."); m->mothurOutEndLine();
520                 
521                 return 0;
522                 
523         }
524         catch(exception& e) {
525                 m->errorOut(e, "RemoveGroupsCommand", "readFasta");
526                 exit(1);
527         }
528 }
529 //**********************************************************************************************************************
530 int RemoveGroupsCommand::readShared(){
531         try {
532                 string thisOutputDir = outputDir;
533                 if (outputDir == "") {  thisOutputDir += m->hasPath(sharedfile);  }
534                 
535                 //get group names from sharedfile so we can set Groups to the groupNames we want to keep
536                 //that way we can take advantage of the reads in inputdata and sharedRabundVector
537                 InputData* tempInput = new InputData(sharedfile, "sharedfile");
538                 vector<SharedRAbundVector*> lookup = tempInput->getSharedRAbundVectors();
539         
540         map<string, string> variables; 
541         variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(sharedfile));
542         variables["[extension]"] = m->getExtension(sharedfile);
543         
544                 //save m->Groups
545                 vector<string> allGroupsNames = m->getAllGroups();
546                 vector<string> mothurOutGroups = m->getGroups();
547                 
548                 vector<string> groupsToKeep;
549                 for (int i = 0; i < allGroupsNames.size(); i++) {
550                         if (!m->inUsersGroups(allGroupsNames[i], m->getGroups())) {
551                                 groupsToKeep.push_back(allGroupsNames[i]);
552                         }
553                 }
554                 
555                 if (allGroupsNames.size() == groupsToKeep.size()) { m->mothurOut("Your file does not contain any groups you wish to remove."); m->mothurOutEndLine(); m->setGroups(mothurOutGroups); delete tempInput; for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  }  return 0; }
556                 
557                 //reset read 
558                 for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } 
559                 delete tempInput;
560                 m->setGroups(groupsToKeep);
561                 m->clearAllGroups();
562                 m->saveNextLabel = "";
563                 m->printedHeaders = false;
564                 m->currentBinLabels.clear();
565                 m->binLabelsInFile.clear();
566                 
567                 InputData input(sharedfile, "sharedfile");
568                 lookup = input.getSharedRAbundVectors();
569
570                 bool wroteSomething = false;
571                 
572                 while(lookup[0] != NULL) {
573                         
574                         variables["[tag]"] = lookup[0]->getLabel();
575             string outputFileName = getOutputFileName("shared", variables);
576                         ofstream out;
577                         m->openOutputFile(outputFileName, out);
578                         outputTypes["shared"].push_back(outputFileName);  outputNames.push_back(outputFileName);
579                         
580                         if (m->control_pressed) { out.close();  m->mothurRemove(outputFileName);  for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; } return 0; }
581                         
582                         lookup[0]->printHeaders(out); 
583                         
584                         for (int i = 0; i < lookup.size(); i++) {
585                                 out << lookup[i]->getLabel() << '\t' << lookup[i]->getGroup() << '\t';
586                                 lookup[i]->print(out);
587                                 wroteSomething = true;
588                                 
589                         }                       
590                         
591                         //get next line to process
592                         //prevent memory leak
593                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } 
594                         lookup = input.getSharedRAbundVectors();
595                         
596                         out.close();
597                 }
598                 
599                 
600                 m->setGroups(mothurOutGroups);
601                 
602                 if (wroteSomething == false) {  m->mothurOut("Your file contains only the groups you wish to remove."); m->mothurOutEndLine();  }
603                 
604                 string groupsString = "";
605                 for (int i = 0; i < Groups.size()-1; i++) {     groupsString += Groups[i] + ", "; }
606                 groupsString += Groups[Groups.size()-1];
607                 
608                 m->mothurOut("Removed groups: " + groupsString + " from your shared file."); m->mothurOutEndLine();
609                 
610                 return 0;
611                 
612         }
613         catch(exception& e) {
614                 m->errorOut(e, "RemoveGroupsCommand", "readShared");
615                 exit(1);
616         }
617 }
618 //**********************************************************************************************************************
619 int RemoveGroupsCommand::readList(){
620         try {
621                 string thisOutputDir = outputDir;
622                 if (outputDir == "") {  thisOutputDir += m->hasPath(listfile);  }
623                 map<string, string> variables; 
624         variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(listfile));
625         variables["[extension]"] = m->getExtension(listfile);
626                 string outputFileName = getOutputFileName("list", variables);
627
628                 
629                 ofstream out;
630                 m->openOutputFile(outputFileName, out);
631                 
632                 ifstream in;
633                 m->openInputFile(listfile, in);
634                 
635                 bool wroteSomething = false;
636                 int removedCount = 0;
637                 
638                 while(!in.eof()){
639                         
640                         removedCount = 0;
641                         
642                         //read in list vector
643                         ListVector list(in);
644                         
645                         //make a new list vector
646                         ListVector newList;
647                         newList.setLabel(list.getLabel());
648                         
649                         //for each bin
650                         for (int i = 0; i < list.getNumBins(); i++) {
651                                 if (m->control_pressed) { in.close();  out.close();  m->mothurRemove(outputFileName);  return 0; }
652                                 
653                                 //parse out names that are in accnos file
654                                 string binnames = list.get(i);
655                                 
656                                 string newNames = "";
657                                 while (binnames.find_first_of(',') != -1) { 
658                                         string name = binnames.substr(0,binnames.find_first_of(','));
659                                         binnames = binnames.substr(binnames.find_first_of(',')+1, binnames.length());
660                                         
661                                         //if that name is in the .accnos file, add it
662                                         if (names.count(name) == 0) {  newNames += name + ",";  }
663                                         else {
664                                                 //if you are not in the accnos file check if you are a name that needs to be changed
665                                                 map<string, string>::iterator it = uniqueToRedundant.find(name);
666                                                 if (it != uniqueToRedundant.end()) {
667                                                         newNames += it->second + ",";
668                                                 }else { removedCount++; }
669                                         }
670                                 }
671                                 
672                                 //get last name
673                                 if (names.count(binnames) == 0) {  newNames += binnames + ",";  }
674                                 else { //if you are not in the accnos file check if you are a name that needs to be changed
675                                         map<string, string>::iterator it = uniqueToRedundant.find(binnames);
676                                         if (it != uniqueToRedundant.end()) {
677                                                 newNames += it->second + ",";
678                                         }else { removedCount++; }
679                                 }
680                                 
681                                 //if there are names in this bin add to new list
682                                 if (newNames != "") {  
683                                         newNames = newNames.substr(0, newNames.length()-1); //rip off extra comma
684                                         newList.push_back(newNames);    
685                                 }
686                         }
687                         
688                         //print new listvector
689                         if (newList.getNumBins() != 0) {
690                                 wroteSomething = true;
691                                 newList.print(out);
692                         }
693                         
694                         m->gobble(in);
695                 }
696                 in.close();     
697                 out.close();
698                 
699                 if (wroteSomething == false) {  m->mothurOut("Your file contains only sequences from the groups you wish to remove."); m->mothurOutEndLine();  }
700                 outputTypes["list"].push_back(outputFileName); outputNames.push_back(outputFileName);
701                 
702                 m->mothurOut("Removed " + toString(removedCount) + " sequences from your list file."); m->mothurOutEndLine();
703                 
704                 return 0;
705                 
706         }
707         catch(exception& e) {
708                 m->errorOut(e, "RemoveGroupsCommand", "readList");
709                 exit(1);
710         }
711 }
712 //**********************************************************************************************************************
713 int RemoveGroupsCommand::readName(){
714         try {
715                 string thisOutputDir = outputDir;
716                 if (outputDir == "") {  thisOutputDir += m->hasPath(namefile);  }
717                 map<string, string> variables; 
718                 variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(namefile));
719         variables["[extension]"] = m->getExtension(namefile);
720                 string outputFileName = getOutputFileName("name", variables);   
721                 ofstream out;
722                 m->openOutputFile(outputFileName, out);
723                 
724                 ifstream in;
725                 m->openInputFile(namefile, in);
726                 string name, firstCol, secondCol;
727                 
728                 bool wroteSomething = false;
729                 int removedCount = 0;
730                 
731                 while(!in.eof()){
732                         if (m->control_pressed) { in.close();  out.close();  m->mothurRemove(outputFileName);  return 0; }
733                         
734                         in >> firstCol;         m->gobble(in);          
735                         in >> secondCol;                        
736                         
737                         vector<string> parsedNames;
738                         m->splitAtComma(secondCol, parsedNames);
739                                                 
740                         vector<string> validSecond;  validSecond.clear();
741                         for (int i = 0; i < parsedNames.size(); i++) {
742                                 if (names.count(parsedNames[i]) == 0) {
743                                         validSecond.push_back(parsedNames[i]);
744                                 }
745                         }
746                         
747                         removedCount += parsedNames.size()-validSecond.size();
748                         
749                         //if the name in the first column is in the set then print it and any other names in second column also in set
750                         if (names.count(firstCol) == 0) {
751                                 
752                                 wroteSomething = true;
753                                 
754                                 out << firstCol << '\t';
755                                 
756                                 //you know you have at least one valid second since first column is valid
757                                 for (int i = 0; i < validSecond.size()-1; i++) {  out << validSecond[i] << ',';  }
758                                 out << validSecond[validSecond.size()-1] << endl;
759                                 
760                                 //make first name in set you come to first column and then add the remaining names to second column
761                         }else {
762                                 
763                                 //you want part of this row
764                                 if (validSecond.size() != 0) {
765                                         
766                                         wroteSomething = true;
767                                         
768                                         out << validSecond[0] << '\t';
769                                         
770                                         //you know you have at least one valid second since first column is valid
771                                         for (int i = 0; i < validSecond.size()-1; i++) {  out << validSecond[i] << ',';  }
772                                         out << validSecond[validSecond.size()-1] << endl;
773                                         uniqueToRedundant[firstCol] = validSecond[0];
774                                 }
775                         }
776                         
777                         m->gobble(in);
778                 }
779                 in.close();
780                 out.close();
781                 
782                 if (wroteSomething == false) {  m->mothurOut("Your file contains only sequences from the groups you wish to remove."); m->mothurOutEndLine();  }
783                 outputTypes["name"].push_back(outputFileName); outputNames.push_back(outputFileName);
784                 
785                 m->mothurOut("Removed " + toString(removedCount) + " sequences from your name file."); m->mothurOutEndLine();
786                 
787                 return 0;
788         }
789         catch(exception& e) {
790                 m->errorOut(e, "RemoveGroupsCommand", "readName");
791                 exit(1);
792         }
793 }
794
795 //**********************************************************************************************************************
796 int RemoveGroupsCommand::readGroup(){
797         try {
798                 string thisOutputDir = outputDir;
799                 if (outputDir == "") {  thisOutputDir += m->hasPath(groupfile);  }
800         map<string, string> variables; 
801                 variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(groupfile));
802         variables["[extension]"] = m->getExtension(groupfile);
803                 string outputFileName = getOutputFileName("group", variables);  
804                 ofstream out;
805                 m->openOutputFile(outputFileName, out);
806                 
807                 ifstream in;
808                 m->openInputFile(groupfile, in);
809                 string name, group;
810                 
811                 bool wroteSomething = false;
812                 int removedCount = 0;
813                 
814                 while(!in.eof()){
815                         if (m->control_pressed) { in.close();  out.close();  m->mothurRemove(outputFileName);  return 0; }
816                         
817                         in >> name;                             //read from first column
818                         in >> group;                    //read from second column
819                         
820                         //if this name is in the accnos file
821                         if (names.count(name) == 0) {
822                                 wroteSomething = true;
823                                 out << name << '\t' << group << endl;
824                         }else {  removedCount++;  }
825                         
826                         m->gobble(in);
827                 }
828                 in.close();
829                 out.close();
830                 
831                 if (wroteSomething == false) {  m->mothurOut("Your file contains only sequences from the groups you wish to remove."); m->mothurOutEndLine();  }
832                 outputTypes["group"].push_back(outputFileName); outputNames.push_back(outputFileName);
833                 
834                 m->mothurOut("Removed " + toString(removedCount) + " sequences from your group file."); m->mothurOutEndLine();
835
836                 
837                 return 0;
838         }
839         catch(exception& e) {
840                 m->errorOut(e, "RemoveGroupsCommand", "readGroup");
841                 exit(1);
842         }
843 }
844 //**********************************************************************************************************************
845 int RemoveGroupsCommand::readCount(){
846         try {
847                 string thisOutputDir = outputDir;
848                 if (outputDir == "") {  thisOutputDir += m->hasPath(countfile);  }
849                 map<string, string> variables; 
850                 variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(countfile));
851         variables["[extension]"] = m->getExtension(countfile);
852                 string outputFileName = getOutputFileName("count", variables);
853                 
854                 ofstream out;
855                 m->openOutputFile(outputFileName, out);
856                 
857                 ifstream in;
858                 m->openInputFile(countfile, in);
859                 
860                 bool wroteSomething = false;
861                 int removedCount = 0;
862                 
863         string headers = m->getline(in); m->gobble(in);
864         vector<string> columnHeaders = m->splitWhiteSpace(headers);
865         
866         vector<string> groups;
867         map<int, string> originalGroupIndexes;
868         map<string, int> GroupIndexes;
869         set<int> indexOfGroupsChosen;
870         for (int i = 2; i < columnHeaders.size(); i++) {  groups.push_back(columnHeaders[i]);  originalGroupIndexes[i-2] = columnHeaders[i]; }
871         //sort groups to keep consistent with how we store the groups in groupmap
872         sort(groups.begin(), groups.end());
873         for (int i = 0; i < groups.size(); i++) {  GroupIndexes[groups[i]] = i; }
874
875                 vector<string> groupsToKeep;
876                 for (int i = 0; i < groups.size(); i++) {
877                         if (!m->inUsersGroups(groups[i], Groups)) { groupsToKeep.push_back(groups[i]); }
878                 }
879         sort(groupsToKeep.begin(), groupsToKeep.end());
880         out << "Representative_Sequence\ttotal\t";
881         for (int i = 0; i < groupsToKeep.size(); i++) { out << groupsToKeep[i] << '\t'; indexOfGroupsChosen.insert(GroupIndexes[groupsToKeep[i]]); }
882         out << endl;
883         
884         string name; int oldTotal;
885         while (!in.eof()) {
886             
887             if (m->control_pressed) { in.close();  out.close();  m->mothurRemove(outputFileName);  return 0; }
888             
889             in >> name; m->gobble(in); in >> oldTotal; m->gobble(in);
890             if (m->debug) { m->mothurOut("[DEBUG]: " + name + '\t' + toString(oldTotal) + "\n"); }
891             
892             if (names.count(name) == 0) {
893                 //if group info, then read it
894                 vector<int> selectedCounts; int thisTotal = 0; int temp;
895                 for (int i = 0; i < groups.size(); i++) {  
896                     int thisIndex = GroupIndexes[originalGroupIndexes[i]]; 
897                     in >> temp;  m->gobble(in);
898                     if (indexOfGroupsChosen.count(thisIndex) != 0) { //we want this group
899                         selectedCounts.push_back(temp); thisTotal += temp;
900                     }
901                 }
902                 
903                 out << name << '\t' << thisTotal << '\t';
904                 for (int i = 0; i < selectedCounts.size(); i++) {  out << selectedCounts[i] << '\t'; }
905                 out << endl;
906                 
907                 wroteSomething = true;
908                 removedCount+= (oldTotal - thisTotal);
909             }else {  m->getline(in); removedCount += oldTotal; }
910             
911             m->gobble(in);
912         }
913         in.close();
914                 out.close();
915                 
916                 if (wroteSomething == false) {  m->mothurOut("Your file does NOT contain sequences from the groups you wish to get."); m->mothurOutEndLine();  }
917                 outputTypes["count"].push_back(outputFileName); outputNames.push_back(outputFileName);
918                 
919                 m->mothurOut("Removed " + toString(removedCount) + " sequences from your count file."); m->mothurOutEndLine();
920         
921                 return 0;
922         }
923         catch(exception& e) {
924                 m->errorOut(e, "RemoveGroupsCommand", "readCount");
925                 exit(1);
926         }
927 }
928 //**********************************************************************************************************************
929 int RemoveGroupsCommand::readDesign(){
930         try {
931                 string thisOutputDir = outputDir;
932                 if (outputDir == "") {  thisOutputDir += m->hasPath(designfile);  }
933         map<string, string> variables; 
934                 variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(designfile));
935         variables["[extension]"] = m->getExtension(designfile);
936                 string outputFileName = getOutputFileName("design", variables);
937                 
938                 ofstream out;
939                 m->openOutputFile(outputFileName, out);
940                 
941                 ifstream in;
942                 m->openInputFile(designfile, in);
943                 string name, group;
944                 
945                 bool wroteSomething = false;
946                 int removedCount = 0;
947                 
948                 while(!in.eof()){
949                         if (m->control_pressed) { in.close();  out.close();  m->mothurRemove(outputFileName);  return 0; }
950                         
951                         in >> name;                             //read from first column
952                         in >> group;                    //read from second column
953                         
954                         //if this name is in the accnos file
955                         if (!(m->inUsersGroups(name, Groups))) {
956                                 wroteSomething = true;
957                                 out << name << '\t' << group << endl;
958                         }else {  removedCount++;  }
959                         
960                         m->gobble(in);
961                 }
962                 in.close();
963                 out.close();
964                 
965                 if (wroteSomething == false) {  m->mothurOut("Your file contains only groups from the groups you wish to remove."); m->mothurOutEndLine();  }
966                 outputTypes["design"].push_back(outputFileName); outputNames.push_back(outputFileName);
967                 
968                 m->mothurOut("Removed " + toString(removedCount) + " groups from your design file."); m->mothurOutEndLine();
969         
970                 
971                 return 0;
972         }
973         catch(exception& e) {
974                 m->errorOut(e, "RemoveGroupsCommand", "readDesign");
975                 exit(1);
976         }
977 }
978
979 //**********************************************************************************************************************
980 int RemoveGroupsCommand::readTax(){
981         try {
982                 string thisOutputDir = outputDir;
983                 if (outputDir == "") {  thisOutputDir += m->hasPath(taxfile);  }
984                 map<string, string> variables; 
985                 variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(taxfile));
986         variables["[extension]"] = m->getExtension(taxfile);
987                 string outputFileName = getOutputFileName("taxonomy", variables);
988                 ofstream out;
989                 m->openOutputFile(outputFileName, out);
990                 
991                 ifstream in;
992                 m->openInputFile(taxfile, in);
993                 string name, tax;
994                 
995                 bool wroteSomething = false;
996                 int removedCount = 0;
997                 
998                 while(!in.eof()){
999                         if (m->control_pressed) { in.close();  out.close();  m->mothurRemove(outputFileName);  return 0; }
1000                         
1001                         in >> name;                             //read from first column
1002                         in >> tax;                      //read from second column
1003                         
1004                         //if this name is in the accnos file
1005                         if (names.count(name) == 0) {
1006                                 wroteSomething = true;
1007                                 out << name << '\t' << tax << endl;
1008                         }else {  //if you are not in the accnos file check if you are a name that needs to be changed
1009                                 map<string, string>::iterator it = uniqueToRedundant.find(name);
1010                                 if (it != uniqueToRedundant.end()) {
1011                                         wroteSomething = true;
1012                                         out << it->second << '\t' << tax << endl;
1013                                 }else { removedCount++; }  }
1014                         
1015                         m->gobble(in);
1016                 }
1017                 in.close();
1018                 out.close();
1019                 
1020                 if (wroteSomething == false) {  m->mothurOut("Your file contains only sequences from the groups you wish to remove."); m->mothurOutEndLine();  }
1021                 outputTypes["taxonomy"].push_back(outputFileName); outputNames.push_back(outputFileName);
1022                 
1023                 m->mothurOut("Removed " + toString(removedCount) + " sequences from your taxonomy file."); m->mothurOutEndLine();
1024                 
1025                 return 0;
1026         }
1027         catch(exception& e) {
1028                 m->errorOut(e, "RemoveGroupsCommand", "readTax");
1029                 exit(1);
1030         }
1031 }
1032 //**********************************************************************************************************************
1033 int RemoveGroupsCommand::fillNames(){
1034         try {
1035                 vector<string> seqs = groupMap->getNamesSeqs();
1036                 
1037                 for (int i = 0; i < seqs.size(); i++) {
1038                         
1039                         if (m->control_pressed) { return 0; }
1040                         
1041                         string group = groupMap->getGroup(seqs[i]);
1042                         
1043                         if (m->inUsersGroups(group, Groups)) {
1044                                 names.insert(seqs[i]);
1045                         }
1046                 }
1047                 
1048                 return 0;
1049         }
1050         catch(exception& e) {
1051                 m->errorOut(e, "RemoveGroupsCommand", "fillNames");
1052                 exit(1);
1053         }
1054 }
1055
1056 //**********************************************************************************************************************
1057
1058
1059