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