5 * Created by westcott on 10/27/10.
6 * Copyright 2010 Schloss Lab. All rights reserved.
10 #include "subsamplecommand.h"
11 #include "sharedutilities.h"
13 //**********************************************************************************************************************
14 vector<string> SubSampleCommand::getValidParameters(){
16 string Array[] = {"fasta", "group", "list","shared","rabund", "name","sabund","size","groups","label","outputdir","inputdir"};
17 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
21 m->errorOut(e, "SubSampleCommand", "getValidParameters");
25 //**********************************************************************************************************************
26 SubSampleCommand::SubSampleCommand(){
29 //initialize outputTypes
30 vector<string> tempOutNames;
31 outputTypes["shared"] = tempOutNames;
32 outputTypes["list"] = tempOutNames;
33 outputTypes["rabund"] = tempOutNames;
34 outputTypes["sabund"] = tempOutNames;
35 outputTypes["fasta"] = tempOutNames;
36 outputTypes["name"] = tempOutNames;
37 outputTypes["group"] = tempOutNames;
40 m->errorOut(e, "SubSampleCommand", "GetRelAbundCommand");
44 //**********************************************************************************************************************
45 vector<string> SubSampleCommand::getRequiredParameters(){
47 string Array[] = {"fasta","list","shared","rabund", "sabund","or"};
48 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
52 m->errorOut(e, "SubSampleCommand", "getRequiredParameters");
56 //**********************************************************************************************************************
57 vector<string> SubSampleCommand::getRequiredFiles(){
59 vector<string> myArray;
63 m->errorOut(e, "SubSampleCommand", "getRequiredFiles");
67 //**********************************************************************************************************************
68 SubSampleCommand::SubSampleCommand(string option) {
70 globaldata = GlobalData::getInstance();
75 //allow user to run help
76 if(option == "help") { help(); abort = true; }
79 //valid paramters for this command
80 string Array[] = {"fasta", "group", "list","shared","rabund", "sabund","name","size","groups","label","outputdir","inputdir"};
81 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
83 OptionParser parser(option);
84 map<string,string> parameters = parser.getParameters();
86 ValidParameters validParameter;
88 //check to make sure all parameters are valid for command
89 map<string,string>::iterator it;
90 for (it = parameters.begin(); it != parameters.end(); it++) {
91 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
94 //initialize outputTypes
95 vector<string> tempOutNames;
96 outputTypes["shared"] = tempOutNames;
97 outputTypes["list"] = tempOutNames;
98 outputTypes["rabund"] = tempOutNames;
99 outputTypes["sabund"] = tempOutNames;
100 outputTypes["fasta"] = tempOutNames;
101 outputTypes["name"] = tempOutNames;
102 outputTypes["group"] = tempOutNames;
104 //if the user changes the output directory command factory will send this info to us in the output parameter
105 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
107 //if the user changes the input directory command factory will send this info to us in the output parameter
108 string inputDir = validParameter.validFile(parameters, "inputdir", false);
109 if (inputDir == "not found"){ inputDir = ""; }
112 it = parameters.find("list");
113 //user has given a template file
114 if(it != parameters.end()){
115 path = m->hasPath(it->second);
116 //if the user has not given a path then, add inputdir. else leave path alone.
117 if (path == "") { parameters["list"] = inputDir + it->second; }
120 it = parameters.find("fasta");
121 //user has given a template file
122 if(it != parameters.end()){
123 path = m->hasPath(it->second);
124 //if the user has not given a path then, add inputdir. else leave path alone.
125 if (path == "") { parameters["fasta"] = inputDir + it->second; }
128 it = parameters.find("shared");
129 //user has given a template file
130 if(it != parameters.end()){
131 path = m->hasPath(it->second);
132 //if the user has not given a path then, add inputdir. else leave path alone.
133 if (path == "") { parameters["shared"] = inputDir + it->second; }
136 it = parameters.find("group");
137 //user has given a template file
138 if(it != parameters.end()){
139 path = m->hasPath(it->second);
140 //if the user has not given a path then, add inputdir. else leave path alone.
141 if (path == "") { parameters["group"] = inputDir + it->second; }
144 it = parameters.find("sabund");
145 //user has given a template file
146 if(it != parameters.end()){
147 path = m->hasPath(it->second);
148 //if the user has not given a path then, add inputdir. else leave path alone.
149 if (path == "") { parameters["sabund"] = inputDir + it->second; }
152 it = parameters.find("rabund");
153 //user has given a template file
154 if(it != parameters.end()){
155 path = m->hasPath(it->second);
156 //if the user has not given a path then, add inputdir. else leave path alone.
157 if (path == "") { parameters["rabund"] = inputDir + it->second; }
160 it = parameters.find("name");
161 //user has given a template file
162 if(it != parameters.end()){
163 path = m->hasPath(it->second);
164 //if the user has not given a path then, add inputdir. else leave path alone.
165 if (path == "") { parameters["name"] = inputDir + it->second; }
169 //check for required parameters
170 listfile = validParameter.validFile(parameters, "list", true);
171 if (listfile == "not open") { listfile = ""; abort = true; }
172 else if (listfile == "not found") { listfile = ""; }
174 sabundfile = validParameter.validFile(parameters, "sabund", true);
175 if (sabundfile == "not open") { sabundfile = ""; abort = true; }
176 else if (sabundfile == "not found") { sabundfile = ""; }
178 rabundfile = validParameter.validFile(parameters, "rabund", true);
179 if (rabundfile == "not open") { rabundfile = ""; abort = true; }
180 else if (rabundfile == "not found") { rabundfile = ""; }
182 fastafile = validParameter.validFile(parameters, "fasta", true);
183 if (fastafile == "not open") { fastafile = ""; abort = true; }
184 else if (fastafile == "not found") { fastafile = ""; }
186 sharedfile = validParameter.validFile(parameters, "shared", true);
187 if (sharedfile == "not open") { sharedfile = ""; abort = true; }
188 else if (sharedfile == "not found") { sharedfile = ""; }
190 namefile = validParameter.validFile(parameters, "name", true);
191 if (namefile == "not open") { namefile = ""; abort = true; }
192 else if (namefile == "not found") { namefile = ""; }
194 groupfile = validParameter.validFile(parameters, "group", true);
195 if (groupfile == "not open") { groupfile = ""; abort = true; }
196 else if (groupfile == "not found") { groupfile = ""; }
199 //check for optional parameter and set defaults
200 // ...at some point should added some additional type checking...
201 label = validParameter.validFile(parameters, "label", false);
202 if (label == "not found") { label = ""; }
204 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
205 else { allLines = 1; }
208 groups = validParameter.validFile(parameters, "groups", false);
209 if (groups == "not found") { groups = ""; pickedGroups = false; }
212 m->splitAtDash(groups, Groups);
213 globaldata->Groups = Groups;
216 string temp = validParameter.validFile(parameters, "size", false); if (temp == "not found"){ temp = "0"; }
219 if ((namefile != "") && (fastafile == "")) { m->mothurOut("You may only use a namefile with a fastafile."); m->mothurOutEndLine(); abort = true; }
221 if ((fastafile == "") && (listfile == "") && (sabundfile == "") && (rabundfile == "") && (sharedfile == "")) {
222 m->mothurOut("You must provide a fasta, list, sabund, rabund or shared file as an input file."); m->mothurOutEndLine(); abort = true; }
224 if (pickedGroups && ((groupfile == "") && (sharedfile == ""))) {
225 m->mothurOut("You cannot pick groups without a valid group file or shared file."); m->mothurOutEndLine(); abort = true; }
227 if ((groupfile != "") && ((fastafile == "") && (listfile == ""))) {
228 m->mothurOut("Group file only valid with listfile or fastafile."); m->mothurOutEndLine(); abort = true; }
230 if ((groupfile != "") && ((fastafile != "") && (listfile != ""))) {
231 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; }
236 catch(exception& e) {
237 m->errorOut(e, "SubSampleCommand", "SubSampleCommand");
242 //**********************************************************************************************************************
244 void SubSampleCommand::help(){
246 m->mothurOut("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");
247 m->mothurOut("The sub.sample command parameters are fasta, name, list, group, rabund, sabund, shared, groups, size and label. You must provide a fasta, list, sabund, rabund or shared file as an input file.\n");
248 m->mothurOut("The namefile is only used with the fasta file, not with the listfile, because the list file should contain all sequences.\n");
249 m->mothurOut("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");
250 m->mothurOut("The label parameter allows you to select what distance levels you would like, and are also separated by dashes.\n");
251 m->mothurOut("The size parameter allows you indicate the size of your subsample.\n");
252 m->mothurOut("The size parameter is not set: with shared file size=number of seqs in smallest sample, with all other files, 10% of number of seqs.\n");
253 m->mothurOut("The sub.sample command should be in the following format: sub.sample(list=yourListFile, group=yourGroupFile, groups=yourGroups, label=yourLabels).\n");
254 m->mothurOut("Example sub.sample(list=abrecovery.fn.list, group=abrecovery.groups, groups=B-C, size=20).\n");
255 m->mothurOut("The default value for groups is all the groups in your groupfile, and all labels in your inputfile will be used.\n");
256 m->mothurOut("The sub.sample command outputs a .subsample file.\n");
257 m->mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
260 catch(exception& e) {
261 m->errorOut(e, "SubSampleCommand", "help");
266 //**********************************************************************************************************************
268 SubSampleCommand::~SubSampleCommand(){}
270 //**********************************************************************************************************************
272 int SubSampleCommand::execute(){
275 if (abort == true) { return 0; }
277 if (sharedfile != "") { getSubSampleShared(); }
278 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); return 0; } }
280 if (listfile != "") { getSubSampleList(); }
281 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); return 0; } }
283 if (rabundfile != "") { getSubSampleRabund(); }
284 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); return 0; } }
286 if (sabundfile != "") { getSubSampleSabund(); }
287 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); return 0; } }
289 if (fastafile != "") { getSubSampleFasta(); }
290 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); return 0; } }
293 m->mothurOutEndLine();
294 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
295 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
296 m->mothurOutEndLine();
300 catch(exception& e) {
301 m->errorOut(e, "SubSampleCommand", "execute");
305 //**********************************************************************************************************************
306 int SubSampleCommand::getSubSampleFasta() {
309 if (namefile != "") { readNames(); } //fills names with all names in namefile.
310 else { getNames(); }//no name file, so get list of names to pick from
313 if (groupfile != "") {
315 groupMap = new GroupMap(groupfile);
318 //takes care of user setting groupNames that are invalid or setting groups=all
319 SharedUtil* util = new SharedUtil();
320 util->setGroups(Groups, groupMap->namesOfGroups);
324 if (names.size() != groupMap->getNumSeqs()) {
325 m->mothurOut("[ERROR]: your fasta file contains " + toString(names.size()) + " sequences, and your groupfile contains " + toString(groupMap->getNumSeqs()) + ", please correct.");
326 m->mothurOutEndLine();
332 if (m->control_pressed) { return 0; }
334 string thisOutputDir = outputDir;
335 if (outputDir == "") { thisOutputDir += m->hasPath(fastafile); }
336 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(fastafile)) + "subsample" + m->getExtension(fastafile);
339 m->openOutputFile(outputFileName, out);
340 outputTypes["fasta"].push_back(outputFileName); outputNames.push_back(outputFileName);
342 //make sure that if your picked groups size is not too big
346 for(int i = 0; i < Groups.size(); i++) {
347 total += groupMap->getNumSeqs(Groups[i]);
350 if (size == 0) { //user has not set size, set size = 10% samples size
351 size = int (total * 0.10);
356 m->mothurOut("Your size is too large for the number of groups you selected. Adjusting to " + toString(int (total * 0.10)) + "."); m->mothurOutEndLine();
358 size = int (total * 0.10);
361 m->mothurOut("Sampling " + toString(size) + " from " + toString(total) + "."); m->mothurOutEndLine();
364 if (size == 0) { //user has not set size, set size = 10% samples size
365 size = int (names.size() * 0.10);
368 int thisSize = names.size();
369 if (size > thisSize) { m->mothurOut("Your fasta file only contains " + toString(thisSize) + " sequences. Setting size to " + toString(thisSize) + "."); m->mothurOutEndLine();
373 random_shuffle(names.begin(), names.end());
375 if (!pickedGroups) { m->mothurOut("Sampling " + toString(size) + " from " + toString(thisSize) + "."); m->mothurOutEndLine(); }
377 //randomly select a subset of those names to include in the subsample
378 set<string> subset; //dont want repeat sequence names added
379 for (int j = 0; j < size; j++) {
381 if (m->control_pressed) { return 0; }
383 //get random sequence to add, making sure we have not already added it
387 myrand = (int)((float)(rand()) / (RAND_MAX / (thisSize-1) + 1));
389 if (subset.count(names[myrand]) == 0) {
391 if (groupfile != "") { //if there is a groupfile given fill in group info
392 string group = groupMap->getGroup(names[myrand]);
393 if (group == "not found") { m->mothurOut("[ERROR]: " + names[myrand] + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
395 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
396 if (m->inUsersGroups(group, Groups)) {
397 subset.insert(names[myrand]); break;
400 subset.insert(names[myrand]); break;
402 }else{ //save everyone, group
403 subset.insert(names[myrand]); break;
409 //read through fasta file outputting only the names on the subsample list
411 m->openInputFile(fastafile, in);
415 map<string, vector<string> >::iterator itNameMap;
419 if (m->control_pressed) { in.close(); out.close(); return 0; }
421 Sequence currSeq(in);
422 thisname = currSeq.getName();
424 if (thisname != "") {
426 //does the subset contain a sequence that this sequence represents
427 itNameMap = nameMap.find(thisname);
428 if (itNameMap != nameMap.end()) {
429 vector<string> nameRepresents = itNameMap->second;
431 for (int i = 0; i < nameRepresents.size(); i++){
432 if (subset.count(nameRepresents[i]) != 0) {
433 out << ">" << nameRepresents[i] << endl << currSeq.getAligned() << endl;
438 m->mothurOut("[ERROR]: " + thisname + " is not in your namefile, please correct."); m->mothurOutEndLine();
446 if (count != subset.size()) {
447 m->mothurOut("[ERROR]: The subset selected contained " + toString(subset.size()) + " sequences, but I only found " + toString(count) + " of those in the fastafile."); m->mothurOutEndLine();
450 //if a groupfile is provided read through the group file only outputting the names on the subsample list
451 if (groupfile != "") {
453 string groupOutputDir = outputDir;
454 if (outputDir == "") { groupOutputDir += m->hasPath(groupfile); }
455 string groupOutputFileName = groupOutputDir + m->getRootName(m->getSimpleName(groupfile)) + "subsample" + m->getExtension(groupfile);
458 m->openOutputFile(groupOutputFileName, outGroup);
459 outputTypes["group"].push_back(groupOutputFileName); outputNames.push_back(groupOutputFileName);
462 m->openInputFile(groupfile, inGroup);
465 while(!inGroup.eof()){
467 if (m->control_pressed) { inGroup.close(); outGroup.close(); return 0; }
469 inGroup >> name; m->gobble(inGroup); //read from first column
470 inGroup >> group; //read from second column
472 //if this name is in the accnos file
473 if (subset.count(name) != 0) {
474 outGroup << name << '\t' << group << endl;
484 if (subset.size() != 0) {
485 m->mothurOut("Your groupfile does not match your fasta file."); m->mothurOutEndLine();
486 for (set<string>::iterator it = subset.begin(); it != subset.end(); it++) {
487 m->mothurOut("[ERROR]: " + *it + " is missing from your groupfile."); m->mothurOutEndLine();
495 catch(exception& e) {
496 m->errorOut(e, "SubSampleCommand", "getSubSampleFasta");
500 //**********************************************************************************************************************
501 int SubSampleCommand::getNames() {
505 m->openInputFile(fastafile, in);
510 if (m->control_pressed) { in.close(); return 0; }
512 Sequence currSeq(in);
513 thisname = currSeq.getName();
515 if (thisname != "") {
516 vector<string> temp; temp.push_back(thisname);
517 nameMap[thisname] = temp;
518 names.push_back(thisname);
525 catch(exception& e) {
526 m->errorOut(e, "SubSampleCommand", "getNames");
530 //**********************************************************************************************************************
531 int SubSampleCommand::readNames() {
535 m->openInputFile(namefile, in);
537 string thisname, repnames;
538 map<string, vector<string> >::iterator it;
542 if (m->control_pressed) { in.close(); return 0; }
544 in >> thisname; m->gobble(in); //read from first column
545 in >> repnames; //read from second column
547 it = nameMap.find(thisname);
548 if (it == nameMap.end()) {
550 vector<string> splitRepNames;
551 m->splitAtComma(repnames, splitRepNames);
553 nameMap[thisname] = splitRepNames;
554 for (int i = 0; i < splitRepNames.size(); i++) { names.push_back(splitRepNames[i]); }
556 }else{ m->mothurOut(thisname + " is already in namesfile. I will use first definition."); m->mothurOutEndLine(); }
563 catch(exception& e) {
564 m->errorOut(e, "SubSampleCommand", "readNames");
568 //**********************************************************************************************************************
569 int SubSampleCommand::getSubSampleShared() {
572 string thisOutputDir = outputDir;
573 if (outputDir == "") { thisOutputDir += m->hasPath(sharedfile); }
574 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(sharedfile)) + "subsample" + m->getExtension(sharedfile);
577 m->openOutputFile(outputFileName, out);
578 outputTypes["shared"].push_back(outputFileName); outputNames.push_back(outputFileName);
580 InputData* input = new InputData(sharedfile, "sharedfile");
581 vector<SharedRAbundVector*> lookup = input->getSharedRAbundVectors();
582 string lastLabel = lookup[0]->getLabel();
584 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
585 set<string> processedLabels;
586 set<string> userLabels = labels;
588 if (size == 0) { //user has not set size, set size = smallest samples size
589 size = lookup[0]->getNumSeqs();
590 for (int i = 1; i < lookup.size(); i++) {
591 int thisSize = lookup[i]->getNumSeqs();
593 if (thisSize < size) { size = thisSize; }
597 m->mothurOut("Sampling " + toString(size) + " from " + toString(lookup[0]->getNumSeqs()) + "."); m->mothurOutEndLine();
599 //as long as you are not at the end of the file or done wih the lines you want
600 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
601 if (m->control_pressed) { delete input; for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; lookup[i] = NULL; } out.close(); return 0; }
603 if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){
605 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
607 processShared(lookup, out);
609 processedLabels.insert(lookup[0]->getLabel());
610 userLabels.erase(lookup[0]->getLabel());
613 if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
614 string saveLabel = lookup[0]->getLabel();
616 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
618 lookup = input->getSharedRAbundVectors(lastLabel);
619 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
621 processShared(lookup, out);
623 processedLabels.insert(lookup[0]->getLabel());
624 userLabels.erase(lookup[0]->getLabel());
626 //restore real lastlabel to save below
627 lookup[0]->setLabel(saveLabel);
630 lastLabel = lookup[0]->getLabel();
631 //prevent memory leak
632 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; lookup[i] = NULL; }
634 //get next line to process
635 lookup = input->getSharedRAbundVectors();
639 if (m->control_pressed) { out.close(); return 0; }
641 //output error messages about any remaining user labels
642 set<string>::iterator it;
643 bool needToRun = false;
644 for (it = userLabels.begin(); it != userLabels.end(); it++) {
645 m->mothurOut("Your file does not include the label " + *it);
646 if (processedLabels.count(lastLabel) != 1) {
647 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
650 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
654 //run last label if you need to
655 if (needToRun == true) {
656 for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }
657 lookup = input->getSharedRAbundVectors(lastLabel);
659 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
661 processShared(lookup, out);
663 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
672 catch(exception& e) {
673 m->errorOut(e, "SubSampleCommand", "getSubSampleShared");
677 //**********************************************************************************************************************
678 int SubSampleCommand::processShared(vector<SharedRAbundVector*>& thislookup, ofstream& out) {
681 int numBins = thislookup[0]->getNumBins();
682 for (int i = 0; i < thislookup.size(); i++) {
683 int thisSize = thislookup[i]->getNumSeqs();
685 if (thisSize != size) {
687 string thisgroup = thislookup[i]->getGroup();
689 OrderVector* order = new OrderVector();
690 for(int p=0;p<numBins;p++){
691 for(int j=0;j<thislookup[i]->getAbundance(p);j++){
695 random_shuffle(order->begin(), order->end());
697 SharedRAbundVector* temp = new SharedRAbundVector(numBins);
698 temp->setLabel(thislookup[i]->getLabel());
699 temp->setGroup(thislookup[i]->getGroup());
701 delete thislookup[i];
702 thislookup[i] = temp;
705 for (int j = 0; j < size; j++) {
707 if (m->control_pressed) { delete order; return 0; }
709 //get random number to sample from order between 0 and thisSize-1.
710 int myrand = (int)((float)(rand()) / (RAND_MAX / (thisSize-1) + 1));
712 int bin = order->get(myrand);
714 int abund = thislookup[i]->getAbundance(bin);
715 thislookup[i]->set(bin, (abund+1), thisgroup);
721 //subsampling may have created some otus with no sequences in them
722 eliminateZeroOTUS(thislookup);
724 if (m->control_pressed) { return 0; }
726 for (int i = 0; i < thislookup.size(); i++) {
727 out << thislookup[i]->getLabel() << '\t' << thislookup[i]->getGroup() << '\t';
728 thislookup[i]->print(out);
734 catch(exception& e) {
735 m->errorOut(e, "SubSampleCommand", "processShared");
739 //**********************************************************************************************************************
740 int SubSampleCommand::getSubSampleList() {
743 string thisOutputDir = outputDir;
744 if (outputDir == "") { thisOutputDir += m->hasPath(listfile); }
745 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(listfile)) + "subsample" + m->getExtension(listfile);
748 m->openOutputFile(outputFileName, out);
749 outputTypes["list"].push_back(outputFileName); outputNames.push_back(outputFileName);
751 InputData* input = new InputData(listfile, "list");
752 ListVector* list = input->getListVector();
753 string lastLabel = list->getLabel();
755 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
756 set<string> processedLabels;
757 set<string> userLabels = labels;
761 if (groupfile != "") {
763 groupMap = new GroupMap(groupfile);
766 //takes care of user setting groupNames that are invalid or setting groups=all
767 SharedUtil* util = new SharedUtil();
768 util->setGroups(Groups, groupMap->namesOfGroups);
772 string groupOutputDir = outputDir;
773 if (outputDir == "") { groupOutputDir += m->hasPath(groupfile); }
774 string groupOutputFileName = groupOutputDir + m->getRootName(m->getSimpleName(groupfile)) + "subsample" + m->getExtension(groupfile);
776 m->openOutputFile(groupOutputFileName, outGroup);
777 outputTypes["group"].push_back(groupOutputFileName); outputNames.push_back(groupOutputFileName);
780 if (list->getNumSeqs() != groupMap->getNumSeqs()) {
781 m->mothurOut("[ERROR]: your list file contains " + toString(list->getNumSeqs()) + " sequences, and your groupfile contains " + toString(groupMap->getNumSeqs()) + ", please correct.");
782 m->mothurOutEndLine();
792 //make sure that if your picked groups size is not too big
795 for(int i = 0; i < Groups.size(); i++) {
796 total += groupMap->getNumSeqs(Groups[i]);
799 if (size == 0) { //user has not set size, set size = 10% samples size
800 size = int (total * 0.10);
804 m->mothurOut("Your size is too large for the number of groups you selected. Adjusting to " + toString(int (total * 0.10)) + "."); m->mothurOutEndLine();
805 size = int (total * 0.10);
808 m->mothurOut("Sampling " + toString(size) + " from " + toString(total) + "."); m->mothurOutEndLine();
811 if (size == 0) { //user has not set size, set size = 10% samples size
812 size = int (list->getNumSeqs() * 0.10);
815 int thisSize = list->getNumSeqs();
816 if (size > thisSize) { m->mothurOut("Your list file only contains " + toString(thisSize) + " sequences. Setting size to " + toString(thisSize) + "."); m->mothurOutEndLine();
820 m->mothurOut("Sampling " + toString(size) + " from " + toString(list->getNumSeqs()) + "."); m->mothurOutEndLine();
824 for (int i = 0; i < list->getNumBins(); i++) {
825 string binnames = list->get(i);
828 string individual = "";
829 int length = binnames.length();
830 for(int j=0;j<length;j++){
831 if(binnames[j] == ','){
833 if (groupfile != "") { //if there is a groupfile given fill in group info
834 string group = groupMap->getGroup(individual);
835 if (group == "not found") { m->mothurOut("[ERROR]: " + individual + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
837 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
838 if (m->inUsersGroups(group, Groups)) {
839 names.push_back(individual);
842 names.push_back(individual);
844 }else{ //save everyone, group
845 names.push_back(individual);
850 individual += binnames[j];
854 if (groupfile != "") { //if there is a groupfile given fill in group info
855 string group = groupMap->getGroup(individual);
856 if (group == "not found") { m->mothurOut("[ERROR]: " + individual + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
858 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
859 if (m->inUsersGroups(group, Groups)) {
860 names.push_back(individual);
863 names.push_back(individual);
865 }else{ //save everyone, group
866 names.push_back(individual);
870 random_shuffle(names.begin(), names.end());
872 //randomly select a subset of those names to include in the subsample
873 set<string> subset; //dont want repeat sequence names added
874 for (int j = 0; j < size; j++) {
876 if (m->control_pressed) { break; }
878 //get random sequence to add, making sure we have not already added it
882 myrand = (int)((float)(rand()) / (RAND_MAX / (names.size()-1) + 1));
884 if (subset.count(names[myrand]) == 0) { subset.insert(names[myrand]); break; }
888 if (groupfile != "") {
889 //write out new groupfile
890 for (set<string>::iterator it = subset.begin(); it != subset.end(); it++) {
891 string group = groupMap->getGroup(*it);
892 if (group == "not found") { group = "NOTFOUND"; }
894 outGroup << *it << '\t' << group << endl;
896 outGroup.close(); delete groupMap;
900 //as long as you are not at the end of the file or done wih the lines you want
901 while((list != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
903 if (m->control_pressed) { delete list; delete input; out.close(); return 0; }
905 if(allLines == 1 || labels.count(list->getLabel()) == 1){
907 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
909 processList(list, out, subset);
911 processedLabels.insert(list->getLabel());
912 userLabels.erase(list->getLabel());
915 if ((m->anyLabelsToProcess(list->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
916 string saveLabel = list->getLabel();
920 list = input->getListVector(lastLabel);
921 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
923 processList(list, out, subset);
925 processedLabels.insert(list->getLabel());
926 userLabels.erase(list->getLabel());
928 //restore real lastlabel to save below
929 list->setLabel(saveLabel);
932 lastLabel = list->getLabel();
934 delete list; list = NULL;
936 //get next line to process
937 list = input->getListVector();
941 if (m->control_pressed) { if (list != NULL) { delete list; } delete input; out.close(); return 0; }
943 //output error messages about any remaining user labels
944 set<string>::iterator it;
945 bool needToRun = false;
946 for (it = userLabels.begin(); it != userLabels.end(); it++) {
947 m->mothurOut("Your file does not include the label " + *it);
948 if (processedLabels.count(lastLabel) != 1) {
949 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
952 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
956 //run last label if you need to
957 if (needToRun == true) {
958 if (list != NULL) { delete list; }
960 list = input->getListVector(lastLabel);
962 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
964 processList(list, out, subset);
966 delete list; list = NULL;
970 if (list != NULL) { delete list; }
976 catch(exception& e) {
977 m->errorOut(e, "SubSampleCommand", "getSubSampleList");
981 //**********************************************************************************************************************
982 int SubSampleCommand::processList(ListVector*& list, ofstream& out, set<string>& subset) {
985 int numBins = list->getNumBins();
987 ListVector* temp = new ListVector();
988 temp->setLabel(list->getLabel());
990 for (int i = 0; i < numBins; i++) {
992 if (m->control_pressed) { break; }
994 string binnames = list->get(i);
997 string individual = "";
998 string newNames = "";
999 int length = binnames.length();
1000 for(int j=0;j<length;j++){
1001 if(binnames[j] == ','){
1002 if (subset.count(individual) != 0) { newNames += individual + ","; }
1005 individual += binnames[j];
1008 if (subset.count(individual) != 0) { newNames += individual; }
1011 //if there are names in this bin add to new list
1012 if (newNames != "") {
1013 newNames = newNames.substr(0, newNames.length()-1); //rip off extra comma
1014 temp->push_back(newNames);
1021 if (m->control_pressed) { return 0; }
1028 catch(exception& e) {
1029 m->errorOut(e, "SubSampleCommand", "processList");
1033 //**********************************************************************************************************************
1034 int SubSampleCommand::getSubSampleRabund() {
1037 string thisOutputDir = outputDir;
1038 if (outputDir == "") { thisOutputDir += m->hasPath(rabundfile); }
1039 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(rabundfile)) + "subsample" + m->getExtension(rabundfile);
1042 m->openOutputFile(outputFileName, out);
1043 outputTypes["rabund"].push_back(outputFileName); outputNames.push_back(outputFileName);
1045 InputData* input = new InputData(rabundfile, "rabund");
1046 RAbundVector* rabund = input->getRAbundVector();
1047 string lastLabel = rabund->getLabel();
1049 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1050 set<string> processedLabels;
1051 set<string> userLabels = labels;
1053 if (size == 0) { //user has not set size, set size = 10%
1054 size = int((rabund->getNumSeqs()) * 0.10);
1057 m->mothurOut("Sampling " + toString(size) + " from " + toString(rabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1059 //as long as you are not at the end of the file or done wih the lines you want
1060 while((rabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1061 if (m->control_pressed) { delete input; delete rabund; out.close(); return 0; }
1063 if(allLines == 1 || labels.count(rabund->getLabel()) == 1){
1065 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1067 processRabund(rabund, out);
1069 processedLabels.insert(rabund->getLabel());
1070 userLabels.erase(rabund->getLabel());
1073 if ((m->anyLabelsToProcess(rabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1074 string saveLabel = rabund->getLabel();
1078 rabund = input->getRAbundVector(lastLabel);
1079 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1081 processRabund(rabund, out);
1083 processedLabels.insert(rabund->getLabel());
1084 userLabels.erase(rabund->getLabel());
1086 //restore real lastlabel to save below
1087 rabund->setLabel(saveLabel);
1090 lastLabel = rabund->getLabel();
1092 //prevent memory leak
1093 delete rabund; rabund = NULL;
1095 //get next line to process
1096 rabund = input->getRAbundVector();
1100 if (m->control_pressed) { out.close(); return 0; }
1102 //output error messages about any remaining user labels
1103 set<string>::iterator it;
1104 bool needToRun = false;
1105 for (it = userLabels.begin(); it != userLabels.end(); it++) {
1106 m->mothurOut("Your file does not include the label " + *it);
1107 if (processedLabels.count(lastLabel) != 1) {
1108 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1111 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1115 //run last label if you need to
1116 if (needToRun == true) {
1117 if (rabund != NULL) { delete rabund; }
1119 rabund = input->getRAbundVector(lastLabel);
1121 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1123 processRabund(rabund, out);
1134 catch(exception& e) {
1135 m->errorOut(e, "SubSampleCommand", "getSubSampleRabund");
1139 //**********************************************************************************************************************
1140 int SubSampleCommand::processRabund(RAbundVector*& rabund, ofstream& out) {
1143 int numBins = rabund->getNumBins();
1144 int thisSize = rabund->getNumSeqs();
1146 if (thisSize != size) {
1148 OrderVector* order = new OrderVector();
1149 for(int p=0;p<numBins;p++){
1150 for(int j=0;j<rabund->get(p);j++){
1151 order->push_back(p);
1154 random_shuffle(order->begin(), order->end());
1156 RAbundVector* temp = new RAbundVector(numBins);
1157 temp->setLabel(rabund->getLabel());
1162 for (int j = 0; j < size; j++) {
1164 if (m->control_pressed) { delete order; return 0; }
1166 //get random number to sample from order between 0 and thisSize-1.
1167 int myrand = (int)((float)(rand()) / (RAND_MAX / (thisSize-1) + 1));
1169 int bin = order->get(myrand);
1171 int abund = rabund->get(bin);
1172 rabund->set(bin, (abund+1));
1178 if (m->control_pressed) { return 0; }
1185 catch(exception& e) {
1186 m->errorOut(e, "SubSampleCommand", "processRabund");
1190 //**********************************************************************************************************************
1191 int SubSampleCommand::getSubSampleSabund() {
1194 string thisOutputDir = outputDir;
1195 if (outputDir == "") { thisOutputDir += m->hasPath(sabundfile); }
1196 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(sabundfile)) + "subsample" + m->getExtension(sabundfile);
1199 m->openOutputFile(outputFileName, out);
1200 outputTypes["sabund"].push_back(outputFileName); outputNames.push_back(outputFileName);
1202 InputData* input = new InputData(sabundfile, "sabund");
1203 SAbundVector* sabund = input->getSAbundVector();
1204 string lastLabel = sabund->getLabel();
1206 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1207 set<string> processedLabels;
1208 set<string> userLabels = labels;
1210 if (size == 0) { //user has not set size, set size = 10%
1211 size = int((sabund->getNumSeqs()) * 0.10);
1214 m->mothurOut("Sampling " + toString(size) + " from " + toString(sabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1216 //as long as you are not at the end of the file or done wih the lines you want
1217 while((sabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1218 if (m->control_pressed) { delete input; delete sabund; out.close(); return 0; }
1220 if(allLines == 1 || labels.count(sabund->getLabel()) == 1){
1222 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1224 processSabund(sabund, out);
1226 processedLabels.insert(sabund->getLabel());
1227 userLabels.erase(sabund->getLabel());
1230 if ((m->anyLabelsToProcess(sabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1231 string saveLabel = sabund->getLabel();
1235 sabund = input->getSAbundVector(lastLabel);
1236 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1238 processSabund(sabund, out);
1240 processedLabels.insert(sabund->getLabel());
1241 userLabels.erase(sabund->getLabel());
1243 //restore real lastlabel to save below
1244 sabund->setLabel(saveLabel);
1247 lastLabel = sabund->getLabel();
1249 //prevent memory leak
1250 delete sabund; sabund = NULL;
1252 //get next line to process
1253 sabund = input->getSAbundVector();
1257 if (m->control_pressed) { out.close(); return 0; }
1259 //output error messages about any remaining user labels
1260 set<string>::iterator it;
1261 bool needToRun = false;
1262 for (it = userLabels.begin(); it != userLabels.end(); it++) {
1263 m->mothurOut("Your file does not include the label " + *it);
1264 if (processedLabels.count(lastLabel) != 1) {
1265 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1268 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1272 //run last label if you need to
1273 if (needToRun == true) {
1274 if (sabund != NULL) { delete sabund; }
1276 sabund = input->getSAbundVector(lastLabel);
1278 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1280 processSabund(sabund, out);
1291 catch(exception& e) {
1292 m->errorOut(e, "SubSampleCommand", "getSubSampleSabund");
1296 //**********************************************************************************************************************
1297 int SubSampleCommand::processSabund(SAbundVector*& sabund, ofstream& out) {
1300 RAbundVector* rabund = new RAbundVector();
1301 *rabund = sabund->getRAbundVector();
1303 int numBins = rabund->getNumBins();
1304 int thisSize = rabund->getNumSeqs();
1306 if (thisSize != size) {
1308 OrderVector* order = new OrderVector();
1309 for(int p=0;p<numBins;p++){
1310 for(int j=0;j<rabund->get(p);j++){
1311 order->push_back(p);
1314 random_shuffle(order->begin(), order->end());
1316 RAbundVector* temp = new RAbundVector(numBins);
1317 temp->setLabel(rabund->getLabel());
1322 for (int j = 0; j < size; j++) {
1324 if (m->control_pressed) { delete order; return 0; }
1326 //get random number to sample from order between 0 and thisSize-1.
1327 int myrand = (int)((float)(rand()) / (RAND_MAX / (thisSize-1) + 1));
1329 int bin = order->get(myrand);
1331 int abund = rabund->get(bin);
1332 rabund->set(bin, (abund+1));
1338 if (m->control_pressed) { return 0; }
1341 sabund = new SAbundVector();
1342 *sabund = rabund->getSAbundVector();
1350 catch(exception& e) {
1351 m->errorOut(e, "SubSampleCommand", "processSabund");
1355 //**********************************************************************************************************************
1356 int SubSampleCommand::eliminateZeroOTUS(vector<SharedRAbundVector*>& thislookup) {
1359 vector<SharedRAbundVector*> newLookup;
1360 for (int i = 0; i < thislookup.size(); i++) {
1361 SharedRAbundVector* temp = new SharedRAbundVector();
1362 temp->setLabel(thislookup[i]->getLabel());
1363 temp->setGroup(thislookup[i]->getGroup());
1364 newLookup.push_back(temp);
1368 for (int i = 0; i < thislookup[0]->getNumBins(); i++) {
1369 if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) { delete newLookup[j]; } return 0; }
1371 //look at each sharedRabund and make sure they are not all zero
1372 bool allZero = true;
1373 for (int j = 0; j < thislookup.size(); j++) {
1374 if (thislookup[j]->getAbundance(i) != 0) { allZero = false; break; }
1377 //if they are not all zero add this bin
1379 for (int j = 0; j < thislookup.size(); j++) {
1380 newLookup[j]->push_back(thislookup[j]->getAbundance(i), thislookup[j]->getGroup());
1385 for (int j = 0; j < thislookup.size(); j++) { delete thislookup[j]; }
1388 thislookup = newLookup;
1393 catch(exception& e) {
1394 m->errorOut(e, "SubSampleCommand", "eliminateZeroOTUS");
1399 //**********************************************************************************************************************