]> git.donarmstrong.com Git - mothur.git/blob - subsamplecommand.cpp
6c0d1bcbe71a3c3c2a7fccda9695f7aef6aec25b
[mothur.git] / subsamplecommand.cpp
1 /*
2  *  subsamplecommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 10/27/10.
6  *  Copyright 2010 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "subsamplecommand.h"
11 #include "sharedutilities.h"
12 #include "deconvolutecommand.h"
13 #include "getseqscommand.h"
14 #include "subsample.h"
15
16 //**********************************************************************************************************************
17 vector<string> SubSampleCommand::setParameters(){       
18         try {           
19                 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "FLSSR", "none","fasta",false,false,true); parameters.push_back(pfasta);
20         CommandParameter pname("name", "InputTypes", "", "", "NameCount", "none", "none","name",false,false,true); parameters.push_back(pname);
21         CommandParameter ptaxonomy("taxonomy", "InputTypes", "", "", "none", "none", "none","taxonomy",false,false,true); parameters.push_back(ptaxonomy);
22         CommandParameter pcount("count", "InputTypes", "", "", "NameCount-CountGroup", "none", "none","count",false,false,true); parameters.push_back(pcount);
23                 CommandParameter pgroup("group", "InputTypes", "", "", "CountGroup", "none", "none","group",false,false,true); parameters.push_back(pgroup);
24                 CommandParameter plist("list", "InputTypes", "", "", "none", "FLSSR", "none","list",false,false,true); parameters.push_back(plist);
25                 CommandParameter pshared("shared", "InputTypes", "", "", "none", "FLSSR", "none","shared",false,false,true); parameters.push_back(pshared);
26                 CommandParameter prabund("rabund", "InputTypes", "", "", "none", "FLSSR", "none","rabund",false,false); parameters.push_back(prabund);
27                 CommandParameter psabund("sabund", "InputTypes", "", "", "none", "FLSSR", "none","sabund",false,false); parameters.push_back(psabund);
28                 CommandParameter plabel("label", "String", "", "", "", "", "","",false,false); parameters.push_back(plabel);
29                 CommandParameter pgroups("groups", "String", "", "", "", "", "","",false,false); parameters.push_back(pgroups);
30                 CommandParameter psize("size", "Number", "", "0", "", "", "","",false,false,true); parameters.push_back(psize);
31                 CommandParameter ppersample("persample", "Boolean", "", "F", "", "", "","",false,false,true); parameters.push_back(ppersample);
32                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
33                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
34                 
35                 vector<string> myArray;
36                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
37                 return myArray;
38         }
39         catch(exception& e) {
40                 m->errorOut(e, "SubSampleCommand", "setParameters");
41                 exit(1);
42         }
43 }
44 //**********************************************************************************************************************
45 string SubSampleCommand::getHelpString(){       
46         try {
47                 string helpString = "";
48                 helpString += "The sub.sample command is designed to be used as a way to normalize your data, or create a smaller set from your original set.\n";
49                 helpString += "The sub.sample command parameters are fasta, name, list, group, count, rabund, sabund, shared, taxonomy, groups, size, persample and label.  You must provide a fasta, list, sabund, rabund or shared file as an input file.\n";
50                 helpString += "The namefile is only used with the fasta file, not with the listfile, because the list file should contain all sequences.\n";
51                 helpString += "The groups parameter allows you to specify which of the groups in your groupfile you would like included. The group names are separated by dashes.\n";
52                 helpString += "The label parameter allows you to select what distance levels you would like, and are also separated by dashes.\n";
53                 helpString += "The size parameter allows you indicate the size of your subsample.\n";
54                 helpString += "The persample parameter allows you indicate you want to select subsample of the same size from each of your groups, default=false. It is only used with the list and fasta files if a groupfile is given.\n";
55                 helpString += "persample=false will select a random set of sequences of the size you select, but the number of seqs from each group may differ.\n";
56                 helpString += "The size parameter is not set: with shared file size=number of seqs in smallest sample, with all other files if a groupfile is given and persample=true, then size=number of seqs in smallest sample, otherwise size=10% of number of seqs.\n";
57                 helpString += "The sub.sample command should be in the following format: sub.sample(list=yourListFile, group=yourGroupFile, groups=yourGroups, label=yourLabels).\n";
58                 helpString += "Example sub.sample(list=abrecovery.fn.list, group=abrecovery.groups, groups=B-C, size=20).\n";
59                 helpString += "The default value for groups is all the groups in your groupfile, and all labels in your inputfile will be used.\n";
60                 helpString += "The sub.sample command outputs a .subsample file.\n";
61                 helpString += "Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n";
62                 return helpString;
63         }
64         catch(exception& e) {
65                 m->errorOut(e, "SubSampleCommand", "getHelpString");
66                 exit(1);
67         }
68 }
69 //**********************************************************************************************************************
70 string SubSampleCommand::getOutputPattern(string type) {
71     try {
72         string pattern = "";
73         
74         if (type == "fasta")            {   pattern = "[filename],subsample,[extension]";    }
75         else if (type == "sabund")      {   pattern = "[filename],subsample,[extension]";    }
76         else if (type == "name")        {   pattern = "[filename],subsample,[extension]";    }
77         else if (type == "group")       {   pattern = "[filename],subsample,[extension]";    }
78         else if (type == "count")       {   pattern = "[filename],subsample,[extension]";    }
79         else if (type == "list")        {   pattern = "[filename],subsample,[extension]";    }
80         else if (type == "taxonomy")    {   pattern = "[filename],subsample,[extension]";    }
81         else if (type == "shared")      {   pattern = "[filename],[distance],subsample,[extension]";    }
82         else if (type == "rabund")      {   pattern = "[filename],subsample,[extension]";    }
83         else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true;  }
84         
85         return pattern;
86     }
87     catch(exception& e) {
88         m->errorOut(e, "SubSampleCommand", "getOutputPattern");
89         exit(1);
90     }
91 }
92 //**********************************************************************************************************************
93 SubSampleCommand::SubSampleCommand(){   
94         try {
95                 abort = true; calledHelp = true; 
96                 setParameters();
97                 vector<string> tempOutNames;
98                 outputTypes["shared"] = tempOutNames;
99                 outputTypes["list"] = tempOutNames;
100                 outputTypes["rabund"] = tempOutNames;
101                 outputTypes["sabund"] = tempOutNames;
102                 outputTypes["fasta"] = tempOutNames;
103                 outputTypes["name"] = tempOutNames;
104                 outputTypes["group"] = tempOutNames;
105         outputTypes["count"] = tempOutNames;
106         outputTypes["taxonomy"] = tempOutNames;
107         }
108         catch(exception& e) {
109                 m->errorOut(e, "SubSampleCommand", "GetRelAbundCommand");
110                 exit(1);
111         }
112 }
113 //**********************************************************************************************************************
114 SubSampleCommand::SubSampleCommand(string option) {
115         try {
116                 abort = false; calledHelp = false;   
117                 allLines = 1;
118                 
119                 //allow user to run help
120                 if(option == "help") { help(); abort = true; calledHelp = true; }
121                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
122                 
123                 else {
124                         vector<string> myArray = setParameters();
125                         
126                         OptionParser parser(option);
127                         map<string,string> parameters = parser.getParameters();
128                         
129                         ValidParameters validParameter;
130                         
131                         //check to make sure all parameters are valid for command
132                         map<string,string>::iterator it;
133                         for (it = parameters.begin(); it != parameters.end(); it++) { 
134                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
135                         }
136                         
137                         //initialize outputTypes
138                         vector<string> tempOutNames;
139                         outputTypes["shared"] = tempOutNames;
140                         outputTypes["list"] = tempOutNames;
141                         outputTypes["rabund"] = tempOutNames;
142                         outputTypes["sabund"] = tempOutNames;
143                         outputTypes["fasta"] = tempOutNames;
144                         outputTypes["name"] = tempOutNames;
145                         outputTypes["group"] = tempOutNames;
146             outputTypes["count"] = tempOutNames;
147             outputTypes["taxonomy"] = tempOutNames;
148                                         
149                         //if the user changes the output directory command factory will send this info to us in the output parameter 
150                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = ""; }
151                         
152                         //if the user changes the input directory command factory will send this info to us in the output parameter 
153                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
154                         if (inputDir == "not found"){   inputDir = "";          }
155                         else {
156                                 string path;
157                                 it = parameters.find("list");
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["list"] = inputDir + it->second;             }
163                                 }
164                                 
165                                 it = parameters.find("fasta");
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["fasta"] = 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("group");
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["group"] = inputDir + it->second;            }
187                                 }
188                                 
189                                 it = parameters.find("sabund");
190                                 //user has given a template file
191                                 if(it != parameters.end()){ 
192                                         path = m->hasPath(it->second);
193                                         //if the user has not given a path then, add inputdir. else leave path alone.
194                                         if (path == "") {       parameters["sabund"] = inputDir + it->second;           }
195                                 }
196                                 
197                                 it = parameters.find("rabund");
198                                 //user has given a template file
199                                 if(it != parameters.end()){ 
200                                         path = m->hasPath(it->second);
201                                         //if the user has not given a path then, add inputdir. else leave path alone.
202                                         if (path == "") {       parameters["rabund"] = inputDir + it->second;           }
203                                 }
204                                 
205                                 it = parameters.find("name");
206                                 //user has given a template file
207                                 if(it != parameters.end()){ 
208                                         path = m->hasPath(it->second);
209                                         //if the user has not given a path then, add inputdir. else leave path alone.
210                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
211                                 }
212                 
213                 it = parameters.find("count");
214                                 //user has given a template file
215                                 if(it != parameters.end()){ 
216                                         path = m->hasPath(it->second);
217                                         //if the user has not given a path then, add inputdir. else leave path alone.
218                                         if (path == "") {       parameters["count"] = inputDir + it->second;            }
219                                 }
220                 
221                 it = parameters.find("taxonomy");
222                                 //user has given a template file
223                                 if(it != parameters.end()){
224                                         path = m->hasPath(it->second);
225                                         //if the user has not given a path then, add inputdir. else leave path alone.
226                                         if (path == "") {       parameters["taxonomy"] = inputDir + it->second;         }
227                                 }
228                         }
229                         
230                         //check for required parameters
231                         listfile = validParameter.validFile(parameters, "list", true);
232                         if (listfile == "not open") { listfile = ""; abort = true; }
233                         else if (listfile == "not found") { listfile = ""; }
234                         else { m->setListFile(listfile); }
235                         
236                         sabundfile = validParameter.validFile(parameters, "sabund", true);
237                         if (sabundfile == "not open") { sabundfile = ""; abort = true; }        
238                         else if (sabundfile == "not found") { sabundfile = ""; }
239                         else { m->setSabundFile(sabundfile); }
240                         
241                         rabundfile = validParameter.validFile(parameters, "rabund", true);
242                         if (rabundfile == "not open") { rabundfile = ""; abort = true; }        
243                         else if (rabundfile == "not found") { rabundfile = ""; }
244                         else { m->setRabundFile(rabundfile); }
245                         
246                         fastafile = validParameter.validFile(parameters, "fasta", true);
247                         if (fastafile == "not open") { fastafile = ""; abort = true; }  
248                         else if (fastafile == "not found") { fastafile = ""; }
249                         else { m->setFastaFile(fastafile); }
250                         
251                         sharedfile = validParameter.validFile(parameters, "shared", true);
252                         if (sharedfile == "not open") { sharedfile = ""; abort = true; }        
253                         else if (sharedfile == "not found") { sharedfile = ""; }
254                         else { m->setSharedFile(sharedfile); }
255                         
256                         namefile = validParameter.validFile(parameters, "name", true);
257                         if (namefile == "not open") { namefile = ""; abort = true; }    
258                         else if (namefile == "not found") { namefile = ""; }
259                         else { m->setNameFile(namefile); }
260                         
261                         groupfile = validParameter.validFile(parameters, "group", true);
262                         if (groupfile == "not open") { groupfile = ""; abort = true; }  
263                         else if (groupfile == "not found") { groupfile = ""; }
264                         else { m->setGroupFile(groupfile); }
265             
266             taxonomyfile = validParameter.validFile(parameters, "taxonomy", true);
267                         if (taxonomyfile == "not open") { taxonomyfile = ""; abort = true; }
268                         else if (taxonomyfile == "not found") { taxonomyfile = ""; }
269                         else { m->setTaxonomyFile(taxonomyfile); }
270                         
271             countfile = validParameter.validFile(parameters, "count", true);
272                         if (countfile == "not open") { countfile = ""; abort = true; }
273                         else if (countfile == "not found") { countfile = "";  } 
274                         else {
275                 m->setCountTableFile(countfile); 
276                 ct.readTable(countfile, true, false);
277             }
278             
279             if ((namefile != "") && (countfile != "")) {
280                 m->mothurOut("[ERROR]: you may only use one of the following: name or count."); m->mothurOutEndLine(); abort = true;
281             }
282                         
283             if ((groupfile != "") && (countfile != "")) {
284                 m->mothurOut("[ERROR]: you may only use one of the following: group or count."); m->mothurOutEndLine(); abort=true;
285             }
286             
287                         //check for optional parameter and set defaults
288                         // ...at some point should added some additional type checking...
289                         label = validParameter.validFile(parameters, "label", false);                   
290                         if (label == "not found") { label = ""; }
291                         else { 
292                                 if(label != "all") {  m->splitAtDash(label, labels);  allLines = 0;  }
293                                 else { allLines = 1;  }
294                         }
295                         
296                         groups = validParameter.validFile(parameters, "groups", false);                 
297                         if (groups == "not found") { groups = ""; pickedGroups = false; }
298                         else { 
299                                 pickedGroups = true;
300                                 m->splitAtDash(groups, Groups);
301                                 m->setGroups(Groups);
302                         }
303                         
304                         string temp = validParameter.validFile(parameters, "size", false);              if (temp == "not found"){       temp = "0";             }
305                         m->mothurConvert(temp, size);  
306                         
307                         temp = validParameter.validFile(parameters, "persample", false);                if (temp == "not found"){       temp = "f";             }
308                         persample = m->isTrue(temp);
309                         
310                         if ((groupfile == "") && (countfile == "")) { persample = false; }
311             if (countfile != "") {
312                 if (!ct.hasGroupInfo()) { 
313                     persample = false; 
314                     if (pickedGroups) { m->mothurOut("You cannot pick groups without group info in your count file."); m->mothurOutEndLine(); abort = true; }
315                 }
316             }
317                         
318                         if ((namefile != "") && ((fastafile == "") && (taxonomyfile == ""))) { m->mothurOut("You may only use a name file with a fasta file or taxonomy file."); m->mothurOutEndLine(); abort = true; }
319             
320             if ((taxonomyfile != "") && ((fastafile == "") && (listfile == ""))) { m->mothurOut("You may only use a taxonomyfile with a fastafile or listfile."); m->mothurOutEndLine(); abort = true; }
321             
322                         
323                         if ((fastafile == "") && (listfile == "") && (sabundfile == "") && (rabundfile == "") && (sharedfile == "")) {
324                                 m->mothurOut("You must provide a fasta, list, sabund, rabund or shared file as an input file."); m->mothurOutEndLine(); abort = true; }
325                         
326                         if (pickedGroups && ((groupfile == "") && (sharedfile == "") && (countfile == ""))) { 
327                                 m->mothurOut("You cannot pick groups without a valid group, count or shared file."); m->mothurOutEndLine(); abort = true; }
328                         
329                         if (((groupfile != "") || (countfile != "")) && ((fastafile == "") && (listfile == ""))) { 
330                                 m->mothurOut("Group or count files are only valid with listfile or fastafile."); m->mothurOutEndLine(); abort = true; }
331                         
332                         if (((groupfile != "") || (countfile != "")) && ((fastafile != "") && (listfile != ""))) { 
333                                 m->mothurOut("A new group or count file can only be made from the subsample of a listfile or fastafile, not both. Please correct."); m->mothurOutEndLine(); abort = true; }
334                         
335             if (countfile == "") {
336                 if ((fastafile != "") && (namefile == "")) {
337                     vector<string> files; files.push_back(fastafile);
338                     parser.getNameFile(files);
339                 }
340             }
341                 }
342
343         }
344         catch(exception& e) {
345                 m->errorOut(e, "SubSampleCommand", "SubSampleCommand");
346                 exit(1);
347         }
348 }
349 //**********************************************************************************************************************
350
351 int SubSampleCommand::execute(){
352         try {
353         
354                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
355                 
356                 if (sharedfile != "")   {   getSubSampleShared();       }
357                 if (m->control_pressed) {  for (int i = 0; i < outputNames.size(); i++) {       m->mothurRemove(outputNames[i]); return 0; } }
358                 
359                 if (listfile != "")             {   getSubSampleList();         }
360                 if (m->control_pressed) {  for (int i = 0; i < outputNames.size(); i++) {       m->mothurRemove(outputNames[i]); return 0; } }
361                 
362                 if (rabundfile != "")   {   getSubSampleRabund();       }
363                 if (m->control_pressed) {  for (int i = 0; i < outputNames.size(); i++) {       m->mothurRemove(outputNames[i]); return 0; } }
364                 
365                 if (sabundfile != "")   {   getSubSampleSabund();       }
366                 if (m->control_pressed) {  for (int i = 0; i < outputNames.size(); i++) {       m->mothurRemove(outputNames[i]); return 0; } }
367                 
368                 if (fastafile != "")    {   getSubSampleFasta();        }
369                 if (m->control_pressed) {  for (int i = 0; i < outputNames.size(); i++) {       m->mothurRemove(outputNames[i]); return 0; } }
370                         
371                 //set fasta file as new current fastafile
372                 string current = "";
373                 itTypes = outputTypes.find("fasta");
374                 if (itTypes != outputTypes.end()) {
375                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
376                 }
377                 
378                 itTypes = outputTypes.find("name");
379                 if (itTypes != outputTypes.end()) {
380                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
381                 }
382                 
383                 itTypes = outputTypes.find("group");
384                 if (itTypes != outputTypes.end()) {
385                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setGroupFile(current); }
386                 }
387                 
388                 itTypes = outputTypes.find("list");
389                 if (itTypes != outputTypes.end()) {
390                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setListFile(current); }
391                 }
392                 
393                 itTypes = outputTypes.find("shared");
394                 if (itTypes != outputTypes.end()) {
395                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSharedFile(current); }
396                 }
397                 
398                 itTypes = outputTypes.find("rabund");
399                 if (itTypes != outputTypes.end()) {
400                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setRabundFile(current); }
401                 }
402                 
403                 itTypes = outputTypes.find("sabund");
404                 if (itTypes != outputTypes.end()) {
405                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSabundFile(current); }
406                 }
407         
408         itTypes = outputTypes.find("count");
409                 if (itTypes != outputTypes.end()) {
410                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setCountTableFile(current); }
411                 }
412                 
413         itTypes = outputTypes.find("taxonomy");
414                 if (itTypes != outputTypes.end()) {
415                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setTaxonomyFile(current); }
416                 }
417                 
418                 m->mothurOutEndLine();
419                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
420                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
421                 m->mothurOutEndLine();
422                 
423                 return 0;
424         }
425         catch(exception& e) {
426                 m->errorOut(e, "SubSampleCommand", "execute");
427                 exit(1);
428         }
429 }
430 //**********************************************************************************************************************
431 int SubSampleCommand::getSubSampleFasta() {
432         try {
433                 
434                 if (namefile != "") { readNames(); }    //fills names with all names in namefile.
435                 else { getNames(); }//no name file, so get list of names to pick from
436                 
437                 GroupMap groupMap;
438                 if (groupfile != "") {
439                         groupMap.readMap(groupfile);
440                         
441                         //takes care of user setting groupNames that are invalid or setting groups=all
442                         SharedUtil util;
443                         vector<string> namesGroups = groupMap.getNamesOfGroups();
444                         util.setGroups(Groups, namesGroups);
445                         
446                         //file mismatch quit
447                         if (names.size() != groupMap.getNumSeqs()) { 
448                                 m->mothurOut("[ERROR]: your fasta file contains " + toString(names.size()) + " sequences, and your groupfile contains " + toString(groupMap.getNumSeqs()) + ", please correct."); 
449                                 m->mothurOutEndLine();
450                                 return 0;
451                         }                       
452                 }else if (countfile != "") {
453             if (ct.hasGroupInfo()) {
454                 SharedUtil util;
455                 vector<string> namesGroups = ct.getNamesOfGroups();
456                 util.setGroups(Groups, namesGroups);
457             }
458             
459             //file mismatch quit
460                         if (names.size() != ct.getNumUniqueSeqs()) { 
461                                 m->mothurOut("[ERROR]: your fasta file contains " + toString(names.size()) + " sequences, and your count file contains " + toString(ct.getNumUniqueSeqs()) + " unique sequences, please correct."); 
462                                 m->mothurOutEndLine();
463                                 return 0;
464                         }       
465         }
466                 
467                 if (m->control_pressed) { return 0; }
468                 
469                 //make sure that if your picked groups size is not too big
470                 int thisSize = 0;
471         if (countfile == "") { thisSize = names.size();  }
472         else {  thisSize = ct. getNumSeqs();  }  //all seqs not just unique
473         
474                 if (persample) { 
475                         if (size == 0) { //user has not set size, set size = smallest samples size
476                                 if (countfile == "") { size = groupMap.getNumSeqs(Groups[0]); }
477                 else {  size = ct.getGroupCount(Groups[0]);  }
478                 
479                                 for (int i = 1; i < Groups.size(); i++) {
480                                         int thisSize = 0;
481                     if (countfile == "") { thisSize = groupMap.getNumSeqs(Groups[i]); }
482                     else {  thisSize = ct.getGroupCount(Groups[i]);  }
483                                         
484                                         if (thisSize < size) {  size = thisSize;        }
485                                 }
486                         }else { //make sure size is not too large
487                                 vector<string> newGroups;
488                                 for (int i = 0; i < Groups.size(); i++) {
489                                         int thisSize = 0;
490                     if (countfile == "") { thisSize = groupMap.getNumSeqs(Groups[i]); }
491                     else {  thisSize = ct.getGroupCount(Groups[i]);  }
492                                         
493                                         if (thisSize >= size) { newGroups.push_back(Groups[i]); }
494                                         else {  m->mothurOut("You have selected a size that is larger than " + Groups[i] + " number of sequences, removing " + Groups[i] + "."); m->mothurOutEndLine(); }
495                                 }
496                                 Groups = newGroups;
497                 if (newGroups.size() == 0) {  m->mothurOut("[ERROR]: all groups removed."); m->mothurOutEndLine(); m->control_pressed = true; }
498                         }
499                         
500                         m->mothurOut("Sampling " + toString(size) + " from each group."); m->mothurOutEndLine();                        
501                 }else {
502                         if (pickedGroups) {
503                                 int total = 0;
504                                 for(int i = 0; i < Groups.size(); i++) {
505                     if (countfile == "") { total += groupMap.getNumSeqs(Groups[i]); }
506                     else {  total += ct.getGroupCount(Groups[i]);  }
507                                 }
508                                 
509                                 if (size == 0) { //user has not set size, set size = 10% samples size
510                                         size = int (total * 0.10);
511                                 }
512                                 
513                                 if (total < size) { 
514                                         if (size != 0) { 
515                                                 m->mothurOut("Your size is too large for the number of groups you selected. Adjusting to " + toString(int (total * 0.10)) + "."); m->mothurOutEndLine();
516                                         }
517                                         size = int (total * 0.10);
518                                 }
519                                 
520                                 m->mothurOut("Sampling " + toString(size) + " from " + toString(total) + "."); m->mothurOutEndLine();
521                         }
522                         
523                         if (size == 0) { //user has not set size, set size = 10% samples size
524                                 if (countfile == "") {  size = int (names.size() * 0.10); }
525                 else {  size = int (ct.getNumSeqs() * 0.10); }
526                         }
527                         
528             
529             if (size > thisSize) { m->mothurOut("Your fasta file only contains " + toString(thisSize) + " sequences. Setting size to " + toString(thisSize) + "."); m->mothurOutEndLine();
530                     size = thisSize;
531             }
532             
533             if (!pickedGroups) { m->mothurOut("Sampling " + toString(size) + " from " + toString(thisSize) + "."); m->mothurOutEndLine(); }
534
535                 }
536                 random_shuffle(names.begin(), names.end());
537                 
538                 set<string> subset; //dont want repeat sequence names added
539                 if (persample) {
540             if (countfile == "") {
541                 //initialize counts
542                 map<string, int> groupCounts;
543                 map<string, int>::iterator itGroupCounts;
544                 for (int i = 0; i < Groups.size(); i++) { groupCounts[Groups[i]] = 0; }
545                         
546                 for (int j = 0; j < names.size(); j++) {
547                                         
548                     if (m->control_pressed) { return 0; }
549                                                                                                 
550                     string group = groupMap.getGroup(names[j]);
551                     if (group == "not found") { m->mothurOut("[ERROR]: " + names[j] + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
552                     else{
553                         itGroupCounts = groupCounts.find(group);
554                         if (itGroupCounts != groupCounts.end()) {
555                             if (itGroupCounts->second < size) { subset.insert(names[j]);        (itGroupCounts->second)++; }
556                         }
557                     }                           
558                 }
559             }else {
560                 SubSample sample;
561                 CountTable sampledCt = sample.getSample(ct, size, Groups);
562                 vector<string> sampledSeqs = sampledCt.getNamesOfSeqs();
563                 for (int i = 0; i < sampledSeqs.size(); i++) { subset.insert(sampledSeqs[i]); }
564                 
565                 string countOutputDir = outputDir;
566                 if (outputDir == "") {  countOutputDir += m->hasPath(countfile);  }
567                 map<string, string> variables; 
568                 variables["[filename]"] = countOutputDir + m->getRootName(m->getSimpleName(countfile));
569                 variables["[extension]"] = m->getExtension(countfile);
570                 string countOutputFileName = getOutputFileName("count", variables);
571                 outputTypes["count"].push_back(countOutputFileName);  outputNames.push_back(countOutputFileName);
572                 sampledCt.printTable(countOutputFileName);
573             }
574                 }else {
575                         if (countfile == "") {
576                 //randomly select a subset of those names to include in the subsample
577                 //since names was randomly shuffled just grab the next one
578                 for (int j = 0; j < names.size(); j++) {
579                     
580                     if (m->control_pressed) { return 0; }
581                     
582                     if (groupfile != "") { //if there is a groupfile given fill in group info
583                         string group = groupMap.getGroup(names[j]);
584                         if (group == "not found") { m->mothurOut("[ERROR]: " + names[j] + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
585                         
586                         if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
587                             if (m->inUsersGroups(group, Groups)) {  subset.insert(names[j]); }
588                         }else{  subset.insert(names[j]); }
589                     }else{ //save everyone, group
590                         subset.insert(names[j]); 
591                     }                                   
592                     
593                     //do we have enough??
594                     if (subset.size() == size) { break; }
595                 }
596             }else {
597                 SubSample sample;
598                 CountTable sampledCt = sample.getSample(ct, size, Groups, pickedGroups);
599                 vector<string> sampledSeqs = sampledCt.getNamesOfSeqs();
600                 for (int i = 0; i < sampledSeqs.size(); i++) { subset.insert(sampledSeqs[i]); }
601                 
602                 string countOutputDir = outputDir;
603                 if (outputDir == "") {  countOutputDir += m->hasPath(countfile);  }
604                 map<string, string> variables; 
605                 variables["[filename]"] = countOutputDir + m->getRootName(m->getSimpleName(countfile));
606                 variables["[extension]"] = m->getExtension(countfile);
607                 string countOutputFileName = getOutputFileName("count", variables);
608                 outputTypes["count"].push_back(countOutputFileName);  outputNames.push_back(countOutputFileName);
609                 sampledCt.printTable(countOutputFileName);
610             }
611                 }
612                 
613                 if (subset.size() == 0) {  m->mothurOut("The size you selected is too large, skipping fasta file."); m->mothurOutEndLine();  return 0; }
614                 
615                 string thisOutputDir = outputDir;
616                 if (outputDir == "") {  thisOutputDir += m->hasPath(fastafile);  }
617         map<string, string> variables; 
618         variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(fastafile));
619         variables["[extension]"] = m->getExtension(fastafile);
620                 string outputFileName = getOutputFileName("fasta", variables);          
621                 ofstream out;
622                 m->openOutputFile(outputFileName, out);
623                 
624                 //read through fasta file outputting only the names on the subsample list
625                 ifstream in;
626                 m->openInputFile(fastafile, in);
627                 
628                 string thisname;
629                 int count = 0;
630                 map<string, vector<string> >::iterator itNameMap;
631                 
632                 while(!in.eof()){
633                         
634                         if (m->control_pressed) { in.close(); out.close();  return 0; }
635                         
636                         Sequence currSeq(in);
637                         thisname = currSeq.getName();
638                         
639                         if (thisname != "") {
640                                 
641                                 //does the subset contain a sequence that this sequence represents
642                                 itNameMap = nameMap.find(thisname);
643                                 if (itNameMap != nameMap.end()) {
644                                         vector<string> nameRepresents = itNameMap->second;
645                                 
646                                         for (int i = 0; i < nameRepresents.size(); i++){
647                                                 if (subset.count(nameRepresents[i]) != 0) {
648                                                         out << ">" << nameRepresents[i] << endl << currSeq.getAligned() << endl;
649                                                         count++;
650                                                 }
651                                         }
652                                 }else{
653                                         m->mothurOut("[ERROR]: " + thisname + " is not in your namefile, please correct."); m->mothurOutEndLine();
654                                 }
655                         }
656                         m->gobble(in);
657                 }
658                 in.close();     
659                 out.close();
660         
661                 
662                 if (count != subset.size()) {
663                         m->mothurOut("[ERROR]: The subset selected contained " + toString(subset.size()) + " sequences, but I only found " + toString(count) + " of those in the fastafile."); m->mothurOutEndLine();
664                 }
665                 
666                 if (namefile != "") {
667                         m->mothurOut("Deconvoluting subsampled fasta file... "); m->mothurOutEndLine();
668                         map<string, string> variables; 
669             variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(namefile));
670             variables["[extension]"] = m->getExtension(namefile);
671             string outputNameFileName = getOutputFileName("name", variables);
672                         //use unique.seqs to create new name and fastafile
673                         string inputString = "fasta=" + outputFileName;
674                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
675                         m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine(); 
676                         m->mothurCalling = true;
677             
678                         Command* uniqueCommand = new DeconvoluteCommand(inputString);
679                         uniqueCommand->execute();
680                         
681                         map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
682                         
683                         delete uniqueCommand;
684                         m->mothurCalling = false;
685             
686             m->renameFile(filenames["name"][0], outputNameFileName); 
687             m->renameFile(filenames["fasta"][0], outputFileName);  
688             
689                         outputTypes["name"].push_back(outputNameFileName);  outputNames.push_back(outputNameFileName);
690
691                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
692                         
693                         m->mothurOut("Done."); m->mothurOutEndLine();
694             
695             if (taxonomyfile != "") {
696                 set<string> tempSubset;
697                 //get new unique names from fasta file
698                 //read through fasta file outputting only the names on the subsample list after deconvolute
699                 ifstream in2;
700                 m->openInputFile(outputFileName, in2);
701                 
702                 while (!in2.eof()) {
703                     Sequence seq(in2); m->gobble(in2);
704                     if (seq.getName() != "") {
705                         tempSubset.insert(seq.getName());
706                     }
707                 }
708                 in2.close();
709                 
710                 //send that list to getTax
711                 int tcount = getTax(tempSubset);
712                 if (tcount != tempSubset.size()) { m->mothurOut("[ERROR]: subsampled fasta file contains " + toString(tempSubset.size()) + " sequences, but I only found " + toString(tcount) + " in your taxonomy file, please correct."); m->mothurOutEndLine(); }
713             }
714                 }else {
715             if (taxonomyfile != "") {
716                 int tcount = getTax(subset);
717                 if (tcount != subset.size()) { m->mothurOut("[ERROR]: subsampled fasta file contains " + toString(subset.size()) + " sequences, but I only found " + toString(tcount) + " in your taxonomy file, please correct."); m->mothurOutEndLine(); }
718             
719             }  //should only contain uniques.
720         }
721                 
722                 outputTypes["fasta"].push_back(outputFileName);  outputNames.push_back(outputFileName);
723                 
724                 //if a groupfile is provided read through the group file only outputting the names on the subsample list
725                 if (groupfile != "") {
726                         
727                         string groupOutputDir = outputDir;
728                         if (outputDir == "") {  groupOutputDir += m->hasPath(groupfile);  }
729             map<string, string> variables; 
730             variables["[filename]"] = groupOutputDir + m->getRootName(m->getSimpleName(groupfile));
731             variables["[extension]"] = m->getExtension(groupfile);
732                         string groupOutputFileName = getOutputFileName("group", variables);
733                         
734                         ofstream outGroup;
735                         m->openOutputFile(groupOutputFileName, outGroup);
736                         outputTypes["group"].push_back(groupOutputFileName);  outputNames.push_back(groupOutputFileName);
737                         
738                         ifstream inGroup;
739                         m->openInputFile(groupfile, inGroup);
740                         string name, group;
741                         
742                         while(!inGroup.eof()){
743                                 
744                                 if (m->control_pressed) { inGroup.close(); outGroup.close(); return 0; }
745                                 
746                                 inGroup >> name;        m->gobble(inGroup);                     //read from first column
747                                 inGroup >> group;                       //read from second column
748                                 
749                                 //if this name is in the accnos file
750                                 if (subset.count(name) != 0) {
751                                         outGroup << name << '\t' << group << endl;
752                                         subset.erase(name);
753                                 }
754                                 
755                                 m->gobble(inGroup);
756                         }
757                         inGroup.close();
758                         outGroup.close();       
759                         
760                         //sanity check
761                         if (subset.size() != 0) {  
762                                 m->mothurOut("Your groupfile does not match your fasta file."); m->mothurOutEndLine();
763                                 for (set<string>::iterator it = subset.begin(); it != subset.end(); it++) {
764                                         m->mothurOut("[ERROR]: " + *it + " is missing from your groupfile."); m->mothurOutEndLine();
765                                 }
766                         }
767                 }
768                         
769                 return 0;
770                 
771         }
772         catch(exception& e) {
773                 m->errorOut(e, "SubSampleCommand", "getSubSampleFasta");
774                 exit(1);
775         }
776 }
777 //**********************************************************************************************************************
778 int SubSampleCommand::getNames() {
779         try {
780                 
781                 ifstream in;
782                 m->openInputFile(fastafile, in);
783                 
784                 string thisname;
785                 while(!in.eof()){
786                         
787                         if (m->control_pressed) { in.close(); return 0; }
788                         
789                         Sequence currSeq(in);
790                         thisname = currSeq.getName();
791                         
792                         if (thisname != "") {
793                                 vector<string> temp; temp.push_back(thisname);
794                                 nameMap[thisname] = temp;
795                                 names.push_back(thisname);
796                         }
797                         m->gobble(in);
798                 }
799                 in.close();     
800                 
801                 return 0;
802                 
803         }
804         catch(exception& e) {
805                 m->errorOut(e, "SubSampleCommand", "getNames");
806                 exit(1);
807         }
808 }       
809 //**********************************************************************************************************************
810 int SubSampleCommand::readNames() {
811         try {
812                 
813         nameMap.clear();
814         m->readNames(namefile, nameMap);
815         
816         //save names of all sequences
817         map<string, vector<string> >::iterator it;
818         for (it = nameMap.begin(); it != nameMap.end(); it++) { for (int i = 0; i < (it->second).size(); i++) { names.push_back((it->second)[i]); } }
819         
820                 return 0;
821                 
822         }
823         catch(exception& e) {
824                 m->errorOut(e, "SubSampleCommand", "readNames");
825                 exit(1);
826         }
827 }               
828 //**********************************************************************************************************************
829 int SubSampleCommand::getSubSampleShared() {
830         try {
831                 
832                 InputData* input = new InputData(sharedfile, "sharedfile");
833                 vector<SharedRAbundVector*> lookup = input->getSharedRAbundVectors();
834                 string lastLabel = lookup[0]->getLabel();
835                 
836                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
837                 set<string> processedLabels;
838                 set<string> userLabels = labels;
839                 
840                 if (size == 0) { //user has not set size, set size = smallest samples size
841                         size = lookup[0]->getNumSeqs();
842                         for (int i = 1; i < lookup.size(); i++) {
843                                 int thisSize = lookup[i]->getNumSeqs();
844                                 
845                                 if (thisSize < size) {  size = thisSize;        }
846                         }
847                 }else {
848                         m->clearGroups();
849                         Groups.clear();
850                         vector<SharedRAbundVector*> temp;
851                         for (int i = 0; i < lookup.size(); i++) {
852                                 if (lookup[i]->getNumSeqs() < size) { 
853                                         m->mothurOut(lookup[i]->getGroup() + " contains " + toString(lookup[i]->getNumSeqs()) + ". Eliminating."); m->mothurOutEndLine();
854                                         delete lookup[i];
855                                 }else { 
856                                         Groups.push_back(lookup[i]->getGroup()); 
857                                         temp.push_back(lookup[i]);
858                                 }
859                         } 
860                         lookup = temp;
861                         m->setGroups(Groups);
862                 }
863                 
864                 if (lookup.size() == 0) {  m->mothurOut("The size you selected is too large, skipping shared file."); m->mothurOutEndLine(); delete input; return 0; }
865                 
866                 m->mothurOut("Sampling " + toString(size) + " from each group."); m->mothurOutEndLine();
867                 
868                 //as long as you are not at the end of the file or done wih the lines you want
869                 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
870                         if (m->control_pressed) {  delete input; for (int i = 0; i < lookup.size(); i++) {  delete lookup[i]; lookup[i] = NULL; }  return 0;  }
871                         
872                         if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){                  
873                                 
874                                 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
875                                 
876                                 processShared(lookup);
877                                 
878                                 processedLabels.insert(lookup[0]->getLabel());
879                                 userLabels.erase(lookup[0]->getLabel());
880                         }
881                         
882                         if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
883                                 string saveLabel = lookup[0]->getLabel();
884                                 
885                                 for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  }  
886                                 
887                                 lookup = input->getSharedRAbundVectors(lastLabel);
888                                 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
889                                 
890                                 processShared(lookup);
891                                 
892                                 processedLabels.insert(lookup[0]->getLabel());
893                                 userLabels.erase(lookup[0]->getLabel());
894                                 
895                                 //restore real lastlabel to save below
896                                 lookup[0]->setLabel(saveLabel);
897                         }
898                         
899                         lastLabel = lookup[0]->getLabel();
900                         //prevent memory leak
901                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i]; lookup[i] = NULL; }
902                         
903                         //get next line to process
904                         lookup = input->getSharedRAbundVectors();                               
905                 }
906                 
907                 
908                 if (m->control_pressed) {   return 0;  }
909                 
910                 //output error messages about any remaining user labels
911                 set<string>::iterator it;
912                 bool needToRun = false;
913                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
914                         m->mothurOut("Your file does not include the label " + *it); 
915                         if (processedLabels.count(lastLabel) != 1) {
916                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
917                                 needToRun = true;
918                         }else {
919                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
920                         }
921                 }
922                 
923                 //run last label if you need to
924                 if (needToRun == true)  {
925                         for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }  
926                         lookup = input->getSharedRAbundVectors(lastLabel);
927                         
928                         m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
929                         
930                         processShared(lookup);
931                         
932                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  }
933                 }
934                 
935                 delete input;
936                 
937                 return 0;
938                 
939         }
940         catch(exception& e) {
941                 m->errorOut(e, "SubSampleCommand", "getSubSampleShared");
942                 exit(1);
943         }
944 }
945 //**********************************************************************************************************************
946 int SubSampleCommand::processShared(vector<SharedRAbundVector*>& thislookup) {
947         try {
948                 
949                 //save mothurOut's binLabels to restore for next label
950                 vector<string> saveBinLabels = m->currentBinLabels;
951                 
952                 string thisOutputDir = outputDir;
953                 if (outputDir == "") {  thisOutputDir += m->hasPath(sharedfile);  }
954         map<string, string> variables; 
955         variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(sharedfile));
956         variables["[extension]"] = m->getExtension(sharedfile);
957         variables["[distance]"] = thislookup[0]->getLabel();
958                 string outputFileName = getOutputFileName("shared", variables);        
959         SubSample sample;
960         vector<string> subsampledLabels = sample.getSample(thislookup, size);
961         
962         if (m->control_pressed) {  return 0; }
963         
964         ofstream out;
965                 m->openOutputFile(outputFileName, out);
966                 outputTypes["shared"].push_back(outputFileName);  outputNames.push_back(outputFileName);
967                 
968         m->currentBinLabels = subsampledLabels;
969         
970                 thislookup[0]->printHeaders(out);
971                 
972                 for (int i = 0; i < thislookup.size(); i++) {
973                         out << thislookup[i]->getLabel() << '\t' << thislookup[i]->getGroup() << '\t';
974                         thislookup[i]->print(out);
975                 }
976                 out.close();
977         
978         
979         //save mothurOut's binLabels to restore for next label
980                 m->currentBinLabels = saveBinLabels;
981                 
982                 return 0;
983                 
984         }
985         catch(exception& e) {
986                 m->errorOut(e, "SubSampleCommand", "processShared");
987                 exit(1);
988         }
989 }                       
990 //**********************************************************************************************************************
991 int SubSampleCommand::getSubSampleList() {
992         try {
993         
994                 if (namefile != "") { m->readNames(namefile, nameMap); }
995         
996                 string thisOutputDir = outputDir;
997                 if (outputDir == "") {  thisOutputDir += m->hasPath(listfile);  }
998                 map<string, string> variables; 
999         variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(listfile));
1000         variables["[extension]"] = m->getExtension(listfile);
1001                 string outputFileName = getOutputFileName("list", variables);   
1002                 ofstream out;
1003                 m->openOutputFile(outputFileName, out);
1004                 outputTypes["list"].push_back(outputFileName);  outputNames.push_back(outputFileName);
1005                 
1006                 InputData* input = new InputData(listfile, "list");
1007                 ListVector* list = input->getListVector();
1008                 string lastLabel = list->getLabel();
1009                 
1010         //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1011                 set<string> processedLabels;
1012                 set<string> userLabels = labels;
1013
1014                 ofstream outGroup;
1015                 GroupMap groupMap;
1016                 if (groupfile != "") {
1017                         groupMap.readMap(groupfile);
1018                         
1019                         //takes care of user setting groupNames that are invalid or setting groups=all
1020                         SharedUtil util; vector<string> namesGroups = groupMap.getNamesOfGroups(); util.setGroups(Groups, namesGroups);
1021                         
1022                         //create outputfiles
1023                         string groupOutputDir = outputDir;
1024                         if (outputDir == "") {  groupOutputDir += m->hasPath(groupfile);  }
1025                         string groupOutputFileName = groupOutputDir + m->getRootName(m->getSimpleName(groupfile)) + "subsample" + m->getExtension(groupfile);
1026                         m->openOutputFile(groupOutputFileName, outGroup);
1027                         outputTypes["group"].push_back(groupOutputFileName);  outputNames.push_back(groupOutputFileName);
1028                         
1029                         //file mismatch quit
1030                         if (list->getNumSeqs() != groupMap.getNumSeqs()) { 
1031                                 m->mothurOut("[ERROR]: your list file contains " + toString(list->getNumSeqs()) + " sequences, and your groupfile contains " + toString(groupMap.getNumSeqs()) + ", please correct."); 
1032                                 m->mothurOutEndLine(); delete list; delete input; out.close(); outGroup.close(); return 0;
1033                         }                       
1034                 }else if (countfile != "") {
1035             if (ct.hasGroupInfo()) {
1036                 SharedUtil util;
1037                 vector<string> namesGroups = ct.getNamesOfGroups();
1038                 util.setGroups(Groups, namesGroups);
1039             }
1040             
1041             //file mismatch quit
1042                         if (list->getNumSeqs() != ct.getNumUniqueSeqs()) { 
1043                                 m->mothurOut("[ERROR]: your list file contains " + toString(list->getNumSeqs()) + " sequences, and your count file contains " + toString(ct.getNumUniqueSeqs()) + " unique sequences, please correct."); 
1044                                 m->mothurOutEndLine();
1045                                 return 0;
1046                         }       
1047         }
1048
1049                 //make sure that if your picked groups size is not too big
1050                 if (persample) {
1051                         if (size == 0) { //user has not set size, set size = smallest samples size
1052                                 if (countfile == "") { size = groupMap.getNumSeqs(Groups[0]); }
1053                 else {  size = ct.getGroupCount(Groups[0]);  }
1054                 
1055                                 for (int i = 1; i < Groups.size(); i++) {
1056                                         int thisSize = 0;
1057                     if (countfile == "") { thisSize = groupMap.getNumSeqs(Groups[i]); }
1058                     else {  thisSize = ct.getGroupCount(Groups[i]);  }
1059                                         
1060                                         if (thisSize < size) {  size = thisSize;        }
1061                                 }
1062                         }else { //make sure size is not too large
1063                                 vector<string> newGroups;
1064                                 for (int i = 0; i < Groups.size(); i++) {
1065                                         int thisSize = 0;
1066                     if (countfile == "") { thisSize = groupMap.getNumSeqs(Groups[i]); }
1067                     else {  thisSize = ct.getGroupCount(Groups[i]);  }
1068                                         
1069                                         if (thisSize >= size) { newGroups.push_back(Groups[i]); }
1070                                         else {  m->mothurOut("You have selected a size that is larger than " + Groups[i] + " number of sequences, removing " + Groups[i] + "."); m->mothurOutEndLine(); }
1071                                 }
1072                                 Groups = newGroups;
1073                 if (newGroups.size() == 0) {  m->mothurOut("[ERROR]: all groups removed."); m->mothurOutEndLine(); m->control_pressed = true; }
1074                         }
1075                         
1076                         m->mothurOut("Sampling " + toString(size) + " from each group."); m->mothurOutEndLine();                
1077                 }else{
1078             if (pickedGroups) {
1079                                 int total = 0;
1080                                 for(int i = 0; i < Groups.size(); i++) {
1081                     if (countfile == "") { total += groupMap.getNumSeqs(Groups[i]); }
1082                     else {  total += ct.getGroupCount(Groups[i]);  }
1083                                 }
1084                                 
1085                                 if (size == 0) { //user has not set size, set size = 10% samples size
1086                                         size = int (total * 0.10);
1087                                 }
1088                                 
1089                                 if (total < size) { 
1090                                         if (size != 0) { 
1091                                                 m->mothurOut("Your size is too large for the number of groups you selected. Adjusting to " + toString(int (total * 0.10)) + "."); m->mothurOutEndLine();
1092                                         }
1093                                         size = int (total * 0.10);
1094                                 }
1095                                 
1096                                 m->mothurOut("Sampling " + toString(size) + " from " + toString(total) + "."); m->mothurOutEndLine();
1097                         }else {
1098                 if (size == 0) { //user has not set size, set size = 10% samples size
1099                                         if (countfile == "") {  size = int (list->getNumSeqs() * 0.10);  }
1100                     else { size = int (ct.getNumSeqs() * 0.10);  }
1101                                 }
1102                                 
1103                                 int thisSize = 0;
1104                 if (countfile == "") { thisSize = list->getNumSeqs();  }
1105                 else { thisSize = ct.getNumSeqs(); }
1106                 
1107                                 if (size > thisSize) { m->mothurOut("Your list file only contains " + toString(thisSize) + " sequences. Setting size to " + toString(thisSize) + "."); m->mothurOutEndLine();
1108                                         size = thisSize;
1109                                 }
1110                                 
1111                                 m->mothurOut("Sampling " + toString(size) + " from " + toString(thisSize) + "."); m->mothurOutEndLine();
1112             }
1113         }
1114                 
1115         set<string> subset; //dont want repeat sequence names added
1116                 if (countfile == "") {
1117             //fill names
1118             for (int i = 0; i < list->getNumBins(); i++) {
1119                 string binnames = list->get(i);
1120                 vector<string> thisBin;
1121                 m->splitAtComma(binnames, thisBin);
1122                 
1123                 for(int j=0;j<thisBin.size();j++){
1124                     if (groupfile != "") { //if there is a groupfile given fill in group info
1125                         string group = groupMap.getGroup(thisBin[j]);
1126                         if (group == "not found") { m->mothurOut("[ERROR]: " + thisBin[j] + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
1127                         
1128                                                 //if hte user picked groups, we only want to keep the names of sequences from those groups
1129                                                 if (pickedGroups) { if (m->inUsersGroups(group, Groups)) { names.push_back(thisBin[j]); }  }
1130                                                 else{ names.push_back(thisBin[j]); } 
1131                     }//save everyone, group
1132                     else{ names.push_back(thisBin[j]); }
1133                 }
1134             }
1135             
1136             random_shuffle(names.begin(), names.end());
1137                         
1138             //randomly select a subset of those names to include in the subsample
1139             if (persample) {
1140                 //initialize counts
1141                 map<string, int> groupCounts;
1142                 map<string, int>::iterator itGroupCounts;
1143                 for (int i = 0; i < Groups.size(); i++) { groupCounts[Groups[i]] = 0; }
1144                 
1145                 for (int j = 0; j < names.size(); j++) {
1146                     
1147                     if (m->control_pressed) { delete list; delete input;  return 0; }
1148                     
1149                     string group = groupMap.getGroup(names[j]);
1150                     if (group == "not found") { m->mothurOut("[ERROR]: " + names[j] + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
1151                     else{
1152                         itGroupCounts = groupCounts.find(group);
1153                         if (itGroupCounts != groupCounts.end()) {
1154                             if (groupCounts[group] < size) {    subset.insert(names[j]);        groupCounts[group]++; }
1155                         }
1156                     }                           
1157                 }
1158             }else{
1159                 for (int j = 0; j < size; j++) {
1160                     if (m->control_pressed) { break; }
1161                     subset.insert(names[j]); 
1162                 }       
1163             }
1164             
1165             if (groupfile != "") { 
1166                 //write out new groupfile
1167                 for (set<string>::iterator it = subset.begin(); it != subset.end(); it++) {
1168                     string group = groupMap.getGroup(*it);
1169                     if (group == "not found") { group = "NOTFOUND"; }
1170                     outGroup << *it << '\t' << group << endl;
1171                 }
1172                 outGroup.close(); 
1173             }
1174                 }else {
1175             SubSample sample; CountTable sampledCt;
1176             
1177             if (persample)  { sampledCt = sample.getSample(ct, size, Groups);               }
1178             else            { sampledCt = sample.getSample(ct, size, Groups, pickedGroups); }
1179             
1180             vector<string> sampledSeqs = sampledCt.getNamesOfSeqs();
1181             for (int i = 0; i < sampledSeqs.size(); i++) { subset.insert(sampledSeqs[i]); }
1182         
1183             string countOutputDir = outputDir;
1184             if (outputDir == "") {  countOutputDir += m->hasPath(countfile);  }
1185             map<string, string> variables; 
1186             variables["[filename]"] = countOutputDir + m->getRootName(m->getSimpleName(countfile));
1187             variables["[extension]"] = m->getExtension(countfile);
1188             string countOutputFileName = getOutputFileName("count", variables);
1189             outputTypes["count"].push_back(countOutputFileName);  outputNames.push_back(countOutputFileName);
1190             sampledCt.printTable(countOutputFileName);
1191         }
1192                                                 
1193                 //as long as you are not at the end of the file or done wih the lines you want
1194                 while((list != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1195                         
1196                         if (m->control_pressed) {  delete list; delete input;  out.close();  return 0;  }
1197                         
1198                         if(allLines == 1 || labels.count(list->getLabel()) == 1){                       
1199                                 
1200                                 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1201                                 
1202                                 processList(list, out, subset);
1203                                 
1204                                 processedLabels.insert(list->getLabel());
1205                                 userLabels.erase(list->getLabel());
1206                         }
1207                         
1208                         if ((m->anyLabelsToProcess(list->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1209                                 string saveLabel = list->getLabel();
1210                                 
1211                                 delete list; 
1212                                 
1213                                 list = input->getListVector(lastLabel);
1214                                 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1215                                 
1216                                 processList(list, out, subset);
1217                                 
1218                                 processedLabels.insert(list->getLabel());
1219                                 userLabels.erase(list->getLabel());
1220                                 
1221                                 //restore real lastlabel to save below
1222                                 list->setLabel(saveLabel);
1223                         }
1224                         
1225                         lastLabel = list->getLabel();
1226                         
1227                         delete list; list = NULL;
1228                         
1229                         //get next line to process
1230                         list = input->getListVector();                          
1231                 }
1232                 
1233                 
1234                 if (m->control_pressed) {  if (list != NULL) { delete list; } delete input; out.close(); return 0;  }
1235                 
1236                 //output error messages about any remaining user labels
1237                 set<string>::iterator it;
1238                 bool needToRun = false;
1239                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
1240                         m->mothurOut("Your file does not include the label " + *it); 
1241                         if (processedLabels.count(lastLabel) != 1) {
1242                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1243                                 needToRun = true;
1244                         }else {
1245                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1246                         }
1247                 }
1248                 
1249                 //run last label if you need to
1250                 if (needToRun == true)  {
1251                         if (list != NULL) { delete list; }
1252                         
1253                         list = input->getListVector(lastLabel);
1254                         
1255                         m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1256                         
1257                         processList(list, out, subset);
1258                         
1259                         delete list; list = NULL;
1260                 }
1261                 
1262                 out.close();  
1263                 if (list != NULL) { delete list; }
1264                 delete input;
1265         
1266         if (taxonomyfile != "") {
1267             if (namefile == "") {
1268                 InputData input(listfile, "list");
1269                 ListVector* list = input.getListVector();
1270                 string lastLabel = list->getLabel();
1271                 
1272                 for (int i = 0; i < list->getNumBins(); i++) {
1273                     vector<string> temp;
1274                     string bin = list->get(i);
1275                     m->splitAtComma(bin, temp);
1276                     for (int j = 0; j < temp.size(); j++) { vector<string> tempFakeOut; tempFakeOut.push_back(temp[j]); nameMap[temp[j]] = tempFakeOut; }
1277                 }
1278                 delete list;
1279                     
1280                 int tcount = getTax(subset);
1281                 if (tcount != subset.size()) { m->mothurOut("[ERROR]: subsampled list file contains " + toString(subset.size()) + " sequences, but I only found " + toString(tcount) + " in your taxonomy file, did you forget a name file? Please correct."); m->mothurOutEndLine(); }
1282             }else {
1283                 string tempAccnos = "temp.accnos";
1284                 ofstream outAccnos;
1285                 m->openOutputFile(tempAccnos, outAccnos);
1286                 for (set<string>::iterator it = subset.begin(); it != subset.end(); it++) { outAccnos << *it << endl; }
1287                 outAccnos.close();
1288                 
1289                 m->mothurOut("Sampling taxonomy and name file... "); m->mothurOutEndLine();
1290                 string thisNameOutputDir = outputDir;
1291                 if (outputDir == "") {  thisNameOutputDir += m->hasPath(namefile);  }
1292                 map<string, string> variables;
1293                 variables["[filename]"] = thisNameOutputDir + m->getRootName(m->getSimpleName(namefile));
1294                 variables["[extension]"] = m->getExtension(namefile);
1295                 string outputNameFileName = getOutputFileName("name", variables);
1296                 
1297                 string thisTaxOutputDir = outputDir;
1298                 if (outputDir == "") {  thisTaxOutputDir += m->hasPath(taxonomyfile);  }
1299                 variables["[filename]"] = thisTaxOutputDir + m->getRootName(m->getSimpleName(taxonomyfile));
1300                 variables["[extension]"] = m->getExtension(taxonomyfile);
1301                 string outputTaxFileName = getOutputFileName("taxonomy", variables);
1302                 
1303                 
1304                 //use unique.seqs to create new name and fastafile
1305                 string inputString = "dups=f, name=" + namefile + ", taxonomy=" + taxonomyfile + ", accnos=" + tempAccnos;
1306                 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
1307                 m->mothurOut("Running command: get.seqs(" + inputString + ")"); m->mothurOutEndLine();
1308                 m->mothurCalling = true;
1309                 
1310                 Command* getCommand = new GetSeqsCommand(inputString);
1311                 getCommand->execute();
1312                 
1313                 map<string, vector<string> > filenames = getCommand->getOutputFiles();
1314                 
1315                 delete getCommand;
1316                 m->mothurCalling = false;
1317                 
1318                 m->renameFile(filenames["name"][0], outputNameFileName);
1319                 m->renameFile(filenames["taxonomy"][0], outputTaxFileName);
1320                 
1321                 outputTypes["name"].push_back(outputNameFileName);  outputNames.push_back(outputNameFileName);
1322                 outputNames.push_back(outputTaxFileName); outputTypes["taxonomy"].push_back(outputTaxFileName);
1323                 
1324                 m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
1325                 
1326                 m->mothurOut("Done."); m->mothurOutEndLine();
1327             }
1328         }
1329                                                 
1330                 return 0;
1331  
1332         }
1333         catch(exception& e) {
1334                 m->errorOut(e, "SubSampleCommand", "getSubSampleList");
1335                 exit(1);
1336         }
1337 }
1338 //**********************************************************************************************************************
1339 int SubSampleCommand::processList(ListVector*& list, ofstream& out, set<string>& subset) {
1340         try {
1341                                 
1342                 int numBins = list->getNumBins();
1343
1344                 ListVector* temp = new ListVector();
1345                 temp->setLabel(list->getLabel());
1346                 
1347                 for (int i = 0; i < numBins; i++) {
1348                         
1349                         if (m->control_pressed) { break; }
1350                         
1351                         string bin = list->get(i);
1352             vector<string> binnames;
1353             m->splitAtComma(bin, binnames);
1354                         
1355             string newNames = "";
1356                         for(int j=0;j<binnames.size();j++){ if (subset.count(binnames[j]) != 0) {  newNames += binnames[j] + ",";  } }
1357                         
1358                         //if there are names in this bin add to new list
1359                         if (newNames != "") { 
1360                                 newNames = newNames.substr(0, newNames.length()-1); //rip off extra comma
1361                                 temp->push_back(newNames);
1362                         }
1363                 }
1364                 
1365                 delete list;
1366                 list = temp;
1367                 
1368                 if (m->control_pressed) { return 0; }
1369                 
1370                 list->print(out);
1371                 
1372                 return 0;
1373                 
1374         }
1375         catch(exception& e) {
1376                 m->errorOut(e, "SubSampleCommand", "processList");
1377                 exit(1);
1378         }
1379 }
1380 //**********************************************************************************************************************
1381 int SubSampleCommand::getSubSampleRabund() {
1382         try {
1383                 InputData* input = new InputData(rabundfile, "rabund");
1384                 RAbundVector* rabund = input->getRAbundVector();
1385                 string lastLabel = rabund->getLabel();
1386                 
1387                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1388                 set<string> processedLabels;
1389                 set<string> userLabels = labels;
1390                 
1391                 if (size == 0) { //user has not set size, set size = 10%
1392                         size = int((rabund->getNumSeqs()) * 0.10);
1393                 }else if (size > rabund->getNumSeqs()) { m->mothurOut("The size you selected is too large, skipping rabund file."); m->mothurOutEndLine(); delete input; delete rabund; return 0; }
1394                 
1395                 m->mothurOut("Sampling " + toString(size) + " from " + toString(rabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1396                 
1397                 string thisOutputDir = outputDir;
1398                 if (outputDir == "") {  thisOutputDir += m->hasPath(rabundfile);  }
1399         map<string, string> variables; 
1400                 variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(rabundfile));
1401         variables["[extension]"] = m->getExtension(rabundfile);
1402                 string outputFileName = getOutputFileName("rabund", variables);         
1403                 ofstream out;
1404                 m->openOutputFile(outputFileName, out);
1405                 outputTypes["rabund"].push_back(outputFileName);  outputNames.push_back(outputFileName);
1406                 
1407                 //as long as you are not at the end of the file or done wih the lines you want
1408                 while((rabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1409                         if (m->control_pressed) {  delete input; delete rabund; out.close(); return 0;  }
1410                         
1411                         if(allLines == 1 || labels.count(rabund->getLabel()) == 1){                     
1412                                 
1413                                 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1414                                 
1415                                 processRabund(rabund, out);
1416                                 
1417                                 processedLabels.insert(rabund->getLabel());
1418                                 userLabels.erase(rabund->getLabel());
1419                         }
1420                         
1421                         if ((m->anyLabelsToProcess(rabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1422                                 string saveLabel = rabund->getLabel();
1423                                 
1424                                 delete rabund; 
1425                                 
1426                                 rabund = input->getRAbundVector(lastLabel);
1427                                 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1428                                 
1429                                 processRabund(rabund, out);
1430                                 
1431                                 processedLabels.insert(rabund->getLabel());
1432                                 userLabels.erase(rabund->getLabel());
1433                                 
1434                                 //restore real lastlabel to save below
1435                                 rabund->setLabel(saveLabel);
1436                         }
1437                         
1438                         lastLabel = rabund->getLabel();
1439                         
1440                         //prevent memory leak
1441                         delete rabund; rabund = NULL;
1442                         
1443                         //get next line to process
1444                         rabund = input->getRAbundVector();                              
1445                 }
1446                 
1447                 
1448                 if (m->control_pressed) {  out.close(); return 0;  }
1449                 
1450                 //output error messages about any remaining user labels
1451                 set<string>::iterator it;
1452                 bool needToRun = false;
1453                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
1454                         m->mothurOut("Your file does not include the label " + *it); 
1455                         if (processedLabels.count(lastLabel) != 1) {
1456                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1457                                 needToRun = true;
1458                         }else {
1459                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1460                         }
1461                 }
1462                 
1463                 //run last label if you need to
1464                 if (needToRun == true)  {
1465                         if (rabund != NULL) { delete rabund; }
1466                         
1467                         rabund = input->getRAbundVector(lastLabel);
1468                         
1469                         m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1470                         
1471                         processRabund(rabund, out);
1472                         
1473                         delete rabund;
1474                 }
1475                 
1476                 delete input;
1477                 out.close();  
1478                 
1479                 return 0;
1480                 
1481         }
1482         catch(exception& e) {
1483                 m->errorOut(e, "SubSampleCommand", "getSubSampleRabund");
1484                 exit(1);
1485         }
1486 }
1487 //**********************************************************************************************************************
1488 int SubSampleCommand::processRabund(RAbundVector*& rabund, ofstream& out) {
1489         try {
1490                 
1491                 int numBins = rabund->getNumBins();
1492                 int thisSize = rabund->getNumSeqs();
1493                         
1494                 if (thisSize != size) {
1495                                 
1496                         OrderVector* order = new OrderVector();
1497                         for(int p=0;p<numBins;p++){
1498                                 for(int j=0;j<rabund->get(p);j++){
1499                                         order->push_back(p);
1500                                 }
1501                         }
1502                         random_shuffle(order->begin(), order->end());
1503                         
1504                         RAbundVector* temp = new RAbundVector(numBins);
1505                         temp->setLabel(rabund->getLabel());
1506                         
1507                         delete rabund;
1508                         rabund = temp;
1509                         
1510                         for (int j = 0; j < size; j++) {
1511                                 
1512                                 if (m->control_pressed) { delete order; return 0; }
1513                                 
1514                                 int bin = order->get(j);
1515                                 
1516                                 int abund = rabund->get(bin);
1517                                 rabund->set(bin, (abund+1));
1518                         }
1519                         
1520                         delete order;
1521                 }
1522                 
1523                 if (m->control_pressed) { return 0; }
1524                 
1525                 rabund->print(out);
1526                 
1527                 return 0;
1528                 
1529         }
1530         catch(exception& e) {
1531                 m->errorOut(e, "SubSampleCommand", "processRabund");
1532                 exit(1);
1533         }
1534 }       
1535 //**********************************************************************************************************************
1536 int SubSampleCommand::getSubSampleSabund() {
1537         try {
1538                                 
1539                 InputData* input = new InputData(sabundfile, "sabund");
1540                 SAbundVector* sabund = input->getSAbundVector();
1541                 string lastLabel = sabund->getLabel();
1542                 
1543                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1544                 set<string> processedLabels;
1545                 set<string> userLabels = labels;
1546                 
1547                 if (size == 0) { //user has not set size, set size = 10%
1548                         size = int((sabund->getNumSeqs()) * 0.10);
1549                 }else if (size > sabund->getNumSeqs()) { m->mothurOut("The size you selected is too large, skipping sabund file."); m->mothurOutEndLine(); delete input; delete sabund; return 0; }
1550                 
1551                 
1552                 m->mothurOut("Sampling " + toString(size) + " from " + toString(sabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1553                 
1554                 string thisOutputDir = outputDir;
1555                 if (outputDir == "") {  thisOutputDir += m->hasPath(sabundfile);  }
1556         map<string, string> variables; 
1557                 variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(sabundfile));
1558         variables["[extension]"] = m->getExtension(sabundfile);
1559                 string outputFileName = getOutputFileName("sabund", variables);         
1560                 ofstream out;
1561                 m->openOutputFile(outputFileName, out);
1562                 outputTypes["sabund"].push_back(outputFileName);  outputNames.push_back(outputFileName);
1563                 
1564                 
1565                 //as long as you are not at the end of the file or done wih the lines you want
1566                 while((sabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1567                         if (m->control_pressed) {  delete input; delete sabund; out.close(); return 0;  }
1568                         
1569                         if(allLines == 1 || labels.count(sabund->getLabel()) == 1){                     
1570                                 
1571                                 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1572                                 
1573                                 processSabund(sabund, out);
1574                                 
1575                                 processedLabels.insert(sabund->getLabel());
1576                                 userLabels.erase(sabund->getLabel());
1577                         }
1578                         
1579                         if ((m->anyLabelsToProcess(sabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1580                                 string saveLabel = sabund->getLabel();
1581                                 
1582                                 delete sabund; 
1583                                 
1584                                 sabund = input->getSAbundVector(lastLabel);
1585                                 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1586                                 
1587                                 processSabund(sabund, out);
1588                                 
1589                                 processedLabels.insert(sabund->getLabel());
1590                                 userLabels.erase(sabund->getLabel());
1591                                 
1592                                 //restore real lastlabel to save below
1593                                 sabund->setLabel(saveLabel);
1594                         }
1595                         
1596                         lastLabel = sabund->getLabel();
1597                         
1598                         //prevent memory leak
1599                         delete sabund; sabund = NULL;
1600                         
1601                         //get next line to process
1602                         sabund = input->getSAbundVector();                              
1603                 }
1604                 
1605                 
1606                 if (m->control_pressed) {  out.close(); return 0;  }
1607                 
1608                 //output error messages about any remaining user labels
1609                 set<string>::iterator it;
1610                 bool needToRun = false;
1611                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
1612                         m->mothurOut("Your file does not include the label " + *it); 
1613                         if (processedLabels.count(lastLabel) != 1) {
1614                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1615                                 needToRun = true;
1616                         }else {
1617                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1618                         }
1619                 }
1620                 
1621                 //run last label if you need to
1622                 if (needToRun == true)  {
1623                         if (sabund != NULL) { delete sabund; }
1624                         
1625                         sabund = input->getSAbundVector(lastLabel);
1626                         
1627                         m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1628                         
1629                         processSabund(sabund, out);
1630                         
1631                         delete sabund;
1632                 }
1633                 
1634                 delete input;
1635                 out.close();  
1636                 
1637                 return 0;
1638                 
1639         }
1640         catch(exception& e) {
1641                 m->errorOut(e, "SubSampleCommand", "getSubSampleSabund");
1642                 exit(1);
1643         }
1644 }
1645 //**********************************************************************************************************************
1646 int SubSampleCommand::processSabund(SAbundVector*& sabund, ofstream& out) {
1647         try {
1648                 
1649                 RAbundVector* rabund = new RAbundVector();
1650                 *rabund = sabund->getRAbundVector();
1651                 
1652                 int numBins = rabund->getNumBins();
1653                 int thisSize = rabund->getNumSeqs();
1654         
1655                 if (thisSize != size) {
1656                         
1657                         OrderVector* order = new OrderVector();
1658                         for(int p=0;p<numBins;p++){
1659                                 for(int j=0;j<rabund->get(p);j++){
1660                                         order->push_back(p);
1661                                 }
1662                         }
1663                         random_shuffle(order->begin(), order->end());
1664                         
1665                         RAbundVector* temp = new RAbundVector(numBins);
1666                         temp->setLabel(rabund->getLabel());
1667                         
1668                         delete rabund;
1669                         rabund = temp;
1670                         
1671                         for (int j = 0; j < size; j++) {
1672         
1673                                 if (m->control_pressed) { delete order; return 0; }
1674                                 
1675                                 int bin = order->get(j);
1676                                 
1677                                 int abund = rabund->get(bin);
1678                                 rabund->set(bin, (abund+1));
1679                         }
1680                         
1681                         delete order;
1682                 }
1683                 
1684                 if (m->control_pressed) { return 0; }
1685
1686                 delete sabund;
1687                 sabund = new SAbundVector();
1688                 *sabund = rabund->getSAbundVector();
1689                 delete rabund;
1690         
1691                 sabund->print(out);
1692                 
1693                 return 0;
1694                 
1695         }
1696         catch(exception& e) {
1697                 m->errorOut(e, "SubSampleCommand", "processSabund");
1698                 exit(1);
1699         }
1700 }
1701
1702 //**********************************************************************************************************************
1703 int SubSampleCommand::getTax(set<string>& subset) {
1704         try {
1705
1706         string thisTaxOutputDir = outputDir;
1707         if (outputDir == "") {  thisTaxOutputDir += m->hasPath(taxonomyfile);  }
1708         map<string, string> variables;
1709         variables["[filename]"] = thisTaxOutputDir + m->getRootName(m->getSimpleName(taxonomyfile));
1710         variables["[extension]"] = m->getExtension(taxonomyfile);
1711         string outputTaxFileName = getOutputFileName("taxonomy", variables);
1712         ofstream outTax;
1713         m->openOutputFile(outputTaxFileName, outTax);
1714         outputNames.push_back(outputTaxFileName); outputTypes["taxonomy"].push_back(outputTaxFileName);
1715         
1716         //read through fasta file outputting only the names on the subsample list
1717         ifstream inTax;
1718         m->openInputFile(taxonomyfile, inTax);
1719         
1720         string tname, tax;
1721         int tcount = 0;
1722         map<string, vector<string> >::iterator itNameMap;
1723         
1724         while(!inTax.eof()){
1725             
1726             if (m->control_pressed) { inTax.close(); outTax.close();  return 0; }
1727             
1728             inTax >> tname;     m->gobble(inTax);                       //read from first column
1729             inTax >> tax;       m->gobble(inTax);               //read from second column
1730             
1731             //does the subset contain a sequence that this sequence represents
1732             itNameMap = nameMap.find(tname);
1733             if (itNameMap != nameMap.end()) {
1734                 vector<string> nameRepresents = itNameMap->second;
1735                 
1736             
1737                 for (int i = 0; i < nameRepresents.size(); i++){
1738                     if (subset.count(nameRepresents[i]) != 0) {
1739                         outTax << nameRepresents[i] << '\t' << tax << endl;
1740                         tcount++;
1741                        
1742                     }
1743                 }
1744             }else{ m->mothurOut("[ERROR]: " + tname + " is missing, please correct."); m->mothurOutEndLine(); }
1745         }
1746         inTax.close();
1747         outTax.close();
1748         
1749         return tcount;
1750     }
1751     catch(exception& e) {
1752         m->errorOut(e, "SubSampleCommand", "getTax");
1753         exit(1);
1754     }
1755 }
1756
1757 //**********************************************************************************************************************
1758
1759
1760