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; }
83 vector<string> myArray = setParameters();
85 OptionParser parser(option);
86 map<string,string> parameters = parser.getParameters();
87 map<string,string>::iterator it;
89 ValidParameters validParameter;
91 //check to make sure all parameters are valid for command
92 for (it = parameters.begin(); it != parameters.end(); it++) {
93 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
96 //initialize outputTypes
97 vector<string> tempOutNames;
98 outputTypes["tree"] = tempOutNames;
100 //if the user changes the input directory command factory will send this info to us in the output parameter
101 string inputDir = validParameter.validFile(parameters, "inputdir", false);
102 if (inputDir == "not found"){ inputDir = ""; }
105 it = parameters.find("shared");
106 //user has given a template file
107 if(it != parameters.end()){
108 path = m->hasPath(it->second);
109 //if the user has not given a path then, add inputdir. else leave path alone.
110 if (path == "") { parameters["shared"] = inputDir + it->second; }
114 sharedfile = validParameter.validFile(parameters, "shared", true);
115 if (sharedfile == "not found") { m->mothurOut("shared is a required parameter."); m->mothurOutEndLine(); sharedfile = ""; abort = true; }
116 else if (sharedfile == "not open") { sharedfile = ""; abort = true; }
118 //if the user changes the output directory command factory will send this info to us in the output parameter
119 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
121 outputDir += m->hasPath(sharedfile); //if user entered a file with a path then preserve it
124 //check for optional parameter and set defaults
125 // ...at some point should added some additional type checking...
126 label = validParameter.validFile(parameters, "label", false);
127 if (label == "not found") { label = ""; }
129 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
130 else { allLines = 1; }
133 groups = validParameter.validFile(parameters, "groups", false);
134 if (groups == "not found") { groups = ""; }
136 m->splitAtDash(groups, Groups);
140 calc = validParameter.validFile(parameters, "calc", false);
141 if (calc == "not found") { calc = "jclass-thetayc"; }
143 if (calc == "default") { calc = "jclass-thetayc"; }
145 m->splitAtDash(calc, Estimators);
148 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "1000"; }
149 convert(temp, iters);
151 if (abort == false) {
153 //used in tree constructor
156 validCalculator = new ValidCalculators();
159 //NOTE: if you add a calc to this if statement you must add it to the setParameters function
160 //or it will not be visible in the gui
162 for (i=0; i<Estimators.size(); i++) {
163 if (validCalculator->isValidCalculator("boot", Estimators[i]) == true) {
164 if (Estimators[i] == "jabund") {
165 treeCalculators.push_back(new JAbund());
166 }else if (Estimators[i] == "sorabund") {
167 treeCalculators.push_back(new SorAbund());
168 }else if (Estimators[i] == "jclass") {
169 treeCalculators.push_back(new Jclass());
170 }else if (Estimators[i] == "sorclass") {
171 treeCalculators.push_back(new SorClass());
172 }else if (Estimators[i] == "jest") {
173 treeCalculators.push_back(new Jest());
174 }else if (Estimators[i] == "sorest") {
175 treeCalculators.push_back(new SorEst());
176 }else if (Estimators[i] == "thetayc") {
177 treeCalculators.push_back(new ThetaYC());
178 }else if (Estimators[i] == "thetan") {
179 treeCalculators.push_back(new ThetaN());
180 }else if (Estimators[i] == "morisitahorn") {
181 treeCalculators.push_back(new MorHorn());
182 }else if (Estimators[i] == "braycurtis") {
183 treeCalculators.push_back(new BrayCurtis());
188 delete validCalculator;
191 for (int i=0; i < treeCalculators.size(); i++) {
192 tempo = new ofstream;
193 out.push_back(tempo);
196 //make a vector of tree* for each calculator
197 trees.resize(treeCalculators.size());
202 catch(exception& e) {
203 m->errorOut(e, "BootSharedCommand", "BootSharedCommand");
207 //**********************************************************************************************************************
208 BootSharedCommand::~BootSharedCommand(){}
209 //**********************************************************************************************************************
211 int BootSharedCommand::execute(){
214 if (abort == true) { if (calledHelp) { return 0; } return 2; }
216 m->mothurOut("bootstrap.shared command is no longer available."); m->mothurOutEndLine();
219 input = new InputData(sharedfile, "sharedfile");
220 order = input->getSharedOrderVector();
221 string lastLabel = order->getLabel();
223 //if the users entered no valid calculators don't execute command
224 if (treeCalculators.size() == 0) { return 0; }
226 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
227 set<string> processedLabels;
228 set<string> userLabels = labels;
231 util = new SharedUtil();
232 util->setGroups(m->Groups, m->namesOfGroups, "treegroup");
234 numGroups = m->Groups.size();
236 //clear globaldatas old tree names if any
237 globaldata->Treenames.clear();
239 //fills globaldatas tree names
240 globaldata->Treenames = m->Groups;
242 //create treemap class from groupmap for tree class to use
243 tmap = new TreeMap();
244 tmap->makeSim(globaldata->gGroupmap);
245 globaldata->gTreemap = tmap;
247 while((order != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
248 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; }
250 if(allLines == 1 || labels.count(order->getLabel()) == 1){
252 m->mothurOut(order->getLabel()); m->mothurOutEndLine();
253 int error = process(order);
254 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; }
256 processedLabels.insert(order->getLabel());
257 userLabels.erase(order->getLabel());
260 //you have a label the user want that is smaller than this label and the last label has not already been processed
261 if ((m->anyLabelsToProcess(order->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
262 string saveLabel = order->getLabel();
265 order = input->getSharedOrderVector(lastLabel);
266 m->mothurOut(order->getLabel()); m->mothurOutEndLine();
267 int error = process(order);
268 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; }
270 processedLabels.insert(order->getLabel());
271 userLabels.erase(order->getLabel());
273 //restore real lastlabel to save below
274 order->setLabel(saveLabel);
278 lastLabel = order->getLabel();
280 //get next line to process
282 order = input->getSharedOrderVector();
286 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; }
288 //output error messages about any remaining user labels
289 set<string>::iterator it;
290 bool needToRun = false;
291 for (it = userLabels.begin(); it != userLabels.end(); it++) {
292 m->mothurOut("Your file does not include the label " + *it);
293 if (processedLabels.count(lastLabel) != 1) {
294 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
297 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
301 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; }
303 //run last line if you need to
304 if (needToRun == true) {
305 if (order != NULL) { delete order; }
306 order = input->getSharedOrderVector(lastLabel);
307 m->mothurOut(order->getLabel()); m->mothurOutEndLine();
308 int error = process(order);
309 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; }
315 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; }
317 //reset groups parameter
318 globaldata->Groups.clear();
320 //set first tree file as new current treefile
321 string currentTree = "";
322 itTypes = outputTypes.find("tree");
323 if (itTypes != outputTypes.end()) {
324 if ((itTypes->second).size() != 0) { currentTree = (itTypes->second)[0]; m->setTreeFile(currentTree); }
330 m->mothurOutEndLine();
331 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
332 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
333 m->mothurOutEndLine();
338 catch(exception& e) {
339 m->errorOut(e, "BootSharedCommand", "execute");
343 //**********************************************************************************************************************
345 int BootSharedCommand::createTree(ostream* out, Tree* t){
348 //do merges and create tree structure by setting parents and children
349 //there are numGroups - 1 merges to do
350 for (int i = 0; i < (numGroups - 1); i++) {
352 if (m->control_pressed) { return 1; }
354 float largest = -1000.0;
356 //find largest value in sims matrix by searching lower triangle
357 for (int j = 1; j < simMatrix.size(); j++) {
358 for (int k = 0; k < j; k++) {
359 if (simMatrix[j][k] > largest) { largest = simMatrix[j][k]; row = j; column = k; }
363 //set non-leaf node info and update leaves to know their parents
365 t->tree[numGroups + i].setChildren(index[row], index[column]);
368 t->tree[index[row]].setParent(numGroups + i);
369 t->tree[index[column]].setParent(numGroups + i);
371 //blength = distance / 2;
372 float blength = ((1.0 - largest) / 2);
375 t->tree[index[row]].setBranchLength(blength - t->tree[index[row]].getLengthToLeaves());
376 t->tree[index[column]].setBranchLength(blength - t->tree[index[column]].getLengthToLeaves());
378 //set your length to leaves to your childs length plus branchlength
379 t->tree[numGroups + i].setLengthToLeaves(t->tree[index[row]].getLengthToLeaves() + t->tree[index[row]].getBranchLength());
383 index[row] = numGroups+i;
384 index[column] = numGroups+i;
386 //zero out highest value that caused the merge.
387 simMatrix[row][column] = -1000.0;
388 simMatrix[column][row] = -1000.0;
390 //merge values in simsMatrix
391 for (int n = 0; n < simMatrix.size(); n++) {
392 //row becomes merge of 2 groups
393 simMatrix[row][n] = (simMatrix[row][n] + simMatrix[column][n]) / 2;
394 simMatrix[n][row] = simMatrix[row][n];
396 simMatrix[column][n] = -1000.0;
397 simMatrix[n][column] = -1000.0;
401 //adjust tree to make sure root to tip length is .5
402 int root = t->findRoot();
403 t->tree[root].setBranchLength((0.5 - t->tree[root].getLengthToLeaves()));
408 if (m->control_pressed) { return 1; }
416 catch(exception& e) {
417 m->errorOut(e, "BootSharedCommand", "createTree");
421 /***********************************************************/
422 void BootSharedCommand::printSims() {
424 m->mothurOut("simsMatrix"); m->mothurOutEndLine();
425 for (int k = 0; k < simMatrix.size(); k++) {
426 for (int n = 0; n < simMatrix.size(); n++) {
427 m->mothurOut(toString(simMatrix[k][n])); m->mothurOut("\t");
429 m->mothurOutEndLine();
433 catch(exception& e) {
434 m->errorOut(e, "BootSharedCommand", "printSims");
438 /***********************************************************/
439 int BootSharedCommand::process(SharedOrderVector* order) {
442 vector<SharedRAbundVector*> subset;
444 //open an ostream for each calc to print to
445 for (int z = 0; z < treeCalculators.size(); z++) {
446 //create a new filename
447 outputFile = outputDir + m->getRootName(m->getSimpleName(sharedfile)) + treeCalculators[z]->getName() + ".boot" + order->getLabel() + ".tre";
448 m->openOutputFile(outputFile, *(out[z]));
449 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile);
452 m->mothurOut("Generating bootstrap trees..."); cout.flush();
454 //create a file for each calculator with the 1000 trees in it.
455 for (int p = 0; p < iters; p++) {
457 if (m->control_pressed) { return 1; }
459 util->getSharedVectorswithReplacement(m->Groups, lookup, order); //fills group vectors from order vector.
462 //for each calculator
463 for(int i = 0 ; i < treeCalculators.size(); i++) {
465 if (m->control_pressed) { return 1; }
467 //initialize simMatrix
469 simMatrix.resize(numGroups);
470 for (int o = 0; o < simMatrix.size(); o++) {
471 for (int j = 0; j < simMatrix.size(); j++) {
472 simMatrix[o].push_back(0.0);
478 for (int g = 0; g < numGroups; g++) { index[g] = g; }
480 for (int k = 0; k < lookup.size(); k++) { // pass cdd each set of groups to commpare
481 for (int l = k; l < lookup.size(); l++) {
482 if (k != l) { //we dont need to similiarity of a groups to itself
483 subset.clear(); //clear out old pair of sharedrabunds
484 //add new pair of sharedrabunds
485 subset.push_back(lookup[k]); subset.push_back(lookup[l]);
487 //get estimated similarity between 2 groups
488 data = treeCalculators[i]->getValues(subset); //saves the calculator outputs
489 //save values in similarity matrix
490 simMatrix[k][l] = data[0];
491 simMatrix[l][k] = data[0];
496 tempTree = new Tree();
498 if (m->control_pressed) { delete tempTree; return 1; }
500 //creates tree from similarity matrix and write out file
501 createTree(out[i], tempTree);
503 if (m->control_pressed) { delete tempTree; return 1; }
505 //save trees for consensus command.
506 trees[i].push_back(tempTree);
510 m->mothurOut("\tDone."); m->mothurOutEndLine();
513 //create consensus trees for each bootstrapped tree set
514 for (int k = 0; k < trees.size(); k++) {
516 m->mothurOut("Generating consensus tree for " + treeCalculators[k]->getName()); m->mothurOutEndLine();
518 if (m->control_pressed) { return 1; }
520 //set global data to calc trees
521 globaldata->gTree = trees[k];
523 string filename = outputDir + m->getRootName(m->getSimpleName(sharedfile)) + treeCalculators[k]->getName() + ".boot" + order->getLabel();
524 consensus = new ConcensusCommand(filename);
525 consensus->execute();
528 outputNames.push_back(filename + ".cons.pairs");
529 outputNames.push_back(filename + ".cons.tre");
535 //close ostream for each calc
536 for (int z = 0; z < treeCalculators.size(); z++) { out[z]->close(); }
541 catch(exception& e) {
542 m->errorOut(e, "BootSharedCommand", "process");
546 /***********************************************************/