5 * Created by westcott on 10/27/10.
6 * Copyright 2010 Schloss Lab. All rights reserved.
10 #include "subsamplecommand.h"
11 #include "sharedutilities.h"
12 #include "deconvolutecommand.h"
13 #include "subsample.h"
15 //**********************************************************************************************************************
16 vector<string> SubSampleCommand::setParameters(){
18 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "FLSSR", "none",false,false); parameters.push_back(pfasta);
19 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
20 CommandParameter pgroup("group", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pgroup);
21 CommandParameter plist("list", "InputTypes", "", "", "none", "FLSSR", "none",false,false); parameters.push_back(plist);
22 CommandParameter pshared("shared", "InputTypes", "", "", "none", "FLSSR", "none",false,false); parameters.push_back(pshared);
23 CommandParameter prabund("rabund", "InputTypes", "", "", "none", "FLSSR", "none",false,false); parameters.push_back(prabund);
24 CommandParameter psabund("sabund", "InputTypes", "", "", "none", "FLSSR", "none",false,false); parameters.push_back(psabund);
25 CommandParameter plabel("label", "String", "", "", "", "", "",false,false); parameters.push_back(plabel);
26 CommandParameter pgroups("groups", "String", "", "", "", "", "",false,false); parameters.push_back(pgroups);
27 CommandParameter psize("size", "Number", "", "0", "", "", "",false,false); parameters.push_back(psize);
28 CommandParameter ppersample("persample", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(ppersample);
29 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
30 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
32 vector<string> myArray;
33 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
37 m->errorOut(e, "SubSampleCommand", "setParameters");
41 //**********************************************************************************************************************
42 string SubSampleCommand::getHelpString(){
44 string helpString = "";
45 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";
46 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";
47 helpString += "The namefile is only used with the fasta file, not with the listfile, because the list file should contain all sequences.\n";
48 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";
49 helpString += "The label parameter allows you to select what distance levels you would like, and are also separated by dashes.\n";
50 helpString += "The size parameter allows you indicate the size of your subsample.\n";
51 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";
52 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";
53 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";
54 helpString += "The sub.sample command should be in the following format: sub.sample(list=yourListFile, group=yourGroupFile, groups=yourGroups, label=yourLabels).\n";
55 helpString += "Example sub.sample(list=abrecovery.fn.list, group=abrecovery.groups, groups=B-C, size=20).\n";
56 helpString += "The default value for groups is all the groups in your groupfile, and all labels in your inputfile will be used.\n";
57 helpString += "The sub.sample command outputs a .subsample file.\n";
58 helpString += "Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n";
62 m->errorOut(e, "SubSampleCommand", "getHelpString");
66 //**********************************************************************************************************************
67 SubSampleCommand::SubSampleCommand(){
69 abort = true; calledHelp = true;
71 vector<string> tempOutNames;
72 outputTypes["shared"] = tempOutNames;
73 outputTypes["list"] = tempOutNames;
74 outputTypes["rabund"] = tempOutNames;
75 outputTypes["sabund"] = tempOutNames;
76 outputTypes["fasta"] = tempOutNames;
77 outputTypes["name"] = tempOutNames;
78 outputTypes["group"] = tempOutNames;
81 m->errorOut(e, "SubSampleCommand", "GetRelAbundCommand");
85 //**********************************************************************************************************************
86 SubSampleCommand::SubSampleCommand(string option) {
88 abort = false; calledHelp = false;
91 //allow user to run help
92 if(option == "help") { help(); abort = true; calledHelp = true; }
93 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
96 vector<string> myArray = setParameters();
98 OptionParser parser(option);
99 map<string,string> parameters = parser.getParameters();
101 ValidParameters validParameter;
103 //check to make sure all parameters are valid for command
104 map<string,string>::iterator it;
105 for (it = parameters.begin(); it != parameters.end(); it++) {
106 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
109 //initialize outputTypes
110 vector<string> tempOutNames;
111 outputTypes["shared"] = tempOutNames;
112 outputTypes["list"] = tempOutNames;
113 outputTypes["rabund"] = tempOutNames;
114 outputTypes["sabund"] = tempOutNames;
115 outputTypes["fasta"] = tempOutNames;
116 outputTypes["name"] = tempOutNames;
117 outputTypes["group"] = tempOutNames;
119 //if the user changes the output directory command factory will send this info to us in the output parameter
120 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
122 //if the user changes the input directory command factory will send this info to us in the output parameter
123 string inputDir = validParameter.validFile(parameters, "inputdir", false);
124 if (inputDir == "not found"){ inputDir = ""; }
127 it = parameters.find("list");
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["list"] = inputDir + it->second; }
135 it = parameters.find("fasta");
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["fasta"] = inputDir + it->second; }
143 it = parameters.find("shared");
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["shared"] = inputDir + it->second; }
151 it = parameters.find("group");
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["group"] = inputDir + it->second; }
159 it = parameters.find("sabund");
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["sabund"] = inputDir + it->second; }
167 it = parameters.find("rabund");
168 //user has given a template file
169 if(it != parameters.end()){
170 path = m->hasPath(it->second);
171 //if the user has not given a path then, add inputdir. else leave path alone.
172 if (path == "") { parameters["rabund"] = inputDir + it->second; }
175 it = parameters.find("name");
176 //user has given a template file
177 if(it != parameters.end()){
178 path = m->hasPath(it->second);
179 //if the user has not given a path then, add inputdir. else leave path alone.
180 if (path == "") { parameters["name"] = inputDir + it->second; }
184 //check for required parameters
185 listfile = validParameter.validFile(parameters, "list", true);
186 if (listfile == "not open") { listfile = ""; abort = true; }
187 else if (listfile == "not found") { listfile = ""; }
188 else { m->setListFile(listfile); }
190 sabundfile = validParameter.validFile(parameters, "sabund", true);
191 if (sabundfile == "not open") { sabundfile = ""; abort = true; }
192 else if (sabundfile == "not found") { sabundfile = ""; }
193 else { m->setSabundFile(sabundfile); }
195 rabundfile = validParameter.validFile(parameters, "rabund", true);
196 if (rabundfile == "not open") { rabundfile = ""; abort = true; }
197 else if (rabundfile == "not found") { rabundfile = ""; }
198 else { m->setRabundFile(rabundfile); }
200 fastafile = validParameter.validFile(parameters, "fasta", true);
201 if (fastafile == "not open") { fastafile = ""; abort = true; }
202 else if (fastafile == "not found") { fastafile = ""; }
203 else { m->setFastaFile(fastafile); }
205 sharedfile = validParameter.validFile(parameters, "shared", true);
206 if (sharedfile == "not open") { sharedfile = ""; abort = true; }
207 else if (sharedfile == "not found") { sharedfile = ""; }
208 else { m->setSharedFile(sharedfile); }
210 namefile = validParameter.validFile(parameters, "name", true);
211 if (namefile == "not open") { namefile = ""; abort = true; }
212 else if (namefile == "not found") { namefile = ""; }
213 else { m->setNameFile(namefile); }
215 groupfile = validParameter.validFile(parameters, "group", true);
216 if (groupfile == "not open") { groupfile = ""; abort = true; }
217 else if (groupfile == "not found") { groupfile = ""; }
218 else { m->setGroupFile(groupfile); }
220 //check for optional parameter and set defaults
221 // ...at some point should added some additional type checking...
222 label = validParameter.validFile(parameters, "label", false);
223 if (label == "not found") { label = ""; }
225 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
226 else { allLines = 1; }
229 groups = validParameter.validFile(parameters, "groups", false);
230 if (groups == "not found") { groups = ""; pickedGroups = false; }
233 m->splitAtDash(groups, Groups);
234 m->setGroups(Groups);
237 string temp = validParameter.validFile(parameters, "size", false); if (temp == "not found"){ temp = "0"; }
238 m->mothurConvert(temp, size);
240 temp = validParameter.validFile(parameters, "persample", false); if (temp == "not found"){ temp = "f"; }
241 persample = m->isTrue(temp);
243 if (groupfile == "") { persample = false; }
245 if ((namefile != "") && (fastafile == "")) { m->mothurOut("You may only use a namefile with a fastafile."); m->mothurOutEndLine(); abort = true; }
247 if ((fastafile == "") && (listfile == "") && (sabundfile == "") && (rabundfile == "") && (sharedfile == "")) {
248 m->mothurOut("You must provide a fasta, list, sabund, rabund or shared file as an input file."); m->mothurOutEndLine(); abort = true; }
250 if (pickedGroups && ((groupfile == "") && (sharedfile == ""))) {
251 m->mothurOut("You cannot pick groups without a valid group file or shared file."); m->mothurOutEndLine(); abort = true; }
253 if ((groupfile != "") && ((fastafile == "") && (listfile == ""))) {
254 m->mothurOut("Group file only valid with listfile or fastafile."); m->mothurOutEndLine(); abort = true; }
256 if ((groupfile != "") && ((fastafile != "") && (listfile != ""))) {
257 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; }
259 if ((fastafile != "") && (namefile == "")) {
260 vector<string> files; files.push_back(fastafile);
261 parser.getNameFile(files);
266 catch(exception& e) {
267 m->errorOut(e, "SubSampleCommand", "SubSampleCommand");
271 //**********************************************************************************************************************
273 int SubSampleCommand::execute(){
276 if (abort == true) { if (calledHelp) { return 0; } return 2; }
278 if (sharedfile != "") { getSubSampleShared(); }
279 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); return 0; } }
281 if (listfile != "") { getSubSampleList(); }
282 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); return 0; } }
284 if (rabundfile != "") { getSubSampleRabund(); }
285 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); return 0; } }
287 if (sabundfile != "") { getSubSampleSabund(); }
288 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); return 0; } }
290 if (fastafile != "") { getSubSampleFasta(); }
291 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); return 0; } }
293 //set fasta file as new current fastafile
295 itTypes = outputTypes.find("fasta");
296 if (itTypes != outputTypes.end()) {
297 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
300 itTypes = outputTypes.find("name");
301 if (itTypes != outputTypes.end()) {
302 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
305 itTypes = outputTypes.find("group");
306 if (itTypes != outputTypes.end()) {
307 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setGroupFile(current); }
310 itTypes = outputTypes.find("list");
311 if (itTypes != outputTypes.end()) {
312 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setListFile(current); }
315 itTypes = outputTypes.find("shared");
316 if (itTypes != outputTypes.end()) {
317 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSharedFile(current); }
320 itTypes = outputTypes.find("rabund");
321 if (itTypes != outputTypes.end()) {
322 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setRabundFile(current); }
325 itTypes = outputTypes.find("sabund");
326 if (itTypes != outputTypes.end()) {
327 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSabundFile(current); }
331 m->mothurOutEndLine();
332 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
333 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
334 m->mothurOutEndLine();
338 catch(exception& e) {
339 m->errorOut(e, "SubSampleCommand", "execute");
343 //**********************************************************************************************************************
344 int SubSampleCommand::getSubSampleFasta() {
347 if (namefile != "") { readNames(); } //fills names with all names in namefile.
348 else { getNames(); }//no name file, so get list of names to pick from
351 if (groupfile != "") {
353 groupMap = new GroupMap(groupfile);
356 //takes care of user setting groupNames that are invalid or setting groups=all
357 SharedUtil* util = new SharedUtil();
358 vector<string> namesGroups = groupMap->getNamesOfGroups();
359 util->setGroups(Groups, namesGroups);
363 if (names.size() != groupMap->getNumSeqs()) {
364 m->mothurOut("[ERROR]: your fasta file contains " + toString(names.size()) + " sequences, and your groupfile contains " + toString(groupMap->getNumSeqs()) + ", please correct.");
365 m->mothurOutEndLine();
371 if (m->control_pressed) { return 0; }
374 //make sure that if your picked groups size is not too big
375 int thisSize = names.size();
377 if (size == 0) { //user has not set size, set size = smallest samples size
378 size = groupMap->getNumSeqs(Groups[0]);
379 for (int i = 1; i < Groups.size(); i++) {
380 int thisSize = groupMap->getNumSeqs(Groups[i]);
382 if (thisSize < size) { size = thisSize; }
384 }else { //make sure size is not too large
385 vector<string> newGroups;
386 for (int i = 0; i < Groups.size(); i++) {
387 int thisSize = groupMap->getNumSeqs(Groups[i]);
389 if (thisSize >= size) { newGroups.push_back(Groups[i]); }
390 else { m->mothurOut("You have selected a size that is larger than " + Groups[i] + " number of sequences, removing " + Groups[i] + "."); m->mothurOutEndLine(); }
395 m->mothurOut("Sampling " + toString(size) + " from each group."); m->mothurOutEndLine();
399 for(int i = 0; i < Groups.size(); i++) {
400 total += groupMap->getNumSeqs(Groups[i]);
403 if (size == 0) { //user has not set size, set size = 10% samples size
404 size = int (total * 0.10);
409 m->mothurOut("Your size is too large for the number of groups you selected. Adjusting to " + toString(int (total * 0.10)) + "."); m->mothurOutEndLine();
411 size = int (total * 0.10);
414 m->mothurOut("Sampling " + toString(size) + " from " + toString(total) + "."); m->mothurOutEndLine();
417 if (size == 0) { //user has not set size, set size = 10% samples size
418 size = int (names.size() * 0.10);
421 if (size > thisSize) { m->mothurOut("Your fasta file only contains " + toString(thisSize) + " sequences. Setting size to " + toString(thisSize) + "."); m->mothurOutEndLine();
425 if (!pickedGroups) { m->mothurOut("Sampling " + toString(size) + " from " + toString(thisSize) + "."); m->mothurOutEndLine(); }
428 random_shuffle(names.begin(), names.end());
430 set<string> subset; //dont want repeat sequence names added
433 map<string, int> groupCounts;
434 map<string, int>::iterator itGroupCounts;
435 for (int i = 0; i < Groups.size(); i++) { groupCounts[Groups[i]] = 0; }
437 for (int j = 0; j < names.size(); j++) {
439 if (m->control_pressed) { return 0; }
441 string group = groupMap->getGroup(names[j]);
442 if (group == "not found") { m->mothurOut("[ERROR]: " + names[j] + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
444 itGroupCounts = groupCounts.find(group);
445 if (itGroupCounts != groupCounts.end()) {
446 if (groupCounts[group] < size) { subset.insert(names[j]); groupCounts[group]++; }
452 //randomly select a subset of those names to include in the subsample
453 //since names was randomly shuffled just grab the next one
454 for (int j = 0; j < names.size(); j++) {
456 if (m->control_pressed) { return 0; }
458 if (groupfile != "") { //if there is a groupfile given fill in group info
459 string group = groupMap->getGroup(names[j]);
460 if (group == "not found") { m->mothurOut("[ERROR]: " + names[j] + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
462 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
463 if (m->inUsersGroups(group, Groups)) {
464 subset.insert(names[j]);
467 subset.insert(names[j]);
469 }else{ //save everyone, group
470 subset.insert(names[j]);
473 //do we have enough??
474 if (subset.size() == size) { break; }
478 if (subset.size() == 0) { m->mothurOut("The size you selected is too large, skipping fasta file."); m->mothurOutEndLine(); return 0; }
480 string thisOutputDir = outputDir;
481 if (outputDir == "") { thisOutputDir += m->hasPath(fastafile); }
482 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(fastafile)) + "subsample" + m->getExtension(fastafile);
485 m->openOutputFile(outputFileName, out);
487 //read through fasta file outputting only the names on the subsample list
489 m->openInputFile(fastafile, in);
493 map<string, vector<string> >::iterator itNameMap;
497 if (m->control_pressed) { in.close(); out.close(); return 0; }
499 Sequence currSeq(in);
500 thisname = currSeq.getName();
502 if (thisname != "") {
504 //does the subset contain a sequence that this sequence represents
505 itNameMap = nameMap.find(thisname);
506 if (itNameMap != nameMap.end()) {
507 vector<string> nameRepresents = itNameMap->second;
509 for (int i = 0; i < nameRepresents.size(); i++){
510 if (subset.count(nameRepresents[i]) != 0) {
511 out << ">" << nameRepresents[i] << endl << currSeq.getAligned() << endl;
516 m->mothurOut("[ERROR]: " + thisname + " is not in your namefile, please correct."); m->mothurOutEndLine();
524 if (count != subset.size()) {
525 m->mothurOut("[ERROR]: The subset selected contained " + toString(subset.size()) + " sequences, but I only found " + toString(count) + " of those in the fastafile."); m->mothurOutEndLine();
528 if (namefile != "") {
529 m->mothurOut("Deconvoluting subsampled fasta file... "); m->mothurOutEndLine();
531 //use unique.seqs to create new name and fastafile
532 string inputString = "fasta=" + outputFileName;
533 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
534 m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine();
535 m->mothurCalling = true;
537 Command* uniqueCommand = new DeconvoluteCommand(inputString);
538 uniqueCommand->execute();
540 map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
542 delete uniqueCommand;
543 m->mothurCalling = false;
545 outputTypes["name"].push_back(filenames["name"][0]); outputNames.push_back(filenames["name"][0]);
546 m->mothurRemove(outputFileName);
547 outputFileName = filenames["fasta"][0];
549 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
551 m->mothurOut("Done."); m->mothurOutEndLine();
554 outputTypes["fasta"].push_back(outputFileName); outputNames.push_back(outputFileName);
556 //if a groupfile is provided read through the group file only outputting the names on the subsample list
557 if (groupfile != "") {
559 string groupOutputDir = outputDir;
560 if (outputDir == "") { groupOutputDir += m->hasPath(groupfile); }
561 string groupOutputFileName = groupOutputDir + m->getRootName(m->getSimpleName(groupfile)) + "subsample" + m->getExtension(groupfile);
564 m->openOutputFile(groupOutputFileName, outGroup);
565 outputTypes["group"].push_back(groupOutputFileName); outputNames.push_back(groupOutputFileName);
568 m->openInputFile(groupfile, inGroup);
571 while(!inGroup.eof()){
573 if (m->control_pressed) { inGroup.close(); outGroup.close(); return 0; }
575 inGroup >> name; m->gobble(inGroup); //read from first column
576 inGroup >> group; //read from second column
578 //if this name is in the accnos file
579 if (subset.count(name) != 0) {
580 outGroup << name << '\t' << group << endl;
590 if (subset.size() != 0) {
591 m->mothurOut("Your groupfile does not match your fasta file."); m->mothurOutEndLine();
592 for (set<string>::iterator it = subset.begin(); it != subset.end(); it++) {
593 m->mothurOut("[ERROR]: " + *it + " is missing from your groupfile."); m->mothurOutEndLine();
601 catch(exception& e) {
602 m->errorOut(e, "SubSampleCommand", "getSubSampleFasta");
606 //**********************************************************************************************************************
607 int SubSampleCommand::getNames() {
611 m->openInputFile(fastafile, in);
616 if (m->control_pressed) { in.close(); return 0; }
618 Sequence currSeq(in);
619 thisname = currSeq.getName();
621 if (thisname != "") {
622 vector<string> temp; temp.push_back(thisname);
623 nameMap[thisname] = temp;
624 names.push_back(thisname);
633 catch(exception& e) {
634 m->errorOut(e, "SubSampleCommand", "getNames");
638 //**********************************************************************************************************************
639 int SubSampleCommand::readNames() {
643 m->openInputFile(namefile, in);
645 string thisname, repnames;
646 map<string, vector<string> >::iterator it;
650 if (m->control_pressed) { in.close(); return 0; }
652 in >> thisname; m->gobble(in); //read from first column
653 in >> repnames; //read from second column
655 it = nameMap.find(thisname);
656 if (it == nameMap.end()) {
658 vector<string> splitRepNames;
659 m->splitAtComma(repnames, splitRepNames);
661 nameMap[thisname] = splitRepNames;
662 for (int i = 0; i < splitRepNames.size(); i++) { names.push_back(splitRepNames[i]); }
664 }else{ m->mothurOut(thisname + " is already in namesfile. I will use first definition."); m->mothurOutEndLine(); }
673 catch(exception& e) {
674 m->errorOut(e, "SubSampleCommand", "readNames");
678 //**********************************************************************************************************************
679 int SubSampleCommand::getSubSampleShared() {
682 InputData* input = new InputData(sharedfile, "sharedfile");
683 vector<SharedRAbundVector*> lookup = input->getSharedRAbundVectors();
684 string lastLabel = lookup[0]->getLabel();
686 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
687 set<string> processedLabels;
688 set<string> userLabels = labels;
690 if (size == 0) { //user has not set size, set size = smallest samples size
691 size = lookup[0]->getNumSeqs();
692 for (int i = 1; i < lookup.size(); i++) {
693 int thisSize = lookup[i]->getNumSeqs();
695 if (thisSize < size) { size = thisSize; }
700 vector<SharedRAbundVector*> temp;
701 for (int i = 0; i < lookup.size(); i++) {
702 if (lookup[i]->getNumSeqs() < size) {
703 m->mothurOut(lookup[i]->getGroup() + " contains " + toString(lookup[i]->getNumSeqs()) + ". Eliminating."); m->mothurOutEndLine();
706 Groups.push_back(lookup[i]->getGroup());
707 temp.push_back(lookup[i]);
711 m->setGroups(Groups);
714 if (lookup.size() == 0) { m->mothurOut("The size you selected is too large, skipping shared file."); m->mothurOutEndLine(); delete input; return 0; }
716 m->mothurOut("Sampling " + toString(size) + " from each group."); m->mothurOutEndLine();
718 //as long as you are not at the end of the file or done wih the lines you want
719 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
720 if (m->control_pressed) { delete input; for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; lookup[i] = NULL; } return 0; }
722 if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){
724 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
726 processShared(lookup);
728 processedLabels.insert(lookup[0]->getLabel());
729 userLabels.erase(lookup[0]->getLabel());
732 if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
733 string saveLabel = lookup[0]->getLabel();
735 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
737 lookup = input->getSharedRAbundVectors(lastLabel);
738 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
740 processShared(lookup);
742 processedLabels.insert(lookup[0]->getLabel());
743 userLabels.erase(lookup[0]->getLabel());
745 //restore real lastlabel to save below
746 lookup[0]->setLabel(saveLabel);
749 lastLabel = lookup[0]->getLabel();
750 //prevent memory leak
751 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; lookup[i] = NULL; }
753 //get next line to process
754 lookup = input->getSharedRAbundVectors();
758 if (m->control_pressed) { return 0; }
760 //output error messages about any remaining user labels
761 set<string>::iterator it;
762 bool needToRun = false;
763 for (it = userLabels.begin(); it != userLabels.end(); it++) {
764 m->mothurOut("Your file does not include the label " + *it);
765 if (processedLabels.count(lastLabel) != 1) {
766 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
769 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
773 //run last label if you need to
774 if (needToRun == true) {
775 for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }
776 lookup = input->getSharedRAbundVectors(lastLabel);
778 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
780 processShared(lookup);
782 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
790 catch(exception& e) {
791 m->errorOut(e, "SubSampleCommand", "getSubSampleShared");
795 //**********************************************************************************************************************
796 int SubSampleCommand::processShared(vector<SharedRAbundVector*>& thislookup) {
799 //save mothurOut's binLabels to restore for next label
800 vector<string> saveBinLabels = m->currentBinLabels;
802 string thisOutputDir = outputDir;
803 if (outputDir == "") { thisOutputDir += m->hasPath(sharedfile); }
804 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(sharedfile)) + thislookup[0]->getLabel() + ".subsample" + m->getExtension(sharedfile);
807 vector<string> subsampledLabels = sample.getSample(thislookup, size);
809 if (m->control_pressed) { return 0; }
812 m->openOutputFile(outputFileName, out);
813 outputTypes["shared"].push_back(outputFileName); outputNames.push_back(outputFileName);
815 m->currentBinLabels = subsampledLabels;
817 thislookup[0]->printHeaders(out);
819 for (int i = 0; i < thislookup.size(); i++) {
820 out << thislookup[i]->getLabel() << '\t' << thislookup[i]->getGroup() << '\t';
821 thislookup[i]->print(out);
826 //save mothurOut's binLabels to restore for next label
827 m->currentBinLabels = saveBinLabels;
832 catch(exception& e) {
833 m->errorOut(e, "SubSampleCommand", "processShared");
837 //**********************************************************************************************************************
838 int SubSampleCommand::getSubSampleList() {
841 string thisOutputDir = outputDir;
842 if (outputDir == "") { thisOutputDir += m->hasPath(listfile); }
843 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(listfile)) + "subsample" + m->getExtension(listfile);
846 m->openOutputFile(outputFileName, out);
847 outputTypes["list"].push_back(outputFileName); outputNames.push_back(outputFileName);
849 InputData* input = new InputData(listfile, "list");
850 ListVector* list = input->getListVector();
851 string lastLabel = list->getLabel();
853 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
854 set<string> processedLabels;
855 set<string> userLabels = labels;
859 if (groupfile != "") {
861 groupMap = new GroupMap(groupfile);
864 //takes care of user setting groupNames that are invalid or setting groups=all
865 SharedUtil* util = new SharedUtil();
866 vector<string> namesGroups = groupMap->getNamesOfGroups();
867 util->setGroups(Groups, namesGroups);
871 string groupOutputDir = outputDir;
872 if (outputDir == "") { groupOutputDir += m->hasPath(groupfile); }
873 string groupOutputFileName = groupOutputDir + m->getRootName(m->getSimpleName(groupfile)) + "subsample" + m->getExtension(groupfile);
875 m->openOutputFile(groupOutputFileName, outGroup);
876 outputTypes["group"].push_back(groupOutputFileName); outputNames.push_back(groupOutputFileName);
879 if (list->getNumSeqs() != groupMap->getNumSeqs()) {
880 m->mothurOut("[ERROR]: your list file contains " + toString(list->getNumSeqs()) + " sequences, and your groupfile contains " + toString(groupMap->getNumSeqs()) + ", please correct.");
881 m->mothurOutEndLine();
891 //make sure that if your picked groups size is not too big
893 if (size == 0) { //user has not set size, set size = smallest samples size
894 size = groupMap->getNumSeqs(Groups[0]);
895 for (int i = 1; i < Groups.size(); i++) {
896 int thisSize = groupMap->getNumSeqs(Groups[i]);
898 if (thisSize < size) { size = thisSize; }
900 }else { //make sure size is not too large
901 vector<string> newGroups;
902 for (int i = 0; i < Groups.size(); i++) {
903 int thisSize = groupMap->getNumSeqs(Groups[i]);
905 if (thisSize >= size) { newGroups.push_back(Groups[i]); }
906 else { m->mothurOut("You have selected a size that is larger than " + Groups[i] + " number of sequences, removing " + Groups[i] + "."); m->mothurOutEndLine(); }
911 m->mothurOut("Sampling " + toString(size) + " from each group."); m->mothurOutEndLine();
915 for(int i = 0; i < Groups.size(); i++) {
916 total += groupMap->getNumSeqs(Groups[i]);
919 if (size == 0) { //user has not set size, set size = 10% samples size
920 size = int (total * 0.10);
924 m->mothurOut("Your size is too large for the number of groups you selected. Adjusting to " + toString(int (total * 0.10)) + "."); m->mothurOutEndLine();
925 size = int (total * 0.10);
928 m->mothurOut("Sampling " + toString(size) + " from " + toString(total) + "."); m->mothurOutEndLine();
931 if (size == 0) { //user has not set size, set size = 10% samples size
932 size = int (list->getNumSeqs() * 0.10);
935 int thisSize = list->getNumSeqs();
936 if (size > thisSize) { m->mothurOut("Your list file only contains " + toString(thisSize) + " sequences. Setting size to " + toString(thisSize) + "."); m->mothurOutEndLine();
940 m->mothurOut("Sampling " + toString(size) + " from " + toString(list->getNumSeqs()) + "."); m->mothurOutEndLine();
946 for (int i = 0; i < list->getNumBins(); i++) {
947 string binnames = list->get(i);
950 string individual = "";
951 int length = binnames.length();
952 for(int j=0;j<length;j++){
953 if(binnames[j] == ','){
955 if (groupfile != "") { //if there is a groupfile given fill in group info
956 string group = groupMap->getGroup(individual);
957 if (group == "not found") { m->mothurOut("[ERROR]: " + individual + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
959 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
960 if (m->inUsersGroups(group, Groups)) {
961 names.push_back(individual);
964 names.push_back(individual);
966 }else{ //save everyone, group
967 names.push_back(individual);
972 individual += binnames[j];
976 if (groupfile != "") { //if there is a groupfile given fill in group info
977 string group = groupMap->getGroup(individual);
978 if (group == "not found") { m->mothurOut("[ERROR]: " + individual + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
980 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
981 if (m->inUsersGroups(group, Groups)) {
982 names.push_back(individual);
985 names.push_back(individual);
987 }else{ //save everyone, group
988 names.push_back(individual);
992 random_shuffle(names.begin(), names.end());
994 //randomly select a subset of those names to include in the subsample
995 set<string> subset; //dont want repeat sequence names added
998 map<string, int> groupCounts;
999 map<string, int>::iterator itGroupCounts;
1000 for (int i = 0; i < Groups.size(); i++) { groupCounts[Groups[i]] = 0; }
1002 for (int j = 0; j < names.size(); j++) {
1004 if (m->control_pressed) { return 0; }
1006 string group = groupMap->getGroup(names[j]);
1007 if (group == "not found") { m->mothurOut("[ERROR]: " + names[j] + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
1009 itGroupCounts = groupCounts.find(group);
1010 if (itGroupCounts != groupCounts.end()) {
1011 if (groupCounts[group] < size) { subset.insert(names[j]); groupCounts[group]++; }
1016 for (int j = 0; j < size; j++) {
1018 if (m->control_pressed) { break; }
1020 subset.insert(names[j]);
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() {
1172 InputData* input = new InputData(rabundfile, "rabund");
1173 RAbundVector* rabund = input->getRAbundVector();
1174 string lastLabel = rabund->getLabel();
1176 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1177 set<string> processedLabels;
1178 set<string> userLabels = labels;
1180 if (size == 0) { //user has not set size, set size = 10%
1181 size = int((rabund->getNumSeqs()) * 0.10);
1182 }else if (size > rabund->getNumSeqs()) { m->mothurOut("The size you selected is too large, skipping rabund file."); m->mothurOutEndLine(); delete input; delete rabund; return 0; }
1184 m->mothurOut("Sampling " + toString(size) + " from " + toString(rabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1186 string thisOutputDir = outputDir;
1187 if (outputDir == "") { thisOutputDir += m->hasPath(rabundfile); }
1188 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(rabundfile)) + "subsample" + m->getExtension(rabundfile);
1191 m->openOutputFile(outputFileName, out);
1192 outputTypes["rabund"].push_back(outputFileName); outputNames.push_back(outputFileName);
1194 //as long as you are not at the end of the file or done wih the lines you want
1195 while((rabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1196 if (m->control_pressed) { delete input; delete rabund; out.close(); return 0; }
1198 if(allLines == 1 || labels.count(rabund->getLabel()) == 1){
1200 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1202 processRabund(rabund, out);
1204 processedLabels.insert(rabund->getLabel());
1205 userLabels.erase(rabund->getLabel());
1208 if ((m->anyLabelsToProcess(rabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1209 string saveLabel = rabund->getLabel();
1213 rabund = input->getRAbundVector(lastLabel);
1214 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1216 processRabund(rabund, out);
1218 processedLabels.insert(rabund->getLabel());
1219 userLabels.erase(rabund->getLabel());
1221 //restore real lastlabel to save below
1222 rabund->setLabel(saveLabel);
1225 lastLabel = rabund->getLabel();
1227 //prevent memory leak
1228 delete rabund; rabund = NULL;
1230 //get next line to process
1231 rabund = input->getRAbundVector();
1235 if (m->control_pressed) { out.close(); return 0; }
1237 //output error messages about any remaining user labels
1238 set<string>::iterator it;
1239 bool needToRun = false;
1240 for (it = userLabels.begin(); it != userLabels.end(); it++) {
1241 m->mothurOut("Your file does not include the label " + *it);
1242 if (processedLabels.count(lastLabel) != 1) {
1243 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1246 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1250 //run last label if you need to
1251 if (needToRun == true) {
1252 if (rabund != NULL) { delete rabund; }
1254 rabund = input->getRAbundVector(lastLabel);
1256 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1258 processRabund(rabund, out);
1269 catch(exception& e) {
1270 m->errorOut(e, "SubSampleCommand", "getSubSampleRabund");
1274 //**********************************************************************************************************************
1275 int SubSampleCommand::processRabund(RAbundVector*& rabund, ofstream& out) {
1278 int numBins = rabund->getNumBins();
1279 int thisSize = rabund->getNumSeqs();
1281 if (thisSize != size) {
1283 OrderVector* order = new OrderVector();
1284 for(int p=0;p<numBins;p++){
1285 for(int j=0;j<rabund->get(p);j++){
1286 order->push_back(p);
1289 random_shuffle(order->begin(), order->end());
1291 RAbundVector* temp = new RAbundVector(numBins);
1292 temp->setLabel(rabund->getLabel());
1297 for (int j = 0; j < size; j++) {
1299 if (m->control_pressed) { delete order; return 0; }
1301 int bin = order->get(j);
1303 int abund = rabund->get(bin);
1304 rabund->set(bin, (abund+1));
1310 if (m->control_pressed) { return 0; }
1317 catch(exception& e) {
1318 m->errorOut(e, "SubSampleCommand", "processRabund");
1322 //**********************************************************************************************************************
1323 int SubSampleCommand::getSubSampleSabund() {
1326 InputData* input = new InputData(sabundfile, "sabund");
1327 SAbundVector* sabund = input->getSAbundVector();
1328 string lastLabel = sabund->getLabel();
1330 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1331 set<string> processedLabels;
1332 set<string> userLabels = labels;
1334 if (size == 0) { //user has not set size, set size = 10%
1335 size = int((sabund->getNumSeqs()) * 0.10);
1336 }else if (size > sabund->getNumSeqs()) { m->mothurOut("The size you selected is too large, skipping sabund file."); m->mothurOutEndLine(); delete input; delete sabund; return 0; }
1339 m->mothurOut("Sampling " + toString(size) + " from " + toString(sabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1341 string thisOutputDir = outputDir;
1342 if (outputDir == "") { thisOutputDir += m->hasPath(sabundfile); }
1343 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(sabundfile)) + "subsample" + m->getExtension(sabundfile);
1346 m->openOutputFile(outputFileName, out);
1347 outputTypes["sabund"].push_back(outputFileName); outputNames.push_back(outputFileName);
1350 //as long as you are not at the end of the file or done wih the lines you want
1351 while((sabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1352 if (m->control_pressed) { delete input; delete sabund; out.close(); return 0; }
1354 if(allLines == 1 || labels.count(sabund->getLabel()) == 1){
1356 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1358 processSabund(sabund, out);
1360 processedLabels.insert(sabund->getLabel());
1361 userLabels.erase(sabund->getLabel());
1364 if ((m->anyLabelsToProcess(sabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1365 string saveLabel = sabund->getLabel();
1369 sabund = input->getSAbundVector(lastLabel);
1370 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1372 processSabund(sabund, out);
1374 processedLabels.insert(sabund->getLabel());
1375 userLabels.erase(sabund->getLabel());
1377 //restore real lastlabel to save below
1378 sabund->setLabel(saveLabel);
1381 lastLabel = sabund->getLabel();
1383 //prevent memory leak
1384 delete sabund; sabund = NULL;
1386 //get next line to process
1387 sabund = input->getSAbundVector();
1391 if (m->control_pressed) { out.close(); return 0; }
1393 //output error messages about any remaining user labels
1394 set<string>::iterator it;
1395 bool needToRun = false;
1396 for (it = userLabels.begin(); it != userLabels.end(); it++) {
1397 m->mothurOut("Your file does not include the label " + *it);
1398 if (processedLabels.count(lastLabel) != 1) {
1399 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1402 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1406 //run last label if you need to
1407 if (needToRun == true) {
1408 if (sabund != NULL) { delete sabund; }
1410 sabund = input->getSAbundVector(lastLabel);
1412 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1414 processSabund(sabund, out);
1425 catch(exception& e) {
1426 m->errorOut(e, "SubSampleCommand", "getSubSampleSabund");
1430 //**********************************************************************************************************************
1431 int SubSampleCommand::processSabund(SAbundVector*& sabund, ofstream& out) {
1434 RAbundVector* rabund = new RAbundVector();
1435 *rabund = sabund->getRAbundVector();
1437 int numBins = rabund->getNumBins();
1438 int thisSize = rabund->getNumSeqs();
1440 if (thisSize != size) {
1442 OrderVector* order = new OrderVector();
1443 for(int p=0;p<numBins;p++){
1444 for(int j=0;j<rabund->get(p);j++){
1445 order->push_back(p);
1448 random_shuffle(order->begin(), order->end());
1450 RAbundVector* temp = new RAbundVector(numBins);
1451 temp->setLabel(rabund->getLabel());
1456 for (int j = 0; j < size; j++) {
1458 if (m->control_pressed) { delete order; return 0; }
1460 int bin = order->get(j);
1462 int abund = rabund->get(bin);
1463 rabund->set(bin, (abund+1));
1469 if (m->control_pressed) { return 0; }
1472 sabund = new SAbundVector();
1473 *sabund = rabund->getSAbundVector();
1481 catch(exception& e) {
1482 m->errorOut(e, "SubSampleCommand", "processSabund");
1486 //**********************************************************************************************************************