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