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);
527 catch(exception& e) {
528 m->errorOut(e, "SubSampleCommand", "getNames");
532 //**********************************************************************************************************************
533 int SubSampleCommand::readNames() {
537 m->openInputFile(namefile, in);
539 string thisname, repnames;
540 map<string, vector<string> >::iterator it;
544 if (m->control_pressed) { in.close(); return 0; }
546 in >> thisname; m->gobble(in); //read from first column
547 in >> repnames; //read from second column
549 it = nameMap.find(thisname);
550 if (it == nameMap.end()) {
552 vector<string> splitRepNames;
553 m->splitAtComma(repnames, splitRepNames);
555 nameMap[thisname] = splitRepNames;
556 for (int i = 0; i < splitRepNames.size(); i++) { names.push_back(splitRepNames[i]); }
558 }else{ m->mothurOut(thisname + " is already in namesfile. I will use first definition."); m->mothurOutEndLine(); }
567 catch(exception& e) {
568 m->errorOut(e, "SubSampleCommand", "readNames");
572 //**********************************************************************************************************************
573 int SubSampleCommand::getSubSampleShared() {
576 string thisOutputDir = outputDir;
577 if (outputDir == "") { thisOutputDir += m->hasPath(sharedfile); }
578 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(sharedfile)) + "subsample" + m->getExtension(sharedfile);
581 m->openOutputFile(outputFileName, out);
582 outputTypes["shared"].push_back(outputFileName); outputNames.push_back(outputFileName);
584 InputData* input = new InputData(sharedfile, "sharedfile");
585 vector<SharedRAbundVector*> lookup = input->getSharedRAbundVectors();
586 string lastLabel = lookup[0]->getLabel();
588 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
589 set<string> processedLabels;
590 set<string> userLabels = labels;
592 if (size == 0) { //user has not set size, set size = smallest samples size
593 size = lookup[0]->getNumSeqs();
594 for (int i = 1; i < lookup.size(); i++) {
595 int thisSize = lookup[i]->getNumSeqs();
597 if (thisSize < size) { size = thisSize; }
601 m->mothurOut("Sampling " + toString(size) + " from " + toString(lookup[0]->getNumSeqs()) + "."); m->mothurOutEndLine();
603 //as long as you are not at the end of the file or done wih the lines you want
604 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
605 if (m->control_pressed) { delete input; for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; lookup[i] = NULL; } out.close(); return 0; }
607 if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){
609 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
611 processShared(lookup, out);
613 processedLabels.insert(lookup[0]->getLabel());
614 userLabels.erase(lookup[0]->getLabel());
617 if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
618 string saveLabel = lookup[0]->getLabel();
620 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
622 lookup = input->getSharedRAbundVectors(lastLabel);
623 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
625 processShared(lookup, out);
627 processedLabels.insert(lookup[0]->getLabel());
628 userLabels.erase(lookup[0]->getLabel());
630 //restore real lastlabel to save below
631 lookup[0]->setLabel(saveLabel);
634 lastLabel = lookup[0]->getLabel();
635 //prevent memory leak
636 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; lookup[i] = NULL; }
638 //get next line to process
639 lookup = input->getSharedRAbundVectors();
643 if (m->control_pressed) { out.close(); return 0; }
645 //output error messages about any remaining user labels
646 set<string>::iterator it;
647 bool needToRun = false;
648 for (it = userLabels.begin(); it != userLabels.end(); it++) {
649 m->mothurOut("Your file does not include the label " + *it);
650 if (processedLabels.count(lastLabel) != 1) {
651 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
654 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
658 //run last label if you need to
659 if (needToRun == true) {
660 for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }
661 lookup = input->getSharedRAbundVectors(lastLabel);
663 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
665 processShared(lookup, out);
667 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
676 catch(exception& e) {
677 m->errorOut(e, "SubSampleCommand", "getSubSampleShared");
681 //**********************************************************************************************************************
682 int SubSampleCommand::processShared(vector<SharedRAbundVector*>& thislookup, ofstream& out) {
685 int numBins = thislookup[0]->getNumBins();
686 for (int i = 0; i < thislookup.size(); i++) {
687 int thisSize = thislookup[i]->getNumSeqs();
689 if (thisSize != size) {
691 string thisgroup = thislookup[i]->getGroup();
693 OrderVector* order = new OrderVector();
694 for(int p=0;p<numBins;p++){
695 for(int j=0;j<thislookup[i]->getAbundance(p);j++){
699 random_shuffle(order->begin(), order->end());
701 SharedRAbundVector* temp = new SharedRAbundVector(numBins);
702 temp->setLabel(thislookup[i]->getLabel());
703 temp->setGroup(thislookup[i]->getGroup());
705 delete thislookup[i];
706 thislookup[i] = temp;
709 for (int j = 0; j < size; j++) {
711 if (m->control_pressed) { delete order; return 0; }
713 //get random number to sample from order between 0 and thisSize-1.
714 int myrand = (int)((float)(rand()) / (RAND_MAX / (thisSize-1) + 1));
716 int bin = order->get(myrand);
718 int abund = thislookup[i]->getAbundance(bin);
719 thislookup[i]->set(bin, (abund+1), thisgroup);
725 //subsampling may have created some otus with no sequences in them
726 eliminateZeroOTUS(thislookup);
728 if (m->control_pressed) { return 0; }
730 for (int i = 0; i < thislookup.size(); i++) {
731 out << thislookup[i]->getLabel() << '\t' << thislookup[i]->getGroup() << '\t';
732 thislookup[i]->print(out);
738 catch(exception& e) {
739 m->errorOut(e, "SubSampleCommand", "processShared");
743 //**********************************************************************************************************************
744 int SubSampleCommand::getSubSampleList() {
747 string thisOutputDir = outputDir;
748 if (outputDir == "") { thisOutputDir += m->hasPath(listfile); }
749 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(listfile)) + "subsample" + m->getExtension(listfile);
752 m->openOutputFile(outputFileName, out);
753 outputTypes["list"].push_back(outputFileName); outputNames.push_back(outputFileName);
755 InputData* input = new InputData(listfile, "list");
756 ListVector* list = input->getListVector();
757 string lastLabel = list->getLabel();
759 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
760 set<string> processedLabels;
761 set<string> userLabels = labels;
765 if (groupfile != "") {
767 groupMap = new GroupMap(groupfile);
770 //takes care of user setting groupNames that are invalid or setting groups=all
771 SharedUtil* util = new SharedUtil();
772 util->setGroups(Groups, groupMap->namesOfGroups);
776 string groupOutputDir = outputDir;
777 if (outputDir == "") { groupOutputDir += m->hasPath(groupfile); }
778 string groupOutputFileName = groupOutputDir + m->getRootName(m->getSimpleName(groupfile)) + "subsample" + m->getExtension(groupfile);
780 m->openOutputFile(groupOutputFileName, outGroup);
781 outputTypes["group"].push_back(groupOutputFileName); outputNames.push_back(groupOutputFileName);
784 if (list->getNumSeqs() != groupMap->getNumSeqs()) {
785 m->mothurOut("[ERROR]: your list file contains " + toString(list->getNumSeqs()) + " sequences, and your groupfile contains " + toString(groupMap->getNumSeqs()) + ", please correct.");
786 m->mothurOutEndLine();
796 //make sure that if your picked groups size is not too big
799 for(int i = 0; i < Groups.size(); i++) {
800 total += groupMap->getNumSeqs(Groups[i]);
803 if (size == 0) { //user has not set size, set size = 10% samples size
804 size = int (total * 0.10);
808 m->mothurOut("Your size is too large for the number of groups you selected. Adjusting to " + toString(int (total * 0.10)) + "."); m->mothurOutEndLine();
809 size = int (total * 0.10);
812 m->mothurOut("Sampling " + toString(size) + " from " + toString(total) + "."); m->mothurOutEndLine();
815 if (size == 0) { //user has not set size, set size = 10% samples size
816 size = int (list->getNumSeqs() * 0.10);
819 int thisSize = list->getNumSeqs();
820 if (size > thisSize) { m->mothurOut("Your list file only contains " + toString(thisSize) + " sequences. Setting size to " + toString(thisSize) + "."); m->mothurOutEndLine();
824 m->mothurOut("Sampling " + toString(size) + " from " + toString(list->getNumSeqs()) + "."); m->mothurOutEndLine();
828 for (int i = 0; i < list->getNumBins(); i++) {
829 string binnames = list->get(i);
832 string individual = "";
833 int length = binnames.length();
834 for(int j=0;j<length;j++){
835 if(binnames[j] == ','){
837 if (groupfile != "") { //if there is a groupfile given fill in group info
838 string group = groupMap->getGroup(individual);
839 if (group == "not found") { m->mothurOut("[ERROR]: " + individual + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
841 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
842 if (m->inUsersGroups(group, Groups)) {
843 names.push_back(individual);
846 names.push_back(individual);
848 }else{ //save everyone, group
849 names.push_back(individual);
854 individual += binnames[j];
858 if (groupfile != "") { //if there is a groupfile given fill in group info
859 string group = groupMap->getGroup(individual);
860 if (group == "not found") { m->mothurOut("[ERROR]: " + individual + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
862 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
863 if (m->inUsersGroups(group, Groups)) {
864 names.push_back(individual);
867 names.push_back(individual);
869 }else{ //save everyone, group
870 names.push_back(individual);
874 random_shuffle(names.begin(), names.end());
876 //randomly select a subset of those names to include in the subsample
877 set<string> subset; //dont want repeat sequence names added
878 for (int j = 0; j < size; j++) {
880 if (m->control_pressed) { break; }
882 //get random sequence to add, making sure we have not already added it
886 myrand = (int)((float)(rand()) / (RAND_MAX / (names.size()-1) + 1));
888 if (subset.count(names[myrand]) == 0) { subset.insert(names[myrand]); break; }
892 if (groupfile != "") {
893 //write out new groupfile
894 for (set<string>::iterator it = subset.begin(); it != subset.end(); it++) {
895 string group = groupMap->getGroup(*it);
896 if (group == "not found") { group = "NOTFOUND"; }
898 outGroup << *it << '\t' << group << endl;
900 outGroup.close(); delete groupMap;
904 //as long as you are not at the end of the file or done wih the lines you want
905 while((list != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
907 if (m->control_pressed) { delete list; delete input; out.close(); return 0; }
909 if(allLines == 1 || labels.count(list->getLabel()) == 1){
911 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
913 processList(list, out, subset);
915 processedLabels.insert(list->getLabel());
916 userLabels.erase(list->getLabel());
919 if ((m->anyLabelsToProcess(list->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
920 string saveLabel = list->getLabel();
924 list = input->getListVector(lastLabel);
925 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
927 processList(list, out, subset);
929 processedLabels.insert(list->getLabel());
930 userLabels.erase(list->getLabel());
932 //restore real lastlabel to save below
933 list->setLabel(saveLabel);
936 lastLabel = list->getLabel();
938 delete list; list = NULL;
940 //get next line to process
941 list = input->getListVector();
945 if (m->control_pressed) { if (list != NULL) { delete list; } delete input; out.close(); return 0; }
947 //output error messages about any remaining user labels
948 set<string>::iterator it;
949 bool needToRun = false;
950 for (it = userLabels.begin(); it != userLabels.end(); it++) {
951 m->mothurOut("Your file does not include the label " + *it);
952 if (processedLabels.count(lastLabel) != 1) {
953 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
956 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
960 //run last label if you need to
961 if (needToRun == true) {
962 if (list != NULL) { delete list; }
964 list = input->getListVector(lastLabel);
966 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
968 processList(list, out, subset);
970 delete list; list = NULL;
974 if (list != NULL) { delete list; }
980 catch(exception& e) {
981 m->errorOut(e, "SubSampleCommand", "getSubSampleList");
985 //**********************************************************************************************************************
986 int SubSampleCommand::processList(ListVector*& list, ofstream& out, set<string>& subset) {
989 int numBins = list->getNumBins();
991 ListVector* temp = new ListVector();
992 temp->setLabel(list->getLabel());
994 for (int i = 0; i < numBins; i++) {
996 if (m->control_pressed) { break; }
998 string binnames = list->get(i);
1001 string individual = "";
1002 string newNames = "";
1003 int length = binnames.length();
1004 for(int j=0;j<length;j++){
1005 if(binnames[j] == ','){
1006 if (subset.count(individual) != 0) { newNames += individual + ","; }
1009 individual += binnames[j];
1012 if (subset.count(individual) != 0) { newNames += individual; }
1015 //if there are names in this bin add to new list
1016 if (newNames != "") {
1017 newNames = newNames.substr(0, newNames.length()-1); //rip off extra comma
1018 temp->push_back(newNames);
1025 if (m->control_pressed) { return 0; }
1032 catch(exception& e) {
1033 m->errorOut(e, "SubSampleCommand", "processList");
1037 //**********************************************************************************************************************
1038 int SubSampleCommand::getSubSampleRabund() {
1041 string thisOutputDir = outputDir;
1042 if (outputDir == "") { thisOutputDir += m->hasPath(rabundfile); }
1043 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(rabundfile)) + "subsample" + m->getExtension(rabundfile);
1046 m->openOutputFile(outputFileName, out);
1047 outputTypes["rabund"].push_back(outputFileName); outputNames.push_back(outputFileName);
1049 InputData* input = new InputData(rabundfile, "rabund");
1050 RAbundVector* rabund = input->getRAbundVector();
1051 string lastLabel = rabund->getLabel();
1053 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1054 set<string> processedLabels;
1055 set<string> userLabels = labels;
1057 if (size == 0) { //user has not set size, set size = 10%
1058 size = int((rabund->getNumSeqs()) * 0.10);
1061 m->mothurOut("Sampling " + toString(size) + " from " + toString(rabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1063 //as long as you are not at the end of the file or done wih the lines you want
1064 while((rabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1065 if (m->control_pressed) { delete input; delete rabund; out.close(); return 0; }
1067 if(allLines == 1 || labels.count(rabund->getLabel()) == 1){
1069 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1071 processRabund(rabund, out);
1073 processedLabels.insert(rabund->getLabel());
1074 userLabels.erase(rabund->getLabel());
1077 if ((m->anyLabelsToProcess(rabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1078 string saveLabel = rabund->getLabel();
1082 rabund = input->getRAbundVector(lastLabel);
1083 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1085 processRabund(rabund, out);
1087 processedLabels.insert(rabund->getLabel());
1088 userLabels.erase(rabund->getLabel());
1090 //restore real lastlabel to save below
1091 rabund->setLabel(saveLabel);
1094 lastLabel = rabund->getLabel();
1096 //prevent memory leak
1097 delete rabund; rabund = NULL;
1099 //get next line to process
1100 rabund = input->getRAbundVector();
1104 if (m->control_pressed) { out.close(); return 0; }
1106 //output error messages about any remaining user labels
1107 set<string>::iterator it;
1108 bool needToRun = false;
1109 for (it = userLabels.begin(); it != userLabels.end(); it++) {
1110 m->mothurOut("Your file does not include the label " + *it);
1111 if (processedLabels.count(lastLabel) != 1) {
1112 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1115 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1119 //run last label if you need to
1120 if (needToRun == true) {
1121 if (rabund != NULL) { delete rabund; }
1123 rabund = input->getRAbundVector(lastLabel);
1125 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1127 processRabund(rabund, out);
1138 catch(exception& e) {
1139 m->errorOut(e, "SubSampleCommand", "getSubSampleRabund");
1143 //**********************************************************************************************************************
1144 int SubSampleCommand::processRabund(RAbundVector*& rabund, ofstream& out) {
1147 int numBins = rabund->getNumBins();
1148 int thisSize = rabund->getNumSeqs();
1150 if (thisSize != size) {
1152 OrderVector* order = new OrderVector();
1153 for(int p=0;p<numBins;p++){
1154 for(int j=0;j<rabund->get(p);j++){
1155 order->push_back(p);
1158 random_shuffle(order->begin(), order->end());
1160 RAbundVector* temp = new RAbundVector(numBins);
1161 temp->setLabel(rabund->getLabel());
1166 for (int j = 0; j < size; j++) {
1168 if (m->control_pressed) { delete order; return 0; }
1170 //get random number to sample from order between 0 and thisSize-1.
1171 int myrand = (int)((float)(rand()) / (RAND_MAX / (thisSize-1) + 1));
1173 int bin = order->get(myrand);
1175 int abund = rabund->get(bin);
1176 rabund->set(bin, (abund+1));
1182 if (m->control_pressed) { return 0; }
1189 catch(exception& e) {
1190 m->errorOut(e, "SubSampleCommand", "processRabund");
1194 //**********************************************************************************************************************
1195 int SubSampleCommand::getSubSampleSabund() {
1198 string thisOutputDir = outputDir;
1199 if (outputDir == "") { thisOutputDir += m->hasPath(sabundfile); }
1200 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(sabundfile)) + "subsample" + m->getExtension(sabundfile);
1203 m->openOutputFile(outputFileName, out);
1204 outputTypes["sabund"].push_back(outputFileName); outputNames.push_back(outputFileName);
1206 InputData* input = new InputData(sabundfile, "sabund");
1207 SAbundVector* sabund = input->getSAbundVector();
1208 string lastLabel = sabund->getLabel();
1210 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1211 set<string> processedLabels;
1212 set<string> userLabels = labels;
1214 if (size == 0) { //user has not set size, set size = 10%
1215 size = int((sabund->getNumSeqs()) * 0.10);
1218 m->mothurOut("Sampling " + toString(size) + " from " + toString(sabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1220 //as long as you are not at the end of the file or done wih the lines you want
1221 while((sabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1222 if (m->control_pressed) { delete input; delete sabund; out.close(); return 0; }
1224 if(allLines == 1 || labels.count(sabund->getLabel()) == 1){
1226 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1228 processSabund(sabund, out);
1230 processedLabels.insert(sabund->getLabel());
1231 userLabels.erase(sabund->getLabel());
1234 if ((m->anyLabelsToProcess(sabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1235 string saveLabel = sabund->getLabel();
1239 sabund = input->getSAbundVector(lastLabel);
1240 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1242 processSabund(sabund, out);
1244 processedLabels.insert(sabund->getLabel());
1245 userLabels.erase(sabund->getLabel());
1247 //restore real lastlabel to save below
1248 sabund->setLabel(saveLabel);
1251 lastLabel = sabund->getLabel();
1253 //prevent memory leak
1254 delete sabund; sabund = NULL;
1256 //get next line to process
1257 sabund = input->getSAbundVector();
1261 if (m->control_pressed) { out.close(); return 0; }
1263 //output error messages about any remaining user labels
1264 set<string>::iterator it;
1265 bool needToRun = false;
1266 for (it = userLabels.begin(); it != userLabels.end(); it++) {
1267 m->mothurOut("Your file does not include the label " + *it);
1268 if (processedLabels.count(lastLabel) != 1) {
1269 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1272 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1276 //run last label if you need to
1277 if (needToRun == true) {
1278 if (sabund != NULL) { delete sabund; }
1280 sabund = input->getSAbundVector(lastLabel);
1282 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1284 processSabund(sabund, out);
1295 catch(exception& e) {
1296 m->errorOut(e, "SubSampleCommand", "getSubSampleSabund");
1300 //**********************************************************************************************************************
1301 int SubSampleCommand::processSabund(SAbundVector*& sabund, ofstream& out) {
1304 RAbundVector* rabund = new RAbundVector();
1305 *rabund = sabund->getRAbundVector();
1307 int numBins = rabund->getNumBins();
1308 int thisSize = rabund->getNumSeqs();
1310 if (thisSize != size) {
1312 OrderVector* order = new OrderVector();
1313 for(int p=0;p<numBins;p++){
1314 for(int j=0;j<rabund->get(p);j++){
1315 order->push_back(p);
1318 random_shuffle(order->begin(), order->end());
1320 RAbundVector* temp = new RAbundVector(numBins);
1321 temp->setLabel(rabund->getLabel());
1326 for (int j = 0; j < size; j++) {
1328 if (m->control_pressed) { delete order; return 0; }
1330 //get random number to sample from order between 0 and thisSize-1.
1331 int myrand = (int)((float)(rand()) / (RAND_MAX / (thisSize-1) + 1));
1333 int bin = order->get(myrand);
1335 int abund = rabund->get(bin);
1336 rabund->set(bin, (abund+1));
1342 if (m->control_pressed) { return 0; }
1345 sabund = new SAbundVector();
1346 *sabund = rabund->getSAbundVector();
1354 catch(exception& e) {
1355 m->errorOut(e, "SubSampleCommand", "processSabund");
1359 //**********************************************************************************************************************
1360 int SubSampleCommand::eliminateZeroOTUS(vector<SharedRAbundVector*>& thislookup) {
1363 vector<SharedRAbundVector*> newLookup;
1364 for (int i = 0; i < thislookup.size(); i++) {
1365 SharedRAbundVector* temp = new SharedRAbundVector();
1366 temp->setLabel(thislookup[i]->getLabel());
1367 temp->setGroup(thislookup[i]->getGroup());
1368 newLookup.push_back(temp);
1372 for (int i = 0; i < thislookup[0]->getNumBins(); i++) {
1373 if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) { delete newLookup[j]; } return 0; }
1375 //look at each sharedRabund and make sure they are not all zero
1376 bool allZero = true;
1377 for (int j = 0; j < thislookup.size(); j++) {
1378 if (thislookup[j]->getAbundance(i) != 0) { allZero = false; break; }
1381 //if they are not all zero add this bin
1383 for (int j = 0; j < thislookup.size(); j++) {
1384 newLookup[j]->push_back(thislookup[j]->getAbundance(i), thislookup[j]->getGroup());
1389 for (int j = 0; j < thislookup.size(); j++) { delete thislookup[j]; }
1392 thislookup = newLookup;
1397 catch(exception& e) {
1398 m->errorOut(e, "SubSampleCommand", "eliminateZeroOTUS");
1403 //**********************************************************************************************************************