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; } }
298 //set fasta file as new current fastafile
300 itTypes = outputTypes.find("fasta");
301 if (itTypes != outputTypes.end()) {
302 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
305 itTypes = outputTypes.find("name");
306 if (itTypes != outputTypes.end()) {
307 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
310 itTypes = outputTypes.find("group");
311 if (itTypes != outputTypes.end()) {
312 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setGroupFile(current); }
315 itTypes = outputTypes.find("list");
316 if (itTypes != outputTypes.end()) {
317 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setListFile(current); }
320 itTypes = outputTypes.find("shared");
321 if (itTypes != outputTypes.end()) {
322 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSharedFile(current); }
325 itTypes = outputTypes.find("rabund");
326 if (itTypes != outputTypes.end()) {
327 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setRabundFile(current); }
330 itTypes = outputTypes.find("sabund");
331 if (itTypes != outputTypes.end()) {
332 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSabundFile(current); }
336 m->mothurOutEndLine();
337 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
338 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
339 m->mothurOutEndLine();
343 catch(exception& e) {
344 m->errorOut(e, "SubSampleCommand", "execute");
348 //**********************************************************************************************************************
349 int SubSampleCommand::getSubSampleFasta() {
352 if (namefile != "") { readNames(); } //fills names with all names in namefile.
353 else { getNames(); }//no name file, so get list of names to pick from
356 if (groupfile != "") {
358 groupMap = new GroupMap(groupfile);
361 //takes care of user setting groupNames that are invalid or setting groups=all
362 SharedUtil* util = new SharedUtil();
363 util->setGroups(Groups, groupMap->namesOfGroups);
367 if (names.size() != groupMap->getNumSeqs()) {
368 m->mothurOut("[ERROR]: your fasta file contains " + toString(names.size()) + " sequences, and your groupfile contains " + toString(groupMap->getNumSeqs()) + ", please correct.");
369 m->mothurOutEndLine();
375 if (m->control_pressed) { return 0; }
377 string thisOutputDir = outputDir;
378 if (outputDir == "") { thisOutputDir += m->hasPath(fastafile); }
379 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(fastafile)) + "subsample" + m->getExtension(fastafile);
382 m->openOutputFile(outputFileName, out);
383 outputTypes["fasta"].push_back(outputFileName); outputNames.push_back(outputFileName);
385 //make sure that if your picked groups size is not too big
386 int thisSize = names.size();
388 if (size == 0) { //user has not set size, set size = smallest samples size
389 size = groupMap->getNumSeqs(Groups[0]);
390 for (int i = 1; i < Groups.size(); i++) {
391 int thisSize = groupMap->getNumSeqs(Groups[i]);
393 if (thisSize < size) { size = thisSize; }
395 }else { //make sure size is not too large
396 int smallestSize = groupMap->getNumSeqs(Groups[0]);
397 for (int i = 1; i < Groups.size(); i++) {
398 int thisSize = groupMap->getNumSeqs(Groups[i]);
400 if (thisSize < smallestSize) { smallestSize = thisSize; }
402 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(); }
405 m->mothurOut("Sampling " + toString(size) + " from each group."); m->mothurOutEndLine();
409 for(int i = 0; i < Groups.size(); i++) {
410 total += groupMap->getNumSeqs(Groups[i]);
413 if (size == 0) { //user has not set size, set size = 10% samples size
414 size = int (total * 0.10);
419 m->mothurOut("Your size is too large for the number of groups you selected. Adjusting to " + toString(int (total * 0.10)) + "."); m->mothurOutEndLine();
421 size = int (total * 0.10);
424 m->mothurOut("Sampling " + toString(size) + " from " + toString(total) + "."); m->mothurOutEndLine();
427 if (size == 0) { //user has not set size, set size = 10% samples size
428 size = int (names.size() * 0.10);
431 if (size > thisSize) { m->mothurOut("Your fasta file only contains " + toString(thisSize) + " sequences. Setting size to " + toString(thisSize) + "."); m->mothurOutEndLine();
435 if (!pickedGroups) { m->mothurOut("Sampling " + toString(size) + " from " + toString(thisSize) + "."); m->mothurOutEndLine(); }
438 random_shuffle(names.begin(), names.end());
440 set<string> subset; //dont want repeat sequence names added
442 for (int i = 0; i < Groups.size(); i++) {
444 //randomly select a subset of those names from this group to include in the subsample
445 for (int j = 0; j < size; j++) {
447 if (m->control_pressed) { return 0; }
449 //get random sequence to add, making sure we have not already added it
453 myrand = int((float)(thisSize) * (float)(rand()) / ((float)RAND_MAX+1.0));
455 if (subset.count(names[myrand]) == 0) {
457 string group = groupMap->getGroup(names[myrand]);
458 if (group == "not found") { m->mothurOut("[ERROR]: " + names[myrand] + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
460 if (group == Groups[i]) { subset.insert(names[myrand]); break; }
467 //randomly select a subset of those names to include in the subsample
468 for (int j = 0; j < size; j++) {
470 if (m->control_pressed) { return 0; }
472 //get random sequence to add, making sure we have not already added it
476 myrand = int((float)(thisSize) * (float)(rand()) / ((float)RAND_MAX+1.0));
478 if (subset.count(names[myrand]) == 0) {
480 if (groupfile != "") { //if there is a groupfile given fill in group info
481 string group = groupMap->getGroup(names[myrand]);
482 if (group == "not found") { m->mothurOut("[ERROR]: " + names[myrand] + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
484 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
485 if (m->inUsersGroups(group, Groups)) {
486 subset.insert(names[myrand]); break;
489 subset.insert(names[myrand]); break;
491 }else{ //save everyone, group
492 subset.insert(names[myrand]); break;
498 //read through fasta file outputting only the names on the subsample list
500 m->openInputFile(fastafile, in);
504 map<string, vector<string> >::iterator itNameMap;
508 if (m->control_pressed) { in.close(); out.close(); return 0; }
510 Sequence currSeq(in);
511 thisname = currSeq.getName();
513 if (thisname != "") {
515 //does the subset contain a sequence that this sequence represents
516 itNameMap = nameMap.find(thisname);
517 if (itNameMap != nameMap.end()) {
518 vector<string> nameRepresents = itNameMap->second;
520 for (int i = 0; i < nameRepresents.size(); i++){
521 if (subset.count(nameRepresents[i]) != 0) {
522 out << ">" << nameRepresents[i] << endl << currSeq.getAligned() << endl;
527 m->mothurOut("[ERROR]: " + thisname + " is not in your namefile, please correct."); m->mothurOutEndLine();
535 if (count != subset.size()) {
536 m->mothurOut("[ERROR]: The subset selected contained " + toString(subset.size()) + " sequences, but I only found " + toString(count) + " of those in the fastafile."); m->mothurOutEndLine();
539 //if a groupfile is provided read through the group file only outputting the names on the subsample list
540 if (groupfile != "") {
542 string groupOutputDir = outputDir;
543 if (outputDir == "") { groupOutputDir += m->hasPath(groupfile); }
544 string groupOutputFileName = groupOutputDir + m->getRootName(m->getSimpleName(groupfile)) + "subsample" + m->getExtension(groupfile);
547 m->openOutputFile(groupOutputFileName, outGroup);
548 outputTypes["group"].push_back(groupOutputFileName); outputNames.push_back(groupOutputFileName);
551 m->openInputFile(groupfile, inGroup);
554 while(!inGroup.eof()){
556 if (m->control_pressed) { inGroup.close(); outGroup.close(); return 0; }
558 inGroup >> name; m->gobble(inGroup); //read from first column
559 inGroup >> group; //read from second column
561 //if this name is in the accnos file
562 if (subset.count(name) != 0) {
563 outGroup << name << '\t' << group << endl;
573 if (subset.size() != 0) {
574 m->mothurOut("Your groupfile does not match your fasta file."); m->mothurOutEndLine();
575 for (set<string>::iterator it = subset.begin(); it != subset.end(); it++) {
576 m->mothurOut("[ERROR]: " + *it + " is missing from your groupfile."); m->mothurOutEndLine();
584 catch(exception& e) {
585 m->errorOut(e, "SubSampleCommand", "getSubSampleFasta");
589 //**********************************************************************************************************************
590 int SubSampleCommand::getNames() {
594 m->openInputFile(fastafile, in);
599 if (m->control_pressed) { in.close(); return 0; }
601 Sequence currSeq(in);
602 thisname = currSeq.getName();
604 if (thisname != "") {
605 vector<string> temp; temp.push_back(thisname);
606 nameMap[thisname] = temp;
607 names.push_back(thisname);
616 catch(exception& e) {
617 m->errorOut(e, "SubSampleCommand", "getNames");
621 //**********************************************************************************************************************
622 int SubSampleCommand::readNames() {
626 m->openInputFile(namefile, in);
628 string thisname, repnames;
629 map<string, vector<string> >::iterator it;
633 if (m->control_pressed) { in.close(); return 0; }
635 in >> thisname; m->gobble(in); //read from first column
636 in >> repnames; //read from second column
638 it = nameMap.find(thisname);
639 if (it == nameMap.end()) {
641 vector<string> splitRepNames;
642 m->splitAtComma(repnames, splitRepNames);
644 nameMap[thisname] = splitRepNames;
645 for (int i = 0; i < splitRepNames.size(); i++) { names.push_back(splitRepNames[i]); }
647 }else{ m->mothurOut(thisname + " is already in namesfile. I will use first definition."); m->mothurOutEndLine(); }
656 catch(exception& e) {
657 m->errorOut(e, "SubSampleCommand", "readNames");
661 //**********************************************************************************************************************
662 int SubSampleCommand::getSubSampleShared() {
665 string thisOutputDir = outputDir;
666 if (outputDir == "") { thisOutputDir += m->hasPath(sharedfile); }
667 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(sharedfile)) + "subsample" + m->getExtension(sharedfile);
670 m->openOutputFile(outputFileName, out);
671 outputTypes["shared"].push_back(outputFileName); outputNames.push_back(outputFileName);
673 InputData* input = new InputData(sharedfile, "sharedfile");
674 vector<SharedRAbundVector*> lookup = input->getSharedRAbundVectors();
675 string lastLabel = lookup[0]->getLabel();
677 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
678 set<string> processedLabels;
679 set<string> userLabels = labels;
681 if (size == 0) { //user has not set size, set size = smallest samples size
682 size = lookup[0]->getNumSeqs();
683 for (int i = 1; i < lookup.size(); i++) {
684 int thisSize = lookup[i]->getNumSeqs();
686 if (thisSize < size) { size = thisSize; }
690 m->mothurOut("Sampling " + toString(size) + " from " + toString(lookup[0]->getNumSeqs()) + "."); m->mothurOutEndLine();
692 //as long as you are not at the end of the file or done wih the lines you want
693 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
694 if (m->control_pressed) { delete input; for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; lookup[i] = NULL; } out.close(); return 0; }
696 if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){
698 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
700 processShared(lookup, out);
702 processedLabels.insert(lookup[0]->getLabel());
703 userLabels.erase(lookup[0]->getLabel());
706 if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
707 string saveLabel = lookup[0]->getLabel();
709 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
711 lookup = input->getSharedRAbundVectors(lastLabel);
712 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
714 processShared(lookup, out);
716 processedLabels.insert(lookup[0]->getLabel());
717 userLabels.erase(lookup[0]->getLabel());
719 //restore real lastlabel to save below
720 lookup[0]->setLabel(saveLabel);
723 lastLabel = lookup[0]->getLabel();
724 //prevent memory leak
725 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; lookup[i] = NULL; }
727 //get next line to process
728 lookup = input->getSharedRAbundVectors();
732 if (m->control_pressed) { out.close(); return 0; }
734 //output error messages about any remaining user labels
735 set<string>::iterator it;
736 bool needToRun = false;
737 for (it = userLabels.begin(); it != userLabels.end(); it++) {
738 m->mothurOut("Your file does not include the label " + *it);
739 if (processedLabels.count(lastLabel) != 1) {
740 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
743 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
747 //run last label if you need to
748 if (needToRun == true) {
749 for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }
750 lookup = input->getSharedRAbundVectors(lastLabel);
752 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
754 processShared(lookup, out);
756 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
765 catch(exception& e) {
766 m->errorOut(e, "SubSampleCommand", "getSubSampleShared");
770 //**********************************************************************************************************************
771 int SubSampleCommand::processShared(vector<SharedRAbundVector*>& thislookup, ofstream& out) {
774 int numBins = thislookup[0]->getNumBins();
775 for (int i = 0; i < thislookup.size(); i++) {
776 int thisSize = thislookup[i]->getNumSeqs();
778 if (thisSize != size) {
780 string thisgroup = thislookup[i]->getGroup();
782 OrderVector* order = new OrderVector();
783 for(int p=0;p<numBins;p++){
784 for(int j=0;j<thislookup[i]->getAbundance(p);j++){
788 random_shuffle(order->begin(), order->end());
790 SharedRAbundVector* temp = new SharedRAbundVector(numBins);
791 temp->setLabel(thislookup[i]->getLabel());
792 temp->setGroup(thislookup[i]->getGroup());
794 delete thislookup[i];
795 thislookup[i] = temp;
798 for (int j = 0; j < size; j++) {
800 if (m->control_pressed) { delete order; return 0; }
802 //get random number to sample from order between 0 and thisSize-1.
803 int myrand = int((float)(thisSize) * (float)(rand()) / ((float)RAND_MAX+1.0));
805 int bin = order->get(myrand);
807 int abund = thislookup[i]->getAbundance(bin);
808 thislookup[i]->set(bin, (abund+1), thisgroup);
814 //subsampling may have created some otus with no sequences in them
815 eliminateZeroOTUS(thislookup);
817 if (m->control_pressed) { return 0; }
819 for (int i = 0; i < thislookup.size(); i++) {
820 out << thislookup[i]->getLabel() << '\t' << thislookup[i]->getGroup() << '\t';
821 thislookup[i]->print(out);
827 catch(exception& e) {
828 m->errorOut(e, "SubSampleCommand", "processShared");
832 //**********************************************************************************************************************
833 int SubSampleCommand::getSubSampleList() {
836 string thisOutputDir = outputDir;
837 if (outputDir == "") { thisOutputDir += m->hasPath(listfile); }
838 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(listfile)) + "subsample" + m->getExtension(listfile);
841 m->openOutputFile(outputFileName, out);
842 outputTypes["list"].push_back(outputFileName); outputNames.push_back(outputFileName);
844 InputData* input = new InputData(listfile, "list");
845 ListVector* list = input->getListVector();
846 string lastLabel = list->getLabel();
848 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
849 set<string> processedLabels;
850 set<string> userLabels = labels;
854 if (groupfile != "") {
856 groupMap = new GroupMap(groupfile);
859 //takes care of user setting groupNames that are invalid or setting groups=all
860 SharedUtil* util = new SharedUtil();
861 util->setGroups(Groups, groupMap->namesOfGroups);
865 string groupOutputDir = outputDir;
866 if (outputDir == "") { groupOutputDir += m->hasPath(groupfile); }
867 string groupOutputFileName = groupOutputDir + m->getRootName(m->getSimpleName(groupfile)) + "subsample" + m->getExtension(groupfile);
869 m->openOutputFile(groupOutputFileName, outGroup);
870 outputTypes["group"].push_back(groupOutputFileName); outputNames.push_back(groupOutputFileName);
873 if (list->getNumSeqs() != groupMap->getNumSeqs()) {
874 m->mothurOut("[ERROR]: your list file contains " + toString(list->getNumSeqs()) + " sequences, and your groupfile contains " + toString(groupMap->getNumSeqs()) + ", please correct.");
875 m->mothurOutEndLine();
885 //make sure that if your picked groups size is not too big
887 if (size == 0) { //user has not set size, set size = smallest samples size
888 size = groupMap->getNumSeqs(Groups[0]);
889 for (int i = 1; i < Groups.size(); i++) {
890 int thisSize = groupMap->getNumSeqs(Groups[i]);
892 if (thisSize < size) { size = thisSize; }
894 }else { //make sure size is not too large
895 int smallestSize = groupMap->getNumSeqs(Groups[0]);
896 for (int i = 1; i < Groups.size(); i++) {
897 int thisSize = groupMap->getNumSeqs(Groups[i]);
899 if (thisSize < smallestSize) { smallestSize = thisSize; }
901 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(); }
904 m->mothurOut("Sampling " + toString(size) + " from each group."); m->mothurOutEndLine();
908 for(int i = 0; i < Groups.size(); i++) {
909 total += groupMap->getNumSeqs(Groups[i]);
912 if (size == 0) { //user has not set size, set size = 10% samples size
913 size = int (total * 0.10);
917 m->mothurOut("Your size is too large for the number of groups you selected. Adjusting to " + toString(int (total * 0.10)) + "."); m->mothurOutEndLine();
918 size = int (total * 0.10);
921 m->mothurOut("Sampling " + toString(size) + " from " + toString(total) + "."); m->mothurOutEndLine();
924 if (size == 0) { //user has not set size, set size = 10% samples size
925 size = int (list->getNumSeqs() * 0.10);
928 int thisSize = list->getNumSeqs();
929 if (size > thisSize) { m->mothurOut("Your list file only contains " + toString(thisSize) + " sequences. Setting size to " + toString(thisSize) + "."); m->mothurOutEndLine();
933 m->mothurOut("Sampling " + toString(size) + " from " + toString(list->getNumSeqs()) + "."); m->mothurOutEndLine();
939 for (int i = 0; i < list->getNumBins(); i++) {
940 string binnames = list->get(i);
943 string individual = "";
944 int length = binnames.length();
945 for(int j=0;j<length;j++){
946 if(binnames[j] == ','){
948 if (groupfile != "") { //if there is a groupfile given fill in group info
949 string group = groupMap->getGroup(individual);
950 if (group == "not found") { m->mothurOut("[ERROR]: " + individual + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
952 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
953 if (m->inUsersGroups(group, Groups)) {
954 names.push_back(individual);
957 names.push_back(individual);
959 }else{ //save everyone, group
960 names.push_back(individual);
965 individual += binnames[j];
969 if (groupfile != "") { //if there is a groupfile given fill in group info
970 string group = groupMap->getGroup(individual);
971 if (group == "not found") { m->mothurOut("[ERROR]: " + individual + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
973 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
974 if (m->inUsersGroups(group, Groups)) {
975 names.push_back(individual);
978 names.push_back(individual);
980 }else{ //save everyone, group
981 names.push_back(individual);
985 random_shuffle(names.begin(), names.end());
987 //randomly select a subset of those names to include in the subsample
988 set<string> subset; //dont want repeat sequence names added
990 for (int i = 0; i < Groups.size(); i++) {
992 for (int j = 0; j < size; j++) {
994 if (m->control_pressed) { break; }
996 //get random sequence to add, making sure we have not already added it
1000 myrand = int((float)(names.size()) * (float)(rand()) / ((float)RAND_MAX+1.0));
1002 if (subset.count(names[myrand]) == 0) { //you are not already added
1003 if (groupMap->getGroup(names[myrand]) == Groups[i]) { subset.insert(names[myrand]); break; }
1009 for (int j = 0; j < size; j++) {
1011 if (m->control_pressed) { break; }
1013 //get random sequence to add, making sure we have not already added it
1017 myrand = int((float)(names.size()) * (float)(rand()) / ((float)RAND_MAX+1.0));
1019 if (subset.count(names[myrand]) == 0) { subset.insert(names[myrand]); break; }
1024 if (groupfile != "") {
1025 //write out new groupfile
1026 for (set<string>::iterator it = subset.begin(); it != subset.end(); it++) {
1027 string group = groupMap->getGroup(*it);
1028 if (group == "not found") { group = "NOTFOUND"; }
1030 outGroup << *it << '\t' << group << endl;
1032 outGroup.close(); delete groupMap;
1036 //as long as you are not at the end of the file or done wih the lines you want
1037 while((list != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1039 if (m->control_pressed) { delete list; delete input; out.close(); return 0; }
1041 if(allLines == 1 || labels.count(list->getLabel()) == 1){
1043 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1045 processList(list, out, subset);
1047 processedLabels.insert(list->getLabel());
1048 userLabels.erase(list->getLabel());
1051 if ((m->anyLabelsToProcess(list->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1052 string saveLabel = list->getLabel();
1056 list = input->getListVector(lastLabel);
1057 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1059 processList(list, out, subset);
1061 processedLabels.insert(list->getLabel());
1062 userLabels.erase(list->getLabel());
1064 //restore real lastlabel to save below
1065 list->setLabel(saveLabel);
1068 lastLabel = list->getLabel();
1070 delete list; list = NULL;
1072 //get next line to process
1073 list = input->getListVector();
1077 if (m->control_pressed) { if (list != NULL) { delete list; } delete input; out.close(); return 0; }
1079 //output error messages about any remaining user labels
1080 set<string>::iterator it;
1081 bool needToRun = false;
1082 for (it = userLabels.begin(); it != userLabels.end(); it++) {
1083 m->mothurOut("Your file does not include the label " + *it);
1084 if (processedLabels.count(lastLabel) != 1) {
1085 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1088 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1092 //run last label if you need to
1093 if (needToRun == true) {
1094 if (list != NULL) { delete list; }
1096 list = input->getListVector(lastLabel);
1098 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1100 processList(list, out, subset);
1102 delete list; list = NULL;
1106 if (list != NULL) { delete list; }
1112 catch(exception& e) {
1113 m->errorOut(e, "SubSampleCommand", "getSubSampleList");
1117 //**********************************************************************************************************************
1118 int SubSampleCommand::processList(ListVector*& list, ofstream& out, set<string>& subset) {
1121 int numBins = list->getNumBins();
1123 ListVector* temp = new ListVector();
1124 temp->setLabel(list->getLabel());
1126 for (int i = 0; i < numBins; i++) {
1128 if (m->control_pressed) { break; }
1130 string binnames = list->get(i);
1133 string individual = "";
1134 string newNames = "";
1135 int length = binnames.length();
1136 for(int j=0;j<length;j++){
1137 if(binnames[j] == ','){
1138 if (subset.count(individual) != 0) { newNames += individual + ","; }
1141 individual += binnames[j];
1144 if (subset.count(individual) != 0) { newNames += individual; }
1147 //if there are names in this bin add to new list
1148 if (newNames != "") {
1149 newNames = newNames.substr(0, newNames.length()-1); //rip off extra comma
1150 temp->push_back(newNames);
1157 if (m->control_pressed) { return 0; }
1164 catch(exception& e) {
1165 m->errorOut(e, "SubSampleCommand", "processList");
1169 //**********************************************************************************************************************
1170 int SubSampleCommand::getSubSampleRabund() {
1173 string thisOutputDir = outputDir;
1174 if (outputDir == "") { thisOutputDir += m->hasPath(rabundfile); }
1175 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(rabundfile)) + "subsample" + m->getExtension(rabundfile);
1178 m->openOutputFile(outputFileName, out);
1179 outputTypes["rabund"].push_back(outputFileName); outputNames.push_back(outputFileName);
1181 InputData* input = new InputData(rabundfile, "rabund");
1182 RAbundVector* rabund = input->getRAbundVector();
1183 string lastLabel = rabund->getLabel();
1185 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1186 set<string> processedLabels;
1187 set<string> userLabels = labels;
1189 if (size == 0) { //user has not set size, set size = 10%
1190 size = int((rabund->getNumSeqs()) * 0.10);
1193 m->mothurOut("Sampling " + toString(size) + " from " + toString(rabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1195 //as long as you are not at the end of the file or done wih the lines you want
1196 while((rabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1197 if (m->control_pressed) { delete input; delete rabund; out.close(); return 0; }
1199 if(allLines == 1 || labels.count(rabund->getLabel()) == 1){
1201 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1203 processRabund(rabund, out);
1205 processedLabels.insert(rabund->getLabel());
1206 userLabels.erase(rabund->getLabel());
1209 if ((m->anyLabelsToProcess(rabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1210 string saveLabel = rabund->getLabel();
1214 rabund = input->getRAbundVector(lastLabel);
1215 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1217 processRabund(rabund, out);
1219 processedLabels.insert(rabund->getLabel());
1220 userLabels.erase(rabund->getLabel());
1222 //restore real lastlabel to save below
1223 rabund->setLabel(saveLabel);
1226 lastLabel = rabund->getLabel();
1228 //prevent memory leak
1229 delete rabund; rabund = NULL;
1231 //get next line to process
1232 rabund = input->getRAbundVector();
1236 if (m->control_pressed) { out.close(); return 0; }
1238 //output error messages about any remaining user labels
1239 set<string>::iterator it;
1240 bool needToRun = false;
1241 for (it = userLabels.begin(); it != userLabels.end(); it++) {
1242 m->mothurOut("Your file does not include the label " + *it);
1243 if (processedLabels.count(lastLabel) != 1) {
1244 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1247 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1251 //run last label if you need to
1252 if (needToRun == true) {
1253 if (rabund != NULL) { delete rabund; }
1255 rabund = input->getRAbundVector(lastLabel);
1257 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1259 processRabund(rabund, out);
1270 catch(exception& e) {
1271 m->errorOut(e, "SubSampleCommand", "getSubSampleRabund");
1275 //**********************************************************************************************************************
1276 int SubSampleCommand::processRabund(RAbundVector*& rabund, ofstream& out) {
1279 int numBins = rabund->getNumBins();
1280 int thisSize = rabund->getNumSeqs();
1282 if (thisSize != size) {
1284 OrderVector* order = new OrderVector();
1285 for(int p=0;p<numBins;p++){
1286 for(int j=0;j<rabund->get(p);j++){
1287 order->push_back(p);
1290 random_shuffle(order->begin(), order->end());
1292 RAbundVector* temp = new RAbundVector(numBins);
1293 temp->setLabel(rabund->getLabel());
1298 for (int j = 0; j < size; j++) {
1300 if (m->control_pressed) { delete order; return 0; }
1302 //get random number to sample from order between 0 and thisSize-1.
1303 int myrand = int((float)(thisSize) * (float)(rand()) / ((float)RAND_MAX+1.0));
1305 int bin = order->get(myrand);
1307 int abund = rabund->get(bin);
1308 rabund->set(bin, (abund+1));
1314 if (m->control_pressed) { return 0; }
1321 catch(exception& e) {
1322 m->errorOut(e, "SubSampleCommand", "processRabund");
1326 //**********************************************************************************************************************
1327 int SubSampleCommand::getSubSampleSabund() {
1330 string thisOutputDir = outputDir;
1331 if (outputDir == "") { thisOutputDir += m->hasPath(sabundfile); }
1332 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(sabundfile)) + "subsample" + m->getExtension(sabundfile);
1335 m->openOutputFile(outputFileName, out);
1336 outputTypes["sabund"].push_back(outputFileName); outputNames.push_back(outputFileName);
1338 InputData* input = new InputData(sabundfile, "sabund");
1339 SAbundVector* sabund = input->getSAbundVector();
1340 string lastLabel = sabund->getLabel();
1342 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1343 set<string> processedLabels;
1344 set<string> userLabels = labels;
1346 if (size == 0) { //user has not set size, set size = 10%
1347 size = int((sabund->getNumSeqs()) * 0.10);
1350 m->mothurOut("Sampling " + toString(size) + " from " + toString(sabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1352 //as long as you are not at the end of the file or done wih the lines you want
1353 while((sabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1354 if (m->control_pressed) { delete input; delete sabund; out.close(); return 0; }
1356 if(allLines == 1 || labels.count(sabund->getLabel()) == 1){
1358 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1360 processSabund(sabund, out);
1362 processedLabels.insert(sabund->getLabel());
1363 userLabels.erase(sabund->getLabel());
1366 if ((m->anyLabelsToProcess(sabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1367 string saveLabel = sabund->getLabel();
1371 sabund = input->getSAbundVector(lastLabel);
1372 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1374 processSabund(sabund, out);
1376 processedLabels.insert(sabund->getLabel());
1377 userLabels.erase(sabund->getLabel());
1379 //restore real lastlabel to save below
1380 sabund->setLabel(saveLabel);
1383 lastLabel = sabund->getLabel();
1385 //prevent memory leak
1386 delete sabund; sabund = NULL;
1388 //get next line to process
1389 sabund = input->getSAbundVector();
1393 if (m->control_pressed) { out.close(); return 0; }
1395 //output error messages about any remaining user labels
1396 set<string>::iterator it;
1397 bool needToRun = false;
1398 for (it = userLabels.begin(); it != userLabels.end(); it++) {
1399 m->mothurOut("Your file does not include the label " + *it);
1400 if (processedLabels.count(lastLabel) != 1) {
1401 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1404 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1408 //run last label if you need to
1409 if (needToRun == true) {
1410 if (sabund != NULL) { delete sabund; }
1412 sabund = input->getSAbundVector(lastLabel);
1414 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1416 processSabund(sabund, out);
1427 catch(exception& e) {
1428 m->errorOut(e, "SubSampleCommand", "getSubSampleSabund");
1432 //**********************************************************************************************************************
1433 int SubSampleCommand::processSabund(SAbundVector*& sabund, ofstream& out) {
1436 RAbundVector* rabund = new RAbundVector();
1437 *rabund = sabund->getRAbundVector();
1439 int numBins = rabund->getNumBins();
1440 int thisSize = rabund->getNumSeqs();
1442 if (thisSize != size) {
1444 OrderVector* order = new OrderVector();
1445 for(int p=0;p<numBins;p++){
1446 for(int j=0;j<rabund->get(p);j++){
1447 order->push_back(p);
1450 random_shuffle(order->begin(), order->end());
1452 RAbundVector* temp = new RAbundVector(numBins);
1453 temp->setLabel(rabund->getLabel());
1458 for (int j = 0; j < size; j++) {
1460 if (m->control_pressed) { delete order; return 0; }
1462 //get random number to sample from order between 0 and thisSize-1.
1463 int myrand = int((float)(thisSize) * (float)(rand()) / ((float)RAND_MAX+1.0));
1465 int bin = order->get(myrand);
1467 int abund = rabund->get(bin);
1468 rabund->set(bin, (abund+1));
1474 if (m->control_pressed) { return 0; }
1477 sabund = new SAbundVector();
1478 *sabund = rabund->getSAbundVector();
1486 catch(exception& e) {
1487 m->errorOut(e, "SubSampleCommand", "processSabund");
1491 //**********************************************************************************************************************
1492 int SubSampleCommand::eliminateZeroOTUS(vector<SharedRAbundVector*>& thislookup) {
1495 vector<SharedRAbundVector*> newLookup;
1496 for (int i = 0; i < thislookup.size(); i++) {
1497 SharedRAbundVector* temp = new SharedRAbundVector();
1498 temp->setLabel(thislookup[i]->getLabel());
1499 temp->setGroup(thislookup[i]->getGroup());
1500 newLookup.push_back(temp);
1504 for (int i = 0; i < thislookup[0]->getNumBins(); i++) {
1505 if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) { delete newLookup[j]; } return 0; }
1507 //look at each sharedRabund and make sure they are not all zero
1508 bool allZero = true;
1509 for (int j = 0; j < thislookup.size(); j++) {
1510 if (thislookup[j]->getAbundance(i) != 0) { allZero = false; break; }
1513 //if they are not all zero add this bin
1515 for (int j = 0; j < thislookup.size(); j++) {
1516 newLookup[j]->push_back(thislookup[j]->getAbundance(i), thislookup[j]->getGroup());
1521 for (int j = 0; j < thislookup.size(); j++) { delete thislookup[j]; }
1524 thislookup = newLookup;
1529 catch(exception& e) {
1530 m->errorOut(e, "SubSampleCommand", "eliminateZeroOTUS");
1535 //**********************************************************************************************************************