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 //initialize outputTypes
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();
79 //allow user to run help
80 if(option == "help") { help(); abort = 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) { return 0; }
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 m->mothurOutEndLine();
344 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
345 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
346 m->mothurOutEndLine();
351 catch(exception& e) {
352 m->errorOut(e, "BootSharedCommand", "execute");
356 //**********************************************************************************************************************
358 int BootSharedCommand::createTree(ostream* out, Tree* t){
361 //do merges and create tree structure by setting parents and children
362 //there are numGroups - 1 merges to do
363 for (int i = 0; i < (numGroups - 1); i++) {
365 if (m->control_pressed) { return 1; }
367 float largest = -1000.0;
369 //find largest value in sims matrix by searching lower triangle
370 for (int j = 1; j < simMatrix.size(); j++) {
371 for (int k = 0; k < j; k++) {
372 if (simMatrix[j][k] > largest) { largest = simMatrix[j][k]; row = j; column = k; }
376 //set non-leaf node info and update leaves to know their parents
378 t->tree[numGroups + i].setChildren(index[row], index[column]);
381 t->tree[index[row]].setParent(numGroups + i);
382 t->tree[index[column]].setParent(numGroups + i);
384 //blength = distance / 2;
385 float blength = ((1.0 - largest) / 2);
388 t->tree[index[row]].setBranchLength(blength - t->tree[index[row]].getLengthToLeaves());
389 t->tree[index[column]].setBranchLength(blength - t->tree[index[column]].getLengthToLeaves());
391 //set your length to leaves to your childs length plus branchlength
392 t->tree[numGroups + i].setLengthToLeaves(t->tree[index[row]].getLengthToLeaves() + t->tree[index[row]].getBranchLength());
396 index[row] = numGroups+i;
397 index[column] = numGroups+i;
399 //zero out highest value that caused the merge.
400 simMatrix[row][column] = -1000.0;
401 simMatrix[column][row] = -1000.0;
403 //merge values in simsMatrix
404 for (int n = 0; n < simMatrix.size(); n++) {
405 //row becomes merge of 2 groups
406 simMatrix[row][n] = (simMatrix[row][n] + simMatrix[column][n]) / 2;
407 simMatrix[n][row] = simMatrix[row][n];
409 simMatrix[column][n] = -1000.0;
410 simMatrix[n][column] = -1000.0;
414 //adjust tree to make sure root to tip length is .5
415 int root = t->findRoot();
416 t->tree[root].setBranchLength((0.5 - t->tree[root].getLengthToLeaves()));
421 if (m->control_pressed) { return 1; }
429 catch(exception& e) {
430 m->errorOut(e, "BootSharedCommand", "createTree");
434 /***********************************************************/
435 void BootSharedCommand::printSims() {
437 m->mothurOut("simsMatrix"); m->mothurOutEndLine();
438 for (int k = 0; k < simMatrix.size(); k++) {
439 for (int n = 0; n < simMatrix.size(); n++) {
440 m->mothurOut(toString(simMatrix[k][n])); m->mothurOut("\t");
442 m->mothurOutEndLine();
446 catch(exception& e) {
447 m->errorOut(e, "BootSharedCommand", "printSims");
451 /***********************************************************/
452 int BootSharedCommand::process(SharedOrderVector* order) {
455 vector<SharedRAbundVector*> subset;
457 //open an ostream for each calc to print to
458 for (int z = 0; z < treeCalculators.size(); z++) {
459 //create a new filename
460 outputFile = outputDir + m->getRootName(m->getSimpleName(globaldata->inputFileName)) + treeCalculators[z]->getName() + ".boot" + order->getLabel() + ".tre";
461 m->openOutputFile(outputFile, *(out[z]));
462 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile);
465 m->mothurOut("Generating bootstrap trees..."); cout.flush();
467 //create a file for each calculator with the 1000 trees in it.
468 for (int p = 0; p < iters; p++) {
470 if (m->control_pressed) { return 1; }
472 util->getSharedVectorswithReplacement(globaldata->Groups, lookup, order); //fills group vectors from order vector.
475 //for each calculator
476 for(int i = 0 ; i < treeCalculators.size(); i++) {
478 if (m->control_pressed) { return 1; }
480 //initialize simMatrix
482 simMatrix.resize(numGroups);
483 for (int o = 0; o < simMatrix.size(); o++) {
484 for (int j = 0; j < simMatrix.size(); j++) {
485 simMatrix[o].push_back(0.0);
491 for (int g = 0; g < numGroups; g++) { index[g] = g; }
493 for (int k = 0; k < lookup.size(); k++) { // pass cdd each set of groups to commpare
494 for (int l = k; l < lookup.size(); l++) {
495 if (k != l) { //we dont need to similiarity of a groups to itself
496 subset.clear(); //clear out old pair of sharedrabunds
497 //add new pair of sharedrabunds
498 subset.push_back(lookup[k]); subset.push_back(lookup[l]);
500 //get estimated similarity between 2 groups
501 data = treeCalculators[i]->getValues(subset); //saves the calculator outputs
502 //save values in similarity matrix
503 simMatrix[k][l] = data[0];
504 simMatrix[l][k] = data[0];
509 tempTree = new Tree();
511 if (m->control_pressed) { delete tempTree; return 1; }
513 //creates tree from similarity matrix and write out file
514 createTree(out[i], tempTree);
516 if (m->control_pressed) { delete tempTree; return 1; }
518 //save trees for consensus command.
519 trees[i].push_back(tempTree);
523 m->mothurOut("\tDone."); m->mothurOutEndLine();
524 //delete globaldata's tree
525 //for (int m = 0; m < globaldata->gTree.size(); m++) { delete globaldata->gTree[m]; }
526 //globaldata->gTree.clear();
529 //create consensus trees for each bootstrapped tree set
530 for (int k = 0; k < trees.size(); k++) {
532 m->mothurOut("Generating consensus tree for " + treeCalculators[k]->getName()); m->mothurOutEndLine();
534 if (m->control_pressed) { return 1; }
536 //set global data to calc trees
537 globaldata->gTree = trees[k];
539 string filename = outputDir + m->getRootName(m->getSimpleName(globaldata->inputFileName)) + treeCalculators[k]->getName() + ".boot" + order->getLabel();
540 consensus = new ConcensusCommand(filename);
541 consensus->execute();
544 outputNames.push_back(filename + ".cons.pairs");
545 outputNames.push_back(filename + ".cons.tre");
547 //delete globaldata's tree
548 //for (int m = 0; m < globaldata->gTree.size(); m++) { delete globaldata->gTree[m]; }
549 //globaldata->gTree.clear();
555 //close ostream for each calc
556 for (int z = 0; z < treeCalculators.size(); z++) { out[z]->close(); }
561 catch(exception& e) {
562 m->errorOut(e, "BootSharedCommand", "process");
566 /***********************************************************/