2 * bootstrapsharedcommand.cpp
5 * Created by Sarah Westcott on 4/16/09.
6 * Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
10 #include "bootstrapsharedcommand.h"
11 #include "sharedjabund.h"
12 #include "sharedsorabund.h"
13 #include "sharedjclass.h"
14 #include "sharedsorclass.h"
15 #include "sharedjest.h"
16 #include "sharedsorest.h"
17 #include "sharedthetayc.h"
18 #include "sharedthetan.h"
19 #include "sharedmorisitahorn.h"
20 #include "sharedbraycurtis.h"
23 //**********************************************************************************************************************
24 vector<string> BootSharedCommand::setParameters(){
26 CommandParameter pshared("shared", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pshared);
27 CommandParameter plabel("label", "String", "", "", "", "", "",false,false); parameters.push_back(plabel);
28 CommandParameter pgroups("groups", "String", "", "", "", "", "",false,false); parameters.push_back(pgroups);
29 CommandParameter piters("iters", "Number", "", "1000", "", "", "",false,false); parameters.push_back(piters);
30 CommandParameter pcalc("calc", "Multiple", "jabund-sorabund-jclass-sorclass-jest-sorest-thetayc-thetan-morisitahorn-braycurtis", "jclass-thetayc", "", "", "",true,false); parameters.push_back(pcalc);
31 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
32 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
34 vector<string> myArray;
35 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
39 m->errorOut(e, "BootSharedCommand", "setParameters");
43 //**********************************************************************************************************************
44 string BootSharedCommand::getHelpString(){
46 string helpString = "";
47 helpString += "The bootstrap.shared command parameters are shared, groups, calc, iters and label. shared is required.\n";
48 helpString += "The groups parameter allows you to specify which of the groups in your groupfile you would like included used.\n";
49 helpString += "The group names are separated by dashes. The label parameter allows you to select what distance levels you would like trees created for, and is also separated by dashes.\n";
50 helpString += "The bootstrap.shared command should be in the following format: bootstrap.shared(groups=yourGroups, calc=yourCalcs, label=yourLabels, iters=yourIters).\n";
51 helpString += "Example bootstrap.shared(groups=A-B-C, calc=jabund-sorabund, iters=100).\n";
52 helpString += "The default value for groups is all the groups in your groupfile.\n";
53 helpString += "The default value for calc is jclass-thetayc. The default for iters is 1000.\n";
57 m->errorOut(e, "BootSharedCommand", "getHelpString");
61 //**********************************************************************************************************************
62 BootSharedCommand::BootSharedCommand(){
64 abort = true; calledHelp = true;
66 vector<string> tempOutNames;
67 outputTypes["tree"] = tempOutNames;
70 m->errorOut(e, "BootSharedCommand", "BootSharedCommand");
74 //**********************************************************************************************************************
75 BootSharedCommand::BootSharedCommand(string option) {
77 abort = false; calledHelp = false;
79 //allow user to run help
80 if(option == "help") { help(); abort = true; calledHelp = true; }
81 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
84 vector<string> myArray = setParameters();
86 OptionParser parser(option);
87 map<string,string> parameters = parser.getParameters();
88 map<string,string>::iterator it;
90 ValidParameters validParameter;
92 //check to make sure all parameters are valid for command
93 for (it = parameters.begin(); it != parameters.end(); it++) {
94 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
97 //initialize outputTypes
98 vector<string> tempOutNames;
99 outputTypes["tree"] = tempOutNames;
101 //if the user changes the input directory command factory will send this info to us in the output parameter
102 string inputDir = validParameter.validFile(parameters, "inputdir", false);
103 if (inputDir == "not found"){ inputDir = ""; }
106 it = parameters.find("shared");
107 //user has given a template file
108 if(it != parameters.end()){
109 path = m->hasPath(it->second);
110 //if the user has not given a path then, add inputdir. else leave path alone.
111 if (path == "") { parameters["shared"] = inputDir + it->second; }
115 sharedfile = validParameter.validFile(parameters, "shared", true);
116 if (sharedfile == "not found") { m->mothurOut("shared is a required parameter."); m->mothurOutEndLine(); sharedfile = ""; abort = true; }
117 else if (sharedfile == "not open") { sharedfile = ""; abort = true; }
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"){
122 outputDir += m->hasPath(sharedfile); //if user entered a file with a path then preserve it
125 //check for optional parameter and set defaults
126 // ...at some point should added some additional type checking...
127 label = validParameter.validFile(parameters, "label", false);
128 if (label == "not found") { label = ""; }
130 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
131 else { allLines = 1; }
134 groups = validParameter.validFile(parameters, "groups", false);
135 if (groups == "not found") { groups = ""; }
137 m->splitAtDash(groups, Groups);
141 calc = validParameter.validFile(parameters, "calc", false);
142 if (calc == "not found") { calc = "jclass-thetayc"; }
144 if (calc == "default") { calc = "jclass-thetayc"; }
146 m->splitAtDash(calc, Estimators);
147 if (m->inUsersGroups("citation", Estimators)) {
148 ValidCalculators validCalc; validCalc.printCitations(Estimators);
149 //remove citation from list of calcs
150 for (int i = 0; i < Estimators.size(); i++) { if (Estimators[i] == "citation") { Estimators.erase(Estimators.begin()+i); break; } }
154 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "1000"; }
155 convert(temp, iters);
157 if (abort == false) {
159 //used in tree constructor
162 validCalculator = new ValidCalculators();
165 //NOTE: if you add a calc to this if statement you must add it to the setParameters function
166 //or it will not be visible in the gui
168 for (i=0; i<Estimators.size(); i++) {
169 if (validCalculator->isValidCalculator("boot", Estimators[i]) == true) {
170 if (Estimators[i] == "jabund") {
171 treeCalculators.push_back(new JAbund());
172 }else if (Estimators[i] == "sorabund") {
173 treeCalculators.push_back(new SorAbund());
174 }else if (Estimators[i] == "jclass") {
175 treeCalculators.push_back(new Jclass());
176 }else if (Estimators[i] == "sorclass") {
177 treeCalculators.push_back(new SorClass());
178 }else if (Estimators[i] == "jest") {
179 treeCalculators.push_back(new Jest());
180 }else if (Estimators[i] == "sorest") {
181 treeCalculators.push_back(new SorEst());
182 }else if (Estimators[i] == "thetayc") {
183 treeCalculators.push_back(new ThetaYC());
184 }else if (Estimators[i] == "thetan") {
185 treeCalculators.push_back(new ThetaN());
186 }else if (Estimators[i] == "morisitahorn") {
187 treeCalculators.push_back(new MorHorn());
188 }else if (Estimators[i] == "braycurtis") {
189 treeCalculators.push_back(new BrayCurtis());
194 delete validCalculator;
197 for (int i=0; i < treeCalculators.size(); i++) {
198 tempo = new ofstream;
199 out.push_back(tempo);
202 //make a vector of tree* for each calculator
203 trees.resize(treeCalculators.size());
208 catch(exception& e) {
209 m->errorOut(e, "BootSharedCommand", "BootSharedCommand");
213 //**********************************************************************************************************************
214 BootSharedCommand::~BootSharedCommand(){}
215 //**********************************************************************************************************************
217 int BootSharedCommand::execute(){
220 if (abort == true) { if (calledHelp) { return 0; } return 2; }
222 m->mothurOut("bootstrap.shared command is no longer available."); m->mothurOutEndLine();
225 input = new InputData(sharedfile, "sharedfile");
226 order = input->getSharedOrderVector();
227 string lastLabel = order->getLabel();
229 //if the users entered no valid calculators don't execute command
230 if (treeCalculators.size() == 0) { return 0; }
232 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
233 set<string> processedLabels;
234 set<string> userLabels = labels;
237 util = new SharedUtil();
238 util->setGroups(m->Groups, m->namesOfGroups, "treegroup");
240 numGroups = m->Groups.size();
242 //clear globaldatas old tree names if any
243 globaldata->Treenames.clear();
245 //fills globaldatas tree names
246 globaldata->Treenames = m->Groups;
248 //create treemap class from groupmap for tree class to use
249 tmap = new TreeMap();
250 tmap->makeSim(globaldata->gGroupmap);
251 globaldata->gTreemap = tmap;
253 while((order != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
254 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); delete input;delete util; return 0; }
256 if(allLines == 1 || labels.count(order->getLabel()) == 1){
258 m->mothurOut(order->getLabel()); m->mothurOutEndLine();
259 int error = process(order);
260 if (error == 1) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); delete input;delete util; return 0; }
262 processedLabels.insert(order->getLabel());
263 userLabels.erase(order->getLabel());
266 //you have a label the user want that is smaller than this label and the last label has not already been processed
267 if ((m->anyLabelsToProcess(order->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
268 string saveLabel = order->getLabel();
271 order = input->getSharedOrderVector(lastLabel);
272 m->mothurOut(order->getLabel()); m->mothurOutEndLine();
273 int error = process(order);
274 if (error == 1) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); delete input;delete util; return 0; }
276 processedLabels.insert(order->getLabel());
277 userLabels.erase(order->getLabel());
279 //restore real lastlabel to save below
280 order->setLabel(saveLabel);
284 lastLabel = order->getLabel();
286 //get next line to process
288 order = input->getSharedOrderVector();
292 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); delete input; delete util; return 0; }
294 //output error messages about any remaining user labels
295 set<string>::iterator it;
296 bool needToRun = false;
297 for (it = userLabels.begin(); it != userLabels.end(); it++) {
298 m->mothurOut("Your file does not include the label " + *it);
299 if (processedLabels.count(lastLabel) != 1) {
300 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
303 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
307 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); delete input; delete util; return 0; }
309 //run last line if you need to
310 if (needToRun == true) {
311 if (order != NULL) { delete order; }
312 order = input->getSharedOrderVector(lastLabel);
313 m->mothurOut(order->getLabel()); m->mothurOutEndLine();
314 int error = process(order);
315 if (error == 1) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); delete input; delete util; return 0; }
321 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear();delete input; delete util; return 0; }
323 //reset groups parameter
324 globaldata->Groups.clear();
326 //set first tree file as new current treefile
327 string currentTree = "";
328 itTypes = outputTypes.find("tree");
329 if (itTypes != outputTypes.end()) {
330 if ((itTypes->second).size() != 0) { currentTree = (itTypes->second)[0]; m->setTreeFile(currentTree); }
336 m->mothurOutEndLine();
337 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
338 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
339 m->mothurOutEndLine();
344 catch(exception& e) {
345 m->errorOut(e, "BootSharedCommand", "execute");
349 //**********************************************************************************************************************
351 int BootSharedCommand::createTree(ostream* out, Tree* t){
354 //do merges and create tree structure by setting parents and children
355 //there are numGroups - 1 merges to do
356 for (int i = 0; i < (numGroups - 1); i++) {
358 if (m->control_pressed) { return 1; }
360 float largest = -1000.0;
362 //find largest value in sims matrix by searching lower triangle
363 for (int j = 1; j < simMatrix.size(); j++) {
364 for (int k = 0; k < j; k++) {
365 if (simMatrix[j][k] > largest) { largest = simMatrix[j][k]; row = j; column = k; }
369 //set non-leaf node info and update leaves to know their parents
371 t->tree[numGroups + i].setChildren(index[row], index[column]);
374 t->tree[index[row]].setParent(numGroups + i);
375 t->tree[index[column]].setParent(numGroups + i);
377 //blength = distance / 2;
378 float blength = ((1.0 - largest) / 2);
381 t->tree[index[row]].setBranchLength(blength - t->tree[index[row]].getLengthToLeaves());
382 t->tree[index[column]].setBranchLength(blength - t->tree[index[column]].getLengthToLeaves());
384 //set your length to leaves to your childs length plus branchlength
385 t->tree[numGroups + i].setLengthToLeaves(t->tree[index[row]].getLengthToLeaves() + t->tree[index[row]].getBranchLength());
389 index[row] = numGroups+i;
390 index[column] = numGroups+i;
392 //zero out highest value that caused the merge.
393 simMatrix[row][column] = -1000.0;
394 simMatrix[column][row] = -1000.0;
396 //merge values in simsMatrix
397 for (int n = 0; n < simMatrix.size(); n++) {
398 //row becomes merge of 2 groups
399 simMatrix[row][n] = (simMatrix[row][n] + simMatrix[column][n]) / 2;
400 simMatrix[n][row] = simMatrix[row][n];
402 simMatrix[column][n] = -1000.0;
403 simMatrix[n][column] = -1000.0;
407 //adjust tree to make sure root to tip length is .5
408 int root = t->findRoot();
409 t->tree[root].setBranchLength((0.5 - t->tree[root].getLengthToLeaves()));
414 if (m->control_pressed) { return 1; }
422 catch(exception& e) {
423 m->errorOut(e, "BootSharedCommand", "createTree");
427 /***********************************************************/
428 void BootSharedCommand::printSims() {
430 m->mothurOut("simsMatrix"); m->mothurOutEndLine();
431 for (int k = 0; k < simMatrix.size(); k++) {
432 for (int n = 0; n < simMatrix.size(); n++) {
433 m->mothurOut(toString(simMatrix[k][n])); m->mothurOut("\t");
435 m->mothurOutEndLine();
439 catch(exception& e) {
440 m->errorOut(e, "BootSharedCommand", "printSims");
444 /***********************************************************/
445 int BootSharedCommand::process(SharedOrderVector* order) {
448 vector<SharedRAbundVector*> subset;
450 //open an ostream for each calc to print to
451 for (int z = 0; z < treeCalculators.size(); z++) {
452 //create a new filename
453 outputFile = outputDir + m->getRootName(m->getSimpleName(sharedfile)) + treeCalculators[z]->getName() + ".boot" + order->getLabel() + ".tre";
454 m->openOutputFile(outputFile, *(out[z]));
455 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile);
458 m->mothurOut("Generating bootstrap trees..."); cout.flush();
460 //create a file for each calculator with the 1000 trees in it.
461 for (int p = 0; p < iters; p++) {
463 if (m->control_pressed) { return 1; }
465 util->getSharedVectorswithReplacement(m->Groups, lookup, order); //fills group vectors from order vector.
468 //for each calculator
469 for(int i = 0 ; i < treeCalculators.size(); i++) {
471 if (m->control_pressed) { return 1; }
473 //initialize simMatrix
475 simMatrix.resize(numGroups);
476 for (int o = 0; o < simMatrix.size(); o++) {
477 for (int j = 0; j < simMatrix.size(); j++) {
478 simMatrix[o].push_back(0.0);
484 for (int g = 0; g < numGroups; g++) { index[g] = g; }
486 for (int k = 0; k < lookup.size(); k++) { // pass cdd each set of groups to commpare
487 for (int l = k; l < lookup.size(); l++) {
488 if (k != l) { //we dont need to similiarity of a groups to itself
489 subset.clear(); //clear out old pair of sharedrabunds
490 //add new pair of sharedrabunds
491 subset.push_back(lookup[k]); subset.push_back(lookup[l]);
493 //get estimated similarity between 2 groups
494 data = treeCalculators[i]->getValues(subset); //saves the calculator outputs
495 //save values in similarity matrix
496 simMatrix[k][l] = data[0];
497 simMatrix[l][k] = data[0];
502 tempTree = new Tree();
504 if (m->control_pressed) { delete tempTree; return 1; }
506 //creates tree from similarity matrix and write out file
507 createTree(out[i], tempTree);
509 if (m->control_pressed) { delete tempTree; return 1; }
511 //save trees for consensus command.
512 trees[i].push_back(tempTree);
516 m->mothurOut("\tDone."); m->mothurOutEndLine();
519 //create consensus trees for each bootstrapped tree set
520 for (int k = 0; k < trees.size(); k++) {
522 m->mothurOut("Generating consensus tree for " + treeCalculators[k]->getName()); m->mothurOutEndLine();
524 if (m->control_pressed) { return 1; }
526 //set global data to calc trees
527 globaldata->gTree = trees[k];
529 string filename = outputDir + m->getRootName(m->getSimpleName(sharedfile)) + treeCalculators[k]->getName() + ".boot" + order->getLabel();
530 consensus = new ConcensusCommand(filename);
531 consensus->execute();
534 outputNames.push_back(filename + ".cons.pairs");
535 outputNames.push_back(filename + ".cons.tre");
541 //close ostream for each calc
542 for (int z = 0; z < treeCalculators.size(); z++) { out[z]->close(); }
547 catch(exception& e) {
548 m->errorOut(e, "BootSharedCommand", "process");
552 /***********************************************************/