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