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