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