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