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"
22 //**********************************************************************************************************************
23 vector<string> BootSharedCommand::getValidParameters(){
25 string AlignArray[] = {"label","calc","groups","iters","outputdir","inputdir"};
26 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
30 m->errorOut(e, "BootSharedCommand", "getValidParameters");
34 //**********************************************************************************************************************
35 BootSharedCommand::BootSharedCommand(){
37 abort = true; calledHelp = true;
38 vector<string> tempOutNames;
39 outputTypes["tree"] = tempOutNames;
42 m->errorOut(e, "BootSharedCommand", "BootSharedCommand");
46 //**********************************************************************************************************************
47 vector<string> BootSharedCommand::getRequiredParameters(){
49 vector<string> myArray;
53 m->errorOut(e, "BootSharedCommand", "getRequiredParameters");
57 //**********************************************************************************************************************
58 vector<string> BootSharedCommand::getRequiredFiles(){
60 string AlignArray[] = {"shared"};
61 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
65 m->errorOut(e, "BootSharedCommand", "getRequiredFiles");
69 //**********************************************************************************************************************
70 BootSharedCommand::BootSharedCommand(string option) {
72 globaldata = GlobalData::getInstance();
73 abort = false; calledHelp = false;
79 //allow user to run help
80 if(option == "help") { help(); abort = true; calledHelp = true; }
83 //valid paramters for this command
84 string Array[] = {"label","calc","groups","iters","outputdir","inputdir"};
85 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
87 OptionParser parser(option);
88 map<string,string> parameters = parser.getParameters();
90 ValidParameters validParameter;
92 //check to make sure all parameters are valid for command
93 for (map<string,string>::iterator 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 output directory command factory will send this info to us in the output parameter
102 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
104 outputDir += m->hasPath(globaldata->inputFileName); //if user entered a file with a path then preserve it
108 //make sure the user has already run the read.otu command
109 if (globaldata->getSharedFile() == "") {
110 if (globaldata->getListFile() == "") { m->mothurOut("You must read a list and a group, or a shared before you can use the bootstrap.shared command."); m->mothurOutEndLine(); abort = true; }
111 else if (globaldata->getGroupFile() == "") { m->mothurOut("You must read a list and a group, or a shared before you can use the bootstrap.shared command."); m->mothurOutEndLine(); abort = true; }
114 //check for optional parameter and set defaults
115 // ...at some point should added some additional type checking...
116 label = validParameter.validFile(parameters, "label", false);
117 if (label == "not found") { label = ""; }
119 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
120 else { allLines = 1; }
123 //if the user has not specified any labels use the ones from read.otu
125 allLines = globaldata->allLines;
126 labels = globaldata->labels;
129 groups = validParameter.validFile(parameters, "groups", false);
130 if (groups == "not found") { groups = ""; }
132 m->splitAtDash(groups, Groups);
133 globaldata->Groups = Groups;
136 calc = validParameter.validFile(parameters, "calc", false);
137 if (calc == "not found") { calc = "jclass-thetayc"; }
139 if (calc == "default") { calc = "jclass-thetayc"; }
141 m->splitAtDash(calc, Estimators);
144 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "1000"; }
145 convert(temp, iters);
147 if (abort == false) {
149 //used in tree constructor
150 globaldata->runParse = false;
152 validCalculator = new ValidCalculators();
155 for (i=0; i<Estimators.size(); i++) {
156 if (validCalculator->isValidCalculator("boot", Estimators[i]) == true) {
157 if (Estimators[i] == "jabund") {
158 treeCalculators.push_back(new JAbund());
159 }else if (Estimators[i] == "sorabund") {
160 treeCalculators.push_back(new SorAbund());
161 }else if (Estimators[i] == "jclass") {
162 treeCalculators.push_back(new Jclass());
163 }else if (Estimators[i] == "sorclass") {
164 treeCalculators.push_back(new SorClass());
165 }else if (Estimators[i] == "jest") {
166 treeCalculators.push_back(new Jest());
167 }else if (Estimators[i] == "sorest") {
168 treeCalculators.push_back(new SorEst());
169 }else if (Estimators[i] == "thetayc") {
170 treeCalculators.push_back(new ThetaYC());
171 }else if (Estimators[i] == "thetan") {
172 treeCalculators.push_back(new ThetaN());
173 }else if (Estimators[i] == "morisitahorn") {
174 treeCalculators.push_back(new MorHorn());
175 }else if (Estimators[i] == "braycurtis") {
176 treeCalculators.push_back(new BrayCurtis());
181 delete validCalculator;
184 for (int i=0; i < treeCalculators.size(); i++) {
185 tempo = new ofstream;
186 out.push_back(tempo);
189 //make a vector of tree* for each calculator
190 trees.resize(treeCalculators.size());
195 catch(exception& e) {
196 m->errorOut(e, "BootSharedCommand", "BootSharedCommand");
201 //**********************************************************************************************************************
203 void BootSharedCommand::help(){
205 m->mothurOut("The bootstrap.shared command can only be executed after a successful read.otu command.\n");
206 m->mothurOut("The bootstrap.shared command parameters are groups, calc, iters and label.\n");
207 m->mothurOut("The groups parameter allows you to specify which of the groups in your groupfile you would like included used.\n");
208 m->mothurOut("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");
209 m->mothurOut("The bootstrap.shared command should be in the following format: bootstrap.shared(groups=yourGroups, calc=yourCalcs, label=yourLabels, iters=yourIters).\n");
210 m->mothurOut("Example bootstrap.shared(groups=A-B-C, calc=jabund-sorabund, iters=100).\n");
211 m->mothurOut("The default value for groups is all the groups in your groupfile.\n");
212 m->mothurOut("The default value for calc is jclass-thetayc. The default for iters is 1000.\n");
214 catch(exception& e) {
215 m->errorOut(e, "BootSharedCommand", "help");
220 //**********************************************************************************************************************
222 BootSharedCommand::~BootSharedCommand(){
223 //made new in execute
224 if (abort == false) {
225 delete input; globaldata->ginput = NULL;
228 globaldata->gorder = NULL;
232 //**********************************************************************************************************************
234 int BootSharedCommand::execute(){
237 if (abort == true) { if (calledHelp) { return 0; } return 2; }
239 util = new SharedUtil();
242 read = new ReadOTUFile(globaldata->inputFileName);
243 read->read(&*globaldata);
244 input = globaldata->ginput;
245 order = input->getSharedOrderVector();
246 string lastLabel = order->getLabel();
248 //if the users entered no valid calculators don't execute command
249 if (treeCalculators.size() == 0) { return 0; }
251 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
252 set<string> processedLabels;
253 set<string> userLabels = labels;
256 util->setGroups(globaldata->Groups, globaldata->gGroupmap->namesOfGroups, "treegroup");
257 numGroups = globaldata->Groups.size();
259 //clear globaldatas old tree names if any
260 globaldata->Treenames.clear();
262 //fills globaldatas tree names
263 globaldata->Treenames = globaldata->Groups;
265 //create treemap class from groupmap for tree class to use
266 tmap = new TreeMap();
267 tmap->makeSim(globaldata->gGroupmap);
268 globaldata->gTreemap = tmap;
270 while((order != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
271 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); return 0; }
273 if(allLines == 1 || labels.count(order->getLabel()) == 1){
275 m->mothurOut(order->getLabel()); m->mothurOutEndLine();
276 int error = process(order);
277 if (error == 1) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); return 0; }
279 processedLabels.insert(order->getLabel());
280 userLabels.erase(order->getLabel());
283 //you have a label the user want that is smaller than this label and the last label has not already been processed
284 if ((m->anyLabelsToProcess(order->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
285 string saveLabel = order->getLabel();
288 order = input->getSharedOrderVector(lastLabel);
289 m->mothurOut(order->getLabel()); m->mothurOutEndLine();
290 int error = process(order);
291 if (error == 1) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); return 0; }
293 processedLabels.insert(order->getLabel());
294 userLabels.erase(order->getLabel());
296 //restore real lastlabel to save below
297 order->setLabel(saveLabel);
301 lastLabel = order->getLabel();
303 //get next line to process
305 order = input->getSharedOrderVector();
309 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); return 0; }
311 //output error messages about any remaining user labels
312 set<string>::iterator it;
313 bool needToRun = false;
314 for (it = userLabels.begin(); it != userLabels.end(); it++) {
315 m->mothurOut("Your file does not include the label " + *it);
316 if (processedLabels.count(lastLabel) != 1) {
317 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
320 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
324 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); return 0; }
326 //run last line if you need to
327 if (needToRun == true) {
328 if (order != NULL) { delete order; }
329 order = input->getSharedOrderVector(lastLabel);
330 m->mothurOut(order->getLabel()); m->mothurOutEndLine();
331 int error = process(order);
332 if (error == 1) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); return 0; }
338 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); return 0; }
340 //reset groups parameter
341 globaldata->Groups.clear();
343 //set first tree file as new current treefile
344 string currentTree = "";
345 itTypes = outputTypes.find("tree");
346 if (itTypes != outputTypes.end()) {
347 if ((itTypes->second).size() != 0) { currentTree = (itTypes->second)[0]; m->setTreeFile(currentTree); }
350 m->mothurOutEndLine();
351 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
352 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
353 m->mothurOutEndLine();
358 catch(exception& e) {
359 m->errorOut(e, "BootSharedCommand", "execute");
363 //**********************************************************************************************************************
365 int BootSharedCommand::createTree(ostream* out, Tree* t){
368 //do merges and create tree structure by setting parents and children
369 //there are numGroups - 1 merges to do
370 for (int i = 0; i < (numGroups - 1); i++) {
372 if (m->control_pressed) { return 1; }
374 float largest = -1000.0;
376 //find largest value in sims matrix by searching lower triangle
377 for (int j = 1; j < simMatrix.size(); j++) {
378 for (int k = 0; k < j; k++) {
379 if (simMatrix[j][k] > largest) { largest = simMatrix[j][k]; row = j; column = k; }
383 //set non-leaf node info and update leaves to know their parents
385 t->tree[numGroups + i].setChildren(index[row], index[column]);
388 t->tree[index[row]].setParent(numGroups + i);
389 t->tree[index[column]].setParent(numGroups + i);
391 //blength = distance / 2;
392 float blength = ((1.0 - largest) / 2);
395 t->tree[index[row]].setBranchLength(blength - t->tree[index[row]].getLengthToLeaves());
396 t->tree[index[column]].setBranchLength(blength - t->tree[index[column]].getLengthToLeaves());
398 //set your length to leaves to your childs length plus branchlength
399 t->tree[numGroups + i].setLengthToLeaves(t->tree[index[row]].getLengthToLeaves() + t->tree[index[row]].getBranchLength());
403 index[row] = numGroups+i;
404 index[column] = numGroups+i;
406 //zero out highest value that caused the merge.
407 simMatrix[row][column] = -1000.0;
408 simMatrix[column][row] = -1000.0;
410 //merge values in simsMatrix
411 for (int n = 0; n < simMatrix.size(); n++) {
412 //row becomes merge of 2 groups
413 simMatrix[row][n] = (simMatrix[row][n] + simMatrix[column][n]) / 2;
414 simMatrix[n][row] = simMatrix[row][n];
416 simMatrix[column][n] = -1000.0;
417 simMatrix[n][column] = -1000.0;
421 //adjust tree to make sure root to tip length is .5
422 int root = t->findRoot();
423 t->tree[root].setBranchLength((0.5 - t->tree[root].getLengthToLeaves()));
428 if (m->control_pressed) { return 1; }
436 catch(exception& e) {
437 m->errorOut(e, "BootSharedCommand", "createTree");
441 /***********************************************************/
442 void BootSharedCommand::printSims() {
444 m->mothurOut("simsMatrix"); m->mothurOutEndLine();
445 for (int k = 0; k < simMatrix.size(); k++) {
446 for (int n = 0; n < simMatrix.size(); n++) {
447 m->mothurOut(toString(simMatrix[k][n])); m->mothurOut("\t");
449 m->mothurOutEndLine();
453 catch(exception& e) {
454 m->errorOut(e, "BootSharedCommand", "printSims");
458 /***********************************************************/
459 int BootSharedCommand::process(SharedOrderVector* order) {
462 vector<SharedRAbundVector*> subset;
464 //open an ostream for each calc to print to
465 for (int z = 0; z < treeCalculators.size(); z++) {
466 //create a new filename
467 outputFile = outputDir + m->getRootName(m->getSimpleName(globaldata->inputFileName)) + treeCalculators[z]->getName() + ".boot" + order->getLabel() + ".tre";
468 m->openOutputFile(outputFile, *(out[z]));
469 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile);
472 m->mothurOut("Generating bootstrap trees..."); cout.flush();
474 //create a file for each calculator with the 1000 trees in it.
475 for (int p = 0; p < iters; p++) {
477 if (m->control_pressed) { return 1; }
479 util->getSharedVectorswithReplacement(globaldata->Groups, lookup, order); //fills group vectors from order vector.
482 //for each calculator
483 for(int i = 0 ; i < treeCalculators.size(); i++) {
485 if (m->control_pressed) { return 1; }
487 //initialize simMatrix
489 simMatrix.resize(numGroups);
490 for (int o = 0; o < simMatrix.size(); o++) {
491 for (int j = 0; j < simMatrix.size(); j++) {
492 simMatrix[o].push_back(0.0);
498 for (int g = 0; g < numGroups; g++) { index[g] = g; }
500 for (int k = 0; k < lookup.size(); k++) { // pass cdd each set of groups to commpare
501 for (int l = k; l < lookup.size(); l++) {
502 if (k != l) { //we dont need to similiarity of a groups to itself
503 subset.clear(); //clear out old pair of sharedrabunds
504 //add new pair of sharedrabunds
505 subset.push_back(lookup[k]); subset.push_back(lookup[l]);
507 //get estimated similarity between 2 groups
508 data = treeCalculators[i]->getValues(subset); //saves the calculator outputs
509 //save values in similarity matrix
510 simMatrix[k][l] = data[0];
511 simMatrix[l][k] = data[0];
516 tempTree = new Tree();
518 if (m->control_pressed) { delete tempTree; return 1; }
520 //creates tree from similarity matrix and write out file
521 createTree(out[i], tempTree);
523 if (m->control_pressed) { delete tempTree; return 1; }
525 //save trees for consensus command.
526 trees[i].push_back(tempTree);
530 m->mothurOut("\tDone."); m->mothurOutEndLine();
531 //delete globaldata's tree
532 //for (int m = 0; m < globaldata->gTree.size(); m++) { delete globaldata->gTree[m]; }
533 //globaldata->gTree.clear();
536 //create consensus trees for each bootstrapped tree set
537 for (int k = 0; k < trees.size(); k++) {
539 m->mothurOut("Generating consensus tree for " + treeCalculators[k]->getName()); m->mothurOutEndLine();
541 if (m->control_pressed) { return 1; }
543 //set global data to calc trees
544 globaldata->gTree = trees[k];
546 string filename = outputDir + m->getRootName(m->getSimpleName(globaldata->inputFileName)) + treeCalculators[k]->getName() + ".boot" + order->getLabel();
547 consensus = new ConcensusCommand(filename);
548 consensus->execute();
551 outputNames.push_back(filename + ".cons.pairs");
552 outputNames.push_back(filename + ".cons.tre");
554 //delete globaldata's tree
555 //for (int m = 0; m < globaldata->gTree.size(); m++) { delete globaldata->gTree[m]; }
556 //globaldata->gTree.clear();
562 //close ostream for each calc
563 for (int z = 0; z < treeCalculators.size(); z++) { out[z]->close(); }
568 catch(exception& e) {
569 m->errorOut(e, "BootSharedCommand", "process");
573 /***********************************************************/