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->readNames(namefile, nameMap);
645 //save names of all sequences
646 map<string, vector<string> >::iterator it;
647 for (it = nameMap.begin(); it != nameMap.end(); it++) { for (int i = 0; i < (it->second).size(); i++) { names.push_back((it->second)[i]); } }
652 catch(exception& e) {
653 m->errorOut(e, "SubSampleCommand", "readNames");
657 //**********************************************************************************************************************
658 int SubSampleCommand::getSubSampleShared() {
661 InputData* input = new InputData(sharedfile, "sharedfile");
662 vector<SharedRAbundVector*> lookup = input->getSharedRAbundVectors();
663 string lastLabel = lookup[0]->getLabel();
665 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
666 set<string> processedLabels;
667 set<string> userLabels = labels;
669 if (size == 0) { //user has not set size, set size = smallest samples size
670 size = lookup[0]->getNumSeqs();
671 for (int i = 1; i < lookup.size(); i++) {
672 int thisSize = lookup[i]->getNumSeqs();
674 if (thisSize < size) { size = thisSize; }
679 vector<SharedRAbundVector*> temp;
680 for (int i = 0; i < lookup.size(); i++) {
681 if (lookup[i]->getNumSeqs() < size) {
682 m->mothurOut(lookup[i]->getGroup() + " contains " + toString(lookup[i]->getNumSeqs()) + ". Eliminating."); m->mothurOutEndLine();
685 Groups.push_back(lookup[i]->getGroup());
686 temp.push_back(lookup[i]);
690 m->setGroups(Groups);
693 if (lookup.size() == 0) { m->mothurOut("The size you selected is too large, skipping shared file."); m->mothurOutEndLine(); delete input; return 0; }
695 m->mothurOut("Sampling " + toString(size) + " from each group."); m->mothurOutEndLine();
697 //as long as you are not at the end of the file or done wih the lines you want
698 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
699 if (m->control_pressed) { delete input; for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; lookup[i] = NULL; } return 0; }
701 if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){
703 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
705 processShared(lookup);
707 processedLabels.insert(lookup[0]->getLabel());
708 userLabels.erase(lookup[0]->getLabel());
711 if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
712 string saveLabel = lookup[0]->getLabel();
714 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
716 lookup = input->getSharedRAbundVectors(lastLabel);
717 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
719 processShared(lookup);
721 processedLabels.insert(lookup[0]->getLabel());
722 userLabels.erase(lookup[0]->getLabel());
724 //restore real lastlabel to save below
725 lookup[0]->setLabel(saveLabel);
728 lastLabel = lookup[0]->getLabel();
729 //prevent memory leak
730 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; lookup[i] = NULL; }
732 //get next line to process
733 lookup = input->getSharedRAbundVectors();
737 if (m->control_pressed) { return 0; }
739 //output error messages about any remaining user labels
740 set<string>::iterator it;
741 bool needToRun = false;
742 for (it = userLabels.begin(); it != userLabels.end(); it++) {
743 m->mothurOut("Your file does not include the label " + *it);
744 if (processedLabels.count(lastLabel) != 1) {
745 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
748 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
752 //run last label if you need to
753 if (needToRun == true) {
754 for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }
755 lookup = input->getSharedRAbundVectors(lastLabel);
757 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
759 processShared(lookup);
761 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
769 catch(exception& e) {
770 m->errorOut(e, "SubSampleCommand", "getSubSampleShared");
774 //**********************************************************************************************************************
775 int SubSampleCommand::processShared(vector<SharedRAbundVector*>& thislookup) {
778 //save mothurOut's binLabels to restore for next label
779 vector<string> saveBinLabels = m->currentBinLabels;
781 string thisOutputDir = outputDir;
782 if (outputDir == "") { thisOutputDir += m->hasPath(sharedfile); }
783 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(sharedfile)) + thislookup[0]->getLabel() + ".subsample" + m->getExtension(sharedfile);
786 vector<string> subsampledLabels = sample.getSample(thislookup, size);
788 if (m->control_pressed) { return 0; }
791 m->openOutputFile(outputFileName, out);
792 outputTypes["shared"].push_back(outputFileName); outputNames.push_back(outputFileName);
794 m->currentBinLabels = subsampledLabels;
796 thislookup[0]->printHeaders(out);
798 for (int i = 0; i < thislookup.size(); i++) {
799 out << thislookup[i]->getLabel() << '\t' << thislookup[i]->getGroup() << '\t';
800 thislookup[i]->print(out);
805 //save mothurOut's binLabels to restore for next label
806 m->currentBinLabels = saveBinLabels;
811 catch(exception& e) {
812 m->errorOut(e, "SubSampleCommand", "processShared");
816 //**********************************************************************************************************************
817 int SubSampleCommand::getSubSampleList() {
820 string thisOutputDir = outputDir;
821 if (outputDir == "") { thisOutputDir += m->hasPath(listfile); }
822 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(listfile)) + "subsample" + m->getExtension(listfile);
825 m->openOutputFile(outputFileName, out);
826 outputTypes["list"].push_back(outputFileName); outputNames.push_back(outputFileName);
828 InputData* input = new InputData(listfile, "list");
829 ListVector* list = input->getListVector();
830 string lastLabel = list->getLabel();
832 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
833 set<string> processedLabels;
834 set<string> userLabels = labels;
838 if (groupfile != "") {
840 groupMap = new GroupMap(groupfile);
843 //takes care of user setting groupNames that are invalid or setting groups=all
844 SharedUtil* util = new SharedUtil();
845 vector<string> namesGroups = groupMap->getNamesOfGroups();
846 util->setGroups(Groups, namesGroups);
850 string groupOutputDir = outputDir;
851 if (outputDir == "") { groupOutputDir += m->hasPath(groupfile); }
852 string groupOutputFileName = groupOutputDir + m->getRootName(m->getSimpleName(groupfile)) + "subsample" + m->getExtension(groupfile);
854 m->openOutputFile(groupOutputFileName, outGroup);
855 outputTypes["group"].push_back(groupOutputFileName); outputNames.push_back(groupOutputFileName);
858 if (list->getNumSeqs() != groupMap->getNumSeqs()) {
859 m->mothurOut("[ERROR]: your list file contains " + toString(list->getNumSeqs()) + " sequences, and your groupfile contains " + toString(groupMap->getNumSeqs()) + ", please correct.");
860 m->mothurOutEndLine();
870 //make sure that if your picked groups size is not too big
872 if (size == 0) { //user has not set size, set size = smallest samples size
873 size = groupMap->getNumSeqs(Groups[0]);
874 for (int i = 1; i < Groups.size(); i++) {
875 int thisSize = groupMap->getNumSeqs(Groups[i]);
877 if (thisSize < size) { size = thisSize; }
879 }else { //make sure size is not too large
880 vector<string> newGroups;
881 for (int i = 0; i < Groups.size(); i++) {
882 int thisSize = groupMap->getNumSeqs(Groups[i]);
884 if (thisSize >= size) { newGroups.push_back(Groups[i]); }
885 else { m->mothurOut("You have selected a size that is larger than " + Groups[i] + " number of sequences, removing " + Groups[i] + "."); m->mothurOutEndLine(); }
890 m->mothurOut("Sampling " + toString(size) + " from each group."); m->mothurOutEndLine();
894 for(int i = 0; i < Groups.size(); i++) {
895 total += groupMap->getNumSeqs(Groups[i]);
898 if (size == 0) { //user has not set size, set size = 10% samples size
899 size = int (total * 0.10);
903 m->mothurOut("Your size is too large for the number of groups you selected. Adjusting to " + toString(int (total * 0.10)) + "."); m->mothurOutEndLine();
904 size = int (total * 0.10);
907 m->mothurOut("Sampling " + toString(size) + " from " + toString(total) + "."); m->mothurOutEndLine();
910 if (size == 0) { //user has not set size, set size = 10% samples size
911 size = int (list->getNumSeqs() * 0.10);
914 int thisSize = list->getNumSeqs();
915 if (size > thisSize) { m->mothurOut("Your list file only contains " + toString(thisSize) + " sequences. Setting size to " + toString(thisSize) + "."); m->mothurOutEndLine();
919 m->mothurOut("Sampling " + toString(size) + " from " + toString(list->getNumSeqs()) + "."); m->mothurOutEndLine();
925 for (int i = 0; i < list->getNumBins(); i++) {
926 string binnames = list->get(i);
929 string individual = "";
930 int length = binnames.length();
931 for(int j=0;j<length;j++){
932 if(binnames[j] == ','){
934 if (groupfile != "") { //if there is a groupfile given fill in group info
935 string group = groupMap->getGroup(individual);
936 if (group == "not found") { m->mothurOut("[ERROR]: " + individual + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
938 if (pickedGroups) { //if hte user picked groups, we only want to keep the names of sequences from those groups
939 if (m->inUsersGroups(group, Groups)) {
940 names.push_back(individual);
943 names.push_back(individual);
945 }else{ //save everyone, group
946 names.push_back(individual);
951 individual += 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);
971 random_shuffle(names.begin(), names.end());
973 //randomly select a subset of those names to include in the subsample
974 set<string> subset; //dont want repeat sequence names added
977 map<string, int> groupCounts;
978 map<string, int>::iterator itGroupCounts;
979 for (int i = 0; i < Groups.size(); i++) { groupCounts[Groups[i]] = 0; }
981 for (int j = 0; j < names.size(); j++) {
983 if (m->control_pressed) { return 0; }
985 string group = groupMap->getGroup(names[j]);
986 if (group == "not found") { m->mothurOut("[ERROR]: " + names[j] + " is not in your groupfile. please correct."); m->mothurOutEndLine(); group = "NOTFOUND"; }
988 itGroupCounts = groupCounts.find(group);
989 if (itGroupCounts != groupCounts.end()) {
990 if (groupCounts[group] < size) { subset.insert(names[j]); groupCounts[group]++; }
995 for (int j = 0; j < size; j++) {
997 if (m->control_pressed) { break; }
999 subset.insert(names[j]);
1003 if (groupfile != "") {
1004 //write out new groupfile
1005 for (set<string>::iterator it = subset.begin(); it != subset.end(); it++) {
1006 string group = groupMap->getGroup(*it);
1007 if (group == "not found") { group = "NOTFOUND"; }
1009 outGroup << *it << '\t' << group << endl;
1011 outGroup.close(); delete groupMap;
1015 //as long as you are not at the end of the file or done wih the lines you want
1016 while((list != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1018 if (m->control_pressed) { delete list; delete input; out.close(); return 0; }
1020 if(allLines == 1 || labels.count(list->getLabel()) == 1){
1022 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1024 processList(list, out, subset);
1026 processedLabels.insert(list->getLabel());
1027 userLabels.erase(list->getLabel());
1030 if ((m->anyLabelsToProcess(list->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1031 string saveLabel = list->getLabel();
1035 list = input->getListVector(lastLabel);
1036 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1038 processList(list, out, subset);
1040 processedLabels.insert(list->getLabel());
1041 userLabels.erase(list->getLabel());
1043 //restore real lastlabel to save below
1044 list->setLabel(saveLabel);
1047 lastLabel = list->getLabel();
1049 delete list; list = NULL;
1051 //get next line to process
1052 list = input->getListVector();
1056 if (m->control_pressed) { if (list != NULL) { delete list; } delete input; out.close(); return 0; }
1058 //output error messages about any remaining user labels
1059 set<string>::iterator it;
1060 bool needToRun = false;
1061 for (it = userLabels.begin(); it != userLabels.end(); it++) {
1062 m->mothurOut("Your file does not include the label " + *it);
1063 if (processedLabels.count(lastLabel) != 1) {
1064 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1067 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1071 //run last label if you need to
1072 if (needToRun == true) {
1073 if (list != NULL) { delete list; }
1075 list = input->getListVector(lastLabel);
1077 m->mothurOut(list->getLabel()); m->mothurOutEndLine();
1079 processList(list, out, subset);
1081 delete list; list = NULL;
1085 if (list != NULL) { delete list; }
1091 catch(exception& e) {
1092 m->errorOut(e, "SubSampleCommand", "getSubSampleList");
1096 //**********************************************************************************************************************
1097 int SubSampleCommand::processList(ListVector*& list, ofstream& out, set<string>& subset) {
1100 int numBins = list->getNumBins();
1102 ListVector* temp = new ListVector();
1103 temp->setLabel(list->getLabel());
1105 for (int i = 0; i < numBins; i++) {
1107 if (m->control_pressed) { break; }
1109 string binnames = list->get(i);
1112 string individual = "";
1113 string newNames = "";
1114 int length = binnames.length();
1115 for(int j=0;j<length;j++){
1116 if(binnames[j] == ','){
1117 if (subset.count(individual) != 0) { newNames += individual + ","; }
1120 individual += binnames[j];
1123 if (subset.count(individual) != 0) { newNames += individual + ","; }
1126 //if there are names in this bin add to new list
1127 if (newNames != "") {
1128 newNames = newNames.substr(0, newNames.length()-1); //rip off extra comma
1129 temp->push_back(newNames);
1136 if (m->control_pressed) { return 0; }
1143 catch(exception& e) {
1144 m->errorOut(e, "SubSampleCommand", "processList");
1148 //**********************************************************************************************************************
1149 int SubSampleCommand::getSubSampleRabund() {
1151 InputData* input = new InputData(rabundfile, "rabund");
1152 RAbundVector* rabund = input->getRAbundVector();
1153 string lastLabel = rabund->getLabel();
1155 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1156 set<string> processedLabels;
1157 set<string> userLabels = labels;
1159 if (size == 0) { //user has not set size, set size = 10%
1160 size = int((rabund->getNumSeqs()) * 0.10);
1161 }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; }
1163 m->mothurOut("Sampling " + toString(size) + " from " + toString(rabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1165 string thisOutputDir = outputDir;
1166 if (outputDir == "") { thisOutputDir += m->hasPath(rabundfile); }
1167 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(rabundfile)) + "subsample" + m->getExtension(rabundfile);
1170 m->openOutputFile(outputFileName, out);
1171 outputTypes["rabund"].push_back(outputFileName); outputNames.push_back(outputFileName);
1173 //as long as you are not at the end of the file or done wih the lines you want
1174 while((rabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1175 if (m->control_pressed) { delete input; delete rabund; out.close(); return 0; }
1177 if(allLines == 1 || labels.count(rabund->getLabel()) == 1){
1179 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1181 processRabund(rabund, out);
1183 processedLabels.insert(rabund->getLabel());
1184 userLabels.erase(rabund->getLabel());
1187 if ((m->anyLabelsToProcess(rabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1188 string saveLabel = rabund->getLabel();
1192 rabund = input->getRAbundVector(lastLabel);
1193 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1195 processRabund(rabund, out);
1197 processedLabels.insert(rabund->getLabel());
1198 userLabels.erase(rabund->getLabel());
1200 //restore real lastlabel to save below
1201 rabund->setLabel(saveLabel);
1204 lastLabel = rabund->getLabel();
1206 //prevent memory leak
1207 delete rabund; rabund = NULL;
1209 //get next line to process
1210 rabund = input->getRAbundVector();
1214 if (m->control_pressed) { out.close(); return 0; }
1216 //output error messages about any remaining user labels
1217 set<string>::iterator it;
1218 bool needToRun = false;
1219 for (it = userLabels.begin(); it != userLabels.end(); it++) {
1220 m->mothurOut("Your file does not include the label " + *it);
1221 if (processedLabels.count(lastLabel) != 1) {
1222 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1225 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1229 //run last label if you need to
1230 if (needToRun == true) {
1231 if (rabund != NULL) { delete rabund; }
1233 rabund = input->getRAbundVector(lastLabel);
1235 m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
1237 processRabund(rabund, out);
1248 catch(exception& e) {
1249 m->errorOut(e, "SubSampleCommand", "getSubSampleRabund");
1253 //**********************************************************************************************************************
1254 int SubSampleCommand::processRabund(RAbundVector*& rabund, ofstream& out) {
1257 int numBins = rabund->getNumBins();
1258 int thisSize = rabund->getNumSeqs();
1260 if (thisSize != size) {
1262 OrderVector* order = new OrderVector();
1263 for(int p=0;p<numBins;p++){
1264 for(int j=0;j<rabund->get(p);j++){
1265 order->push_back(p);
1268 random_shuffle(order->begin(), order->end());
1270 RAbundVector* temp = new RAbundVector(numBins);
1271 temp->setLabel(rabund->getLabel());
1276 for (int j = 0; j < size; j++) {
1278 if (m->control_pressed) { delete order; return 0; }
1280 int bin = order->get(j);
1282 int abund = rabund->get(bin);
1283 rabund->set(bin, (abund+1));
1289 if (m->control_pressed) { return 0; }
1296 catch(exception& e) {
1297 m->errorOut(e, "SubSampleCommand", "processRabund");
1301 //**********************************************************************************************************************
1302 int SubSampleCommand::getSubSampleSabund() {
1305 InputData* input = new InputData(sabundfile, "sabund");
1306 SAbundVector* sabund = input->getSAbundVector();
1307 string lastLabel = sabund->getLabel();
1309 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
1310 set<string> processedLabels;
1311 set<string> userLabels = labels;
1313 if (size == 0) { //user has not set size, set size = 10%
1314 size = int((sabund->getNumSeqs()) * 0.10);
1315 }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; }
1318 m->mothurOut("Sampling " + toString(size) + " from " + toString(sabund->getNumSeqs()) + "."); m->mothurOutEndLine();
1320 string thisOutputDir = outputDir;
1321 if (outputDir == "") { thisOutputDir += m->hasPath(sabundfile); }
1322 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(sabundfile)) + "subsample" + m->getExtension(sabundfile);
1325 m->openOutputFile(outputFileName, out);
1326 outputTypes["sabund"].push_back(outputFileName); outputNames.push_back(outputFileName);
1329 //as long as you are not at the end of the file or done wih the lines you want
1330 while((sabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
1331 if (m->control_pressed) { delete input; delete sabund; out.close(); return 0; }
1333 if(allLines == 1 || labels.count(sabund->getLabel()) == 1){
1335 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1337 processSabund(sabund, out);
1339 processedLabels.insert(sabund->getLabel());
1340 userLabels.erase(sabund->getLabel());
1343 if ((m->anyLabelsToProcess(sabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
1344 string saveLabel = sabund->getLabel();
1348 sabund = input->getSAbundVector(lastLabel);
1349 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1351 processSabund(sabund, out);
1353 processedLabels.insert(sabund->getLabel());
1354 userLabels.erase(sabund->getLabel());
1356 //restore real lastlabel to save below
1357 sabund->setLabel(saveLabel);
1360 lastLabel = sabund->getLabel();
1362 //prevent memory leak
1363 delete sabund; sabund = NULL;
1365 //get next line to process
1366 sabund = input->getSAbundVector();
1370 if (m->control_pressed) { out.close(); return 0; }
1372 //output error messages about any remaining user labels
1373 set<string>::iterator it;
1374 bool needToRun = false;
1375 for (it = userLabels.begin(); it != userLabels.end(); it++) {
1376 m->mothurOut("Your file does not include the label " + *it);
1377 if (processedLabels.count(lastLabel) != 1) {
1378 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
1381 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
1385 //run last label if you need to
1386 if (needToRun == true) {
1387 if (sabund != NULL) { delete sabund; }
1389 sabund = input->getSAbundVector(lastLabel);
1391 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
1393 processSabund(sabund, out);
1404 catch(exception& e) {
1405 m->errorOut(e, "SubSampleCommand", "getSubSampleSabund");
1409 //**********************************************************************************************************************
1410 int SubSampleCommand::processSabund(SAbundVector*& sabund, ofstream& out) {
1413 RAbundVector* rabund = new RAbundVector();
1414 *rabund = sabund->getRAbundVector();
1416 int numBins = rabund->getNumBins();
1417 int thisSize = rabund->getNumSeqs();
1419 if (thisSize != size) {
1421 OrderVector* order = new OrderVector();
1422 for(int p=0;p<numBins;p++){
1423 for(int j=0;j<rabund->get(p);j++){
1424 order->push_back(p);
1427 random_shuffle(order->begin(), order->end());
1429 RAbundVector* temp = new RAbundVector(numBins);
1430 temp->setLabel(rabund->getLabel());
1435 for (int j = 0; j < size; j++) {
1437 if (m->control_pressed) { delete order; return 0; }
1439 int bin = order->get(j);
1441 int abund = rabund->get(bin);
1442 rabund->set(bin, (abund+1));
1448 if (m->control_pressed) { return 0; }
1451 sabund = new SAbundVector();
1452 *sabund = rabund->getSAbundVector();
1460 catch(exception& e) {
1461 m->errorOut(e, "SubSampleCommand", "processSabund");
1465 //**********************************************************************************************************************