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","persample", "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(){
28 abort = true; calledHelp = true;
29 vector<string> tempOutNames;
30 outputTypes["shared"] = tempOutNames;
31 outputTypes["list"] = tempOutNames;
32 outputTypes["rabund"] = tempOutNames;
33 outputTypes["sabund"] = tempOutNames;
34 outputTypes["fasta"] = tempOutNames;
35 outputTypes["name"] = tempOutNames;
36 outputTypes["group"] = tempOutNames;
39 m->errorOut(e, "SubSampleCommand", "GetRelAbundCommand");
43 //**********************************************************************************************************************
44 vector<string> SubSampleCommand::getRequiredParameters(){
46 string Array[] = {"fasta","list","shared","rabund", "sabund","or"};
47 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
51 m->errorOut(e, "SubSampleCommand", "getRequiredParameters");
55 //**********************************************************************************************************************
56 vector<string> SubSampleCommand::getRequiredFiles(){
58 vector<string> myArray;
62 m->errorOut(e, "SubSampleCommand", "getRequiredFiles");
66 //**********************************************************************************************************************
67 SubSampleCommand::SubSampleCommand(string option) {
69 globaldata = GlobalData::getInstance();
70 abort = false; calledHelp = false;
74 //allow user to run help
75 if(option == "help") { help(); abort = true; calledHelp = true; }
78 //valid paramters for this command
79 string Array[] = {"fasta", "group", "list","shared","rabund","persample", "sabund","name","size","groups","label","outputdir","inputdir"};
80 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
82 OptionParser parser(option);
83 map<string,string> parameters = parser.getParameters();
85 ValidParameters validParameter;
87 //check to make sure all parameters are valid for command
88 map<string,string>::iterator it;
89 for (it = parameters.begin(); it != parameters.end(); it++) {
90 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
93 //initialize outputTypes
94 vector<string> tempOutNames;
95 outputTypes["shared"] = tempOutNames;
96 outputTypes["list"] = tempOutNames;
97 outputTypes["rabund"] = tempOutNames;
98 outputTypes["sabund"] = tempOutNames;
99 outputTypes["fasta"] = tempOutNames;
100 outputTypes["name"] = tempOutNames;
101 outputTypes["group"] = tempOutNames;
103 //if the user changes the output directory command factory will send this info to us in the output parameter
104 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
106 //if the user changes the input directory command factory will send this info to us in the output parameter
107 string inputDir = validParameter.validFile(parameters, "inputdir", false);
108 if (inputDir == "not found"){ inputDir = ""; }
111 it = parameters.find("list");
112 //user has given a template file
113 if(it != parameters.end()){
114 path = m->hasPath(it->second);
115 //if the user has not given a path then, add inputdir. else leave path alone.
116 if (path == "") { parameters["list"] = inputDir + it->second; }
119 it = parameters.find("fasta");
120 //user has given a template file
121 if(it != parameters.end()){
122 path = m->hasPath(it->second);
123 //if the user has not given a path then, add inputdir. else leave path alone.
124 if (path == "") { parameters["fasta"] = inputDir + it->second; }
127 it = parameters.find("shared");
128 //user has given a template file
129 if(it != parameters.end()){
130 path = m->hasPath(it->second);
131 //if the user has not given a path then, add inputdir. else leave path alone.
132 if (path == "") { parameters["shared"] = inputDir + it->second; }
135 it = parameters.find("group");
136 //user has given a template file
137 if(it != parameters.end()){
138 path = m->hasPath(it->second);
139 //if the user has not given a path then, add inputdir. else leave path alone.
140 if (path == "") { parameters["group"] = inputDir + it->second; }
143 it = parameters.find("sabund");
144 //user has given a template file
145 if(it != parameters.end()){
146 path = m->hasPath(it->second);
147 //if the user has not given a path then, add inputdir. else leave path alone.
148 if (path == "") { parameters["sabund"] = inputDir + it->second; }
151 it = parameters.find("rabund");
152 //user has given a template file
153 if(it != parameters.end()){
154 path = m->hasPath(it->second);
155 //if the user has not given a path then, add inputdir. else leave path alone.
156 if (path == "") { parameters["rabund"] = inputDir + it->second; }
159 it = parameters.find("name");
160 //user has given a template file
161 if(it != parameters.end()){
162 path = m->hasPath(it->second);
163 //if the user has not given a path then, add inputdir. else leave path alone.
164 if (path == "") { parameters["name"] = inputDir + it->second; }
168 //check for required parameters
169 listfile = validParameter.validFile(parameters, "list", true);
170 if (listfile == "not open") { listfile = ""; abort = true; }
171 else if (listfile == "not found") { listfile = ""; }
173 sabundfile = validParameter.validFile(parameters, "sabund", true);
174 if (sabundfile == "not open") { sabundfile = ""; abort = true; }
175 else if (sabundfile == "not found") { sabundfile = ""; }
177 rabundfile = validParameter.validFile(parameters, "rabund", true);
178 if (rabundfile == "not open") { rabundfile = ""; abort = true; }
179 else if (rabundfile == "not found") { rabundfile = ""; }
181 fastafile = validParameter.validFile(parameters, "fasta", true);
182 if (fastafile == "not open") { fastafile = ""; abort = true; }
183 else if (fastafile == "not found") { fastafile = ""; }
185 sharedfile = validParameter.validFile(parameters, "shared", true);
186 if (sharedfile == "not open") { sharedfile = ""; abort = true; }
187 else if (sharedfile == "not found") { sharedfile = ""; }
189 namefile = validParameter.validFile(parameters, "name", true);
190 if (namefile == "not open") { namefile = ""; abort = true; }
191 else if (namefile == "not found") { namefile = ""; }
193 groupfile = validParameter.validFile(parameters, "group", true);
194 if (groupfile == "not open") { groupfile = ""; abort = true; }
195 else if (groupfile == "not found") { groupfile = ""; }
198 //check for optional parameter and set defaults
199 // ...at some point should added some additional type checking...
200 label = validParameter.validFile(parameters, "label", false);
201 if (label == "not found") { label = ""; }
203 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
204 else { allLines = 1; }
207 groups = validParameter.validFile(parameters, "groups", false);
208 if (groups == "not found") { groups = ""; pickedGroups = false; }
211 m->splitAtDash(groups, Groups);
212 globaldata->Groups = Groups;
215 string temp = validParameter.validFile(parameters, "size", false); if (temp == "not found"){ temp = "0"; }
218 temp = validParameter.validFile(parameters, "persample", false); if (temp == "not found"){ temp = "f"; }
219 persample = m->isTrue(temp);
221 if (groupfile == "") { persample = false; }
223 if ((namefile != "") && (fastafile == "")) { m->mothurOut("You may only use a namefile with a fastafile."); m->mothurOutEndLine(); abort = true; }
225 if ((fastafile == "") && (listfile == "") && (sabundfile == "") && (rabundfile == "") && (sharedfile == "")) {
226 m->mothurOut("You must provide a fasta, list, sabund, rabund or shared file as an input file."); m->mothurOutEndLine(); abort = true; }
228 if (pickedGroups && ((groupfile == "") && (sharedfile == ""))) {
229 m->mothurOut("You cannot pick groups without a valid group file or shared file."); m->mothurOutEndLine(); abort = true; }
231 if ((groupfile != "") && ((fastafile == "") && (listfile == ""))) {
232 m->mothurOut("Group file only valid with listfile or fastafile."); m->mothurOutEndLine(); abort = true; }
234 if ((groupfile != "") && ((fastafile != "") && (listfile != ""))) {
235 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; }
240 catch(exception& e) {
241 m->errorOut(e, "SubSampleCommand", "SubSampleCommand");
246 //**********************************************************************************************************************
248 void SubSampleCommand::help(){
250 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");
251 m->mothurOut("The sub.sample command parameters are fasta, name, list, group, rabund, sabund, shared, groups, size, persample and label. You must provide a fasta, list, sabund, rabund or shared file as an input file.\n");
252 m->mothurOut("The namefile is only used with the fasta file, not with the listfile, because the list file should contain all sequences.\n");
253 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");
254 m->mothurOut("The label parameter allows you to select what distance levels you would like, and are also separated by dashes.\n");
255 m->mothurOut("The size parameter allows you indicate the size of your subsample.\n");
256 m->mothurOut("The persample parameter allows you indicate you want to select subsample of the same size from each of your groups, default=false. It is only used with the list and fasta files if a groupfile is given.\n");
257 m->mothurOut("persample=false will select a random set of sequences of the size you select, but the number of seqs from each group may differ.\n");
258 m->mothurOut("The size parameter is not set: with shared file size=number of seqs in smallest sample, with all other files if a groupfile is given and persample=true, then size=number of seqs in smallest sample, otherwise size=10% of number of seqs.\n");
259 m->mothurOut("The sub.sample command should be in the following format: sub.sample(list=yourListFile, group=yourGroupFile, groups=yourGroups, label=yourLabels).\n");
260 m->mothurOut("Example sub.sample(list=abrecovery.fn.list, group=abrecovery.groups, groups=B-C, size=20).\n");
261 m->mothurOut("The default value for groups is all the groups in your groupfile, and all labels in your inputfile will be used.\n");
262 m->mothurOut("The sub.sample command outputs a .subsample file.\n");
263 m->mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
266 catch(exception& e) {
267 m->errorOut(e, "SubSampleCommand", "help");
272 //**********************************************************************************************************************
274 SubSampleCommand::~SubSampleCommand(){}
276 //**********************************************************************************************************************
278 int SubSampleCommand::execute(){
281 if (abort == true) { if (calledHelp) { return 0; } return 2; }
283 if (sharedfile != "") { getSubSampleShared(); }
284 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); return 0; } }
286 if (listfile != "") { getSubSampleList(); }
287 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); return 0; } }
289 if (rabundfile != "") { getSubSampleRabund(); }
290 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); return 0; } }
292 if (sabundfile != "") { getSubSampleSabund(); }
293 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); return 0; } }
295 if (fastafile != "") { getSubSampleFasta(); }
296 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); return 0; } }
299 m->mothurOutEndLine();
300 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
301 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
302 m->mothurOutEndLine();
306 catch(exception& e) {
307 m->errorOut(e, "SubSampleCommand", "execute");
311 //**********************************************************************************************************************
312 int SubSampleCommand::getSubSampleFasta() {
315 if (namefile != "") { readNames(); } //fills names with all names in namefile.
316 else { getNames(); }//no name file, so get list of names to pick from
319 if (groupfile != "") {
321 groupMap = new GroupMap(groupfile);
324 //takes care of user setting groupNames that are invalid or setting groups=all
325 SharedUtil* util = new SharedUtil();
326 util->setGroups(Groups, groupMap->namesOfGroups);
330 if (names.size() != groupMap->getNumSeqs()) {
331 m->mothurOut("[ERROR]: your fasta file contains " + toString(names.size()) + " sequences, and your groupfile contains " + toString(groupMap->getNumSeqs()) + ", please correct.");
332 m->mothurOutEndLine();
338 if (m->control_pressed) { return 0; }
340 string thisOutputDir = outputDir;
341 if (outputDir == "") { thisOutputDir += m->hasPath(fastafile); }
342 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(fastafile)) + "subsample" + m->getExtension(fastafile);
345 m->openOutputFile(outputFileName, out);
346 outputTypes["fasta"].push_back(outputFileName); outputNames.push_back(outputFileName);
348 //make sure that if your picked groups size is not too big
349 int thisSize = names.size();
351 if (size == 0) { //user has not set size, set size = smallest samples size
352 size = groupMap->getNumSeqs(Groups[0]);
353 for (int i = 1; i < Groups.size(); i++) {
354 int thisSize = groupMap->getNumSeqs(Groups[i]);
356 if (thisSize < size) { size = thisSize; }
358 }else { //make sure size is not too large
359 int smallestSize = groupMap->getNumSeqs(Groups[0]);
360 for (int i = 1; i < Groups.size(); i++) {
361 int thisSize = groupMap->getNumSeqs(Groups[i]);
363 if (thisSize < smallestSize) { smallestSize = thisSize; }
365 if (smallestSize < size) { size = smallestSize; m->mothurOut("You have selected a size that is larger than your smallest sample, using your samllest sample size, " + toString(smallestSize) + "."); m->mothurOutEndLine(); }
368 m->mothurOut("Sampling " + toString(size) + " from each group."); m->mothurOutEndLine();
372 for(int i = 0; i < Groups.size(); i++) {
373 total += groupMap->getNumSeqs(Groups[i]);
376 if (size == 0) { //user has not set size, set size = 10% samples size
377 size = int (total * 0.10);
382 m->mothurOut("Your size is too large for the number of groups you selected. Adjusting to " + toString(int (total * 0.10)) + "."); m->mothurOutEndLine();
384 size = int (total * 0.10);
387 m->mothurOut("Sampling " + toString(size) + " from " + toString(total) + "."); m->mothurOutEndLine();
390 if (size == 0) { //user has not set size, set size = 10% samples size
391 size = int (names.size() * 0.10);
394 if (size > thisSize) { m->mothurOut("Your fasta file only contains " + toString(thisSize) + " sequences. Setting size to " + toString(thisSize) + "."); m->mothurOutEndLine();
398 if (!pickedGroups) { m->mothurOut("Sampling " + toString(size) + " from " + toString(thisSize) + "."); m->mothurOutEndLine(); }
401 random_shuffle(names.begin(), names.end());
403 set<string> subset; //dont want repeat sequence names added
405 for (int i = 0; i < Groups.size(); i++) {
407 //randomly select a subset of those names from this group to include in the subsample
408 for (int j = 0; j < size; j++) {
410 if (m->control_pressed) { return 0; }
412 //get random sequence to add, making sure we have not already added it
416 myrand = (int)((float)(rand()) / (RAND_MAX / (thisSize-1) + 1));
418 if (subset.count(names[myrand]) == 0) {
420 string group = groupMap->getGroup(names[myrand]);
421 if (group == "not found") { m->mothurOut("[ERROR]: " + names[myrand] + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
423 if (group == Groups[i]) { subset.insert(names[myrand]); break; }
429 //randomly select a subset of those names to include in the subsample
430 for (int j = 0; j < size; j++) {
432 if (m->control_pressed) { return 0; }
434 //get random sequence to add, making sure we have not already added it
438 myrand = (int)((float)(rand()) / (RAND_MAX / (thisSize-1) + 1));
440 if (subset.count(names[myrand]) == 0) {
442 if (groupfile != "") { //if there is a groupfile given fill in group info
443 string group = groupMap->getGroup(names[myrand]);
444 if (group == "not found") { m->mothurOut("[ERROR]: " + names[myrand] + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
446 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
447 if (m->inUsersGroups(group, Groups)) {
448 subset.insert(names[myrand]); break;
451 subset.insert(names[myrand]); break;
453 }else{ //save everyone, group
454 subset.insert(names[myrand]); break;
460 //read through fasta file outputting only the names on the subsample list
462 m->openInputFile(fastafile, in);
466 map<string, vector<string> >::iterator itNameMap;
470 if (m->control_pressed) { in.close(); out.close(); return 0; }
472 Sequence currSeq(in);
473 thisname = currSeq.getName();
475 if (thisname != "") {
477 //does the subset contain a sequence that this sequence represents
478 itNameMap = nameMap.find(thisname);
479 if (itNameMap != nameMap.end()) {
480 vector<string> nameRepresents = itNameMap->second;
482 for (int i = 0; i < nameRepresents.size(); i++){
483 if (subset.count(nameRepresents[i]) != 0) {
484 out << ">" << nameRepresents[i] << endl << currSeq.getAligned() << endl;
489 m->mothurOut("[ERROR]: " + thisname + " is not in your namefile, please correct."); m->mothurOutEndLine();
497 if (count != subset.size()) {
498 m->mothurOut("[ERROR]: The subset selected contained " + toString(subset.size()) + " sequences, but I only found " + toString(count) + " of those in the fastafile."); m->mothurOutEndLine();
501 //if a groupfile is provided read through the group file only outputting the names on the subsample list
502 if (groupfile != "") {
504 string groupOutputDir = outputDir;
505 if (outputDir == "") { groupOutputDir += m->hasPath(groupfile); }
506 string groupOutputFileName = groupOutputDir + m->getRootName(m->getSimpleName(groupfile)) + "subsample" + m->getExtension(groupfile);
509 m->openOutputFile(groupOutputFileName, outGroup);
510 outputTypes["group"].push_back(groupOutputFileName); outputNames.push_back(groupOutputFileName);
513 m->openInputFile(groupfile, inGroup);
516 while(!inGroup.eof()){
518 if (m->control_pressed) { inGroup.close(); outGroup.close(); return 0; }
520 inGroup >> name; m->gobble(inGroup); //read from first column
521 inGroup >> group; //read from second column
523 //if this name is in the accnos file
524 if (subset.count(name) != 0) {
525 outGroup << name << '\t' << group << endl;
535 if (subset.size() != 0) {
536 m->mothurOut("Your groupfile does not match your fasta file."); m->mothurOutEndLine();
537 for (set<string>::iterator it = subset.begin(); it != subset.end(); it++) {
538 m->mothurOut("[ERROR]: " + *it + " is missing from your groupfile."); m->mothurOutEndLine();
546 catch(exception& e) {
547 m->errorOut(e, "SubSampleCommand", "getSubSampleFasta");
551 //**********************************************************************************************************************
552 int SubSampleCommand::getNames() {
556 m->openInputFile(fastafile, in);
561 if (m->control_pressed) { in.close(); return 0; }
563 Sequence currSeq(in);
564 thisname = currSeq.getName();
566 if (thisname != "") {
567 vector<string> temp; temp.push_back(thisname);
568 nameMap[thisname] = temp;
569 names.push_back(thisname);
578 catch(exception& e) {
579 m->errorOut(e, "SubSampleCommand", "getNames");
583 //**********************************************************************************************************************
584 int SubSampleCommand::readNames() {
588 m->openInputFile(namefile, in);
590 string thisname, repnames;
591 map<string, vector<string> >::iterator it;
595 if (m->control_pressed) { in.close(); return 0; }
597 in >> thisname; m->gobble(in); //read from first column
598 in >> repnames; //read from second column
600 it = nameMap.find(thisname);
601 if (it == nameMap.end()) {
603 vector<string> splitRepNames;
604 m->splitAtComma(repnames, splitRepNames);
606 nameMap[thisname] = splitRepNames;
607 for (int i = 0; i < splitRepNames.size(); i++) { names.push_back(splitRepNames[i]); }
609 }else{ m->mothurOut(thisname + " is already in namesfile. I will use first definition."); m->mothurOutEndLine(); }
618 catch(exception& e) {
619 m->errorOut(e, "SubSampleCommand", "readNames");
623 //**********************************************************************************************************************
624 int SubSampleCommand::getSubSampleShared() {
627 string thisOutputDir = outputDir;
628 if (outputDir == "") { thisOutputDir += m->hasPath(sharedfile); }
629 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(sharedfile)) + "subsample" + m->getExtension(sharedfile);
632 m->openOutputFile(outputFileName, out);
633 outputTypes["shared"].push_back(outputFileName); outputNames.push_back(outputFileName);
635 InputData* input = new InputData(sharedfile, "sharedfile");
636 vector<SharedRAbundVector*> lookup = input->getSharedRAbundVectors();
637 string lastLabel = lookup[0]->getLabel();
639 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
640 set<string> processedLabels;
641 set<string> userLabels = labels;
643 if (size == 0) { //user has not set size, set size = smallest samples size
644 size = lookup[0]->getNumSeqs();
645 for (int i = 1; i < lookup.size(); i++) {
646 int thisSize = lookup[i]->getNumSeqs();
648 if (thisSize < size) { size = thisSize; }
652 m->mothurOut("Sampling " + toString(size) + " from " + toString(lookup[0]->getNumSeqs()) + "."); m->mothurOutEndLine();
654 //as long as you are not at the end of the file or done wih the lines you want
655 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
656 if (m->control_pressed) { delete input; for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; lookup[i] = NULL; } out.close(); return 0; }
658 if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){
660 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
662 processShared(lookup, out);
664 processedLabels.insert(lookup[0]->getLabel());
665 userLabels.erase(lookup[0]->getLabel());
668 if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
669 string saveLabel = lookup[0]->getLabel();
671 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
673 lookup = input->getSharedRAbundVectors(lastLabel);
674 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
676 processShared(lookup, out);
678 processedLabels.insert(lookup[0]->getLabel());
679 userLabels.erase(lookup[0]->getLabel());
681 //restore real lastlabel to save below
682 lookup[0]->setLabel(saveLabel);
685 lastLabel = lookup[0]->getLabel();
686 //prevent memory leak
687 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; lookup[i] = NULL; }
689 //get next line to process
690 lookup = input->getSharedRAbundVectors();
694 if (m->control_pressed) { out.close(); return 0; }
696 //output error messages about any remaining user labels
697 set<string>::iterator it;
698 bool needToRun = false;
699 for (it = userLabels.begin(); it != userLabels.end(); it++) {
700 m->mothurOut("Your file does not include the label " + *it);
701 if (processedLabels.count(lastLabel) != 1) {
702 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
705 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
709 //run last label if you need to
710 if (needToRun == true) {
711 for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }
712 lookup = input->getSharedRAbundVectors(lastLabel);
714 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
716 processShared(lookup, out);
718 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
727 catch(exception& e) {
728 m->errorOut(e, "SubSampleCommand", "getSubSampleShared");
732 //**********************************************************************************************************************
733 int SubSampleCommand::processShared(vector<SharedRAbundVector*>& thislookup, ofstream& out) {
736 int numBins = thislookup[0]->getNumBins();
737 for (int i = 0; i < thislookup.size(); i++) {
738 int thisSize = thislookup[i]->getNumSeqs();
740 if (thisSize != size) {
742 string thisgroup = thislookup[i]->getGroup();
744 OrderVector* order = new OrderVector();
745 for(int p=0;p<numBins;p++){
746 for(int j=0;j<thislookup[i]->getAbundance(p);j++){
750 random_shuffle(order->begin(), order->end());
752 SharedRAbundVector* temp = new SharedRAbundVector(numBins);
753 temp->setLabel(thislookup[i]->getLabel());
754 temp->setGroup(thislookup[i]->getGroup());
756 delete thislookup[i];
757 thislookup[i] = temp;
760 for (int j = 0; j < size; j++) {
762 if (m->control_pressed) { delete order; return 0; }
764 //get random number to sample from order between 0 and thisSize-1.
765 int myrand = (int)((float)(rand()) / (RAND_MAX / (thisSize-1) + 1));
767 int bin = order->get(myrand);
769 int abund = thislookup[i]->getAbundance(bin);
770 thislookup[i]->set(bin, (abund+1), thisgroup);
776 //subsampling may have created some otus with no sequences in them
777 eliminateZeroOTUS(thislookup);
779 if (m->control_pressed) { return 0; }
781 for (int i = 0; i < thislookup.size(); i++) {
782 out << thislookup[i]->getLabel() << '\t' << thislookup[i]->getGroup() << '\t';
783 thislookup[i]->print(out);
789 catch(exception& e) {
790 m->errorOut(e, "SubSampleCommand", "processShared");
794 //**********************************************************************************************************************
795 int SubSampleCommand::getSubSampleList() {
798 string thisOutputDir = outputDir;
799 if (outputDir == "") { thisOutputDir += m->hasPath(listfile); }
800 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(listfile)) + "subsample" + m->getExtension(listfile);
803 m->openOutputFile(outputFileName, out);
804 outputTypes["list"].push_back(outputFileName); outputNames.push_back(outputFileName);
806 InputData* input = new InputData(listfile, "list");
807 ListVector* list = input->getListVector();
808 string lastLabel = list->getLabel();
810 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
811 set<string> processedLabels;
812 set<string> userLabels = labels;
816 if (groupfile != "") {
818 groupMap = new GroupMap(groupfile);
821 //takes care of user setting groupNames that are invalid or setting groups=all
822 SharedUtil* util = new SharedUtil();
823 util->setGroups(Groups, groupMap->namesOfGroups);
827 string groupOutputDir = outputDir;
828 if (outputDir == "") { groupOutputDir += m->hasPath(groupfile); }
829 string groupOutputFileName = groupOutputDir + m->getRootName(m->getSimpleName(groupfile)) + "subsample" + m->getExtension(groupfile);
831 m->openOutputFile(groupOutputFileName, outGroup);
832 outputTypes["group"].push_back(groupOutputFileName); outputNames.push_back(groupOutputFileName);
835 if (list->getNumSeqs() != groupMap->getNumSeqs()) {
836 m->mothurOut("[ERROR]: your list file contains " + toString(list->getNumSeqs()) + " sequences, and your groupfile contains " + toString(groupMap->getNumSeqs()) + ", please correct.");
837 m->mothurOutEndLine();
847 //make sure that if your picked groups size is not too big
849 if (size == 0) { //user has not set size, set size = smallest samples size
850 size = groupMap->getNumSeqs(Groups[0]);
851 for (int i = 1; i < Groups.size(); i++) {
852 int thisSize = groupMap->getNumSeqs(Groups[i]);
854 if (thisSize < size) { size = thisSize; }
856 }else { //make sure size is not too large
857 int smallestSize = groupMap->getNumSeqs(Groups[0]);
858 for (int i = 1; i < Groups.size(); i++) {
859 int thisSize = groupMap->getNumSeqs(Groups[i]);
861 if (thisSize < smallestSize) { smallestSize = thisSize; }
863 if (smallestSize < size) { size = smallestSize; m->mothurOut("You have selected a size that is larger than your smallest sample, using your samllest sample size, " + toString(smallestSize) + "."); m->mothurOutEndLine(); }
866 m->mothurOut("Sampling " + toString(size) + " from each group."); m->mothurOutEndLine();
870 for(int i = 0; i < Groups.size(); i++) {
871 total += groupMap->getNumSeqs(Groups[i]);
874 if (size == 0) { //user has not set size, set size = 10% samples size
875 size = int (total * 0.10);
879 m->mothurOut("Your size is too large for the number of groups you selected. Adjusting to " + toString(int (total * 0.10)) + "."); m->mothurOutEndLine();
880 size = int (total * 0.10);
883 m->mothurOut("Sampling " + toString(size) + " from " + toString(total) + "."); m->mothurOutEndLine();
886 if (size == 0) { //user has not set size, set size = 10% samples size
887 size = int (list->getNumSeqs() * 0.10);
890 int thisSize = list->getNumSeqs();
891 if (size > thisSize) { m->mothurOut("Your list file only contains " + toString(thisSize) + " sequences. Setting size to " + toString(thisSize) + "."); m->mothurOutEndLine();
895 m->mothurOut("Sampling " + toString(size) + " from " + toString(list->getNumSeqs()) + "."); m->mothurOutEndLine();
901 for (int i = 0; i < list->getNumBins(); i++) {
902 string binnames = list->get(i);
905 string individual = "";
906 int length = binnames.length();
907 for(int j=0;j<length;j++){
908 if(binnames[j] == ','){
910 if (groupfile != "") { //if there is a groupfile given fill in group info
911 string group = groupMap->getGroup(individual);
912 if (group == "not found") { m->mothurOut("[ERROR]: " + individual + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
914 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
915 if (m->inUsersGroups(group, Groups)) {
916 names.push_back(individual);
919 names.push_back(individual);
921 }else{ //save everyone, group
922 names.push_back(individual);
927 individual += binnames[j];
931 if (groupfile != "") { //if there is a groupfile given fill in group info
932 string group = groupMap->getGroup(individual);
933 if (group == "not found") { m->mothurOut("[ERROR]: " + individual + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
935 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
936 if (m->inUsersGroups(group, Groups)) {
937 names.push_back(individual);
940 names.push_back(individual);
942 }else{ //save everyone, group
943 names.push_back(individual);
947 random_shuffle(names.begin(), names.end());
949 //randomly select a subset of those names to include in the subsample
950 set<string> subset; //dont want repeat sequence names added
952 for (int i = 0; i < Groups.size(); i++) {
954 for (int j = 0; j < size; j++) {
956 if (m->control_pressed) { break; }
958 //get random sequence to add, making sure we have not already added it
962 myrand = (int)((float)(rand()) / (RAND_MAX / (names.size()-1) + 1));
964 if (subset.count(names[myrand]) == 0) { //you are not already added
965 if (groupMap->getGroup(names[myrand]) == Groups[i]) { subset.insert(names[myrand]); break; }
971 for (int j = 0; j < size; j++) {
973 if (m->control_pressed) { break; }
975 //get random sequence to add, making sure we have not already added it
979 myrand = (int)((float)(rand()) / (RAND_MAX / (names.size()-1) + 1));
981 if (subset.count(names[myrand]) == 0) { subset.insert(names[myrand]); break; }
986 if (groupfile != "") {
987 //write out new groupfile
988 for (set<string>::iterator it = subset.begin(); it != subset.end(); it++) {
989 string group = groupMap->getGroup(*it);
990 if (group == "not found") { group = "NOTFOUND"; }
992 outGroup << *it << '\t' << group << endl;
994 outGroup.close(); delete groupMap;
998 //as long as you are not at the end of the file or done wih the lines you want
999 while((list != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1001 if (m->control_pressed) { delete list; delete input; out.close(); return 0; }
1003 if(allLines == 1 || labels.count(list->getLabel()) == 1){
1005 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1007 processList(list, out, subset);
1009 processedLabels.insert(list->getLabel());
1010 userLabels.erase(list->getLabel());
1013 if ((m->anyLabelsToProcess(list->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1014 string saveLabel = list->getLabel();
1018 list = input->getListVector(lastLabel);
1019 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1021 processList(list, out, subset);
1023 processedLabels.insert(list->getLabel());
1024 userLabels.erase(list->getLabel());
1026 //restore real lastlabel to save below
1027 list->setLabel(saveLabel);
1030 lastLabel = list->getLabel();
1032 delete list; list = NULL;
1034 //get next line to process
1035 list = input->getListVector();
1039 if (m->control_pressed) { if (list != NULL) { delete list; } delete input; out.close(); return 0; }
1041 //output error messages about any remaining user labels
1042 set<string>::iterator it;
1043 bool needToRun = false;
1044 for (it = userLabels.begin(); it != userLabels.end(); it++) {
1045 m->mothurOut("Your file does not include the label " + *it);
1046 if (processedLabels.count(lastLabel) != 1) {
1047 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1050 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1054 //run last label if you need to
1055 if (needToRun == true) {
1056 if (list != NULL) { delete list; }
1058 list = input->getListVector(lastLabel);
1060 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1062 processList(list, out, subset);
1064 delete list; list = NULL;
1068 if (list != NULL) { delete list; }
1074 catch(exception& e) {
1075 m->errorOut(e, "SubSampleCommand", "getSubSampleList");
1079 //**********************************************************************************************************************
1080 int SubSampleCommand::processList(ListVector*& list, ofstream& out, set<string>& subset) {
1083 int numBins = list->getNumBins();
1085 ListVector* temp = new ListVector();
1086 temp->setLabel(list->getLabel());
1088 for (int i = 0; i < numBins; i++) {
1090 if (m->control_pressed) { break; }
1092 string binnames = list->get(i);
1095 string individual = "";
1096 string newNames = "";
1097 int length = binnames.length();
1098 for(int j=0;j<length;j++){
1099 if(binnames[j] == ','){
1100 if (subset.count(individual) != 0) { newNames += individual + ","; }
1103 individual += binnames[j];
1106 if (subset.count(individual) != 0) { newNames += individual; }
1109 //if there are names in this bin add to new list
1110 if (newNames != "") {
1111 newNames = newNames.substr(0, newNames.length()-1); //rip off extra comma
1112 temp->push_back(newNames);
1119 if (m->control_pressed) { return 0; }
1126 catch(exception& e) {
1127 m->errorOut(e, "SubSampleCommand", "processList");
1131 //**********************************************************************************************************************
1132 int SubSampleCommand::getSubSampleRabund() {
1135 string thisOutputDir = outputDir;
1136 if (outputDir == "") { thisOutputDir += m->hasPath(rabundfile); }
1137 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(rabundfile)) + "subsample" + m->getExtension(rabundfile);
1140 m->openOutputFile(outputFileName, out);
1141 outputTypes["rabund"].push_back(outputFileName); outputNames.push_back(outputFileName);
1143 InputData* input = new InputData(rabundfile, "rabund");
1144 RAbundVector* rabund = input->getRAbundVector();
1145 string lastLabel = rabund->getLabel();
1147 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1148 set<string> processedLabels;
1149 set<string> userLabels = labels;
1151 if (size == 0) { //user has not set size, set size = 10%
1152 size = int((rabund->getNumSeqs()) * 0.10);
1155 m->mothurOut("Sampling " + toString(size) + " from " + toString(rabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1157 //as long as you are not at the end of the file or done wih the lines you want
1158 while((rabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1159 if (m->control_pressed) { delete input; delete rabund; out.close(); return 0; }
1161 if(allLines == 1 || labels.count(rabund->getLabel()) == 1){
1163 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1165 processRabund(rabund, out);
1167 processedLabels.insert(rabund->getLabel());
1168 userLabels.erase(rabund->getLabel());
1171 if ((m->anyLabelsToProcess(rabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1172 string saveLabel = rabund->getLabel();
1176 rabund = input->getRAbundVector(lastLabel);
1177 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1179 processRabund(rabund, out);
1181 processedLabels.insert(rabund->getLabel());
1182 userLabels.erase(rabund->getLabel());
1184 //restore real lastlabel to save below
1185 rabund->setLabel(saveLabel);
1188 lastLabel = rabund->getLabel();
1190 //prevent memory leak
1191 delete rabund; rabund = NULL;
1193 //get next line to process
1194 rabund = input->getRAbundVector();
1198 if (m->control_pressed) { out.close(); return 0; }
1200 //output error messages about any remaining user labels
1201 set<string>::iterator it;
1202 bool needToRun = false;
1203 for (it = userLabels.begin(); it != userLabels.end(); it++) {
1204 m->mothurOut("Your file does not include the label " + *it);
1205 if (processedLabels.count(lastLabel) != 1) {
1206 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1209 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1213 //run last label if you need to
1214 if (needToRun == true) {
1215 if (rabund != NULL) { delete rabund; }
1217 rabund = input->getRAbundVector(lastLabel);
1219 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1221 processRabund(rabund, out);
1232 catch(exception& e) {
1233 m->errorOut(e, "SubSampleCommand", "getSubSampleRabund");
1237 //**********************************************************************************************************************
1238 int SubSampleCommand::processRabund(RAbundVector*& rabund, ofstream& out) {
1241 int numBins = rabund->getNumBins();
1242 int thisSize = rabund->getNumSeqs();
1244 if (thisSize != size) {
1246 OrderVector* order = new OrderVector();
1247 for(int p=0;p<numBins;p++){
1248 for(int j=0;j<rabund->get(p);j++){
1249 order->push_back(p);
1252 random_shuffle(order->begin(), order->end());
1254 RAbundVector* temp = new RAbundVector(numBins);
1255 temp->setLabel(rabund->getLabel());
1260 for (int j = 0; j < size; j++) {
1262 if (m->control_pressed) { delete order; return 0; }
1264 //get random number to sample from order between 0 and thisSize-1.
1265 int myrand = (int)((float)(rand()) / (RAND_MAX / (thisSize-1) + 1));
1267 int bin = order->get(myrand);
1269 int abund = rabund->get(bin);
1270 rabund->set(bin, (abund+1));
1276 if (m->control_pressed) { return 0; }
1283 catch(exception& e) {
1284 m->errorOut(e, "SubSampleCommand", "processRabund");
1288 //**********************************************************************************************************************
1289 int SubSampleCommand::getSubSampleSabund() {
1292 string thisOutputDir = outputDir;
1293 if (outputDir == "") { thisOutputDir += m->hasPath(sabundfile); }
1294 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(sabundfile)) + "subsample" + m->getExtension(sabundfile);
1297 m->openOutputFile(outputFileName, out);
1298 outputTypes["sabund"].push_back(outputFileName); outputNames.push_back(outputFileName);
1300 InputData* input = new InputData(sabundfile, "sabund");
1301 SAbundVector* sabund = input->getSAbundVector();
1302 string lastLabel = sabund->getLabel();
1304 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1305 set<string> processedLabels;
1306 set<string> userLabels = labels;
1308 if (size == 0) { //user has not set size, set size = 10%
1309 size = int((sabund->getNumSeqs()) * 0.10);
1312 m->mothurOut("Sampling " + toString(size) + " from " + toString(sabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1314 //as long as you are not at the end of the file or done wih the lines you want
1315 while((sabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1316 if (m->control_pressed) { delete input; delete sabund; out.close(); return 0; }
1318 if(allLines == 1 || labels.count(sabund->getLabel()) == 1){
1320 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1322 processSabund(sabund, out);
1324 processedLabels.insert(sabund->getLabel());
1325 userLabels.erase(sabund->getLabel());
1328 if ((m->anyLabelsToProcess(sabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1329 string saveLabel = sabund->getLabel();
1333 sabund = input->getSAbundVector(lastLabel);
1334 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1336 processSabund(sabund, out);
1338 processedLabels.insert(sabund->getLabel());
1339 userLabels.erase(sabund->getLabel());
1341 //restore real lastlabel to save below
1342 sabund->setLabel(saveLabel);
1345 lastLabel = sabund->getLabel();
1347 //prevent memory leak
1348 delete sabund; sabund = NULL;
1350 //get next line to process
1351 sabund = input->getSAbundVector();
1355 if (m->control_pressed) { out.close(); return 0; }
1357 //output error messages about any remaining user labels
1358 set<string>::iterator it;
1359 bool needToRun = false;
1360 for (it = userLabels.begin(); it != userLabels.end(); it++) {
1361 m->mothurOut("Your file does not include the label " + *it);
1362 if (processedLabels.count(lastLabel) != 1) {
1363 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1366 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1370 //run last label if you need to
1371 if (needToRun == true) {
1372 if (sabund != NULL) { delete sabund; }
1374 sabund = input->getSAbundVector(lastLabel);
1376 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1378 processSabund(sabund, out);
1389 catch(exception& e) {
1390 m->errorOut(e, "SubSampleCommand", "getSubSampleSabund");
1394 //**********************************************************************************************************************
1395 int SubSampleCommand::processSabund(SAbundVector*& sabund, ofstream& out) {
1398 RAbundVector* rabund = new RAbundVector();
1399 *rabund = sabund->getRAbundVector();
1401 int numBins = rabund->getNumBins();
1402 int thisSize = rabund->getNumSeqs();
1404 if (thisSize != size) {
1406 OrderVector* order = new OrderVector();
1407 for(int p=0;p<numBins;p++){
1408 for(int j=0;j<rabund->get(p);j++){
1409 order->push_back(p);
1412 random_shuffle(order->begin(), order->end());
1414 RAbundVector* temp = new RAbundVector(numBins);
1415 temp->setLabel(rabund->getLabel());
1420 for (int j = 0; j < size; j++) {
1422 if (m->control_pressed) { delete order; return 0; }
1424 //get random number to sample from order between 0 and thisSize-1.
1425 int myrand = (int)((float)(rand()) / (RAND_MAX / (thisSize-1) + 1));
1427 int bin = order->get(myrand);
1429 int abund = rabund->get(bin);
1430 rabund->set(bin, (abund+1));
1436 if (m->control_pressed) { return 0; }
1439 sabund = new SAbundVector();
1440 *sabund = rabund->getSAbundVector();
1448 catch(exception& e) {
1449 m->errorOut(e, "SubSampleCommand", "processSabund");
1453 //**********************************************************************************************************************
1454 int SubSampleCommand::eliminateZeroOTUS(vector<SharedRAbundVector*>& thislookup) {
1457 vector<SharedRAbundVector*> newLookup;
1458 for (int i = 0; i < thislookup.size(); i++) {
1459 SharedRAbundVector* temp = new SharedRAbundVector();
1460 temp->setLabel(thislookup[i]->getLabel());
1461 temp->setGroup(thislookup[i]->getGroup());
1462 newLookup.push_back(temp);
1466 for (int i = 0; i < thislookup[0]->getNumBins(); i++) {
1467 if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) { delete newLookup[j]; } return 0; }
1469 //look at each sharedRabund and make sure they are not all zero
1470 bool allZero = true;
1471 for (int j = 0; j < thislookup.size(); j++) {
1472 if (thislookup[j]->getAbundance(i) != 0) { allZero = false; break; }
1475 //if they are not all zero add this bin
1477 for (int j = 0; j < thislookup.size(); j++) {
1478 newLookup[j]->push_back(thislookup[j]->getAbundance(i), thislookup[j]->getGroup());
1483 for (int j = 0; j < thislookup.size(); j++) { delete thislookup[j]; }
1486 thislookup = newLookup;
1491 catch(exception& e) {
1492 m->errorOut(e, "SubSampleCommand", "eliminateZeroOTUS");
1497 //**********************************************************************************************************************