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::setParameters(){
16 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "FLSSR", "none",false,false); parameters.push_back(pfasta);
17 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
18 CommandParameter pgroup("group", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pgroup);
19 CommandParameter plist("list", "InputTypes", "", "", "none", "FLSSR", "none",false,false); parameters.push_back(plist);
20 CommandParameter pshared("shared", "InputTypes", "", "", "none", "FLSSR", "none",false,false); parameters.push_back(pshared);
21 CommandParameter prabund("rabund", "InputTypes", "", "", "none", "FLSSR", "none",false,false); parameters.push_back(prabund);
22 CommandParameter psabund("sabund", "InputTypes", "", "", "none", "FLSSR", "none",false,false); parameters.push_back(psabund);
23 CommandParameter plabel("label", "String", "", "", "", "", "",false,false); parameters.push_back(plabel);
24 CommandParameter pgroups("groups", "String", "", "", "", "", "",false,false); parameters.push_back(pgroups);
25 CommandParameter psize("size", "Number", "", "0", "", "", "",false,false); parameters.push_back(psize);
26 CommandParameter ppersample("persample", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(ppersample);
27 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
28 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
30 vector<string> myArray;
31 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
35 m->errorOut(e, "SubSampleCommand", "setParameters");
39 //**********************************************************************************************************************
40 string SubSampleCommand::getHelpString(){
42 string helpString = "";
43 helpString += "The sub.sample command is designed to be used as a way to normalize your data, or create a smaller set from your original set.\n";
44 helpString += "The sub.sample command parameters are fasta, name, list, group, rabund, sabund, shared, groups, size, persample and label. You must provide a fasta, list, sabund, rabund or shared file as an input file.\n";
45 helpString += "The namefile is only used with the fasta file, not with the listfile, because the list file should contain all sequences.\n";
46 helpString += "The groups parameter allows you to specify which of the groups in your groupfile you would like included. The group names are separated by dashes.\n";
47 helpString += "The label parameter allows you to select what distance levels you would like, and are also separated by dashes.\n";
48 helpString += "The size parameter allows you indicate the size of your subsample.\n";
49 helpString += "The persample parameter allows you indicate you want to select subsample of the same size from each of your groups, default=false. It is only used with the list and fasta files if a groupfile is given.\n";
50 helpString += "persample=false will select a random set of sequences of the size you select, but the number of seqs from each group may differ.\n";
51 helpString += "The size parameter is not set: with shared file size=number of seqs in smallest sample, with all other files if a groupfile is given and persample=true, then size=number of seqs in smallest sample, otherwise size=10% of number of seqs.\n";
52 helpString += "The sub.sample command should be in the following format: sub.sample(list=yourListFile, group=yourGroupFile, groups=yourGroups, label=yourLabels).\n";
53 helpString += "Example sub.sample(list=abrecovery.fn.list, group=abrecovery.groups, groups=B-C, size=20).\n";
54 helpString += "The default value for groups is all the groups in your groupfile, and all labels in your inputfile will be used.\n";
55 helpString += "The sub.sample command outputs a .subsample file.\n";
56 helpString += "Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n";
60 m->errorOut(e, "SubSampleCommand", "getHelpString");
64 //**********************************************************************************************************************
65 SubSampleCommand::SubSampleCommand(){
67 abort = true; calledHelp = true;
69 vector<string> tempOutNames;
70 outputTypes["shared"] = tempOutNames;
71 outputTypes["list"] = tempOutNames;
72 outputTypes["rabund"] = tempOutNames;
73 outputTypes["sabund"] = tempOutNames;
74 outputTypes["fasta"] = tempOutNames;
75 outputTypes["name"] = tempOutNames;
76 outputTypes["group"] = tempOutNames;
79 m->errorOut(e, "SubSampleCommand", "GetRelAbundCommand");
83 //**********************************************************************************************************************
84 SubSampleCommand::SubSampleCommand(string option) {
86 abort = false; calledHelp = false;
89 //allow user to run help
90 if(option == "help") { help(); abort = true; calledHelp = true; }
93 vector<string> myArray = setParameters();
95 OptionParser parser(option);
96 map<string,string> parameters = parser.getParameters();
98 ValidParameters validParameter;
100 //check to make sure all parameters are valid for command
101 map<string,string>::iterator it;
102 for (it = parameters.begin(); it != parameters.end(); it++) {
103 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
106 //initialize outputTypes
107 vector<string> tempOutNames;
108 outputTypes["shared"] = tempOutNames;
109 outputTypes["list"] = tempOutNames;
110 outputTypes["rabund"] = tempOutNames;
111 outputTypes["sabund"] = tempOutNames;
112 outputTypes["fasta"] = tempOutNames;
113 outputTypes["name"] = tempOutNames;
114 outputTypes["group"] = tempOutNames;
116 //if the user changes the output directory command factory will send this info to us in the output parameter
117 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
119 //if the user changes the input directory command factory will send this info to us in the output parameter
120 string inputDir = validParameter.validFile(parameters, "inputdir", false);
121 if (inputDir == "not found"){ inputDir = ""; }
124 it = parameters.find("list");
125 //user has given a template file
126 if(it != parameters.end()){
127 path = m->hasPath(it->second);
128 //if the user has not given a path then, add inputdir. else leave path alone.
129 if (path == "") { parameters["list"] = inputDir + it->second; }
132 it = parameters.find("fasta");
133 //user has given a template file
134 if(it != parameters.end()){
135 path = m->hasPath(it->second);
136 //if the user has not given a path then, add inputdir. else leave path alone.
137 if (path == "") { parameters["fasta"] = inputDir + it->second; }
140 it = parameters.find("shared");
141 //user has given a template file
142 if(it != parameters.end()){
143 path = m->hasPath(it->second);
144 //if the user has not given a path then, add inputdir. else leave path alone.
145 if (path == "") { parameters["shared"] = inputDir + it->second; }
148 it = parameters.find("group");
149 //user has given a template file
150 if(it != parameters.end()){
151 path = m->hasPath(it->second);
152 //if the user has not given a path then, add inputdir. else leave path alone.
153 if (path == "") { parameters["group"] = inputDir + it->second; }
156 it = parameters.find("sabund");
157 //user has given a template file
158 if(it != parameters.end()){
159 path = m->hasPath(it->second);
160 //if the user has not given a path then, add inputdir. else leave path alone.
161 if (path == "") { parameters["sabund"] = inputDir + it->second; }
164 it = parameters.find("rabund");
165 //user has given a template file
166 if(it != parameters.end()){
167 path = m->hasPath(it->second);
168 //if the user has not given a path then, add inputdir. else leave path alone.
169 if (path == "") { parameters["rabund"] = inputDir + it->second; }
172 it = parameters.find("name");
173 //user has given a template file
174 if(it != parameters.end()){
175 path = m->hasPath(it->second);
176 //if the user has not given a path then, add inputdir. else leave path alone.
177 if (path == "") { parameters["name"] = inputDir + it->second; }
181 //check for required parameters
182 listfile = validParameter.validFile(parameters, "list", true);
183 if (listfile == "not open") { listfile = ""; abort = true; }
184 else if (listfile == "not found") { listfile = ""; }
186 sabundfile = validParameter.validFile(parameters, "sabund", true);
187 if (sabundfile == "not open") { sabundfile = ""; abort = true; }
188 else if (sabundfile == "not found") { sabundfile = ""; }
190 rabundfile = validParameter.validFile(parameters, "rabund", true);
191 if (rabundfile == "not open") { rabundfile = ""; abort = true; }
192 else if (rabundfile == "not found") { rabundfile = ""; }
194 fastafile = validParameter.validFile(parameters, "fasta", true);
195 if (fastafile == "not open") { fastafile = ""; abort = true; }
196 else if (fastafile == "not found") { fastafile = ""; }
198 sharedfile = validParameter.validFile(parameters, "shared", true);
199 if (sharedfile == "not open") { sharedfile = ""; abort = true; }
200 else if (sharedfile == "not found") { sharedfile = ""; }
202 namefile = validParameter.validFile(parameters, "name", true);
203 if (namefile == "not open") { namefile = ""; abort = true; }
204 else if (namefile == "not found") { namefile = ""; }
206 groupfile = validParameter.validFile(parameters, "group", true);
207 if (groupfile == "not open") { groupfile = ""; abort = true; }
208 else if (groupfile == "not found") { groupfile = ""; }
211 //check for optional parameter and set defaults
212 // ...at some point should added some additional type checking...
213 label = validParameter.validFile(parameters, "label", false);
214 if (label == "not found") { label = ""; }
216 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
217 else { allLines = 1; }
220 groups = validParameter.validFile(parameters, "groups", false);
221 if (groups == "not found") { groups = ""; pickedGroups = false; }
224 m->splitAtDash(groups, Groups);
228 string temp = validParameter.validFile(parameters, "size", false); if (temp == "not found"){ temp = "0"; }
231 temp = validParameter.validFile(parameters, "persample", false); if (temp == "not found"){ temp = "f"; }
232 persample = m->isTrue(temp);
234 if (groupfile == "") { persample = false; }
236 if ((namefile != "") && (fastafile == "")) { m->mothurOut("You may only use a namefile with a fastafile."); m->mothurOutEndLine(); abort = true; }
238 if ((fastafile == "") && (listfile == "") && (sabundfile == "") && (rabundfile == "") && (sharedfile == "")) {
239 m->mothurOut("You must provide a fasta, list, sabund, rabund or shared file as an input file."); m->mothurOutEndLine(); abort = true; }
241 if (pickedGroups && ((groupfile == "") && (sharedfile == ""))) {
242 m->mothurOut("You cannot pick groups without a valid group file or shared file."); m->mothurOutEndLine(); abort = true; }
244 if ((groupfile != "") && ((fastafile == "") && (listfile == ""))) {
245 m->mothurOut("Group file only valid with listfile or fastafile."); m->mothurOutEndLine(); abort = true; }
247 if ((groupfile != "") && ((fastafile != "") && (listfile != ""))) {
248 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; }
253 catch(exception& e) {
254 m->errorOut(e, "SubSampleCommand", "SubSampleCommand");
258 //**********************************************************************************************************************
260 int SubSampleCommand::execute(){
263 if (abort == true) { if (calledHelp) { return 0; } return 2; }
265 if (sharedfile != "") { getSubSampleShared(); }
266 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); return 0; } }
268 if (listfile != "") { getSubSampleList(); }
269 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); return 0; } }
271 if (rabundfile != "") { getSubSampleRabund(); }
272 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); return 0; } }
274 if (sabundfile != "") { getSubSampleSabund(); }
275 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); return 0; } }
277 if (fastafile != "") { getSubSampleFasta(); }
278 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); return 0; } }
280 //set fasta file as new current fastafile
282 itTypes = outputTypes.find("fasta");
283 if (itTypes != outputTypes.end()) {
284 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
287 itTypes = outputTypes.find("name");
288 if (itTypes != outputTypes.end()) {
289 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
292 itTypes = outputTypes.find("group");
293 if (itTypes != outputTypes.end()) {
294 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setGroupFile(current); }
297 itTypes = outputTypes.find("list");
298 if (itTypes != outputTypes.end()) {
299 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setListFile(current); }
302 itTypes = outputTypes.find("shared");
303 if (itTypes != outputTypes.end()) {
304 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSharedFile(current); }
307 itTypes = outputTypes.find("rabund");
308 if (itTypes != outputTypes.end()) {
309 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setRabundFile(current); }
312 itTypes = outputTypes.find("sabund");
313 if (itTypes != outputTypes.end()) {
314 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSabundFile(current); }
318 m->mothurOutEndLine();
319 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
320 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
321 m->mothurOutEndLine();
325 catch(exception& e) {
326 m->errorOut(e, "SubSampleCommand", "execute");
330 //**********************************************************************************************************************
331 int SubSampleCommand::getSubSampleFasta() {
334 if (namefile != "") { readNames(); } //fills names with all names in namefile.
335 else { getNames(); }//no name file, so get list of names to pick from
338 if (groupfile != "") {
340 groupMap = new GroupMap(groupfile);
343 //takes care of user setting groupNames that are invalid or setting groups=all
344 SharedUtil* util = new SharedUtil();
345 util->setGroups(Groups, groupMap->namesOfGroups);
349 if (names.size() != groupMap->getNumSeqs()) {
350 m->mothurOut("[ERROR]: your fasta file contains " + toString(names.size()) + " sequences, and your groupfile contains " + toString(groupMap->getNumSeqs()) + ", please correct.");
351 m->mothurOutEndLine();
357 if (m->control_pressed) { return 0; }
359 string thisOutputDir = outputDir;
360 if (outputDir == "") { thisOutputDir += m->hasPath(fastafile); }
361 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(fastafile)) + "subsample" + m->getExtension(fastafile);
364 m->openOutputFile(outputFileName, out);
365 outputTypes["fasta"].push_back(outputFileName); outputNames.push_back(outputFileName);
367 //make sure that if your picked groups size is not too big
368 int thisSize = names.size();
370 if (size == 0) { //user has not set size, set size = smallest samples size
371 size = groupMap->getNumSeqs(Groups[0]);
372 for (int i = 1; i < Groups.size(); i++) {
373 int thisSize = groupMap->getNumSeqs(Groups[i]);
375 if (thisSize < size) { size = thisSize; }
377 }else { //make sure size is not too large
378 int smallestSize = groupMap->getNumSeqs(Groups[0]);
379 for (int i = 1; i < Groups.size(); i++) {
380 int thisSize = groupMap->getNumSeqs(Groups[i]);
382 if (thisSize < smallestSize) { smallestSize = thisSize; }
384 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(); }
387 m->mothurOut("Sampling " + toString(size) + " from each group."); m->mothurOutEndLine();
391 for(int i = 0; i < Groups.size(); i++) {
392 total += groupMap->getNumSeqs(Groups[i]);
395 if (size == 0) { //user has not set size, set size = 10% samples size
396 size = int (total * 0.10);
401 m->mothurOut("Your size is too large for the number of groups you selected. Adjusting to " + toString(int (total * 0.10)) + "."); m->mothurOutEndLine();
403 size = int (total * 0.10);
406 m->mothurOut("Sampling " + toString(size) + " from " + toString(total) + "."); m->mothurOutEndLine();
409 if (size == 0) { //user has not set size, set size = 10% samples size
410 size = int (names.size() * 0.10);
413 if (size > thisSize) { m->mothurOut("Your fasta file only contains " + toString(thisSize) + " sequences. Setting size to " + toString(thisSize) + "."); m->mothurOutEndLine();
417 if (!pickedGroups) { m->mothurOut("Sampling " + toString(size) + " from " + toString(thisSize) + "."); m->mothurOutEndLine(); }
420 random_shuffle(names.begin(), names.end());
422 set<string> subset; //dont want repeat sequence names added
424 for (int i = 0; i < Groups.size(); i++) {
426 //randomly select a subset of those names from this group to include in the subsample
427 for (int j = 0; j < size; j++) {
429 if (m->control_pressed) { return 0; }
431 //get random sequence to add, making sure we have not already added it
435 myrand = int((float)(thisSize) * (float)(rand()) / ((float)RAND_MAX+1.0));
437 if (subset.count(names[myrand]) == 0) {
439 string group = groupMap->getGroup(names[myrand]);
440 if (group == "not found") { m->mothurOut("[ERROR]: " + names[myrand] + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
442 if (group == Groups[i]) { subset.insert(names[myrand]); break; }
449 //randomly select a subset of those names to include in the subsample
450 for (int j = 0; j < size; j++) {
452 if (m->control_pressed) { return 0; }
454 //get random sequence to add, making sure we have not already added it
458 myrand = int((float)(thisSize) * (float)(rand()) / ((float)RAND_MAX+1.0));
460 if (subset.count(names[myrand]) == 0) {
462 if (groupfile != "") { //if there is a groupfile given fill in group info
463 string group = groupMap->getGroup(names[myrand]);
464 if (group == "not found") { m->mothurOut("[ERROR]: " + names[myrand] + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
466 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
467 if (m->inUsersGroups(group, Groups)) {
468 subset.insert(names[myrand]); break;
471 subset.insert(names[myrand]); break;
473 }else{ //save everyone, group
474 subset.insert(names[myrand]); break;
480 //read through fasta file outputting only the names on the subsample list
482 m->openInputFile(fastafile, in);
486 map<string, vector<string> >::iterator itNameMap;
490 if (m->control_pressed) { in.close(); out.close(); return 0; }
492 Sequence currSeq(in);
493 thisname = currSeq.getName();
495 if (thisname != "") {
497 //does the subset contain a sequence that this sequence represents
498 itNameMap = nameMap.find(thisname);
499 if (itNameMap != nameMap.end()) {
500 vector<string> nameRepresents = itNameMap->second;
502 for (int i = 0; i < nameRepresents.size(); i++){
503 if (subset.count(nameRepresents[i]) != 0) {
504 out << ">" << nameRepresents[i] << endl << currSeq.getAligned() << endl;
509 m->mothurOut("[ERROR]: " + thisname + " is not in your namefile, please correct."); m->mothurOutEndLine();
517 if (count != subset.size()) {
518 m->mothurOut("[ERROR]: The subset selected contained " + toString(subset.size()) + " sequences, but I only found " + toString(count) + " of those in the fastafile."); m->mothurOutEndLine();
521 //if a groupfile is provided read through the group file only outputting the names on the subsample list
522 if (groupfile != "") {
524 string groupOutputDir = outputDir;
525 if (outputDir == "") { groupOutputDir += m->hasPath(groupfile); }
526 string groupOutputFileName = groupOutputDir + m->getRootName(m->getSimpleName(groupfile)) + "subsample" + m->getExtension(groupfile);
529 m->openOutputFile(groupOutputFileName, outGroup);
530 outputTypes["group"].push_back(groupOutputFileName); outputNames.push_back(groupOutputFileName);
533 m->openInputFile(groupfile, inGroup);
536 while(!inGroup.eof()){
538 if (m->control_pressed) { inGroup.close(); outGroup.close(); return 0; }
540 inGroup >> name; m->gobble(inGroup); //read from first column
541 inGroup >> group; //read from second column
543 //if this name is in the accnos file
544 if (subset.count(name) != 0) {
545 outGroup << name << '\t' << group << endl;
555 if (subset.size() != 0) {
556 m->mothurOut("Your groupfile does not match your fasta file."); m->mothurOutEndLine();
557 for (set<string>::iterator it = subset.begin(); it != subset.end(); it++) {
558 m->mothurOut("[ERROR]: " + *it + " is missing from your groupfile."); m->mothurOutEndLine();
566 catch(exception& e) {
567 m->errorOut(e, "SubSampleCommand", "getSubSampleFasta");
571 //**********************************************************************************************************************
572 int SubSampleCommand::getNames() {
576 m->openInputFile(fastafile, in);
581 if (m->control_pressed) { in.close(); return 0; }
583 Sequence currSeq(in);
584 thisname = currSeq.getName();
586 if (thisname != "") {
587 vector<string> temp; temp.push_back(thisname);
588 nameMap[thisname] = temp;
589 names.push_back(thisname);
598 catch(exception& e) {
599 m->errorOut(e, "SubSampleCommand", "getNames");
603 //**********************************************************************************************************************
604 int SubSampleCommand::readNames() {
608 m->openInputFile(namefile, in);
610 string thisname, repnames;
611 map<string, vector<string> >::iterator it;
615 if (m->control_pressed) { in.close(); return 0; }
617 in >> thisname; m->gobble(in); //read from first column
618 in >> repnames; //read from second column
620 it = nameMap.find(thisname);
621 if (it == nameMap.end()) {
623 vector<string> splitRepNames;
624 m->splitAtComma(repnames, splitRepNames);
626 nameMap[thisname] = splitRepNames;
627 for (int i = 0; i < splitRepNames.size(); i++) { names.push_back(splitRepNames[i]); }
629 }else{ m->mothurOut(thisname + " is already in namesfile. I will use first definition."); m->mothurOutEndLine(); }
638 catch(exception& e) {
639 m->errorOut(e, "SubSampleCommand", "readNames");
643 //**********************************************************************************************************************
644 int SubSampleCommand::getSubSampleShared() {
647 string thisOutputDir = outputDir;
648 if (outputDir == "") { thisOutputDir += m->hasPath(sharedfile); }
649 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(sharedfile)) + "subsample" + m->getExtension(sharedfile);
652 m->openOutputFile(outputFileName, out);
653 outputTypes["shared"].push_back(outputFileName); outputNames.push_back(outputFileName);
655 InputData* input = new InputData(sharedfile, "sharedfile");
656 vector<SharedRAbundVector*> lookup = input->getSharedRAbundVectors();
657 string lastLabel = lookup[0]->getLabel();
659 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
660 set<string> processedLabels;
661 set<string> userLabels = labels;
663 if (size == 0) { //user has not set size, set size = smallest samples size
664 size = lookup[0]->getNumSeqs();
665 for (int i = 1; i < lookup.size(); i++) {
666 int thisSize = lookup[i]->getNumSeqs();
668 if (thisSize < size) { size = thisSize; }
672 m->mothurOut("Sampling " + toString(size) + " from " + toString(lookup[0]->getNumSeqs()) + "."); m->mothurOutEndLine();
674 //as long as you are not at the end of the file or done wih the lines you want
675 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
676 if (m->control_pressed) { delete input; for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; lookup[i] = NULL; } out.close(); return 0; }
678 if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){
680 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
682 processShared(lookup, out);
684 processedLabels.insert(lookup[0]->getLabel());
685 userLabels.erase(lookup[0]->getLabel());
688 if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
689 string saveLabel = lookup[0]->getLabel();
691 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
693 lookup = input->getSharedRAbundVectors(lastLabel);
694 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
696 processShared(lookup, out);
698 processedLabels.insert(lookup[0]->getLabel());
699 userLabels.erase(lookup[0]->getLabel());
701 //restore real lastlabel to save below
702 lookup[0]->setLabel(saveLabel);
705 lastLabel = lookup[0]->getLabel();
706 //prevent memory leak
707 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; lookup[i] = NULL; }
709 //get next line to process
710 lookup = input->getSharedRAbundVectors();
714 if (m->control_pressed) { out.close(); return 0; }
716 //output error messages about any remaining user labels
717 set<string>::iterator it;
718 bool needToRun = false;
719 for (it = userLabels.begin(); it != userLabels.end(); it++) {
720 m->mothurOut("Your file does not include the label " + *it);
721 if (processedLabels.count(lastLabel) != 1) {
722 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
725 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
729 //run last label if you need to
730 if (needToRun == true) {
731 for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }
732 lookup = input->getSharedRAbundVectors(lastLabel);
734 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
736 processShared(lookup, out);
738 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
747 catch(exception& e) {
748 m->errorOut(e, "SubSampleCommand", "getSubSampleShared");
752 //**********************************************************************************************************************
753 int SubSampleCommand::processShared(vector<SharedRAbundVector*>& thislookup, ofstream& out) {
756 int numBins = thislookup[0]->getNumBins();
757 for (int i = 0; i < thislookup.size(); i++) {
758 int thisSize = thislookup[i]->getNumSeqs();
760 if (thisSize != size) {
762 string thisgroup = thislookup[i]->getGroup();
764 OrderVector* order = new OrderVector();
765 for(int p=0;p<numBins;p++){
766 for(int j=0;j<thislookup[i]->getAbundance(p);j++){
770 random_shuffle(order->begin(), order->end());
772 SharedRAbundVector* temp = new SharedRAbundVector(numBins);
773 temp->setLabel(thislookup[i]->getLabel());
774 temp->setGroup(thislookup[i]->getGroup());
776 delete thislookup[i];
777 thislookup[i] = temp;
780 for (int j = 0; j < size; j++) {
782 if (m->control_pressed) { delete order; return 0; }
784 //get random number to sample from order between 0 and thisSize-1.
785 int myrand = int((float)(thisSize) * (float)(rand()) / ((float)RAND_MAX+1.0));
787 int bin = order->get(myrand);
789 int abund = thislookup[i]->getAbundance(bin);
790 thislookup[i]->set(bin, (abund+1), thisgroup);
796 //subsampling may have created some otus with no sequences in them
797 eliminateZeroOTUS(thislookup);
799 if (m->control_pressed) { return 0; }
801 for (int i = 0; i < thislookup.size(); i++) {
802 out << thislookup[i]->getLabel() << '\t' << thislookup[i]->getGroup() << '\t';
803 thislookup[i]->print(out);
809 catch(exception& e) {
810 m->errorOut(e, "SubSampleCommand", "processShared");
814 //**********************************************************************************************************************
815 int SubSampleCommand::getSubSampleList() {
818 string thisOutputDir = outputDir;
819 if (outputDir == "") { thisOutputDir += m->hasPath(listfile); }
820 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(listfile)) + "subsample" + m->getExtension(listfile);
823 m->openOutputFile(outputFileName, out);
824 outputTypes["list"].push_back(outputFileName); outputNames.push_back(outputFileName);
826 InputData* input = new InputData(listfile, "list");
827 ListVector* list = input->getListVector();
828 string lastLabel = list->getLabel();
830 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
831 set<string> processedLabels;
832 set<string> userLabels = labels;
836 if (groupfile != "") {
838 groupMap = new GroupMap(groupfile);
841 //takes care of user setting groupNames that are invalid or setting groups=all
842 SharedUtil* util = new SharedUtil();
843 util->setGroups(Groups, groupMap->namesOfGroups);
847 string groupOutputDir = outputDir;
848 if (outputDir == "") { groupOutputDir += m->hasPath(groupfile); }
849 string groupOutputFileName = groupOutputDir + m->getRootName(m->getSimpleName(groupfile)) + "subsample" + m->getExtension(groupfile);
851 m->openOutputFile(groupOutputFileName, outGroup);
852 outputTypes["group"].push_back(groupOutputFileName); outputNames.push_back(groupOutputFileName);
855 if (list->getNumSeqs() != groupMap->getNumSeqs()) {
856 m->mothurOut("[ERROR]: your list file contains " + toString(list->getNumSeqs()) + " sequences, and your groupfile contains " + toString(groupMap->getNumSeqs()) + ", please correct.");
857 m->mothurOutEndLine();
867 //make sure that if your picked groups size is not too big
869 if (size == 0) { //user has not set size, set size = smallest samples size
870 size = groupMap->getNumSeqs(Groups[0]);
871 for (int i = 1; i < Groups.size(); i++) {
872 int thisSize = groupMap->getNumSeqs(Groups[i]);
874 if (thisSize < size) { size = thisSize; }
876 }else { //make sure size is not too large
877 int smallestSize = groupMap->getNumSeqs(Groups[0]);
878 for (int i = 1; i < Groups.size(); i++) {
879 int thisSize = groupMap->getNumSeqs(Groups[i]);
881 if (thisSize < smallestSize) { smallestSize = thisSize; }
883 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(); }
886 m->mothurOut("Sampling " + toString(size) + " from each group."); m->mothurOutEndLine();
890 for(int i = 0; i < Groups.size(); i++) {
891 total += groupMap->getNumSeqs(Groups[i]);
894 if (size == 0) { //user has not set size, set size = 10% samples size
895 size = int (total * 0.10);
899 m->mothurOut("Your size is too large for the number of groups you selected. Adjusting to " + toString(int (total * 0.10)) + "."); m->mothurOutEndLine();
900 size = int (total * 0.10);
903 m->mothurOut("Sampling " + toString(size) + " from " + toString(total) + "."); m->mothurOutEndLine();
906 if (size == 0) { //user has not set size, set size = 10% samples size
907 size = int (list->getNumSeqs() * 0.10);
910 int thisSize = list->getNumSeqs();
911 if (size > thisSize) { m->mothurOut("Your list file only contains " + toString(thisSize) + " sequences. Setting size to " + toString(thisSize) + "."); m->mothurOutEndLine();
915 m->mothurOut("Sampling " + toString(size) + " from " + toString(list->getNumSeqs()) + "."); m->mothurOutEndLine();
921 for (int i = 0; i < list->getNumBins(); i++) {
922 string binnames = list->get(i);
925 string individual = "";
926 int length = binnames.length();
927 for(int j=0;j<length;j++){
928 if(binnames[j] == ','){
930 if (groupfile != "") { //if there is a groupfile given fill in group info
931 string group = groupMap->getGroup(individual);
932 if (group == "not found") { m->mothurOut("[ERROR]: " + individual + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
934 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
935 if (m->inUsersGroups(group, Groups)) {
936 names.push_back(individual);
939 names.push_back(individual);
941 }else{ //save everyone, group
942 names.push_back(individual);
947 individual += binnames[j];
951 if (groupfile != "") { //if there is a groupfile given fill in group info
952 string group = groupMap->getGroup(individual);
953 if (group == "not found") { m->mothurOut("[ERROR]: " + individual + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
955 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
956 if (m->inUsersGroups(group, Groups)) {
957 names.push_back(individual);
960 names.push_back(individual);
962 }else{ //save everyone, group
963 names.push_back(individual);
967 random_shuffle(names.begin(), names.end());
969 //randomly select a subset of those names to include in the subsample
970 set<string> subset; //dont want repeat sequence names added
972 for (int i = 0; i < Groups.size(); i++) {
974 for (int j = 0; j < size; j++) {
976 if (m->control_pressed) { break; }
978 //get random sequence to add, making sure we have not already added it
982 myrand = int((float)(names.size()) * (float)(rand()) / ((float)RAND_MAX+1.0));
984 if (subset.count(names[myrand]) == 0) { //you are not already added
985 if (groupMap->getGroup(names[myrand]) == Groups[i]) { subset.insert(names[myrand]); break; }
991 for (int j = 0; j < size; j++) {
993 if (m->control_pressed) { break; }
995 //get random sequence to add, making sure we have not already added it
999 myrand = int((float)(names.size()) * (float)(rand()) / ((float)RAND_MAX+1.0));
1001 if (subset.count(names[myrand]) == 0) { subset.insert(names[myrand]); break; }
1006 if (groupfile != "") {
1007 //write out new groupfile
1008 for (set<string>::iterator it = subset.begin(); it != subset.end(); it++) {
1009 string group = groupMap->getGroup(*it);
1010 if (group == "not found") { group = "NOTFOUND"; }
1012 outGroup << *it << '\t' << group << endl;
1014 outGroup.close(); delete groupMap;
1018 //as long as you are not at the end of the file or done wih the lines you want
1019 while((list != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1021 if (m->control_pressed) { delete list; delete input; out.close(); return 0; }
1023 if(allLines == 1 || labels.count(list->getLabel()) == 1){
1025 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1027 processList(list, out, subset);
1029 processedLabels.insert(list->getLabel());
1030 userLabels.erase(list->getLabel());
1033 if ((m->anyLabelsToProcess(list->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1034 string saveLabel = list->getLabel();
1038 list = input->getListVector(lastLabel);
1039 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1041 processList(list, out, subset);
1043 processedLabels.insert(list->getLabel());
1044 userLabels.erase(list->getLabel());
1046 //restore real lastlabel to save below
1047 list->setLabel(saveLabel);
1050 lastLabel = list->getLabel();
1052 delete list; list = NULL;
1054 //get next line to process
1055 list = input->getListVector();
1059 if (m->control_pressed) { if (list != NULL) { delete list; } delete input; out.close(); return 0; }
1061 //output error messages about any remaining user labels
1062 set<string>::iterator it;
1063 bool needToRun = false;
1064 for (it = userLabels.begin(); it != userLabels.end(); it++) {
1065 m->mothurOut("Your file does not include the label " + *it);
1066 if (processedLabels.count(lastLabel) != 1) {
1067 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1070 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1074 //run last label if you need to
1075 if (needToRun == true) {
1076 if (list != NULL) { delete list; }
1078 list = input->getListVector(lastLabel);
1080 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1082 processList(list, out, subset);
1084 delete list; list = NULL;
1088 if (list != NULL) { delete list; }
1094 catch(exception& e) {
1095 m->errorOut(e, "SubSampleCommand", "getSubSampleList");
1099 //**********************************************************************************************************************
1100 int SubSampleCommand::processList(ListVector*& list, ofstream& out, set<string>& subset) {
1103 int numBins = list->getNumBins();
1105 ListVector* temp = new ListVector();
1106 temp->setLabel(list->getLabel());
1108 for (int i = 0; i < numBins; i++) {
1110 if (m->control_pressed) { break; }
1112 string binnames = list->get(i);
1115 string individual = "";
1116 string newNames = "";
1117 int length = binnames.length();
1118 for(int j=0;j<length;j++){
1119 if(binnames[j] == ','){
1120 if (subset.count(individual) != 0) { newNames += individual + ","; }
1123 individual += binnames[j];
1126 if (subset.count(individual) != 0) { newNames += individual; }
1129 //if there are names in this bin add to new list
1130 if (newNames != "") {
1131 newNames = newNames.substr(0, newNames.length()-1); //rip off extra comma
1132 temp->push_back(newNames);
1139 if (m->control_pressed) { return 0; }
1146 catch(exception& e) {
1147 m->errorOut(e, "SubSampleCommand", "processList");
1151 //**********************************************************************************************************************
1152 int SubSampleCommand::getSubSampleRabund() {
1155 string thisOutputDir = outputDir;
1156 if (outputDir == "") { thisOutputDir += m->hasPath(rabundfile); }
1157 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(rabundfile)) + "subsample" + m->getExtension(rabundfile);
1160 m->openOutputFile(outputFileName, out);
1161 outputTypes["rabund"].push_back(outputFileName); outputNames.push_back(outputFileName);
1163 InputData* input = new InputData(rabundfile, "rabund");
1164 RAbundVector* rabund = input->getRAbundVector();
1165 string lastLabel = rabund->getLabel();
1167 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1168 set<string> processedLabels;
1169 set<string> userLabels = labels;
1171 if (size == 0) { //user has not set size, set size = 10%
1172 size = int((rabund->getNumSeqs()) * 0.10);
1175 m->mothurOut("Sampling " + toString(size) + " from " + toString(rabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1177 //as long as you are not at the end of the file or done wih the lines you want
1178 while((rabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1179 if (m->control_pressed) { delete input; delete rabund; out.close(); return 0; }
1181 if(allLines == 1 || labels.count(rabund->getLabel()) == 1){
1183 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1185 processRabund(rabund, out);
1187 processedLabels.insert(rabund->getLabel());
1188 userLabels.erase(rabund->getLabel());
1191 if ((m->anyLabelsToProcess(rabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1192 string saveLabel = rabund->getLabel();
1196 rabund = input->getRAbundVector(lastLabel);
1197 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1199 processRabund(rabund, out);
1201 processedLabels.insert(rabund->getLabel());
1202 userLabels.erase(rabund->getLabel());
1204 //restore real lastlabel to save below
1205 rabund->setLabel(saveLabel);
1208 lastLabel = rabund->getLabel();
1210 //prevent memory leak
1211 delete rabund; rabund = NULL;
1213 //get next line to process
1214 rabund = input->getRAbundVector();
1218 if (m->control_pressed) { out.close(); return 0; }
1220 //output error messages about any remaining user labels
1221 set<string>::iterator it;
1222 bool needToRun = false;
1223 for (it = userLabels.begin(); it != userLabels.end(); it++) {
1224 m->mothurOut("Your file does not include the label " + *it);
1225 if (processedLabels.count(lastLabel) != 1) {
1226 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1229 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1233 //run last label if you need to
1234 if (needToRun == true) {
1235 if (rabund != NULL) { delete rabund; }
1237 rabund = input->getRAbundVector(lastLabel);
1239 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1241 processRabund(rabund, out);
1252 catch(exception& e) {
1253 m->errorOut(e, "SubSampleCommand", "getSubSampleRabund");
1257 //**********************************************************************************************************************
1258 int SubSampleCommand::processRabund(RAbundVector*& rabund, ofstream& out) {
1261 int numBins = rabund->getNumBins();
1262 int thisSize = rabund->getNumSeqs();
1264 if (thisSize != size) {
1266 OrderVector* order = new OrderVector();
1267 for(int p=0;p<numBins;p++){
1268 for(int j=0;j<rabund->get(p);j++){
1269 order->push_back(p);
1272 random_shuffle(order->begin(), order->end());
1274 RAbundVector* temp = new RAbundVector(numBins);
1275 temp->setLabel(rabund->getLabel());
1280 for (int j = 0; j < size; j++) {
1282 if (m->control_pressed) { delete order; return 0; }
1284 //get random number to sample from order between 0 and thisSize-1.
1285 int myrand = int((float)(thisSize) * (float)(rand()) / ((float)RAND_MAX+1.0));
1287 int bin = order->get(myrand);
1289 int abund = rabund->get(bin);
1290 rabund->set(bin, (abund+1));
1296 if (m->control_pressed) { return 0; }
1303 catch(exception& e) {
1304 m->errorOut(e, "SubSampleCommand", "processRabund");
1308 //**********************************************************************************************************************
1309 int SubSampleCommand::getSubSampleSabund() {
1312 string thisOutputDir = outputDir;
1313 if (outputDir == "") { thisOutputDir += m->hasPath(sabundfile); }
1314 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(sabundfile)) + "subsample" + m->getExtension(sabundfile);
1317 m->openOutputFile(outputFileName, out);
1318 outputTypes["sabund"].push_back(outputFileName); outputNames.push_back(outputFileName);
1320 InputData* input = new InputData(sabundfile, "sabund");
1321 SAbundVector* sabund = input->getSAbundVector();
1322 string lastLabel = sabund->getLabel();
1324 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1325 set<string> processedLabels;
1326 set<string> userLabels = labels;
1328 if (size == 0) { //user has not set size, set size = 10%
1329 size = int((sabund->getNumSeqs()) * 0.10);
1332 m->mothurOut("Sampling " + toString(size) + " from " + toString(sabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1334 //as long as you are not at the end of the file or done wih the lines you want
1335 while((sabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1336 if (m->control_pressed) { delete input; delete sabund; out.close(); return 0; }
1338 if(allLines == 1 || labels.count(sabund->getLabel()) == 1){
1340 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1342 processSabund(sabund, out);
1344 processedLabels.insert(sabund->getLabel());
1345 userLabels.erase(sabund->getLabel());
1348 if ((m->anyLabelsToProcess(sabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1349 string saveLabel = sabund->getLabel();
1353 sabund = input->getSAbundVector(lastLabel);
1354 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1356 processSabund(sabund, out);
1358 processedLabels.insert(sabund->getLabel());
1359 userLabels.erase(sabund->getLabel());
1361 //restore real lastlabel to save below
1362 sabund->setLabel(saveLabel);
1365 lastLabel = sabund->getLabel();
1367 //prevent memory leak
1368 delete sabund; sabund = NULL;
1370 //get next line to process
1371 sabund = input->getSAbundVector();
1375 if (m->control_pressed) { out.close(); return 0; }
1377 //output error messages about any remaining user labels
1378 set<string>::iterator it;
1379 bool needToRun = false;
1380 for (it = userLabels.begin(); it != userLabels.end(); it++) {
1381 m->mothurOut("Your file does not include the label " + *it);
1382 if (processedLabels.count(lastLabel) != 1) {
1383 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1386 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1390 //run last label if you need to
1391 if (needToRun == true) {
1392 if (sabund != NULL) { delete sabund; }
1394 sabund = input->getSAbundVector(lastLabel);
1396 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1398 processSabund(sabund, out);
1409 catch(exception& e) {
1410 m->errorOut(e, "SubSampleCommand", "getSubSampleSabund");
1414 //**********************************************************************************************************************
1415 int SubSampleCommand::processSabund(SAbundVector*& sabund, ofstream& out) {
1418 RAbundVector* rabund = new RAbundVector();
1419 *rabund = sabund->getRAbundVector();
1421 int numBins = rabund->getNumBins();
1422 int thisSize = rabund->getNumSeqs();
1424 if (thisSize != size) {
1426 OrderVector* order = new OrderVector();
1427 for(int p=0;p<numBins;p++){
1428 for(int j=0;j<rabund->get(p);j++){
1429 order->push_back(p);
1432 random_shuffle(order->begin(), order->end());
1434 RAbundVector* temp = new RAbundVector(numBins);
1435 temp->setLabel(rabund->getLabel());
1440 for (int j = 0; j < size; j++) {
1442 if (m->control_pressed) { delete order; return 0; }
1444 //get random number to sample from order between 0 and thisSize-1.
1445 int myrand = int((float)(thisSize) * (float)(rand()) / ((float)RAND_MAX+1.0));
1447 int bin = order->get(myrand);
1449 int abund = rabund->get(bin);
1450 rabund->set(bin, (abund+1));
1456 if (m->control_pressed) { return 0; }
1459 sabund = new SAbundVector();
1460 *sabund = rabund->getSAbundVector();
1468 catch(exception& e) {
1469 m->errorOut(e, "SubSampleCommand", "processSabund");
1473 //**********************************************************************************************************************
1474 int SubSampleCommand::eliminateZeroOTUS(vector<SharedRAbundVector*>& thislookup) {
1477 vector<SharedRAbundVector*> newLookup;
1478 for (int i = 0; i < thislookup.size(); i++) {
1479 SharedRAbundVector* temp = new SharedRAbundVector();
1480 temp->setLabel(thislookup[i]->getLabel());
1481 temp->setGroup(thislookup[i]->getGroup());
1482 newLookup.push_back(temp);
1486 for (int i = 0; i < thislookup[0]->getNumBins(); i++) {
1487 if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) { delete newLookup[j]; } return 0; }
1489 //look at each sharedRabund and make sure they are not all zero
1490 bool allZero = true;
1491 for (int j = 0; j < thislookup.size(); j++) {
1492 if (thislookup[j]->getAbundance(i) != 0) { allZero = false; break; }
1495 //if they are not all zero add this bin
1497 for (int j = 0; j < thislookup.size(); j++) {
1498 newLookup[j]->push_back(thislookup[j]->getAbundance(i), thislookup[j]->getGroup());
1503 for (int j = 0; j < thislookup.size(); j++) { delete thislookup[j]; }
1506 thislookup = newLookup;
1511 catch(exception& e) {
1512 m->errorOut(e, "SubSampleCommand", "eliminateZeroOTUS");
1517 //**********************************************************************************************************************