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 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");
249 m->mothurOut("The label parameter allows you to select what distance levels you would like, and are also separated by dashes.\n");
250 m->mothurOut("The size parameter allows you indicate the size of your subsample.\n");
251 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");
252 m->mothurOut("The sub.sample command should be in the following format: sub.sample(list=yourListFile, group=yourGroupFile, groups=yourGroups, label=yourLabels).\n");
253 m->mothurOut("Example sub.sample(list=abrecovery.fn.list, group=abrecovery.groups, groups=B-C, size=20).\n");
254 m->mothurOut("The default value for groups is all the groups in your groupfile, and all labels in your inputfile will be used.\n");
255 m->mothurOut("The sub.sample command outputs a .subsample file.\n");
256 m->mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
259 catch(exception& e) {
260 m->errorOut(e, "SubSampleCommand", "help");
265 //**********************************************************************************************************************
267 SubSampleCommand::~SubSampleCommand(){}
269 //**********************************************************************************************************************
271 int SubSampleCommand::execute(){
274 if (abort == true) { return 0; }
276 if (sharedfile != "") { getSubSampleShared(); }
277 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); return 0; } }
279 if (listfile != "") { getSubSampleList(); }
280 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); return 0; } }
282 if (rabundfile != "") { getSubSampleRabund(); }
283 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); return 0; } }
285 if (sabundfile != "") { getSubSampleSabund(); }
286 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); return 0; } }
288 if (fastafile != "") { getSubSampleFasta(); }
289 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); return 0; } }
292 m->mothurOutEndLine();
293 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
294 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
295 m->mothurOutEndLine();
299 catch(exception& e) {
300 m->errorOut(e, "SubSampleCommand", "execute");
304 //**********************************************************************************************************************
305 int SubSampleCommand::getSubSampleFasta() {
308 if (namefile != "") { readNames(); } //fills names with all names in namefile.
309 else { getNames(); }//no name file, so get list of names to pick from
312 if (groupfile != "") {
314 groupMap = new GroupMap(groupfile);
317 //takes care of user setting groupNames that are invalid or setting groups=all
318 SharedUtil* util = new SharedUtil();
319 util->setGroups(Groups, groupMap->namesOfGroups);
323 if (names.size() != groupMap->getNumSeqs()) {
324 m->mothurOut("[ERROR]: your fasta file contains " + toString(names.size()) + " sequences, and your groupfile contains " + toString(groupMap->getNumSeqs()) + ", please correct.");
325 m->mothurOutEndLine();
331 if (m->control_pressed) { return 0; }
333 string thisOutputDir = outputDir;
334 if (outputDir == "") { thisOutputDir += m->hasPath(fastafile); }
335 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(fastafile)) + "subsample" + m->getExtension(fastafile);
338 m->openOutputFile(outputFileName, out);
339 outputTypes["fasta"].push_back(outputFileName); outputNames.push_back(outputFileName);
341 //make sure that if your picked groups size is not too big
345 for(int i = 0; i < Groups.size(); i++) {
346 total += groupMap->getNumSeqs(Groups[i]);
349 if (size == 0) { //user has not set size, set size = 10% samples size
350 size = int (total * 0.10);
355 m->mothurOut("Your size is too large for the number of groups you selected. Adjusting to " + toString(int (total * 0.10)) + "."); m->mothurOutEndLine();
357 size = int (total * 0.10);
360 m->mothurOut("Sampling " + toString(size) + " from " + toString(total) + "."); m->mothurOutEndLine();
363 if (size == 0) { //user has not set size, set size = 10% samples size
364 size = int (names.size() * 0.10);
367 int thisSize = names.size();
368 if (size > thisSize) { m->mothurOut("Your fasta file only contains " + toString(thisSize) + " sequences. Setting size to " + toString(thisSize) + "."); m->mothurOutEndLine();
372 random_shuffle(names.begin(), names.end());
374 if (!pickedGroups) { m->mothurOut("Sampling " + toString(size) + " from " + toString(thisSize) + "."); m->mothurOutEndLine(); }
376 //randomly select a subset of those names to include in the subsample
377 set<string> subset; //dont want repeat sequence names added
378 for (int j = 0; j < size; j++) {
380 if (m->control_pressed) { return 0; }
382 //get random sequence to add, making sure we have not already added it
386 myrand = (int)((float)(rand()) / (RAND_MAX / (thisSize-1) + 1));
388 if (subset.count(names[myrand]) == 0) {
390 if (groupfile != "") { //if there is a groupfile given fill in group info
391 string group = groupMap->getGroup(names[myrand]);
392 if (group == "not found") { m->mothurOut("[ERROR]: " + names[myrand] + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
394 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
395 if (m->inUsersGroups(group, Groups)) {
396 subset.insert(names[myrand]); break;
399 subset.insert(names[myrand]); break;
401 }else{ //save everyone, group
402 subset.insert(names[myrand]); break;
408 //read through fasta file outputting only the names on the subsample list
410 m->openInputFile(fastafile, in);
414 map<string, vector<string> >::iterator itNameMap;
418 if (m->control_pressed) { in.close(); out.close(); return 0; }
420 Sequence currSeq(in);
421 thisname = currSeq.getName();
423 if (thisname != "") {
425 //does the subset contain a sequence that this sequence represents
426 itNameMap = nameMap.find(thisname);
427 if (itNameMap != nameMap.end()) {
428 vector<string> nameRepresents = itNameMap->second;
430 for (int i = 0; i < nameRepresents.size(); i++){
431 if (subset.count(nameRepresents[i]) != 0) {
432 out << ">" << nameRepresents[i] << endl << currSeq.getAligned() << endl;
437 m->mothurOut("[ERROR]: " + thisname + " is not in your namefile, please correct."); m->mothurOutEndLine();
445 if (count != subset.size()) {
446 m->mothurOut("[ERROR]: The subset selected contained " + toString(subset.size()) + " sequences, but I only found " + toString(count) + " of those in the fastafile."); m->mothurOutEndLine();
449 //if a groupfile is provided read through the group file only outputting the names on the subsample list
450 if (groupfile != "") {
452 string groupOutputDir = outputDir;
453 if (outputDir == "") { groupOutputDir += m->hasPath(groupfile); }
454 string groupOutputFileName = groupOutputDir + m->getRootName(m->getSimpleName(groupfile)) + "subsample" + m->getExtension(groupfile);
457 m->openOutputFile(groupOutputFileName, outGroup);
458 outputTypes["group"].push_back(groupOutputFileName); outputNames.push_back(groupOutputFileName);
461 m->openInputFile(groupfile, inGroup);
464 while(!inGroup.eof()){
466 if (m->control_pressed) { inGroup.close(); outGroup.close(); return 0; }
468 inGroup >> name; m->gobble(inGroup); //read from first column
469 inGroup >> group; //read from second column
471 //if this name is in the accnos file
472 if (subset.count(name) != 0) {
473 outGroup << name << '\t' << group << endl;
483 if (subset.size() != 0) {
484 m->mothurOut("Your groupfile does not match your fasta file."); m->mothurOutEndLine();
485 for (set<string>::iterator it = subset.begin(); it != subset.end(); it++) {
486 m->mothurOut("[ERROR]: " + *it + " is missing from your groupfile."); m->mothurOutEndLine();
494 catch(exception& e) {
495 m->errorOut(e, "SubSampleCommand", "getSubSampleFasta");
499 //**********************************************************************************************************************
500 int SubSampleCommand::getNames() {
504 m->openInputFile(fastafile, in);
509 if (m->control_pressed) { in.close(); return 0; }
511 Sequence currSeq(in);
512 thisname = currSeq.getName();
514 if (thisname != "") {
515 vector<string> temp; temp.push_back(thisname);
516 nameMap[thisname] = temp;
517 names.push_back(thisname);
524 catch(exception& e) {
525 m->errorOut(e, "SubSampleCommand", "getNames");
529 //**********************************************************************************************************************
530 int SubSampleCommand::readNames() {
534 m->openInputFile(namefile, in);
536 string thisname, repnames;
537 map<string, vector<string> >::iterator it;
541 if (m->control_pressed) { in.close(); return 0; }
543 in >> thisname; m->gobble(in); //read from first column
544 in >> repnames; //read from second column
546 it = nameMap.find(thisname);
547 if (it == nameMap.end()) {
549 vector<string> splitRepNames;
550 m->splitAtComma(repnames, splitRepNames);
552 nameMap[thisname] = splitRepNames;
553 for (int i = 0; i < splitRepNames.size(); i++) { names.push_back(splitRepNames[i]); }
555 }else{ m->mothurOut(thisname + " is already in namesfile. I will use first definition."); m->mothurOutEndLine(); }
562 catch(exception& e) {
563 m->errorOut(e, "SubSampleCommand", "readNames");
567 //**********************************************************************************************************************
568 int SubSampleCommand::getSubSampleShared() {
571 string thisOutputDir = outputDir;
572 if (outputDir == "") { thisOutputDir += m->hasPath(sharedfile); }
573 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(sharedfile)) + "subsample" + m->getExtension(sharedfile);
576 m->openOutputFile(outputFileName, out);
577 outputTypes["shared"].push_back(outputFileName); outputNames.push_back(outputFileName);
579 InputData* input = new InputData(sharedfile, "sharedfile");
580 vector<SharedRAbundVector*> lookup = input->getSharedRAbundVectors();
581 string lastLabel = lookup[0]->getLabel();
583 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
584 set<string> processedLabels;
585 set<string> userLabels = labels;
587 if (size == 0) { //user has not set size, set size = smallest samples size
588 size = lookup[0]->getNumSeqs();
589 for (int i = 1; i < lookup.size(); i++) {
590 int thisSize = lookup[i]->getNumSeqs();
592 if (thisSize < size) { size = thisSize; }
596 m->mothurOut("Sampling " + toString(size) + " from " + toString(lookup[0]->getNumSeqs()) + "."); m->mothurOutEndLine();
598 //as long as you are not at the end of the file or done wih the lines you want
599 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
600 if (m->control_pressed) { delete input; for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; lookup[i] = NULL; } out.close(); return 0; }
602 if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){
604 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
606 processShared(lookup, out);
608 processedLabels.insert(lookup[0]->getLabel());
609 userLabels.erase(lookup[0]->getLabel());
612 if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
613 string saveLabel = lookup[0]->getLabel();
615 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
617 lookup = input->getSharedRAbundVectors(lastLabel);
618 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
620 processShared(lookup, out);
622 processedLabels.insert(lookup[0]->getLabel());
623 userLabels.erase(lookup[0]->getLabel());
625 //restore real lastlabel to save below
626 lookup[0]->setLabel(saveLabel);
629 lastLabel = lookup[0]->getLabel();
630 //prevent memory leak
631 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; lookup[i] = NULL; }
633 //get next line to process
634 lookup = input->getSharedRAbundVectors();
638 if (m->control_pressed) { out.close(); return 0; }
640 //output error messages about any remaining user labels
641 set<string>::iterator it;
642 bool needToRun = false;
643 for (it = userLabels.begin(); it != userLabels.end(); it++) {
644 m->mothurOut("Your file does not include the label " + *it);
645 if (processedLabels.count(lastLabel) != 1) {
646 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
649 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
653 //run last label if you need to
654 if (needToRun == true) {
655 for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }
656 lookup = input->getSharedRAbundVectors(lastLabel);
658 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
660 processShared(lookup, out);
662 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
671 catch(exception& e) {
672 m->errorOut(e, "SubSampleCommand", "getSubSampleShared");
676 //**********************************************************************************************************************
677 int SubSampleCommand::processShared(vector<SharedRAbundVector*>& thislookup, ofstream& out) {
680 int numBins = thislookup[0]->getNumBins();
681 for (int i = 0; i < thislookup.size(); i++) {
682 int thisSize = thislookup[i]->getNumSeqs();
684 if (thisSize != size) {
686 string thisgroup = thislookup[i]->getGroup();
688 OrderVector* order = new OrderVector();
689 for(int p=0;p<numBins;p++){
690 for(int j=0;j<thislookup[i]->getAbundance(p);j++){
694 random_shuffle(order->begin(), order->end());
696 SharedRAbundVector* temp = new SharedRAbundVector(numBins);
697 temp->setLabel(thislookup[i]->getLabel());
698 temp->setGroup(thislookup[i]->getGroup());
700 delete thislookup[i];
701 thislookup[i] = temp;
704 for (int j = 0; j < size; j++) {
706 if (m->control_pressed) { delete order; return 0; }
708 //get random number to sample from order between 0 and thisSize-1.
709 int myrand = (int)((float)(rand()) / (RAND_MAX / (thisSize-1) + 1));
711 int bin = order->get(myrand);
713 int abund = thislookup[i]->getAbundance(bin);
714 thislookup[i]->set(bin, (abund+1), thisgroup);
720 //subsampling may have created some otus with no sequences in them
721 eliminateZeroOTUS(thislookup);
723 if (m->control_pressed) { return 0; }
725 for (int i = 0; i < thislookup.size(); i++) {
726 out << thislookup[i]->getLabel() << '\t' << thislookup[i]->getGroup() << '\t';
727 thislookup[i]->print(out);
733 catch(exception& e) {
734 m->errorOut(e, "SubSampleCommand", "processShared");
738 //**********************************************************************************************************************
739 int SubSampleCommand::getSubSampleList() {
742 string thisOutputDir = outputDir;
743 if (outputDir == "") { thisOutputDir += m->hasPath(listfile); }
744 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(listfile)) + "subsample" + m->getExtension(listfile);
747 m->openOutputFile(outputFileName, out);
748 outputTypes["list"].push_back(outputFileName); outputNames.push_back(outputFileName);
750 InputData* input = new InputData(listfile, "list");
751 ListVector* list = input->getListVector();
752 string lastLabel = list->getLabel();
754 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
755 set<string> processedLabels;
756 set<string> userLabels = labels;
760 if (groupfile != "") {
762 groupMap = new GroupMap(groupfile);
765 //takes care of user setting groupNames that are invalid or setting groups=all
766 SharedUtil* util = new SharedUtil();
767 util->setGroups(Groups, groupMap->namesOfGroups);
771 string groupOutputDir = outputDir;
772 if (outputDir == "") { groupOutputDir += m->hasPath(groupfile); }
773 string groupOutputFileName = groupOutputDir + m->getRootName(m->getSimpleName(groupfile)) + "subsample" + m->getExtension(groupfile);
775 m->openOutputFile(groupOutputFileName, outGroup);
776 outputTypes["group"].push_back(groupOutputFileName); outputNames.push_back(groupOutputFileName);
779 if (list->getNumSeqs() != groupMap->getNumSeqs()) {
780 m->mothurOut("[ERROR]: your list file contains " + toString(list->getNumSeqs()) + " sequences, and your groupfile contains " + toString(groupMap->getNumSeqs()) + ", please correct.");
781 m->mothurOutEndLine();
791 //make sure that if your picked groups size is not too big
794 for(int i = 0; i < Groups.size(); i++) {
795 total += groupMap->getNumSeqs(Groups[i]);
798 if (size == 0) { //user has not set size, set size = 10% samples size
799 size = int (total * 0.10);
803 m->mothurOut("Your size is too large for the number of groups you selected. Adjusting to " + toString(int (total * 0.10)) + "."); m->mothurOutEndLine();
804 size = int (total * 0.10);
807 m->mothurOut("Sampling " + toString(size) + " from " + toString(total) + "."); m->mothurOutEndLine();
810 if (size == 0) { //user has not set size, set size = 10% samples size
811 size = int (list->getNumSeqs() * 0.10);
814 int thisSize = list->getNumSeqs();
815 if (size > thisSize) { m->mothurOut("Your list file only contains " + toString(thisSize) + " sequences. Setting size to " + toString(thisSize) + "."); m->mothurOutEndLine();
819 m->mothurOut("Sampling " + toString(size) + " from " + toString(list->getNumSeqs()) + "."); m->mothurOutEndLine();
823 for (int i = 0; i < list->getNumBins(); i++) {
824 string binnames = list->get(i);
827 string individual = "";
828 int length = binnames.length();
829 for(int j=0;j<length;j++){
830 if(binnames[j] == ','){
832 if (groupfile != "") { //if there is a groupfile given fill in group info
833 string group = groupMap->getGroup(individual);
834 if (group == "not found") { m->mothurOut("[ERROR]: " + individual + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
836 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
837 if (m->inUsersGroups(group, Groups)) {
838 names.push_back(individual);
841 names.push_back(individual);
843 }else{ //save everyone, group
844 names.push_back(individual);
849 individual += binnames[j];
853 if (groupfile != "") { //if there is a groupfile given fill in group info
854 string group = groupMap->getGroup(individual);
855 if (group == "not found") { m->mothurOut("[ERROR]: " + individual + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
857 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
858 if (m->inUsersGroups(group, Groups)) {
859 names.push_back(individual);
862 names.push_back(individual);
864 }else{ //save everyone, group
865 names.push_back(individual);
869 random_shuffle(names.begin(), names.end());
871 //randomly select a subset of those names to include in the subsample
872 set<string> subset; //dont want repeat sequence names added
873 for (int j = 0; j < size; j++) {
875 if (m->control_pressed) { break; }
877 //get random sequence to add, making sure we have not already added it
881 myrand = (int)((float)(rand()) / (RAND_MAX / (names.size()-1) + 1));
883 if (subset.count(names[myrand]) == 0) { subset.insert(names[myrand]); break; }
887 if (groupfile != "") {
888 //write out new groupfile
889 for (set<string>::iterator it = subset.begin(); it != subset.end(); it++) {
890 string group = groupMap->getGroup(*it);
891 if (group == "not found") { group = "NOTFOUND"; }
893 outGroup << *it << '\t' << group << endl;
895 outGroup.close(); delete groupMap;
899 //as long as you are not at the end of the file or done wih the lines you want
900 while((list != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
902 if (m->control_pressed) { delete list; delete input; out.close(); return 0; }
904 if(allLines == 1 || labels.count(list->getLabel()) == 1){
906 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
908 processList(list, out, subset);
910 processedLabels.insert(list->getLabel());
911 userLabels.erase(list->getLabel());
914 if ((m->anyLabelsToProcess(list->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
915 string saveLabel = list->getLabel();
919 list = input->getListVector(lastLabel);
920 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
922 processList(list, out, subset);
924 processedLabels.insert(list->getLabel());
925 userLabels.erase(list->getLabel());
927 //restore real lastlabel to save below
928 list->setLabel(saveLabel);
931 lastLabel = list->getLabel();
933 delete list; list = NULL;
935 //get next line to process
936 list = input->getListVector();
940 if (m->control_pressed) { if (list != NULL) { delete list; } delete input; out.close(); return 0; }
942 //output error messages about any remaining user labels
943 set<string>::iterator it;
944 bool needToRun = false;
945 for (it = userLabels.begin(); it != userLabels.end(); it++) {
946 m->mothurOut("Your file does not include the label " + *it);
947 if (processedLabels.count(lastLabel) != 1) {
948 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
951 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
955 //run last label if you need to
956 if (needToRun == true) {
957 if (list != NULL) { delete list; }
959 list = input->getListVector(lastLabel);
961 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
963 processList(list, out, subset);
965 delete list; list = NULL;
969 if (list != NULL) { delete list; }
975 catch(exception& e) {
976 m->errorOut(e, "SubSampleCommand", "getSubSampleList");
980 //**********************************************************************************************************************
981 int SubSampleCommand::processList(ListVector*& list, ofstream& out, set<string>& subset) {
984 int numBins = list->getNumBins();
986 ListVector* temp = new ListVector();
987 temp->setLabel(list->getLabel());
989 for (int i = 0; i < numBins; i++) {
991 if (m->control_pressed) { break; }
993 string binnames = list->get(i);
996 string individual = "";
997 string newNames = "";
998 int length = binnames.length();
999 for(int j=0;j<length;j++){
1000 if(binnames[j] == ','){
1001 if (subset.count(individual) != 0) { newNames += individual + ","; }
1004 individual += binnames[j];
1007 if (subset.count(individual) != 0) { newNames += individual; }
1010 //if there are names in this bin add to new list
1011 if (newNames != "") {
1012 newNames = newNames.substr(0, newNames.length()-1); //rip off extra comma
1013 temp->push_back(newNames);
1020 if (m->control_pressed) { return 0; }
1027 catch(exception& e) {
1028 m->errorOut(e, "SubSampleCommand", "processList");
1032 //**********************************************************************************************************************
1033 int SubSampleCommand::getSubSampleRabund() {
1036 string thisOutputDir = outputDir;
1037 if (outputDir == "") { thisOutputDir += m->hasPath(rabundfile); }
1038 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(rabundfile)) + "subsample" + m->getExtension(rabundfile);
1041 m->openOutputFile(outputFileName, out);
1042 outputTypes["rabund"].push_back(outputFileName); outputNames.push_back(outputFileName);
1044 InputData* input = new InputData(rabundfile, "rabund");
1045 RAbundVector* rabund = input->getRAbundVector();
1046 string lastLabel = rabund->getLabel();
1048 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1049 set<string> processedLabels;
1050 set<string> userLabels = labels;
1052 if (size == 0) { //user has not set size, set size = 10%
1053 size = int((rabund->getNumSeqs()) * 0.10);
1056 m->mothurOut("Sampling " + toString(size) + " from " + toString(rabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1058 //as long as you are not at the end of the file or done wih the lines you want
1059 while((rabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1060 if (m->control_pressed) { delete input; delete rabund; out.close(); return 0; }
1062 if(allLines == 1 || labels.count(rabund->getLabel()) == 1){
1064 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1066 processRabund(rabund, out);
1068 processedLabels.insert(rabund->getLabel());
1069 userLabels.erase(rabund->getLabel());
1072 if ((m->anyLabelsToProcess(rabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1073 string saveLabel = rabund->getLabel();
1077 rabund = input->getRAbundVector(lastLabel);
1078 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1080 processRabund(rabund, out);
1082 processedLabels.insert(rabund->getLabel());
1083 userLabels.erase(rabund->getLabel());
1085 //restore real lastlabel to save below
1086 rabund->setLabel(saveLabel);
1089 lastLabel = rabund->getLabel();
1091 //prevent memory leak
1092 delete rabund; rabund = NULL;
1094 //get next line to process
1095 rabund = input->getRAbundVector();
1099 if (m->control_pressed) { out.close(); return 0; }
1101 //output error messages about any remaining user labels
1102 set<string>::iterator it;
1103 bool needToRun = false;
1104 for (it = userLabels.begin(); it != userLabels.end(); it++) {
1105 m->mothurOut("Your file does not include the label " + *it);
1106 if (processedLabels.count(lastLabel) != 1) {
1107 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1110 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1114 //run last label if you need to
1115 if (needToRun == true) {
1116 if (rabund != NULL) { delete rabund; }
1118 rabund = input->getRAbundVector(lastLabel);
1120 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1122 processRabund(rabund, out);
1133 catch(exception& e) {
1134 m->errorOut(e, "SubSampleCommand", "getSubSampleRabund");
1138 //**********************************************************************************************************************
1139 int SubSampleCommand::processRabund(RAbundVector*& rabund, ofstream& out) {
1142 int numBins = rabund->getNumBins();
1143 int thisSize = rabund->getNumSeqs();
1145 if (thisSize != size) {
1147 OrderVector* order = new OrderVector();
1148 for(int p=0;p<numBins;p++){
1149 for(int j=0;j<rabund->get(p);j++){
1150 order->push_back(p);
1153 random_shuffle(order->begin(), order->end());
1155 RAbundVector* temp = new RAbundVector(numBins);
1156 temp->setLabel(rabund->getLabel());
1161 for (int j = 0; j < size; j++) {
1163 if (m->control_pressed) { delete order; return 0; }
1165 //get random number to sample from order between 0 and thisSize-1.
1166 int myrand = (int)((float)(rand()) / (RAND_MAX / (thisSize-1) + 1));
1168 int bin = order->get(myrand);
1170 int abund = rabund->get(bin);
1171 rabund->set(bin, (abund+1));
1177 if (m->control_pressed) { return 0; }
1184 catch(exception& e) {
1185 m->errorOut(e, "SubSampleCommand", "processRabund");
1189 //**********************************************************************************************************************
1190 int SubSampleCommand::getSubSampleSabund() {
1193 string thisOutputDir = outputDir;
1194 if (outputDir == "") { thisOutputDir += m->hasPath(sabundfile); }
1195 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(sabundfile)) + "subsample" + m->getExtension(sabundfile);
1198 m->openOutputFile(outputFileName, out);
1199 outputTypes["sabund"].push_back(outputFileName); outputNames.push_back(outputFileName);
1201 InputData* input = new InputData(sabundfile, "sabund");
1202 SAbundVector* sabund = input->getSAbundVector();
1203 string lastLabel = sabund->getLabel();
1205 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1206 set<string> processedLabels;
1207 set<string> userLabels = labels;
1209 if (size == 0) { //user has not set size, set size = 10%
1210 size = int((sabund->getNumSeqs()) * 0.10);
1213 m->mothurOut("Sampling " + toString(size) + " from " + toString(sabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1215 //as long as you are not at the end of the file or done wih the lines you want
1216 while((sabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1217 if (m->control_pressed) { delete input; delete sabund; out.close(); return 0; }
1219 if(allLines == 1 || labels.count(sabund->getLabel()) == 1){
1221 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1223 processSabund(sabund, out);
1225 processedLabels.insert(sabund->getLabel());
1226 userLabels.erase(sabund->getLabel());
1229 if ((m->anyLabelsToProcess(sabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1230 string saveLabel = sabund->getLabel();
1234 sabund = input->getSAbundVector(lastLabel);
1235 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1237 processSabund(sabund, out);
1239 processedLabels.insert(sabund->getLabel());
1240 userLabels.erase(sabund->getLabel());
1242 //restore real lastlabel to save below
1243 sabund->setLabel(saveLabel);
1246 lastLabel = sabund->getLabel();
1248 //prevent memory leak
1249 delete sabund; sabund = NULL;
1251 //get next line to process
1252 sabund = input->getSAbundVector();
1256 if (m->control_pressed) { out.close(); return 0; }
1258 //output error messages about any remaining user labels
1259 set<string>::iterator it;
1260 bool needToRun = false;
1261 for (it = userLabels.begin(); it != userLabels.end(); it++) {
1262 m->mothurOut("Your file does not include the label " + *it);
1263 if (processedLabels.count(lastLabel) != 1) {
1264 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1267 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1271 //run last label if you need to
1272 if (needToRun == true) {
1273 if (sabund != NULL) { delete sabund; }
1275 sabund = input->getSAbundVector(lastLabel);
1277 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1279 processSabund(sabund, out);
1290 catch(exception& e) {
1291 m->errorOut(e, "SubSampleCommand", "getSubSampleSabund");
1295 //**********************************************************************************************************************
1296 int SubSampleCommand::processSabund(SAbundVector*& sabund, ofstream& out) {
1299 RAbundVector* rabund = new RAbundVector();
1300 *rabund = sabund->getRAbundVector();
1302 int numBins = rabund->getNumBins();
1303 int thisSize = rabund->getNumSeqs();
1305 if (thisSize != size) {
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);
1313 random_shuffle(order->begin(), order->end());
1315 RAbundVector* temp = new RAbundVector(numBins);
1316 temp->setLabel(rabund->getLabel());
1321 for (int j = 0; j < size; j++) {
1323 if (m->control_pressed) { delete order; return 0; }
1325 //get random number to sample from order between 0 and thisSize-1.
1326 int myrand = (int)((float)(rand()) / (RAND_MAX / (thisSize-1) + 1));
1328 int bin = order->get(myrand);
1330 int abund = rabund->get(bin);
1331 rabund->set(bin, (abund+1));
1337 if (m->control_pressed) { return 0; }
1340 sabund = new SAbundVector();
1341 *sabund = rabund->getSAbundVector();
1349 catch(exception& e) {
1350 m->errorOut(e, "SubSampleCommand", "processSabund");
1354 //**********************************************************************************************************************
1355 int SubSampleCommand::eliminateZeroOTUS(vector<SharedRAbundVector*>& thislookup) {
1358 vector<SharedRAbundVector*> newLookup;
1359 for (int i = 0; i < thislookup.size(); i++) {
1360 SharedRAbundVector* temp = new SharedRAbundVector();
1361 temp->setLabel(thislookup[i]->getLabel());
1362 temp->setGroup(thislookup[i]->getGroup());
1363 newLookup.push_back(temp);
1367 for (int i = 0; i < thislookup[0]->getNumBins(); i++) {
1368 if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) { delete newLookup[j]; } return 0; }
1370 //look at each sharedRabund and make sure they are not all zero
1371 bool allZero = true;
1372 for (int j = 0; j < thislookup.size(); j++) {
1373 if (thislookup[j]->getAbundance(i) != 0) { allZero = false; break; }
1376 //if they are not all zero add this bin
1378 for (int j = 0; j < thislookup.size(); j++) {
1379 newLookup[j]->push_back(thislookup[j]->getAbundance(i), thislookup[j]->getGroup());
1384 for (int j = 0; j < thislookup.size(); j++) { delete thislookup[j]; }
1387 thislookup = newLookup;
1392 catch(exception& e) {
1393 m->errorOut(e, "SubSampleCommand", "eliminateZeroOTUS");
1398 //**********************************************************************************************************************