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