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