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