]> git.donarmstrong.com Git - mothur.git/blob - subsamplecommand.cpp
added headers to shared and relabund files
[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                                 if (!m->printedHeaders) { lookup[0]->printHeaders(out); }
706                                 processShared(lookup, out);
707                                 
708                                 processedLabels.insert(lookup[0]->getLabel());
709                                 userLabels.erase(lookup[0]->getLabel());
710                         }
711                         
712                         if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
713                                 string saveLabel = lookup[0]->getLabel();
714                                 
715                                 for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  }  
716                                 
717                                 lookup = input->getSharedRAbundVectors(lastLabel);
718                                 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
719                                 
720                                 if (!m->printedHeaders) { lookup[0]->printHeaders(out); }
721                                 processShared(lookup, out);
722                                 
723                                 processedLabels.insert(lookup[0]->getLabel());
724                                 userLabels.erase(lookup[0]->getLabel());
725                                 
726                                 //restore real lastlabel to save below
727                                 lookup[0]->setLabel(saveLabel);
728                         }
729                         
730                         lastLabel = lookup[0]->getLabel();
731                         //prevent memory leak
732                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i]; lookup[i] = NULL; }
733                         
734                         //get next line to process
735                         lookup = input->getSharedRAbundVectors();                               
736                 }
737                 
738                 
739                 if (m->control_pressed) {  out.close(); return 0;  }
740                 
741                 //output error messages about any remaining user labels
742                 set<string>::iterator it;
743                 bool needToRun = false;
744                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
745                         m->mothurOut("Your file does not include the label " + *it); 
746                         if (processedLabels.count(lastLabel) != 1) {
747                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
748                                 needToRun = true;
749                         }else {
750                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
751                         }
752                 }
753                 
754                 //run last label if you need to
755                 if (needToRun == true)  {
756                         for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }  
757                         lookup = input->getSharedRAbundVectors(lastLabel);
758                         
759                         m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
760                         
761                         if (!m->printedHeaders) { lookup[0]->printHeaders(out); }
762                         processShared(lookup, out);
763                         
764                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  }
765                 }
766                 
767                 delete input;
768                 out.close();  
769                 
770                 return 0;
771                 
772         }
773         catch(exception& e) {
774                 m->errorOut(e, "SubSampleCommand", "getSubSampleShared");
775                 exit(1);
776         }
777 }
778 //**********************************************************************************************************************
779 int SubSampleCommand::processShared(vector<SharedRAbundVector*>& thislookup, ofstream& out) {
780         try {
781                 
782                 int numBins = thislookup[0]->getNumBins();
783                 for (int i = 0; i < thislookup.size(); i++) {           
784                         int thisSize = thislookup[i]->getNumSeqs();
785                         
786                         if (thisSize != size) {
787                                 
788                                 string thisgroup = thislookup[i]->getGroup();
789                                 
790                                 OrderVector* order = new OrderVector();
791                                 for(int p=0;p<numBins;p++){
792                                         for(int j=0;j<thislookup[i]->getAbundance(p);j++){
793                                                 order->push_back(p);
794                                         }
795                                 }
796                                 random_shuffle(order->begin(), order->end());
797                                 
798                                 SharedRAbundVector* temp = new SharedRAbundVector(numBins);
799                                 temp->setLabel(thislookup[i]->getLabel());
800                                 temp->setGroup(thislookup[i]->getGroup());
801                                 
802                                 delete thislookup[i];
803                                 thislookup[i] = temp;
804                                 
805                                 
806                                 for (int j = 0; j < size; j++) {
807                                         
808                                         if (m->control_pressed) { delete order; return 0; }
809                                         
810                                         //get random number to sample from order between 0 and thisSize-1.
811                                         int myrand = int((float)(thisSize) * (float)(rand()) / ((float)RAND_MAX+1.0));
812                                         
813                                         int bin = order->get(myrand);
814                                         
815                                         int abund = thislookup[i]->getAbundance(bin);
816                                         thislookup[i]->set(bin, (abund+1), thisgroup);
817                                 }       
818                                 delete order;
819                         }
820                 }
821                 
822                 //subsampling may have created some otus with no sequences in them
823                 eliminateZeroOTUS(thislookup);
824                 
825                 if (m->control_pressed) { return 0; }
826                 
827                 for (int i = 0; i < thislookup.size(); i++) {
828                         out << thislookup[i]->getLabel() << '\t' << thislookup[i]->getGroup() << '\t';
829                         thislookup[i]->print(out);
830                 }
831                 
832                 return 0;
833                 
834         }
835         catch(exception& e) {
836                 m->errorOut(e, "SubSampleCommand", "processShared");
837                 exit(1);
838         }
839 }                       
840 //**********************************************************************************************************************
841 int SubSampleCommand::getSubSampleList() {
842         try {
843                 
844                 string thisOutputDir = outputDir;
845                 if (outputDir == "") {  thisOutputDir += m->hasPath(listfile);  }
846                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(listfile)) + "subsample" + m->getExtension(listfile);
847                 
848                 ofstream out;
849                 m->openOutputFile(outputFileName, out);
850                 outputTypes["list"].push_back(outputFileName);  outputNames.push_back(outputFileName);
851                 
852                 InputData* input = new InputData(listfile, "list");
853                 ListVector* list = input->getListVector();
854                 string lastLabel = list->getLabel();
855                 
856                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
857                 set<string> processedLabels;
858                 set<string> userLabels = labels;
859                 
860                 ofstream outGroup;
861                 GroupMap* groupMap;
862                 if (groupfile != "") {
863                         
864                         groupMap = new GroupMap(groupfile);
865                         groupMap->readMap();
866                         
867                         //takes care of user setting groupNames that are invalid or setting groups=all
868                         SharedUtil* util = new SharedUtil();
869                         util->setGroups(Groups, groupMap->namesOfGroups);
870                         delete util;
871                         
872                         //create outputfiles
873                         string groupOutputDir = outputDir;
874                         if (outputDir == "") {  groupOutputDir += m->hasPath(groupfile);  }
875                         string groupOutputFileName = groupOutputDir + m->getRootName(m->getSimpleName(groupfile)) + "subsample" + m->getExtension(groupfile);
876                         
877                         m->openOutputFile(groupOutputFileName, outGroup);
878                         outputTypes["group"].push_back(groupOutputFileName);  outputNames.push_back(groupOutputFileName);
879                         
880                         //file mismatch quit
881                         if (list->getNumSeqs() != groupMap->getNumSeqs()) { 
882                                 m->mothurOut("[ERROR]: your list file contains " + toString(list->getNumSeqs()) + " sequences, and your groupfile contains " + toString(groupMap->getNumSeqs()) + ", please correct."); 
883                                 m->mothurOutEndLine();
884                                 delete groupMap;
885                                 delete list;
886                                 delete input;
887                                 out.close();
888                                 outGroup.close();
889                                 return 0;
890                         }                       
891                 }
892                 
893                 //make sure that if your picked groups size is not too big
894                 if (persample) {
895                         if (size == 0) { //user has not set size, set size = smallest samples size
896                                 size = groupMap->getNumSeqs(Groups[0]);
897                                 for (int i = 1; i < Groups.size(); i++) {
898                                         int thisSize = groupMap->getNumSeqs(Groups[i]);
899                                         
900                                         if (thisSize < size) {  size = thisSize;        }
901                                 }
902                         }else { //make sure size is not too large
903                                 vector<string> newGroups;
904                                 for (int i = 0; i < Groups.size(); i++) {
905                                         int thisSize = groupMap->getNumSeqs(Groups[i]);
906                                         
907                                         if (thisSize >= size) { newGroups.push_back(Groups[i]); }
908                                         else {  m->mothurOut("You have selected a size that is larger than " + Groups[i] + " number of sequences, removing " + Groups[i] + "."); m->mothurOutEndLine(); }
909                                 }
910                                 Groups = newGroups;
911                         }
912                         
913                         m->mothurOut("Sampling " + toString(size) + " from each group."); m->mothurOutEndLine();        
914                 }else{
915                         if (pickedGroups) {
916                                 int total = 0;
917                                 for(int i = 0; i < Groups.size(); i++) {
918                                         total += groupMap->getNumSeqs(Groups[i]);
919                                 }
920                                 
921                                 if (size == 0) { //user has not set size, set size = 10% samples size
922                                         size = int (total * 0.10);
923                                 }
924                                 
925                                 if (total < size) { 
926                                         m->mothurOut("Your size is too large for the number of groups you selected. Adjusting to " + toString(int (total * 0.10)) + "."); m->mothurOutEndLine();
927                                         size = int (total * 0.10);
928                                 }
929                                 
930                                 m->mothurOut("Sampling " + toString(size) + " from " + toString(total) + "."); m->mothurOutEndLine();
931                         }else{
932                                 
933                                 if (size == 0) { //user has not set size, set size = 10% samples size
934                                         size = int (list->getNumSeqs() * 0.10);
935                                 }
936                                 
937                                 int thisSize = list->getNumSeqs();
938                                 if (size > thisSize) { m->mothurOut("Your list file only contains " + toString(thisSize) + " sequences. Setting size to " + toString(thisSize) + "."); m->mothurOutEndLine();
939                                         size = thisSize;
940                                 }
941                                 
942                                 m->mothurOut("Sampling " + toString(size) + " from " + toString(list->getNumSeqs()) + "."); m->mothurOutEndLine();
943                         }
944                 }
945                 
946                 
947                 //fill names
948                 for (int i = 0; i < list->getNumBins(); i++) {
949                         string binnames = list->get(i);
950                         
951                         //parse names
952                         string individual = "";
953                         int length = binnames.length();
954                         for(int j=0;j<length;j++){
955                                 if(binnames[j] == ','){
956                                         
957                                         if (groupfile != "") { //if there is a groupfile given fill in group info
958                                                 string group = groupMap->getGroup(individual);
959                                                 if (group == "not found") { m->mothurOut("[ERROR]: " + individual + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
960                                                 
961                                                 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
962                                                         if (m->inUsersGroups(group, Groups)) {
963                                                                 names.push_back(individual);
964                                                         }
965                                                 }else{
966                                                         names.push_back(individual);
967                                                 }
968                                         }else{ //save everyone, group
969                                                 names.push_back(individual);
970                                         }
971                                         individual = "";                                
972                                 }
973                                 else{
974                                         individual += binnames[j];
975                                 }
976                         }
977                         //save last name
978                         if (groupfile != "") { //if there is a groupfile given fill in group info
979                                 string group = groupMap->getGroup(individual);
980                                 if (group == "not found") { m->mothurOut("[ERROR]: " + individual + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
981                                 
982                                 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
983                                         if (m->inUsersGroups(group, Groups)) {
984                                                 names.push_back(individual);
985                                         }
986                                 }else{
987                                         names.push_back(individual);
988                                 }
989                         }else{ //save everyone, group
990                                 names.push_back(individual);
991                         }
992                 }
993                 
994                 random_shuffle(names.begin(), names.end());
995                         
996                 //randomly select a subset of those names to include in the subsample
997                 set<string> subset; //dont want repeat sequence names added
998                 if (persample) {
999                         for (int i = 0; i < Groups.size(); i++) {
1000                                 
1001                                 for (int j = 0; j < size; j++) {
1002                                         
1003                                         if (m->control_pressed) { break; }
1004                                         
1005                                         //get random sequence to add, making sure we have not already added it
1006                                         bool done = false;
1007                                         int myrand;
1008                                         while (!done) {
1009                                                 myrand = int((float)(names.size()) * (float)(rand()) / ((float)RAND_MAX+1.0));
1010                                                 
1011                                                 if (subset.count(names[myrand]) == 0) { //you are not already added
1012                                                         if (groupMap->getGroup(names[myrand]) == Groups[i])  { subset.insert(names[myrand]); break;     }
1013                                                 }
1014                                         }
1015                                 }
1016                         }
1017                 }else{
1018                         for (int j = 0; j < size; j++) {
1019                                 
1020                                 if (m->control_pressed) { break; }
1021                                 
1022                                 //get random sequence to add, making sure we have not already added it
1023                                 bool done = false;
1024                                 int myrand;
1025                                 while (!done) {
1026                                         myrand = int((float)(names.size()) * (float)(rand()) / ((float)RAND_MAX+1.0));
1027                                         
1028                                         if (subset.count(names[myrand]) == 0)  { subset.insert(names[myrand]); break;   }
1029                                 }
1030                         }       
1031                 }
1032                 
1033                 if (groupfile != "") { 
1034                         //write out new groupfile
1035                         for (set<string>::iterator it = subset.begin(); it != subset.end(); it++) {
1036                                 string group = groupMap->getGroup(*it);
1037                                 if (group == "not found") { group = "NOTFOUND"; }
1038                                 
1039                                 outGroup << *it << '\t' << group << endl;
1040                         }
1041                         outGroup.close(); delete groupMap; 
1042                 }
1043                 
1044                                                 
1045                 //as long as you are not at the end of the file or done wih the lines you want
1046                 while((list != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1047                         
1048                         if (m->control_pressed) {  delete list; delete input; out.close();  return 0;  }
1049                         
1050                         if(allLines == 1 || labels.count(list->getLabel()) == 1){                       
1051                                 
1052                                 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1053                                 
1054                                 processList(list, out, subset);
1055                                 
1056                                 processedLabels.insert(list->getLabel());
1057                                 userLabels.erase(list->getLabel());
1058                         }
1059                         
1060                         if ((m->anyLabelsToProcess(list->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1061                                 string saveLabel = list->getLabel();
1062                                 
1063                                 delete list; 
1064                                 
1065                                 list = input->getListVector(lastLabel);
1066                                 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1067                                 
1068                                 processList(list, out, subset);
1069                                 
1070                                 processedLabels.insert(list->getLabel());
1071                                 userLabels.erase(list->getLabel());
1072                                 
1073                                 //restore real lastlabel to save below
1074                                 list->setLabel(saveLabel);
1075                         }
1076                         
1077                         lastLabel = list->getLabel();
1078                         
1079                         delete list; list = NULL;
1080                         
1081                         //get next line to process
1082                         list = input->getListVector();                          
1083                 }
1084                 
1085                 
1086                 if (m->control_pressed) {  if (list != NULL) { delete list; } delete input; out.close(); return 0;  }
1087                 
1088                 //output error messages about any remaining user labels
1089                 set<string>::iterator it;
1090                 bool needToRun = false;
1091                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
1092                         m->mothurOut("Your file does not include the label " + *it); 
1093                         if (processedLabels.count(lastLabel) != 1) {
1094                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1095                                 needToRun = true;
1096                         }else {
1097                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1098                         }
1099                 }
1100                 
1101                 //run last label if you need to
1102                 if (needToRun == true)  {
1103                         if (list != NULL) { delete list; }
1104                         
1105                         list = input->getListVector(lastLabel);
1106                         
1107                         m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1108                         
1109                         processList(list, out, subset);
1110                         
1111                         delete list; list = NULL;
1112                 }
1113                 
1114                 out.close();  
1115                 if (list != NULL) { delete list; }
1116                 delete input;
1117                                                 
1118                 return 0;
1119  
1120         }
1121         catch(exception& e) {
1122                 m->errorOut(e, "SubSampleCommand", "getSubSampleList");
1123                 exit(1);
1124         }
1125 }
1126 //**********************************************************************************************************************
1127 int SubSampleCommand::processList(ListVector*& list, ofstream& out, set<string>& subset) {
1128         try {
1129                                 
1130                 int numBins = list->getNumBins();
1131
1132                 ListVector* temp = new ListVector();
1133                 temp->setLabel(list->getLabel());
1134                 
1135                 for (int i = 0; i < numBins; i++) {
1136                         
1137                         if (m->control_pressed) { break; }
1138                         
1139                         string binnames = list->get(i);
1140                         
1141                         //parse names
1142                         string individual = "";
1143                         string newNames = "";
1144                         int length = binnames.length();
1145                         for(int j=0;j<length;j++){
1146                                 if(binnames[j] == ','){
1147                                         if (subset.count(individual) != 0) {  newNames += individual + ",";  }
1148                                         individual = "";                                
1149                                 }else{
1150                                         individual += binnames[j];
1151                                 }
1152                         }
1153                         if (subset.count(individual) != 0) {  newNames += individual + ",";  }
1154                         
1155                         
1156                         //if there are names in this bin add to new list
1157                         if (newNames != "") { 
1158                                 newNames = newNames.substr(0, newNames.length()-1); //rip off extra comma
1159                                 temp->push_back(newNames);
1160                         }
1161                 }
1162                 
1163                 delete list;
1164                 list = temp;
1165                 
1166                 if (m->control_pressed) { return 0; }
1167                 
1168                 list->print(out);
1169                 
1170                 return 0;
1171                 
1172         }
1173         catch(exception& e) {
1174                 m->errorOut(e, "SubSampleCommand", "processList");
1175                 exit(1);
1176         }
1177 }
1178 //**********************************************************************************************************************
1179 int SubSampleCommand::getSubSampleRabund() {
1180         try {
1181                 InputData* input = new InputData(rabundfile, "rabund");
1182                 RAbundVector* rabund = input->getRAbundVector();
1183                 string lastLabel = rabund->getLabel();
1184                 
1185                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1186                 set<string> processedLabels;
1187                 set<string> userLabels = labels;
1188                 
1189                 if (size == 0) { //user has not set size, set size = 10%
1190                         size = int((rabund->getNumSeqs()) * 0.10);
1191                 }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; }
1192                 
1193                 m->mothurOut("Sampling " + toString(size) + " from " + toString(rabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1194                 
1195                 string thisOutputDir = outputDir;
1196                 if (outputDir == "") {  thisOutputDir += m->hasPath(rabundfile);  }
1197                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(rabundfile)) + "subsample" + m->getExtension(rabundfile);
1198                 
1199                 ofstream out;
1200                 m->openOutputFile(outputFileName, out);
1201                 outputTypes["rabund"].push_back(outputFileName);  outputNames.push_back(outputFileName);
1202                 
1203                 //as long as you are not at the end of the file or done wih the lines you want
1204                 while((rabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1205                         if (m->control_pressed) {  delete input; delete rabund; out.close(); return 0;  }
1206                         
1207                         if(allLines == 1 || labels.count(rabund->getLabel()) == 1){                     
1208                                 
1209                                 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1210                                 
1211                                 processRabund(rabund, out);
1212                                 
1213                                 processedLabels.insert(rabund->getLabel());
1214                                 userLabels.erase(rabund->getLabel());
1215                         }
1216                         
1217                         if ((m->anyLabelsToProcess(rabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1218                                 string saveLabel = rabund->getLabel();
1219                                 
1220                                 delete rabund; 
1221                                 
1222                                 rabund = input->getRAbundVector(lastLabel);
1223                                 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1224                                 
1225                                 processRabund(rabund, out);
1226                                 
1227                                 processedLabels.insert(rabund->getLabel());
1228                                 userLabels.erase(rabund->getLabel());
1229                                 
1230                                 //restore real lastlabel to save below
1231                                 rabund->setLabel(saveLabel);
1232                         }
1233                         
1234                         lastLabel = rabund->getLabel();
1235                         
1236                         //prevent memory leak
1237                         delete rabund; rabund = NULL;
1238                         
1239                         //get next line to process
1240                         rabund = input->getRAbundVector();                              
1241                 }
1242                 
1243                 
1244                 if (m->control_pressed) {  out.close(); return 0;  }
1245                 
1246                 //output error messages about any remaining user labels
1247                 set<string>::iterator it;
1248                 bool needToRun = false;
1249                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
1250                         m->mothurOut("Your file does not include the label " + *it); 
1251                         if (processedLabels.count(lastLabel) != 1) {
1252                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1253                                 needToRun = true;
1254                         }else {
1255                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1256                         }
1257                 }
1258                 
1259                 //run last label if you need to
1260                 if (needToRun == true)  {
1261                         if (rabund != NULL) { delete rabund; }
1262                         
1263                         rabund = input->getRAbundVector(lastLabel);
1264                         
1265                         m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1266                         
1267                         processRabund(rabund, out);
1268                         
1269                         delete rabund;
1270                 }
1271                 
1272                 delete input;
1273                 out.close();  
1274                 
1275                 return 0;
1276                 
1277         }
1278         catch(exception& e) {
1279                 m->errorOut(e, "SubSampleCommand", "getSubSampleRabund");
1280                 exit(1);
1281         }
1282 }
1283 //**********************************************************************************************************************
1284 int SubSampleCommand::processRabund(RAbundVector*& rabund, ofstream& out) {
1285         try {
1286                 
1287                 int numBins = rabund->getNumBins();
1288                 int thisSize = rabund->getNumSeqs();
1289                         
1290                 if (thisSize != size) {
1291                                 
1292                         OrderVector* order = new OrderVector();
1293                         for(int p=0;p<numBins;p++){
1294                                 for(int j=0;j<rabund->get(p);j++){
1295                                         order->push_back(p);
1296                                 }
1297                         }
1298                         random_shuffle(order->begin(), order->end());
1299                         
1300                         RAbundVector* temp = new RAbundVector(numBins);
1301                         temp->setLabel(rabund->getLabel());
1302                         
1303                         delete rabund;
1304                         rabund = temp;
1305                         
1306                         for (int j = 0; j < size; j++) {
1307                                 
1308                                 if (m->control_pressed) { delete order; return 0; }
1309                                 
1310                                 //get random number to sample from order between 0 and thisSize-1.
1311                                 int myrand = int((float)(thisSize) * (float)(rand()) / ((float)RAND_MAX+1.0));
1312                                 
1313                                 int bin = order->get(myrand);
1314                                 
1315                                 int abund = rabund->get(bin);
1316                                 rabund->set(bin, (abund+1));
1317                         }
1318                         
1319                         delete order;
1320                 }
1321                 
1322                 if (m->control_pressed) { return 0; }
1323                 
1324                 rabund->print(out);
1325                 
1326                 return 0;
1327                 
1328         }
1329         catch(exception& e) {
1330                 m->errorOut(e, "SubSampleCommand", "processRabund");
1331                 exit(1);
1332         }
1333 }       
1334 //**********************************************************************************************************************
1335 int SubSampleCommand::getSubSampleSabund() {
1336         try {
1337                                 
1338                 InputData* input = new InputData(sabundfile, "sabund");
1339                 SAbundVector* sabund = input->getSAbundVector();
1340                 string lastLabel = sabund->getLabel();
1341                 
1342                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1343                 set<string> processedLabels;
1344                 set<string> userLabels = labels;
1345                 
1346                 if (size == 0) { //user has not set size, set size = 10%
1347                         size = int((sabund->getNumSeqs()) * 0.10);
1348                 }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; }
1349                 
1350                 
1351                 m->mothurOut("Sampling " + toString(size) + " from " + toString(sabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1352                 
1353                 string thisOutputDir = outputDir;
1354                 if (outputDir == "") {  thisOutputDir += m->hasPath(sabundfile);  }
1355                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(sabundfile)) + "subsample" + m->getExtension(sabundfile);
1356                 
1357                 ofstream out;
1358                 m->openOutputFile(outputFileName, out);
1359                 outputTypes["sabund"].push_back(outputFileName);  outputNames.push_back(outputFileName);
1360                 
1361                 
1362                 //as long as you are not at the end of the file or done wih the lines you want
1363                 while((sabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1364                         if (m->control_pressed) {  delete input; delete sabund; out.close(); return 0;  }
1365                         
1366                         if(allLines == 1 || labels.count(sabund->getLabel()) == 1){                     
1367                                 
1368                                 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1369                                 
1370                                 processSabund(sabund, out);
1371                                 
1372                                 processedLabels.insert(sabund->getLabel());
1373                                 userLabels.erase(sabund->getLabel());
1374                         }
1375                         
1376                         if ((m->anyLabelsToProcess(sabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1377                                 string saveLabel = sabund->getLabel();
1378                                 
1379                                 delete sabund; 
1380                                 
1381                                 sabund = input->getSAbundVector(lastLabel);
1382                                 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1383                                 
1384                                 processSabund(sabund, out);
1385                                 
1386                                 processedLabels.insert(sabund->getLabel());
1387                                 userLabels.erase(sabund->getLabel());
1388                                 
1389                                 //restore real lastlabel to save below
1390                                 sabund->setLabel(saveLabel);
1391                         }
1392                         
1393                         lastLabel = sabund->getLabel();
1394                         
1395                         //prevent memory leak
1396                         delete sabund; sabund = NULL;
1397                         
1398                         //get next line to process
1399                         sabund = input->getSAbundVector();                              
1400                 }
1401                 
1402                 
1403                 if (m->control_pressed) {  out.close(); return 0;  }
1404                 
1405                 //output error messages about any remaining user labels
1406                 set<string>::iterator it;
1407                 bool needToRun = false;
1408                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
1409                         m->mothurOut("Your file does not include the label " + *it); 
1410                         if (processedLabels.count(lastLabel) != 1) {
1411                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1412                                 needToRun = true;
1413                         }else {
1414                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1415                         }
1416                 }
1417                 
1418                 //run last label if you need to
1419                 if (needToRun == true)  {
1420                         if (sabund != NULL) { delete sabund; }
1421                         
1422                         sabund = input->getSAbundVector(lastLabel);
1423                         
1424                         m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1425                         
1426                         processSabund(sabund, out);
1427                         
1428                         delete sabund;
1429                 }
1430                 
1431                 delete input;
1432                 out.close();  
1433                 
1434                 return 0;
1435                 
1436         }
1437         catch(exception& e) {
1438                 m->errorOut(e, "SubSampleCommand", "getSubSampleSabund");
1439                 exit(1);
1440         }
1441 }
1442 //**********************************************************************************************************************
1443 int SubSampleCommand::processSabund(SAbundVector*& sabund, ofstream& out) {
1444         try {
1445                 
1446                 RAbundVector* rabund = new RAbundVector();
1447                 *rabund = sabund->getRAbundVector();
1448                 
1449                 int numBins = rabund->getNumBins();
1450                 int thisSize = rabund->getNumSeqs();
1451         
1452                 if (thisSize != size) {
1453                         
1454                         OrderVector* order = new OrderVector();
1455                         for(int p=0;p<numBins;p++){
1456                                 for(int j=0;j<rabund->get(p);j++){
1457                                         order->push_back(p);
1458                                 }
1459                         }
1460                         random_shuffle(order->begin(), order->end());
1461                         
1462                         RAbundVector* temp = new RAbundVector(numBins);
1463                         temp->setLabel(rabund->getLabel());
1464                         
1465                         delete rabund;
1466                         rabund = temp;
1467                         
1468                         for (int j = 0; j < size; j++) {
1469         
1470                                 if (m->control_pressed) { delete order; return 0; }
1471                                 
1472                                 //get random number to sample from order between 0 and thisSize-1.
1473                                 int myrand = int((float)(thisSize) * (float)(rand()) / ((float)RAND_MAX+1.0));
1474                                 
1475                                 int bin = order->get(myrand);
1476                                 
1477                                 int abund = rabund->get(bin);
1478                                 rabund->set(bin, (abund+1));
1479                         }
1480                         
1481                         delete order;
1482                 }
1483                 
1484                 if (m->control_pressed) { return 0; }
1485
1486                 delete sabund;
1487                 sabund = new SAbundVector();
1488                 *sabund = rabund->getSAbundVector();
1489                 delete rabund;
1490         
1491                 sabund->print(out);
1492                 
1493                 return 0;
1494                 
1495         }
1496         catch(exception& e) {
1497                 m->errorOut(e, "SubSampleCommand", "processSabund");
1498                 exit(1);
1499         }
1500 }                       
1501 //**********************************************************************************************************************
1502 int SubSampleCommand::eliminateZeroOTUS(vector<SharedRAbundVector*>& thislookup) {
1503         try {
1504                 
1505                 vector<SharedRAbundVector*> newLookup;
1506                 for (int i = 0; i < thislookup.size(); i++) {
1507                         SharedRAbundVector* temp = new SharedRAbundVector();
1508                         temp->setLabel(thislookup[i]->getLabel());
1509                         temp->setGroup(thislookup[i]->getGroup());
1510                         newLookup.push_back(temp);
1511                 }
1512                 
1513                 //for each bin
1514                 for (int i = 0; i < thislookup[0]->getNumBins(); i++) {
1515                         if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) {  delete newLookup[j];  } return 0; }
1516                         
1517                         //look at each sharedRabund and make sure they are not all zero
1518                         bool allZero = true;
1519                         for (int j = 0; j < thislookup.size(); j++) {
1520                                 if (thislookup[j]->getAbundance(i) != 0) { allZero = false;  break;  }
1521                         }
1522                         
1523                         //if they are not all zero add this bin
1524                         if (!allZero) {
1525                                 for (int j = 0; j < thislookup.size(); j++) {
1526                                         newLookup[j]->push_back(thislookup[j]->getAbundance(i), thislookup[j]->getGroup());
1527                                 }
1528                         }
1529                 }
1530                 
1531                 for (int j = 0; j < thislookup.size(); j++) {  delete thislookup[j];  }
1532                 thislookup.clear();
1533                 
1534                 thislookup = newLookup;
1535                 
1536                 return 0;
1537                 
1538         }
1539         catch(exception& e) {
1540                 m->errorOut(e, "SubSampleCommand", "eliminateZeroOTUS");
1541                 exit(1);
1542         }
1543 }
1544
1545 //**********************************************************************************************************************
1546
1547
1548