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