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