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