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