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