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