]> git.donarmstrong.com Git - mothur.git/blob - subsamplecommand.cpp
fixes while testing 1.33.0
[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],[distance],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->currentSharedBinLabels;
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->currentSharedBinLabels = 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->currentSharedBinLabels = 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                 InputData* input = new InputData(listfile, "list");
997                 ListVector* list = input->getListVector();
998                 string lastLabel = list->getLabel();
999                 
1000         //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1001                 set<string> processedLabels;
1002                 set<string> userLabels = labels;
1003
1004                 ofstream outGroup;
1005                 GroupMap groupMap;
1006                 if (groupfile != "") {
1007                         groupMap.readMap(groupfile);
1008                         
1009                         //takes care of user setting groupNames that are invalid or setting groups=all
1010                         SharedUtil util; vector<string> namesGroups = groupMap.getNamesOfGroups(); util.setGroups(Groups, namesGroups);
1011                         
1012                         //create outputfiles
1013                         string groupOutputDir = outputDir;
1014                         if (outputDir == "") {  groupOutputDir += m->hasPath(groupfile);  }
1015                         string groupOutputFileName = groupOutputDir + m->getRootName(m->getSimpleName(groupfile)) + "subsample" + m->getExtension(groupfile);
1016                         m->openOutputFile(groupOutputFileName, outGroup);
1017                         outputTypes["group"].push_back(groupOutputFileName);  outputNames.push_back(groupOutputFileName);
1018                         
1019                         //file mismatch quit
1020                         if (list->getNumSeqs() != groupMap.getNumSeqs()) { 
1021                                 m->mothurOut("[ERROR]: your list file contains " + toString(list->getNumSeqs()) + " sequences, and your groupfile contains " + toString(groupMap.getNumSeqs()) + ", please correct."); 
1022                                 m->mothurOutEndLine(); delete list; delete input;  outGroup.close(); return 0;
1023                         }                       
1024                 }else if (countfile != "") {
1025             if (ct.hasGroupInfo()) {
1026                 SharedUtil util;
1027                 vector<string> namesGroups = ct.getNamesOfGroups();
1028                 util.setGroups(Groups, namesGroups);
1029             }
1030             
1031             //file mismatch quit
1032                         if (list->getNumSeqs() != ct.getNumUniqueSeqs()) { 
1033                                 m->mothurOut("[ERROR]: your list file contains " + toString(list->getNumSeqs()) + " sequences, and your count file contains " + toString(ct.getNumUniqueSeqs()) + " unique sequences, please correct."); 
1034                                 m->mothurOutEndLine();
1035                                 return 0;
1036                         }       
1037         }
1038
1039                 //make sure that if your picked groups size is not too big
1040                 if (persample) {
1041                         if (size == 0) { //user has not set size, set size = smallest samples size
1042                                 if (countfile == "") { size = groupMap.getNumSeqs(Groups[0]); }
1043                 else {  size = ct.getGroupCount(Groups[0]);  }
1044                 
1045                                 for (int i = 1; i < Groups.size(); i++) {
1046                                         int thisSize = 0;
1047                     if (countfile == "") { thisSize = groupMap.getNumSeqs(Groups[i]); }
1048                     else {  thisSize = ct.getGroupCount(Groups[i]);  }
1049                                         
1050                                         if (thisSize < size) {  size = thisSize;        }
1051                                 }
1052                         }else { //make sure size is not too large
1053                                 vector<string> newGroups;
1054                                 for (int i = 0; i < Groups.size(); i++) {
1055                                         int thisSize = 0;
1056                     if (countfile == "") { thisSize = groupMap.getNumSeqs(Groups[i]); }
1057                     else {  thisSize = ct.getGroupCount(Groups[i]);  }
1058                                         
1059                                         if (thisSize >= size) { newGroups.push_back(Groups[i]); }
1060                                         else {  m->mothurOut("You have selected a size that is larger than " + Groups[i] + " number of sequences, removing " + Groups[i] + "."); m->mothurOutEndLine(); }
1061                                 }
1062                                 Groups = newGroups;
1063                 if (newGroups.size() == 0) {  m->mothurOut("[ERROR]: all groups removed."); m->mothurOutEndLine(); m->control_pressed = true; }
1064                         }
1065                         
1066                         m->mothurOut("Sampling " + toString(size) + " from each group."); m->mothurOutEndLine();                
1067                 }else{
1068             if (pickedGroups) {
1069                                 int total = 0;
1070                                 for(int i = 0; i < Groups.size(); i++) {
1071                     if (countfile == "") { total += groupMap.getNumSeqs(Groups[i]); }
1072                     else {  total += ct.getGroupCount(Groups[i]);  }
1073                                 }
1074                                 
1075                                 if (size == 0) { //user has not set size, set size = 10% samples size
1076                                         size = int (total * 0.10);
1077                                 }
1078                                 
1079                                 if (total < size) { 
1080                                         if (size != 0) { 
1081                                                 m->mothurOut("Your size is too large for the number of groups you selected. Adjusting to " + toString(int (total * 0.10)) + "."); m->mothurOutEndLine();
1082                                         }
1083                                         size = int (total * 0.10);
1084                                 }
1085                                 
1086                                 m->mothurOut("Sampling " + toString(size) + " from " + toString(total) + "."); m->mothurOutEndLine();
1087                         }else {
1088                 if (size == 0) { //user has not set size, set size = 10% samples size
1089                                         if (countfile == "") {  size = int (list->getNumSeqs() * 0.10);  }
1090                     else { size = int (ct.getNumSeqs() * 0.10);  }
1091                                 }
1092                                 
1093                                 int thisSize = 0;
1094                 if (countfile == "") { thisSize = list->getNumSeqs();  }
1095                 else { thisSize = ct.getNumSeqs(); }
1096                 
1097                                 if (size > thisSize) { m->mothurOut("Your list file only contains " + toString(thisSize) + " sequences. Setting size to " + toString(thisSize) + "."); m->mothurOutEndLine();
1098                                         size = thisSize;
1099                                 }
1100                                 
1101                                 m->mothurOut("Sampling " + toString(size) + " from " + toString(thisSize) + "."); m->mothurOutEndLine();
1102             }
1103         }
1104                 
1105         set<string> subset; //dont want repeat sequence names added
1106                 if (countfile == "") {
1107             //fill names
1108             for (int i = 0; i < list->getNumBins(); i++) {
1109                 string binnames = list->get(i);
1110                 vector<string> thisBin;
1111                 m->splitAtComma(binnames, thisBin);
1112                 
1113                 for(int j=0;j<thisBin.size();j++){
1114                     if (groupfile != "") { //if there is a groupfile given fill in group info
1115                         string group = groupMap.getGroup(thisBin[j]);
1116                         if (group == "not found") { m->mothurOut("[ERROR]: " + thisBin[j] + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
1117                         
1118                                                 //if hte user picked groups, we only want to keep the names of sequences from those groups
1119                                                 if (pickedGroups) { if (m->inUsersGroups(group, Groups)) { names.push_back(thisBin[j]); }  }
1120                                                 else{ names.push_back(thisBin[j]); } 
1121                     }//save everyone, group
1122                     else{ names.push_back(thisBin[j]); }
1123                 }
1124             }
1125             
1126             random_shuffle(names.begin(), names.end());
1127                         
1128             //randomly select a subset of those names to include in the subsample
1129             if (persample) {
1130                 //initialize counts
1131                 map<string, int> groupCounts;
1132                 map<string, int>::iterator itGroupCounts;
1133                 for (int i = 0; i < Groups.size(); i++) { groupCounts[Groups[i]] = 0; }
1134                 
1135                 for (int j = 0; j < names.size(); j++) {
1136                     
1137                     if (m->control_pressed) { delete list; delete input;  return 0; }
1138                     
1139                     string group = groupMap.getGroup(names[j]);
1140                     if (group == "not found") { m->mothurOut("[ERROR]: " + names[j] + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
1141                     else{
1142                         itGroupCounts = groupCounts.find(group);
1143                         if (itGroupCounts != groupCounts.end()) {
1144                             if (groupCounts[group] < size) {    subset.insert(names[j]);        groupCounts[group]++; }
1145                         }
1146                     }                           
1147                 }
1148             }else{
1149                 for (int j = 0; j < size; j++) {
1150                     if (m->control_pressed) { break; }
1151                     subset.insert(names[j]); 
1152                 }       
1153             }
1154             
1155             if (groupfile != "") { 
1156                 //write out new groupfile
1157                 for (set<string>::iterator it = subset.begin(); it != subset.end(); it++) {
1158                     string group = groupMap.getGroup(*it);
1159                     if (group == "not found") { group = "NOTFOUND"; }
1160                     outGroup << *it << '\t' << group << endl;
1161                 }
1162                 outGroup.close(); 
1163             }
1164                 }else {
1165             SubSample sample; CountTable sampledCt;
1166             
1167             if (persample)  { sampledCt = sample.getSample(ct, size, Groups);               }
1168             else            { sampledCt = sample.getSample(ct, size, Groups, pickedGroups); }
1169             
1170             vector<string> sampledSeqs = sampledCt.getNamesOfSeqs();
1171             for (int i = 0; i < sampledSeqs.size(); i++) { subset.insert(sampledSeqs[i]); }
1172         
1173             string countOutputDir = outputDir;
1174             if (outputDir == "") {  countOutputDir += m->hasPath(countfile);  }
1175             map<string, string> variables; 
1176             variables["[filename]"] = countOutputDir + m->getRootName(m->getSimpleName(countfile));
1177             variables["[extension]"] = m->getExtension(countfile);
1178             string countOutputFileName = getOutputFileName("count", variables);
1179             outputTypes["count"].push_back(countOutputFileName);  outputNames.push_back(countOutputFileName);
1180             sampledCt.printTable(countOutputFileName);
1181         }
1182                                                 
1183                 //as long as you are not at the end of the file or done wih the lines you want
1184                 while((list != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1185                         
1186                         if (m->control_pressed) {  delete list; delete input;  return 0;  }
1187                         
1188                         if(allLines == 1 || labels.count(list->getLabel()) == 1){                       
1189                                 
1190                                 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1191                                 
1192                                 processList(list,  subset);
1193                                 
1194                                 processedLabels.insert(list->getLabel());
1195                                 userLabels.erase(list->getLabel());
1196                         }
1197                         
1198                         if ((m->anyLabelsToProcess(list->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1199                                 string saveLabel = list->getLabel();
1200                                 
1201                                 delete list; 
1202                                 
1203                                 list = input->getListVector(lastLabel);
1204                                 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1205                                 
1206                                 processList(list,  subset);
1207                                 
1208                                 processedLabels.insert(list->getLabel());
1209                                 userLabels.erase(list->getLabel());
1210                                 
1211                                 //restore real lastlabel to save below
1212                                 list->setLabel(saveLabel);
1213                         }
1214                         
1215                         lastLabel = list->getLabel();
1216                         
1217                         delete list; list = NULL;
1218                         
1219                         //get next line to process
1220                         list = input->getListVector();                          
1221                 }
1222                 
1223                 
1224                 if (m->control_pressed) {  if (list != NULL) { delete list; } delete input;  return 0;  }
1225                 
1226                 //output error messages about any remaining user labels
1227                 set<string>::iterator it;
1228                 bool needToRun = false;
1229                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
1230                         m->mothurOut("Your file does not include the label " + *it); 
1231                         if (processedLabels.count(lastLabel) != 1) {
1232                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1233                                 needToRun = true;
1234                         }else {
1235                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1236                         }
1237                 }
1238                 
1239                 //run last label if you need to
1240                 if (needToRun == true)  {
1241                         if (list != NULL) { delete list; }
1242                         
1243                         list = input->getListVector(lastLabel);
1244                         
1245                         m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1246                         
1247                         processList(list, subset);
1248                         
1249                         delete list; list = NULL;
1250                 }
1251                 
1252                 if (list != NULL) { delete list; }
1253                 delete input;
1254         
1255         if (taxonomyfile != "") {
1256             if (namefile == "") {
1257                 InputData input(listfile, "list");
1258                 ListVector* list = input.getListVector();
1259                 string lastLabel = list->getLabel();
1260                 
1261                 for (int i = 0; i < list->getNumBins(); i++) {
1262                     vector<string> temp;
1263                     string bin = list->get(i);
1264                     m->splitAtComma(bin, temp);
1265                     for (int j = 0; j < temp.size(); j++) { vector<string> tempFakeOut; tempFakeOut.push_back(temp[j]); nameMap[temp[j]] = tempFakeOut; }
1266                 }
1267                 delete list;
1268                     
1269                 int tcount = getTax(subset);
1270                 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(); }
1271             }else {
1272                 string tempAccnos = "temp.accnos";
1273                 ofstream outAccnos;
1274                 m->openOutputFile(tempAccnos, outAccnos);
1275                 for (set<string>::iterator it = subset.begin(); it != subset.end(); it++) { outAccnos << *it << endl; }
1276                 outAccnos.close();
1277                 
1278                 m->mothurOut("Sampling taxonomy and name file... "); m->mothurOutEndLine();
1279                 string thisNameOutputDir = outputDir;
1280                 if (outputDir == "") {  thisNameOutputDir += m->hasPath(namefile);  }
1281                 map<string, string> variables;
1282                 variables["[filename]"] = thisNameOutputDir + m->getRootName(m->getSimpleName(namefile));
1283                 variables["[extension]"] = m->getExtension(namefile);
1284                 string outputNameFileName = getOutputFileName("name", variables);
1285                 
1286                 string thisTaxOutputDir = outputDir;
1287                 if (outputDir == "") {  thisTaxOutputDir += m->hasPath(taxonomyfile);  }
1288                 variables["[filename]"] = thisTaxOutputDir + m->getRootName(m->getSimpleName(taxonomyfile));
1289                 variables["[extension]"] = m->getExtension(taxonomyfile);
1290                 string outputTaxFileName = getOutputFileName("taxonomy", variables);
1291                 
1292                 
1293                 //use unique.seqs to create new name and fastafile
1294                 string inputString = "dups=f, name=" + namefile + ", taxonomy=" + taxonomyfile + ", accnos=" + tempAccnos;
1295                 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
1296                 m->mothurOut("Running command: get.seqs(" + inputString + ")"); m->mothurOutEndLine();
1297                 m->mothurCalling = true;
1298                 
1299                 Command* getCommand = new GetSeqsCommand(inputString);
1300                 getCommand->execute();
1301                 
1302                 map<string, vector<string> > filenames = getCommand->getOutputFiles();
1303                 
1304                 delete getCommand;
1305                 m->mothurCalling = false;
1306                 
1307                 m->renameFile(filenames["name"][0], outputNameFileName);
1308                 m->renameFile(filenames["taxonomy"][0], outputTaxFileName);
1309                 
1310                 outputTypes["name"].push_back(outputNameFileName);  outputNames.push_back(outputNameFileName);
1311                 outputNames.push_back(outputTaxFileName); outputTypes["taxonomy"].push_back(outputTaxFileName);
1312                 
1313                 m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
1314                 
1315                 m->mothurOut("Done."); m->mothurOutEndLine();
1316             }
1317         }
1318                                                 
1319                 return 0;
1320  
1321         }
1322         catch(exception& e) {
1323                 m->errorOut(e, "SubSampleCommand", "getSubSampleList");
1324                 exit(1);
1325         }
1326 }
1327 //**********************************************************************************************************************
1328 int SubSampleCommand::processList(ListVector*& list, set<string>& subset) {
1329         try {
1330                 string thisOutputDir = outputDir;
1331                 if (outputDir == "") {  thisOutputDir += m->hasPath(listfile);  }
1332                 map<string, string> variables;
1333         variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(listfile));
1334         variables["[extension]"] = m->getExtension(listfile);
1335         variables["[distance]"] = list->getLabel();
1336                 string outputFileName = getOutputFileName("list", variables);
1337                 ofstream out;
1338                 m->openOutputFile(outputFileName, out);
1339                 outputTypes["list"].push_back(outputFileName);  outputNames.push_back(outputFileName);
1340                 
1341                 int numBins = list->getNumBins();
1342
1343                 ListVector* temp = new ListVector();
1344                 temp->setLabel(list->getLabel());
1345                 
1346         vector<string> binLabels = list->getLabels();
1347         vector<string> newLabels;
1348                 for (int i = 0; i < numBins; i++) {
1349                         
1350                         if (m->control_pressed) { break; }
1351                         
1352                         string bin = list->get(i);
1353             vector<string> binnames;
1354             m->splitAtComma(bin, binnames);
1355                         
1356             string newNames = "";
1357                         for(int j=0;j<binnames.size();j++){ if (subset.count(binnames[j]) != 0) {  newNames += binnames[j] + ",";  } }
1358                         
1359                         //if there are names in this bin add to new list
1360                         if (newNames != "") { 
1361                                 newNames = newNames.substr(0, newNames.length()-1); //rip off extra comma
1362                                 temp->push_back(newNames);
1363                 newLabels.push_back(binLabels[i]);
1364                         }
1365                 }
1366                 
1367         temp->setLabels(newLabels);
1368                 delete list;
1369                 list = temp;
1370                 
1371                 if (m->control_pressed) { out.close(); return 0; }
1372                 
1373         list->printHeaders(out);
1374                 list->print(out);
1375         out.close();
1376                 
1377                 return 0;
1378                 
1379         }
1380         catch(exception& e) {
1381                 m->errorOut(e, "SubSampleCommand", "processList");
1382                 exit(1);
1383         }
1384 }
1385 //**********************************************************************************************************************
1386 int SubSampleCommand::getSubSampleRabund() {
1387         try {
1388                 InputData* input = new InputData(rabundfile, "rabund");
1389                 RAbundVector* rabund = input->getRAbundVector();
1390                 string lastLabel = rabund->getLabel();
1391                 
1392                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1393                 set<string> processedLabels;
1394                 set<string> userLabels = labels;
1395                 
1396                 if (size == 0) { //user has not set size, set size = 10%
1397                         size = int((rabund->getNumSeqs()) * 0.10);
1398                 }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; }
1399                 
1400                 m->mothurOut("Sampling " + toString(size) + " from " + toString(rabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1401                 
1402                 string thisOutputDir = outputDir;
1403                 if (outputDir == "") {  thisOutputDir += m->hasPath(rabundfile);  }
1404         map<string, string> variables; 
1405                 variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(rabundfile));
1406         variables["[extension]"] = m->getExtension(rabundfile);
1407                 string outputFileName = getOutputFileName("rabund", variables);         
1408                 ofstream out;
1409                 m->openOutputFile(outputFileName, out);
1410                 outputTypes["rabund"].push_back(outputFileName);  outputNames.push_back(outputFileName);
1411                 
1412                 //as long as you are not at the end of the file or done wih the lines you want
1413                 while((rabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1414                         if (m->control_pressed) {  delete input; delete rabund; out.close(); return 0;  }
1415                         
1416                         if(allLines == 1 || labels.count(rabund->getLabel()) == 1){                     
1417                                 
1418                                 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1419                                 
1420                                 processRabund(rabund, out);
1421                                 
1422                                 processedLabels.insert(rabund->getLabel());
1423                                 userLabels.erase(rabund->getLabel());
1424                         }
1425                         
1426                         if ((m->anyLabelsToProcess(rabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1427                                 string saveLabel = rabund->getLabel();
1428                                 
1429                                 delete rabund; 
1430                                 
1431                                 rabund = input->getRAbundVector(lastLabel);
1432                                 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1433                                 
1434                                 processRabund(rabund, out);
1435                                 
1436                                 processedLabels.insert(rabund->getLabel());
1437                                 userLabels.erase(rabund->getLabel());
1438                                 
1439                                 //restore real lastlabel to save below
1440                                 rabund->setLabel(saveLabel);
1441                         }
1442                         
1443                         lastLabel = rabund->getLabel();
1444                         
1445                         //prevent memory leak
1446                         delete rabund; rabund = NULL;
1447                         
1448                         //get next line to process
1449                         rabund = input->getRAbundVector();                              
1450                 }
1451                 
1452                 
1453                 if (m->control_pressed) {  out.close(); return 0;  }
1454                 
1455                 //output error messages about any remaining user labels
1456                 set<string>::iterator it;
1457                 bool needToRun = false;
1458                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
1459                         m->mothurOut("Your file does not include the label " + *it); 
1460                         if (processedLabels.count(lastLabel) != 1) {
1461                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1462                                 needToRun = true;
1463                         }else {
1464                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1465                         }
1466                 }
1467                 
1468                 //run last label if you need to
1469                 if (needToRun == true)  {
1470                         if (rabund != NULL) { delete rabund; }
1471                         
1472                         rabund = input->getRAbundVector(lastLabel);
1473                         
1474                         m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1475                         
1476                         processRabund(rabund, out);
1477                         
1478                         delete rabund;
1479                 }
1480                 
1481                 delete input;
1482                 out.close();  
1483                 
1484                 return 0;
1485                 
1486         }
1487         catch(exception& e) {
1488                 m->errorOut(e, "SubSampleCommand", "getSubSampleRabund");
1489                 exit(1);
1490         }
1491 }
1492 //**********************************************************************************************************************
1493 int SubSampleCommand::processRabund(RAbundVector*& rabund, ofstream& out) {
1494         try {
1495                 
1496                 int numBins = rabund->getNumBins();
1497                 int thisSize = rabund->getNumSeqs();
1498                         
1499                 if (thisSize != size) {
1500                                 
1501                         OrderVector* order = new OrderVector();
1502                         for(int p=0;p<numBins;p++){
1503                                 for(int j=0;j<rabund->get(p);j++){
1504                                         order->push_back(p);
1505                                 }
1506                         }
1507                         random_shuffle(order->begin(), order->end());
1508                         
1509                         RAbundVector* temp = new RAbundVector(numBins);
1510                         temp->setLabel(rabund->getLabel());
1511                         
1512                         delete rabund;
1513                         rabund = temp;
1514                         
1515                         for (int j = 0; j < size; j++) {
1516                                 
1517                                 if (m->control_pressed) { delete order; return 0; }
1518                                 
1519                                 int bin = order->get(j);
1520                                 
1521                                 int abund = rabund->get(bin);
1522                                 rabund->set(bin, (abund+1));
1523                         }
1524                         
1525                         delete order;
1526                 }
1527                 
1528                 if (m->control_pressed) { return 0; }
1529                 
1530                 rabund->print(out);
1531                 
1532                 return 0;
1533                 
1534         }
1535         catch(exception& e) {
1536                 m->errorOut(e, "SubSampleCommand", "processRabund");
1537                 exit(1);
1538         }
1539 }       
1540 //**********************************************************************************************************************
1541 int SubSampleCommand::getSubSampleSabund() {
1542         try {
1543                                 
1544                 InputData* input = new InputData(sabundfile, "sabund");
1545                 SAbundVector* sabund = input->getSAbundVector();
1546                 string lastLabel = sabund->getLabel();
1547                 
1548                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1549                 set<string> processedLabels;
1550                 set<string> userLabels = labels;
1551                 
1552                 if (size == 0) { //user has not set size, set size = 10%
1553                         size = int((sabund->getNumSeqs()) * 0.10);
1554                 }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; }
1555                 
1556                 
1557                 m->mothurOut("Sampling " + toString(size) + " from " + toString(sabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1558                 
1559                 string thisOutputDir = outputDir;
1560                 if (outputDir == "") {  thisOutputDir += m->hasPath(sabundfile);  }
1561         map<string, string> variables; 
1562                 variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(sabundfile));
1563         variables["[extension]"] = m->getExtension(sabundfile);
1564                 string outputFileName = getOutputFileName("sabund", variables);         
1565                 ofstream out;
1566                 m->openOutputFile(outputFileName, out);
1567                 outputTypes["sabund"].push_back(outputFileName);  outputNames.push_back(outputFileName);
1568                 
1569                 
1570                 //as long as you are not at the end of the file or done wih the lines you want
1571                 while((sabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1572                         if (m->control_pressed) {  delete input; delete sabund; out.close(); return 0;  }
1573                         
1574                         if(allLines == 1 || labels.count(sabund->getLabel()) == 1){                     
1575                                 
1576                                 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1577                                 
1578                                 processSabund(sabund, out);
1579                                 
1580                                 processedLabels.insert(sabund->getLabel());
1581                                 userLabels.erase(sabund->getLabel());
1582                         }
1583                         
1584                         if ((m->anyLabelsToProcess(sabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1585                                 string saveLabel = sabund->getLabel();
1586                                 
1587                                 delete sabund; 
1588                                 
1589                                 sabund = input->getSAbundVector(lastLabel);
1590                                 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1591                                 
1592                                 processSabund(sabund, out);
1593                                 
1594                                 processedLabels.insert(sabund->getLabel());
1595                                 userLabels.erase(sabund->getLabel());
1596                                 
1597                                 //restore real lastlabel to save below
1598                                 sabund->setLabel(saveLabel);
1599                         }
1600                         
1601                         lastLabel = sabund->getLabel();
1602                         
1603                         //prevent memory leak
1604                         delete sabund; sabund = NULL;
1605                         
1606                         //get next line to process
1607                         sabund = input->getSAbundVector();                              
1608                 }
1609                 
1610                 
1611                 if (m->control_pressed) {  out.close(); return 0;  }
1612                 
1613                 //output error messages about any remaining user labels
1614                 set<string>::iterator it;
1615                 bool needToRun = false;
1616                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
1617                         m->mothurOut("Your file does not include the label " + *it); 
1618                         if (processedLabels.count(lastLabel) != 1) {
1619                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1620                                 needToRun = true;
1621                         }else {
1622                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1623                         }
1624                 }
1625                 
1626                 //run last label if you need to
1627                 if (needToRun == true)  {
1628                         if (sabund != NULL) { delete sabund; }
1629                         
1630                         sabund = input->getSAbundVector(lastLabel);
1631                         
1632                         m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1633                         
1634                         processSabund(sabund, out);
1635                         
1636                         delete sabund;
1637                 }
1638                 
1639                 delete input;
1640                 out.close();  
1641                 
1642                 return 0;
1643                 
1644         }
1645         catch(exception& e) {
1646                 m->errorOut(e, "SubSampleCommand", "getSubSampleSabund");
1647                 exit(1);
1648         }
1649 }
1650 //**********************************************************************************************************************
1651 int SubSampleCommand::processSabund(SAbundVector*& sabund, ofstream& out) {
1652         try {
1653                 
1654                 RAbundVector* rabund = new RAbundVector();
1655                 *rabund = sabund->getRAbundVector();
1656                 
1657                 int numBins = rabund->getNumBins();
1658                 int thisSize = rabund->getNumSeqs();
1659         
1660                 if (thisSize != size) {
1661                         
1662                         OrderVector* order = new OrderVector();
1663                         for(int p=0;p<numBins;p++){
1664                                 for(int j=0;j<rabund->get(p);j++){
1665                                         order->push_back(p);
1666                                 }
1667                         }
1668                         random_shuffle(order->begin(), order->end());
1669                         
1670                         RAbundVector* temp = new RAbundVector(numBins);
1671                         temp->setLabel(rabund->getLabel());
1672                         
1673                         delete rabund;
1674                         rabund = temp;
1675                         
1676                         for (int j = 0; j < size; j++) {
1677         
1678                                 if (m->control_pressed) { delete order; return 0; }
1679                                 
1680                                 int bin = order->get(j);
1681                                 
1682                                 int abund = rabund->get(bin);
1683                                 rabund->set(bin, (abund+1));
1684                         }
1685                         
1686                         delete order;
1687                 }
1688                 
1689                 if (m->control_pressed) { return 0; }
1690
1691                 delete sabund;
1692                 sabund = new SAbundVector();
1693                 *sabund = rabund->getSAbundVector();
1694                 delete rabund;
1695         
1696                 sabund->print(out);
1697                 
1698                 return 0;
1699                 
1700         }
1701         catch(exception& e) {
1702                 m->errorOut(e, "SubSampleCommand", "processSabund");
1703                 exit(1);
1704         }
1705 }
1706
1707 //**********************************************************************************************************************
1708 int SubSampleCommand::getTax(set<string>& subset) {
1709         try {
1710
1711         string thisTaxOutputDir = outputDir;
1712         if (outputDir == "") {  thisTaxOutputDir += m->hasPath(taxonomyfile);  }
1713         map<string, string> variables;
1714         variables["[filename]"] = thisTaxOutputDir + m->getRootName(m->getSimpleName(taxonomyfile));
1715         variables["[extension]"] = m->getExtension(taxonomyfile);
1716         string outputTaxFileName = getOutputFileName("taxonomy", variables);
1717         ofstream outTax;
1718         m->openOutputFile(outputTaxFileName, outTax);
1719         outputNames.push_back(outputTaxFileName); outputTypes["taxonomy"].push_back(outputTaxFileName);
1720         
1721         //read through fasta file outputting only the names on the subsample list
1722         ifstream inTax;
1723         m->openInputFile(taxonomyfile, inTax);
1724         
1725         string tname, tax;
1726         int tcount = 0;
1727         map<string, vector<string> >::iterator itNameMap;
1728         
1729         while(!inTax.eof()){
1730             
1731             if (m->control_pressed) { inTax.close(); outTax.close();  return 0; }
1732             
1733             inTax >> tname;     m->gobble(inTax);                       //read from first column
1734             inTax >> tax;       m->gobble(inTax);               //read from second column
1735             
1736             //does the subset contain a sequence that this sequence represents
1737             itNameMap = nameMap.find(tname);
1738             if (itNameMap != nameMap.end()) {
1739                 vector<string> nameRepresents = itNameMap->second;
1740                 
1741             
1742                 for (int i = 0; i < nameRepresents.size(); i++){
1743                     if (subset.count(nameRepresents[i]) != 0) {
1744                         outTax << nameRepresents[i] << '\t' << tax << endl;
1745                         tcount++;
1746                        
1747                     }
1748                 }
1749             }else{ m->mothurOut("[ERROR]: " + tname + " is missing, please correct."); m->mothurOutEndLine(); }
1750         }
1751         inTax.close();
1752         outTax.close();
1753         
1754         return tcount;
1755     }
1756     catch(exception& e) {
1757         m->errorOut(e, "SubSampleCommand", "getTax");
1758         exit(1);
1759     }
1760 }
1761
1762 //**********************************************************************************************************************
1763
1764
1765