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