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