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(){
38 //initialize outputTypes
39 vector<string> tempOutNames;
40 outputTypes["tree"] = tempOutNames;
43 m->errorOut(e, "BootSharedCommand", "BootSharedCommand");
47 //**********************************************************************************************************************
48 vector<string> BootSharedCommand::getRequiredParameters(){
50 vector<string> myArray;
54 m->errorOut(e, "BootSharedCommand", "getRequiredParameters");
58 //**********************************************************************************************************************
59 vector<string> BootSharedCommand::getRequiredFiles(){
61 string AlignArray[] = {"shared"};
62 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
66 m->errorOut(e, "BootSharedCommand", "getRequiredFiles");
70 //**********************************************************************************************************************
71 BootSharedCommand::BootSharedCommand(string option) {
73 globaldata = GlobalData::getInstance();
80 //allow user to run help
81 if(option == "help") { help(); abort = true; }
84 //valid paramters for this command
85 string Array[] = {"label","calc","groups","iters","outputdir","inputdir"};
86 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
88 OptionParser parser(option);
89 map<string,string> parameters = parser.getParameters();
91 ValidParameters validParameter;
93 //check to make sure all parameters are valid for command
94 for (map<string,string>::iterator it = parameters.begin(); it != parameters.end(); it++) {
95 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
98 //initialize outputTypes
99 vector<string> tempOutNames;
100 outputTypes["tree"] = tempOutNames;
102 //if the user changes the output directory command factory will send this info to us in the output parameter
103 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
105 outputDir += m->hasPath(globaldata->inputFileName); //if user entered a file with a path then preserve it
109 //make sure the user has already run the read.otu command
110 if (globaldata->getSharedFile() == "") {
111 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; }
112 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; }
115 //check for optional parameter and set defaults
116 // ...at some point should added some additional type checking...
117 label = validParameter.validFile(parameters, "label", false);
118 if (label == "not found") { label = ""; }
120 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
121 else { allLines = 1; }
124 //if the user has not specified any labels use the ones from read.otu
126 allLines = globaldata->allLines;
127 labels = globaldata->labels;
130 groups = validParameter.validFile(parameters, "groups", false);
131 if (groups == "not found") { groups = ""; }
133 m->splitAtDash(groups, Groups);
134 globaldata->Groups = Groups;
137 calc = validParameter.validFile(parameters, "calc", false);
138 if (calc == "not found") { calc = "jclass-thetayc"; }
140 if (calc == "default") { calc = "jclass-thetayc"; }
142 m->splitAtDash(calc, Estimators);
145 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "1000"; }
146 convert(temp, iters);
148 if (abort == false) {
150 //used in tree constructor
151 globaldata->runParse = false;
153 validCalculator = new ValidCalculators();
156 for (i=0; i<Estimators.size(); i++) {
157 if (validCalculator->isValidCalculator("boot", Estimators[i]) == true) {
158 if (Estimators[i] == "jabund") {
159 treeCalculators.push_back(new JAbund());
160 }else if (Estimators[i] == "sorabund") {
161 treeCalculators.push_back(new SorAbund());
162 }else if (Estimators[i] == "jclass") {
163 treeCalculators.push_back(new Jclass());
164 }else if (Estimators[i] == "sorclass") {
165 treeCalculators.push_back(new SorClass());
166 }else if (Estimators[i] == "jest") {
167 treeCalculators.push_back(new Jest());
168 }else if (Estimators[i] == "sorest") {
169 treeCalculators.push_back(new SorEst());
170 }else if (Estimators[i] == "thetayc") {
171 treeCalculators.push_back(new ThetaYC());
172 }else if (Estimators[i] == "thetan") {
173 treeCalculators.push_back(new ThetaN());
174 }else if (Estimators[i] == "morisitahorn") {
175 treeCalculators.push_back(new MorHorn());
176 }else if (Estimators[i] == "braycurtis") {
177 treeCalculators.push_back(new BrayCurtis());
182 delete validCalculator;
185 for (int i=0; i < treeCalculators.size(); i++) {
186 tempo = new ofstream;
187 out.push_back(tempo);
190 //make a vector of tree* for each calculator
191 trees.resize(treeCalculators.size());
196 catch(exception& e) {
197 m->errorOut(e, "BootSharedCommand", "BootSharedCommand");
202 //**********************************************************************************************************************
204 void BootSharedCommand::help(){
206 m->mothurOut("The bootstrap.shared command can only be executed after a successful read.otu command.\n");
207 m->mothurOut("The bootstrap.shared command parameters are groups, calc, iters and label.\n");
208 m->mothurOut("The groups parameter allows you to specify which of the groups in your groupfile you would like included used.\n");
209 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");
210 m->mothurOut("The bootstrap.shared command should be in the following format: bootstrap.shared(groups=yourGroups, calc=yourCalcs, label=yourLabels, iters=yourIters).\n");
211 m->mothurOut("Example bootstrap.shared(groups=A-B-C, calc=jabund-sorabund, iters=100).\n");
212 m->mothurOut("The default value for groups is all the groups in your groupfile.\n");
213 m->mothurOut("The default value for calc is jclass-thetayc. The default for iters is 1000.\n");
215 catch(exception& e) {
216 m->errorOut(e, "BootSharedCommand", "help");
221 //**********************************************************************************************************************
223 BootSharedCommand::~BootSharedCommand(){
224 //made new in execute
225 if (abort == false) {
226 delete input; globaldata->ginput = NULL;
229 globaldata->gorder = NULL;
233 //**********************************************************************************************************************
235 int BootSharedCommand::execute(){
238 if (abort == true) { return 0; }
240 util = new SharedUtil();
243 read = new ReadOTUFile(globaldata->inputFileName);
244 read->read(&*globaldata);
245 input = globaldata->ginput;
246 order = input->getSharedOrderVector();
247 string lastLabel = order->getLabel();
249 //if the users entered no valid calculators don't execute command
250 if (treeCalculators.size() == 0) { return 0; }
252 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
253 set<string> processedLabels;
254 set<string> userLabels = labels;
257 util->setGroups(globaldata->Groups, globaldata->gGroupmap->namesOfGroups, "treegroup");
258 numGroups = globaldata->Groups.size();
260 //clear globaldatas old tree names if any
261 globaldata->Treenames.clear();
263 //fills globaldatas tree names
264 globaldata->Treenames = globaldata->Groups;
266 //create treemap class from groupmap for tree class to use
267 tmap = new TreeMap();
268 tmap->makeSim(globaldata->gGroupmap);
269 globaldata->gTreemap = tmap;
271 while((order != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
272 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); return 0; }
274 if(allLines == 1 || labels.count(order->getLabel()) == 1){
276 m->mothurOut(order->getLabel()); m->mothurOutEndLine();
277 int error = process(order);
278 if (error == 1) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); return 0; }
280 processedLabels.insert(order->getLabel());
281 userLabels.erase(order->getLabel());
284 //you have a label the user want that is smaller than this label and the last label has not already been processed
285 if ((m->anyLabelsToProcess(order->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
286 string saveLabel = order->getLabel();
289 order = input->getSharedOrderVector(lastLabel);
290 m->mothurOut(order->getLabel()); m->mothurOutEndLine();
291 int error = process(order);
292 if (error == 1) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); return 0; }
294 processedLabels.insert(order->getLabel());
295 userLabels.erase(order->getLabel());
297 //restore real lastlabel to save below
298 order->setLabel(saveLabel);
302 lastLabel = order->getLabel();
304 //get next line to process
306 order = input->getSharedOrderVector();
310 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); return 0; }
312 //output error messages about any remaining user labels
313 set<string>::iterator it;
314 bool needToRun = false;
315 for (it = userLabels.begin(); it != userLabels.end(); it++) {
316 m->mothurOut("Your file does not include the label " + *it);
317 if (processedLabels.count(lastLabel) != 1) {
318 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
321 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
325 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); return 0; }
327 //run last line if you need to
328 if (needToRun == true) {
329 if (order != NULL) { delete order; }
330 order = input->getSharedOrderVector(lastLabel);
331 m->mothurOut(order->getLabel()); m->mothurOutEndLine();
332 int error = process(order);
333 if (error == 1) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); return 0; }
339 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); return 0; }
341 //reset groups parameter
342 globaldata->Groups.clear();
344 m->mothurOutEndLine();
345 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
346 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
347 m->mothurOutEndLine();
352 catch(exception& e) {
353 m->errorOut(e, "BootSharedCommand", "execute");
357 //**********************************************************************************************************************
359 int BootSharedCommand::createTree(ostream* out, Tree* t){
362 //do merges and create tree structure by setting parents and children
363 //there are numGroups - 1 merges to do
364 for (int i = 0; i < (numGroups - 1); i++) {
366 if (m->control_pressed) { return 1; }
368 float largest = -1000.0;
370 //find largest value in sims matrix by searching lower triangle
371 for (int j = 1; j < simMatrix.size(); j++) {
372 for (int k = 0; k < j; k++) {
373 if (simMatrix[j][k] > largest) { largest = simMatrix[j][k]; row = j; column = k; }
377 //set non-leaf node info and update leaves to know their parents
379 t->tree[numGroups + i].setChildren(index[row], index[column]);
382 t->tree[index[row]].setParent(numGroups + i);
383 t->tree[index[column]].setParent(numGroups + i);
385 //blength = distance / 2;
386 float blength = ((1.0 - largest) / 2);
389 t->tree[index[row]].setBranchLength(blength - t->tree[index[row]].getLengthToLeaves());
390 t->tree[index[column]].setBranchLength(blength - t->tree[index[column]].getLengthToLeaves());
392 //set your length to leaves to your childs length plus branchlength
393 t->tree[numGroups + i].setLengthToLeaves(t->tree[index[row]].getLengthToLeaves() + t->tree[index[row]].getBranchLength());
397 index[row] = numGroups+i;
398 index[column] = numGroups+i;
400 //zero out highest value that caused the merge.
401 simMatrix[row][column] = -1000.0;
402 simMatrix[column][row] = -1000.0;
404 //merge values in simsMatrix
405 for (int n = 0; n < simMatrix.size(); n++) {
406 //row becomes merge of 2 groups
407 simMatrix[row][n] = (simMatrix[row][n] + simMatrix[column][n]) / 2;
408 simMatrix[n][row] = simMatrix[row][n];
410 simMatrix[column][n] = -1000.0;
411 simMatrix[n][column] = -1000.0;
415 //adjust tree to make sure root to tip length is .5
416 int root = t->findRoot();
417 t->tree[root].setBranchLength((0.5 - t->tree[root].getLengthToLeaves()));
422 if (m->control_pressed) { return 1; }
430 catch(exception& e) {
431 m->errorOut(e, "BootSharedCommand", "createTree");
435 /***********************************************************/
436 void BootSharedCommand::printSims() {
438 m->mothurOut("simsMatrix"); m->mothurOutEndLine();
439 for (int k = 0; k < simMatrix.size(); k++) {
440 for (int n = 0; n < simMatrix.size(); n++) {
441 m->mothurOut(toString(simMatrix[k][n])); m->mothurOut("\t");
443 m->mothurOutEndLine();
447 catch(exception& e) {
448 m->errorOut(e, "BootSharedCommand", "printSims");
452 /***********************************************************/
453 int BootSharedCommand::process(SharedOrderVector* order) {
456 vector<SharedRAbundVector*> subset;
458 //open an ostream for each calc to print to
459 for (int z = 0; z < treeCalculators.size(); z++) {
460 //create a new filename
461 outputFile = outputDir + m->getRootName(m->getSimpleName(globaldata->inputFileName)) + treeCalculators[z]->getName() + ".boot" + order->getLabel() + ".tre";
462 m->openOutputFile(outputFile, *(out[z]));
463 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile);
466 m->mothurOut("Generating bootstrap trees..."); cout.flush();
468 //create a file for each calculator with the 1000 trees in it.
469 for (int p = 0; p < iters; p++) {
471 if (m->control_pressed) { return 1; }
473 util->getSharedVectorswithReplacement(globaldata->Groups, lookup, order); //fills group vectors from order vector.
476 //for each calculator
477 for(int i = 0 ; i < treeCalculators.size(); i++) {
479 if (m->control_pressed) { return 1; }
481 //initialize simMatrix
483 simMatrix.resize(numGroups);
484 for (int o = 0; o < simMatrix.size(); o++) {
485 for (int j = 0; j < simMatrix.size(); j++) {
486 simMatrix[o].push_back(0.0);
492 for (int g = 0; g < numGroups; g++) { index[g] = g; }
494 for (int k = 0; k < lookup.size(); k++) { // pass cdd each set of groups to commpare
495 for (int l = k; l < lookup.size(); l++) {
496 if (k != l) { //we dont need to similiarity of a groups to itself
497 subset.clear(); //clear out old pair of sharedrabunds
498 //add new pair of sharedrabunds
499 subset.push_back(lookup[k]); subset.push_back(lookup[l]);
501 //get estimated similarity between 2 groups
502 data = treeCalculators[i]->getValues(subset); //saves the calculator outputs
503 //save values in similarity matrix
504 simMatrix[k][l] = data[0];
505 simMatrix[l][k] = data[0];
510 tempTree = new Tree();
512 if (m->control_pressed) { delete tempTree; return 1; }
514 //creates tree from similarity matrix and write out file
515 createTree(out[i], tempTree);
517 if (m->control_pressed) { delete tempTree; return 1; }
519 //save trees for consensus command.
520 trees[i].push_back(tempTree);
524 m->mothurOut("\tDone."); m->mothurOutEndLine();
525 //delete globaldata's tree
526 //for (int m = 0; m < globaldata->gTree.size(); m++) { delete globaldata->gTree[m]; }
527 //globaldata->gTree.clear();
530 //create consensus trees for each bootstrapped tree set
531 for (int k = 0; k < trees.size(); k++) {
533 m->mothurOut("Generating consensus tree for " + treeCalculators[k]->getName()); m->mothurOutEndLine();
535 if (m->control_pressed) { return 1; }
537 //set global data to calc trees
538 globaldata->gTree = trees[k];
540 string filename = outputDir + m->getRootName(m->getSimpleName(globaldata->inputFileName)) + treeCalculators[k]->getName() + ".boot" + order->getLabel();
541 consensus = new ConcensusCommand(filename);
542 consensus->execute();
545 outputNames.push_back(filename + ".cons.pairs");
546 outputNames.push_back(filename + ".cons.tre");
548 //delete globaldata's tree
549 //for (int m = 0; m < globaldata->gTree.size(); m++) { delete globaldata->gTree[m]; }
550 //globaldata->gTree.clear();
556 //close ostream for each calc
557 for (int z = 0; z < treeCalculators.size(); z++) { out[z]->close(); }
562 catch(exception& e) {
563 m->errorOut(e, "BootSharedCommand", "process");
567 /***********************************************************/